content
stringlengths 5
1.05M
|
---|
position = get_self_pos()
x = position["x"]
y = position["y"]
dir_left = x - 1
dir_right = x + 1
dir_up = y - 1
dir_down = y + 1
if get_turn_count() == 0 then
left()
elseif get_tile_in_front() ~= "empty" then
right()
else
forward()
end
directions = {}
directions['up_dir'] = get_tile_at_pos(x, dir_up)
directions['down_dir'] = get_tile_at_pos(x, dir_down)
directions['left_dir'] = get_tile_at_pos(dir_left, x)
directions['right_dir'] = get_tile_at_pos(dir_right, x)
return get_tile_in_front()
|
------ init.lua ------
--- Textures PreLoading
-- General textures
ButtonDown = Texture.new("images/button_down.png")
ButtonUp = Texture.new("images/button_up.png")
GrayButton = Texture.new("images/gray_button.png")
LittleButtonDown = Texture.new("images/little_button_down.png")
LittleButtonUp = Texture.new("images/little_button_up.png")
LongButtonDown = Texture.new("images/long_button_down.png")
LongButtonGray = Texture.new("images/long_button_gray.png")
LongButtonUp = Texture.new("images/long_button_up.png")
QuitButtonDown = Texture.new("images/quit_button_down.png")
QuitButtonUp = Texture.new("images/quit_button_up.png")
LeftArrow = Texture.new("images/left_arrow.png")
RightArrow = Texture.new("images/right_arrow.png")
FondNiveau = Texture.new("images/FondNiveauBlanc.png")
FondPreservatif = Texture.new('images/preservatifs.jpg')
-- Minigames textures
GameOver = Texture.new("images/gameover.png")
PlayerTxtu = Texture.new("images/player.png")
PlayerTxtu2 = Texture.new("images/penis.png")
PlayerTxtu3 = Texture.new("images/vulva.png")
Squaredodge = Texture.new("images/squaredodge.png")
--Mireille textures
Mireille1 = Texture.new("images/mireille_1.png")
Mireille2 = Texture.new("images/mireille_2.png")
Mireille3 = Texture.new("images/mireille_3.png")
Mireille4 = Texture.new("images/mireille_4.png")
Mireille5 = Texture.new("images/mireille_5.png")
Mireille6 = Texture.new("images/mireille_6.png")
Mireille7 = Texture.new("images/mireille_7.png")
Mireille8 = Texture.new("images/mireille_8.png")
Mireille9 = Texture.new("images/mireille_9.png")
TextBubble = Texture.new("images/TextBubble.png")
--- Fonts definitions
smallFont = TTFont.new("fonts/Roboto-Condensed.ttf", 10)
font = TTFont.new("fonts/Roboto-Condensed.ttf", 12)
titleFont = TTFont.new("fonts/Roboto-Condensed.ttf", 14)
bigTitleFont = TTFont.new("fonts/Roboto-Condensed.ttf", 28)
--- Constants used for element positions
MIN_MARGE_W_LEFT = 40
MIN_MARGE_H_UP = 40
TXTBUTTON_W = 90
TXTBUTTON_H = 35
TITLE_W = 107 -- Third of screen Width to position Big titles
--- global variables that lock and unlock continents
lock1 = 2 --lock = 0 lauch the initial animation
lock2 = 1 -- Continent 2 (and 3) is locked
lock3 = 1
lock4 = 0
|
local spottedColor = Color(250/255, 250/255, 250/255, 1)
local networkVars =
{
spotted = "boolean"
}
function MapBlip:GetIsSighted()
local owner = Shared.GetEntity(self.ownerEntityId)
if owner then
if owner.GetTeamNumber and owner:GetTeamNumber() == kTeamReadyRoom and owner:GetAttached() then
owner = owner:GetAttached()
end
return HasMixin(owner, "LOS") and owner:GetIsSpotted() or false
end
return false
end
-- Called (server side) when a mapblips owner has changed its map-blip dependent state
local oldUpdate = MapBlip.Update
function MapBlip:Update()
oldUpdate(self)
if self.ownerEntityId and Shared.GetEntity(self.ownerEntityId) then
local owner = Shared.GetEntity(self.ownerEntityId)
self.spotted = (HasMixin(owner, "LOS") and owner:GetIsSpotted() and not owner:GetIsSighted())
end
end
if Client then
if kAnyTeamEnabled then
local kFriendly = {}
kFriendly[kMinimapBlipTeam.Friendly] = true
kFriendly[kMinimapBlipTeam.FriendFriendly] = true
kFriendly[kMinimapBlipTeam.InactiveFriendly] = true
kFriendly[kMinimapBlipTeam.Neutral] = true
function IsAnyTeamFriendly(blipTeam)
return kFriendly[blipTeam] == true
end
end
local oldUpdateMinimapItemHook = MapBlip.UpdateMinimapItemHook
function MapBlip:UpdateMinimapItemHook(minimap, item)
oldUpdateMinimapItemHook(self, minimap, item)
local blipTeam = self:GetMapBlipTeam(minimap)
if self.spotted and not minimap.spectating and
((not kAnyTeamEnabled and not self.OnSameMinimapBlipTeam(minimap.playerTeam, blipTeam)) or
(kAnyTeamEnabled and not IsAnyTeamFriendly(blipTeam))) then
self.currentMapBlipColor = Color(spottedColor.r, spottedColor.g, spottedColor.b, self.currentMapBlipColor.a)
end
end
end
Shared.LinkClassToMap("MapBlip", MapBlip.kMapName, networkVars) |
return {
name = 'voronianski/http-utils',
version = '1.0.5',
description = 'List of basic http helpers for luvit.io servers',
repository = {
url = 'http://github.com/luvitrocks/http-utils.git',
},
tags = {'http', 'server', 'helpers', 'utils', 'methods', 'rest', 'api', 'mimetypes', 'mimes'},
author = {
name = 'Dmitri Voronianski',
email = '[email protected]'
},
homepage = 'https://github.com/luvitrocks/http-utils',
licenses = {'MIT'},
dependencies = {
'voronianski/file-type'
},
files = {
'**.lua',
'!test*',
'!example*'
}
}
|
-- calc-ui-prototypes.lua
data:extend({
{
type = "shortcut",
name = "calcui_4func",
order = "b[blueprints]-h[calculator-ui]",
action = "lua",
toggleable = true,
icon =
{
filename = "__calculator-ui__/graphics/calculator.png",
priority = "extra-high-no-scale",
size = 64,
scale = 1,
flags = {"icon"}
}
}
}) |
-- craftscripts.lua
-- Implements the cCraftScript class which represents a player's script.
local function LOGSCRIPTERROR(a_Msg)
if (not g_Config.Scripting.Debug) then
return
end
LOGERROR(a_Msg)
end
local g_BlockedFunctions = table.todictionary{
"rawset",
"rawget",
"setfenv",
"io",
"os",
"debug",
"cFile",
"loadstring",
"loadfile",
"load",
"dofile",
"ExecuteString",
"_G",
"cPluginManager",
}
local g_CraftScriptEnvironment = setmetatable({}, {
__index = function(_, a_Key)
if (g_BlockedFunctions[a_Key]) then
local ScriptInfo = debug.getinfo(2)
error("Edits tried to use blocked variable at line " .. ScriptInfo.currentline .. " in file " .. ScriptInfo.short_src .. ".")
return nil
end
return _G[a_Key]
end
}
)
cCraftScript = {}
function cCraftScript:new(a_Obj)
a_Obj = a_Obj or {}
setmetatable(a_Obj, cCraftScript)
self.__index = self
a_Obj.SelectedScript = nil
return a_Obj;
end
function cCraftScript:SelectScript(a_ScriptName)
local Path = cPluginManager:GetCurrentPlugin():GetLocalFolder() .. "/craftscripts/" .. a_ScriptName .. ".lua"
if (not cFile:IsFile(Path)) then
return false, "Couldn't find that script."
end
local Function, Err = loadfile(Path)
if (not Function) then
LOGSCRIPTERROR(Err)
return false, "Couldn't execute that script."
end
setfenv(Function, g_CraftScriptEnvironment)
self.SelectedScript = Function
return true
end
function cCraftScript:Execute(a_Player, a_Split)
if (not self.SelectedScript) then
return false, "Couldn't find a script."
end
if (g_Config.Scripting.MaxExecutionTime > 0) then
local TimeLimit = os.clock() + g_Config.Scripting.MaxExecutionTime
debug.sethook(function()
if (TimeLimit < os.clock()) then
debug.sethook()
error("Exceeded the time limit for script executions.")
end
end, "", 100000)
end
local Success, Err = pcall(self.SelectedScript, a_Player, a_Split)
debug.sethook()
if (not Success) then
LOGSCRIPTERROR(Err)
return false, "Couldn't execute that script."
end
return true
end
|
Locales['es'] = {
-- Cloakroom
['cloakroom'] = 'Guardarropa',
['ems_clothes_civil'] = 'Camiseta',
['ems_clothes_ems'] = 'Equipo de ambulancia',
['headbandage'] = 'Pastilla Anti inflamatoria',
['torsobandage'] = 'Vendaje de Torax',
['extbandage'] = 'Tratamiento de extremidades',
-- Vehicles
['ambulance'] = 'Ambulancia',
['helicopter_prompt'] = 'Presiona ~INPUT_CONTEXT~ para acceder a ~y~Acciones de helicóptero~s~.',
['garage_prompt'] = 'Presiona ~INPUT_CONTEXT~ para acceder a ~y~Acciones de Vehículos~s~.',
['garage_title'] = 'Acciones de Vehículos.',
['garage_stored'] = 'Almacenado.',
['garage_notstored'] = 'No en el garaje.',
['garage_storing'] = 'Estamos intentando retirar el vehículo, asegúrese de que no haya jugadores cerca.',
['garage_has_stored'] = 'El vehículo ha sido almacenado en su garaje.',
['garage_has_notstored'] = 'No se encontraron vehículos cercanos.',
['garage_notavailable'] = 'Su vehículo no está guardado en el garaje.',
['garage_blocked'] = '¡No hay puntos de generación disponibles!',
['garage_empty'] = 'No tiene ningún vehículo en su garaje.',
['garage_released'] = 'Su vehículo ha sido liberado del garaje.',
['garage_store_nearby'] = 'No hay vehículos cercanos.',
['garage_storeditem'] = 'Garaje abierto',
['garage_storeitem'] = 'Almacenar vehículo en garaje',
['garage_buyitem'] = 'Tienda de vehículos',
['shop_item'] = '$%s',
['vehicleshop_title'] = 'Tienda de vehículos',
['vehicleshop_confirm'] = '¿Quieres comprar este vehículo?',
['vehicleshop_bought'] = 'Usted ha comprado ~y~%s~s~ por ~g~$%s~s~',
['vehicleshop_money'] = 'No puedes pagar ese vehículo',
['vehicleshop_awaiting_model'] = 'El vehículo está actualmente ~g~DESCARGANDO Y CARGANDO~s~ por favor espere.',
['confirm_no'] = 'No',
['confirm_yes'] = 'Si',
-- Action Menu
['revive_inprogress'] = 'Reanimación en curso',
['revive_complete'] = 'Has sido reanimado ~y~%s~s~',
['revive_complete_award'] = 'Has sido reanimado ~y~%s~s~, ~g~$%s~s~',
['revive_fail_offline'] = 'Ese jugador ya no está en línea',
['heal_inprogress'] = '¡Te están curando!',
['heal_complete'] = 'Estas curado ~y~%s~s~',
['no_players'] = 'Ningún jugador cerca',
['player_not_unconscious'] = 'n\'estás inconsciente',
['player_not_conscious'] = '!Ese jugador no esta consciente!',
-- Boss Menu
['boss_actions'] = 'Acciones del jefe',
-- Misc
['invalid_amount'] = '~r~Cantidad no válida',
['actions_prompt'] = 'Presiona ~INPUT_CONTEXT~ para acceder a ~y~Acciones de Ambulancia~s~.',
['deposit_amount'] = 'Cantidad de fianza depositada',
['money_withdraw'] = 'Cantidad de fianza retirada',
['fast_travel'] = 'Presiona ~INPUT_CONTEXT~ para viajar rápido.',
['open_pharmacy'] = 'Presiona ~INPUT_CONTEXT~ para abrir la farmacia',
['pharmacy_menu_title'] = 'Farmacia',
['pharmacy_take'] = 'Tomar <span style="color:blue;">%s</span>',
['medikit'] = 'Kit de primeros Auxilios',
['used_extbandage'] = 'Has usado el ~b~Tratamiento de extremidades~w~ sobre ti.',
['used_torsobandage'] = 'Has usado el ~b~Vendaje de torax~w~ sobre ti.',
['used_headbandage'] = 'Has tomado una~b~pastilla Anti Inflamatoria.',
['bandage'] = 'Vendaje',
['max_item'] = 'Ya estás cargando lo suficiente contigo mismo.',
-- F6 Menu
['ems_menu'] = 'Ayuda ciudadana',
['ems_menu_title'] = 'Ambulancia - Ayuda Ciudadana',
['ems_menu_revive'] = 'Reanimar',
['ems_menu_info'] = 'Diagnosticar',
['vista_general'] = 'Diagnostico general',
['damage_info'] = 'Diagnosticar heridas',
['tratamientos_info'] = 'Tratar heridas',
['tratar_cabeza'] = 'Tratar heridas craneales',
['healhead_inprogress'] = 'Estas tratando heridas craneales',
['not_enough_headbandage'] = 'No tienes Pastillas Anti inflamatorias',
['healcabeza_complete'] = 'Has proporcionado pastillas Anti inflamatorias',
['healbrazo_inprogress'] = 'Estas tratando heridas en los brazos',
['not_enough_extbandage'] = 'No tienes tratamiento de extremidades',
['healbrazo_complete'] = 'Has proporcionado tratamiento de extremidades',
['healtorso_inprogress'] = 'Estas tratando heridas en el torso',
['not_enough_torsobandage'] = 'No tienes Vendaje de torax',
['healtorso_complete'] = 'Has proporcionado vendaje abdominal',
['healleg_complete'] = 'Has proporcionado tratamiento de extremidades',
['healleg_inprogress'] = 'Estas tratando heridas en las piernas',
['tratar_pierna'] = 'Tratar heridas de piernas',
['tratar_brazo'] = 'Tratar heridas de brazos',
['tratar_torso'] = 'Tratar heridas abdominales',
['ems_menu_putincar'] = 'Meter en el vehículo',
['ems_menu_small'] = 'Curar heridas pequeñas',
['ems_menu_big'] = 'Tratar lesiones graves',
-- Phone
['alert_ambulance'] = 'Alerta de ambulancia',
-- Death
['respawn_available_in'] = 'Reaparecer disponible en ~b~%s minutes %s seconds~s~',
['respawn_bleedout_in'] = 'Te desangrarás ~b~%s minutes %s seconds~s~\n',
['respawn_bleedout_prompt'] = 'Sostiene [~b~E~s~] para reaparecer.',
['respawn_bleedout_fine'] = 'Sostiene [~b~E~s~] para reaparecer por ~g~$%s~s~',
['respawn_bleedout_fine_msg'] = 'Has pagado ~r~$%s~s~ para reaparecer.',
['distress_send'] = 'Presiona [~b~G~s~] enviar señal de socorro.',
['distress_sent'] = '¡Señal de socorro ha sido enviada a las unidades disponibles!',
['combatlog_message'] = 'Ha sido reaparecido por la fuerza porque anteriormente dejó el servidor cuando estaba muerto.',
-- Revive
['revive_help'] = 'Revivir un jugador',
-- Item
['used_medikit'] = 'Has usado ~y~1x~s~ Kit de primeros Auxilios',
['used_bandage'] = 'Has usado ~y~1x~s~ Vendaje',
['not_enough_medikit'] = 'Usted no tiene ~b~Kit de primeros Auxilios~s~.',
['not_enough_bandage'] = 'Usted no tiene ~b~Vendaje~s~.',
['healed'] = 'Has sido tratado',
-- Blips
['blip_hospital'] = 'Hospital Pillbox',
['blip_dead'] = 'Jugador inconsciente',
}
|
-- ===========================================================================
-- CityBannerManager for Expansion 1 and Expansion 2
-- ===========================================================================
-- Functions and objects common to basegame and expansions
include( "citybannermanager_CQUI.lua");
-- #59 Infixo they are local and not visible in this file
local m_isReligionLensActive:boolean = false;
local m_HexColoringReligion:number = UILens.CreateLensLayerHash("Hex_Coloring_Religion");
local DATA_FIELD_RELIGION_ICONS_IM:string = "m_IconsIM";
local DATA_FIELD_RELIGION_FOLLOWER_LIST_IM:string = "m_FollowerListIM";
local DATA_FIELD_RELIGION_POP_CHART_IM:string = "m_PopChartIM";
local RELIGION_POP_CHART_TOOLTIP_HEADER:string = Locale.Lookup("LOC_CITY_BANNER_FOLLOWER_PRESSURE_TOOLTIP_HEADER");
-- ===========================================================================
-- Cached Base Functions (Expansions only)
-- ===========================================================================
BASE_CQUI_CityBanner_Initialize = CityBanner.Initialize;
BASE_CQUI_CityBanner_Uninitialize = CityBanner.Uninitialize;
BASE_CQUI_CityBanner_UpdateInfo = CityBanner.UpdateInfo;
BASE_CQUI_CityBanner_UpdatePopulation = CityBanner.UpdatePopulation;
BASE_CQUI_CityBanner_UpdateStats = CityBanner.UpdateStats;
-- ============================================================================
-- CQUI Expansion Extension Functions
-- ============================================================================
function CityBanner.Initialize(self, playerID, cityID, districtID, bannerType, bannerStyle)
-- print_debug("CityBannerManager_CQUI_Expansions: CityBanner:Initialize ENTRY: playerID:"..tostring(playerID).." cityID:"..tostring(cityID).." districtID:"..tostring(districtID).." bannerType:"..tostring(bannerType).." bannerStyle:"..tostring(bannerStyle));
CQUI_Common_CityBanner_Initialize(self, playerID, cityID, districtID, bannerType, bannerStyle);
if (IsBannerTypeCityCenter(bannerType) and (self.CQUI_DistrictBuiltIM == nil)) then
self.CQUI_DistrictBuiltIM = InstanceManager:new( "CQUI_DistrictBuilt", "Icon", self.m_Instance.CQUI_Districts );
end
end
-- ============================================================================
function CityBanner.Uninitialize(self)
-- print_debug("CityBannerManager_CQUI_Expansions: CityBanner.Uninitialize ENTRY");
BASE_CQUI_CityBanner_Uninitialize(self);
-- CQUI : Clear CQUI_DistrictBuiltIM
if self.CQUI_DistrictBuiltIM then
self.CQUI_DistrictBuiltIM:DestroyInstances();
end
end
-- ============================================================================
function CityBanner.UpdateInfo(self, pCity : table )
-- print_debug("CityBannerManager_CQUI_Expansions: CityBanner.UpdateInfo ENTRY pCity:"..tostring(pCity));
BASE_CQUI_CityBanner_UpdateInfo(self, pCity);
if (pCity == nil) then
return;
end
local playerID:number = pCity:GetOwner();
--CQUI : Unlocked citizen check
if (playerID == Game.GetLocalPlayer() and IsCQUI_SmartBanner_Unmanaged_CitizenEnabled()) then
local tParameters :table = {};
tParameters[CityCommandTypes.PARAM_MANAGE_CITIZEN] = UI.GetInterfaceModeParameter(CityCommandTypes.PARAM_MANAGE_CITIZEN);
local tResults:table = CityManager.GetCommandTargets( pCity, CityCommandTypes.MANAGE, tParameters );
if tResults ~= nil then
local tPlots:table = tResults[CityCommandResults.PLOTS];
local tUnits:table = tResults[CityCommandResults.CITIZENS];
local tMaxUnits:table = tResults[CityCommandResults.MAX_CITIZENS];
local tLockedUnits:table = tResults[CityCommandResults.LOCKED_CITIZENS];
if tPlots ~= nil and (table.count(tPlots) > 0) then
for i,plotId in pairs(tPlots) do
local kPlot :table = Map.GetPlotByIndex(plotId);
if (tMaxUnits[i] >= 1 and tUnits[i] >= 1 and tLockedUnits[i] <= 0) then
local instance:table = self.m_InfoIconIM:GetInstance();
instance.Icon:SetIcon("EXCLAMATION");
instance.Icon:SetToolTipString(Locale.Lookup("LOC_CQUI_SMARTBANNER_UNLOCKEDCITIZEN_TOOLTIP"));
instance.Button:RegisterCallback(Mouse.eLClick, OnCityBannerClick);
instance.Button:SetVoid1(pCity:GetOriginalOwner());
instance.Button:SetVoid2(cityID);
break;
end
end
end
end
end
-- #62 Infixo always show an original owner of the city if different than the current one
-- this piece of code is taken from CityBannerManager.lua to allow an extra line inside a tooltip
local pPlayer:table = Players[playerID];
if pPlayer == nil then
return;
end
local tooltip:string, tooltipOrignal:string = "", "";
-- #62 Infixo check if this city was previously owned by someone else
local originalOwner:number = pCity:GetOriginalOwner();
if originalOwner ~= playerID then
if pCity:IsOriginalCapital() then
tooltipOrignal = Locale.Lookup("LOC_CQUI_CITY_BANNER_ORIGINAL_CAPITAL_TT", PlayerConfigurations[originalOwner]:GetCivilizationShortDescription());
else
tooltipOrignal = Locale.Lookup("LOC_CQUI_CITY_BANNER_ORIGINAL_CITY_TT", PlayerConfigurations[originalOwner]:GetCivilizationShortDescription());
end
end
if pPlayer:IsMajor() then
if pCity:IsOriginalCapital() and originalOwner == playerID then
-- Original capital
tooltip = Locale.Lookup("LOC_CITY_BANNER_ORIGINAL_CAPITAL_TT", PlayerConfigurations[playerID]:GetCivilizationShortDescription()); -- no need for original owner info
elseif pCity:IsCapital() then
-- New capital
tooltip = Locale.Lookup("LOC_CITY_BANNER_NEW_CAPITAL_TT", PlayerConfigurations[playerID]:GetCivilizationShortDescription()) .. tooltipOrignal;
else
-- Other cities
tooltip = Locale.Lookup("LOC_CITY_BANNER_OTHER_CITY_TT", PlayerConfigurations[playerID]:GetCivilizationShortDescription()) .. tooltipOrignal;
end
-- espionage info (added in XP2)
if g_bIsGatheringStorm and GameCapabilities.HasCapability("CAPABILITY_ESPIONAGE") then
if Game.GetLocalPlayer() == playerID or HasEspionageView(playerID, pCity:GetID()) then
tooltip = tooltip .. Locale.Lookup("LOC_ESPIONAGE_VIEW_ENABLED_TT");
else
tooltip = tooltip .. Locale.Lookup("LOC_ESPIONAGE_VIEW_DISABLED_TT");
end
end
elseif pPlayer:IsMinor() then
CQUI_UpdateCityStateBannerSuzerain(pPlayer, self);
CQUI_UpdateCityStateBannerAtWarIcon(pPlayer, self);
elseif pPlayer:IsFreeCities() then
tooltip = Locale.Lookup("LOC_CITY_BANNER_FREE_CITY_TT") .. tooltipOrignal;
else -- city states
tooltip = Locale.Lookup("LOC_CITY_BANNER_CITY_STATE_TT") .. tooltipOrignal; -- just in case CS could capture capitals?
end
-- update the tooltip
local cityIconInstance:table = self.m_InfoIconIM:GetAllocatedInstance();
cityIconInstance.Button:SetToolTipString(tooltip);
self:Resize();
end
-- ============================================================================
function CityBanner.UpdatePopulation(self, isLocalPlayer:boolean, pCity:table, pCityGrowth:table)
-- print_debug("CityBannerManager_CQUI_Expansions: CityBanner:UpdatePopulation: pCity: "..tostring(pCity).." pCityGrowth:"..tostring(pCityGrowth));
BASE_CQUI_CityBanner_UpdatePopulation(self, isLocalPlayer, pCity, pCityGrowth);
if (isLocalPlayer == false) then
return;
end
local currentPopulation:number = pCity:GetPopulation();
-- XP1+, grab the first instance
local populationInstance = CQUI_GetInstanceObject(self.m_StatPopulationIM);
-- Get real housing from improvements value
local localPlayerID = Game.GetLocalPlayer();
-- CQUI : housing left
if (IsCQUI_SmartBanner_PopulationEnabled()) then
local cqui_HousingFromImprovementsCalc = CQUI_GetRealHousingFromImprovements(pCity);
if (cqui_HousingFromImprovementsCalc ~= nil) then -- CQUI real housing from improvements fix to show correct values when waiting for the next turn
local housingText, housingLeft = CQUI_GetHousingString(pCity, cqui_HousingFromImprovementsCalc, true);
populationInstance.CQUI_CityHousing:SetText(housingText);
populationInstance.CQUI_CityHousing:SetHide(false);
-- CQUI : add housing left to tooltip
local popTooltip = populationInstance.FillMeter:GetToolTipString();
local CQUI_housingLeftPopupText = "[NEWLINE] [ICON_Housing]" .. Locale.Lookup("LOC_HUD_CITY_HOUSING") .. ": " .. housingLeft;
popTooltip = popTooltip .. CQUI_housingLeftPopupText;
populationInstance.FillMeter:SetToolTipString(popTooltip);
end
else
populationInstance.CQUI_CityHousing:SetHide(true);
end
if (IsCQUI_SmartBanner_CulturalEnabled()) then
-- Show the turns left until border expansion to the left of the population
local pCityCulture = pCity:GetCulture();
local turnsUntilBorderGrowth = pCityCulture:GetTurnsUntilExpansion();
populationInstance.CityCultureTurnsLeft:SetText(turnsUntilBorderGrowth);
populationInstance.CityCultureTurnsLeft:SetHide(false);
local popTooltip = populationInstance.FillMeter:GetToolTipString();
-- The Locale.Lookup for Border Growth requires the value be included... but doesn't then put that value in the string itself, apparently.
popTooltip = popTooltip .. "[NEWLINE] [ICON_Culture]" ..tostring(turnsUntilBorderGrowth).. " " .. Locale.Lookup("LOC_HUD_CITY_TURNS_UNTIL_BORDER_GROWTH", turnsUntilBorderGrowth);
populationInstance.FillMeter:SetToolTipString(popTooltip);
else
populationInstance.CityCultureTurnsLeft:SetHide(true);
end
end
-- ============================================================================
function CityBanner.UpdateStats(self)
-- print_debug("CityBannerManager_CQUI_Expansions: CityBanner.UpdateStats ENTRY");
BASE_CQUI_CityBanner_UpdateStats(self);
local pDistrict:table = self:GetDistrict();
if (pDistrict ~= nil and IsBannerTypeCityCenter(self.m_Type)) then
local localPlayerID:number = Game.GetLocalPlayer();
local pCity :table = self:GetCity();
local iCityOwner :number = pCity:GetOwner();
if (localPlayerID == iCityOwner and self.CQUI_DistrictBuiltIM ~= nil) then
-- On first call into UpdateStats, CQUI_DistrictBuiltIM may not be instantiated yet
-- However this is called often enough that it's not a problem
self.CQUI_DistrictBuiltIM:ResetInstances(); -- CQUI : Reset CQUI_DistrictBuiltIM
self.m_Instance.CQUI_DistrictAvailable:SetHide(true);
local pCityDistricts:table = pCity:GetDistricts();
if (IsCQUI_SmartBanner_DistrictsEnabled()) then
local districtTooltipString = "";
local districtCount = 0;
local neighborhoodAdded = false;
-- Update the built districts
for i, district in pCityDistricts:Members() do
local districtType = district:GetType();
local districtInfo:table = GameInfo.Districts[districtType];
local isBuilt = pCityDistricts:HasDistrict(districtInfo.Index, true);
-- If the district is built, is not the City Center, is not a Wonder, and a Neighborhood Icon has already been shown...
if (isBuilt == true
and districtInfo.DistrictType ~= "DISTRICT_WONDER"
and districtInfo.DistrictType ~= "DISTRICT_CITY_CENTER"
and (districtInfo.DistrictType ~= "DISTRICT_NEIGHBORHOOD" or neighborhoodAdded == false)) then
SetDetailIcon(self.CQUI_DistrictBuiltIM:GetInstance(), "ICON_"..districtInfo.DistrictType);
districtTooltipString = districtTooltipString .. "[ICON_".. districtInfo.DistrictType .. "] ".. Locale.Lookup(districtInfo.Name) .. "[NEWLINE]";
districtCount = districtCount + 1;
if (districtInfo.DistrictType == "DISTRICT_NEIGHBORHOOD") then
neighborhoodAdded = true;
end
end
end
-- Trim the trailing [NEWLINE]
districtTooltipString = string.sub(districtTooltipString, 1, string.len(districtTooltipString) - 9);
-- Determine the overlap of the district icons based on the number built
-- Note: GetNumZonedDistrictsRequiringPopulation does not include Aqueducts or Neighborhoods
-- The padding value was -12 before this dynamic calculation was introduced
local districtIconPadding = 8 + districtCount;
if districtIconPadding < 12 then districtIconPadding = 12; end
if districtIconPadding > 20 then districtIconPadding = 20; end
self.m_Instance.CQUI_Districts:SetStackPadding(districtIconPadding * -1);
self.m_Instance.CQUI_Districts:CalculateSize(); -- Sets the correct banner width with the padding update
self.m_Instance.CQUI_DistrictsContainer:SetToolTipString(districtTooltipString);
end
if (IsCQUI_SmartBanner_DistrictsAvailableEnabled()) then
-- Infixo: 2020-06-08 district available flag and tooltip
local iDistrictsNum:number = pCityDistricts:GetNumZonedDistrictsRequiringPopulation();
local iDistrictsPossibleNum:number = pCityDistricts:GetNumAllowedDistrictsRequiringPopulation();
if iDistrictsPossibleNum > iDistrictsNum then
self.m_Instance.CQUI_DistrictAvailable:SetHide(false);
self.m_Instance.CQUI_DistrictAvailable:SetToolTipString( string.format("%s %d / %d", Locale.Lookup("LOC_HUD_DISTRICTS"), iDistrictsNum, iDistrictsPossibleNum) );
else
self.m_Instance.CQUI_DistrictAvailable:SetHide(true);
end
end
end
end
end
-- ===========================================================================
function CQUI_OnLensLayerOn( layerNum:number )
--print("FUN OnLensLayerOn", layerNum);
if layerNum == m_HexColoringReligion then
m_isReligionLensActive = true;
RealizeReligion();
end
end
-- ===========================================================================
function CQUI_OnLensLayerOff( layerNum:number )
--print("FUN OnLensLayerOff", layerNum);
if layerNum == m_HexColoringReligion then
m_isReligionLensActive = false;
RealizeReligion();
end
end
-- ============================================================================
-- CQUI Replacement Functions
-- ============================================================================
function OnCityStrikeButtonClick( playerID, cityID )
-- print_debug("CityBannerManager_CQUI_Expansions: OnCityStrikeButtonClick ENTRY playerID:"..tostring(playerID).." cityID:"..tostring(cityID));
CQUI_OnCityRangeStrikeButtonClick(playerID, cityID);
end
-- ===========================================================================
-- #59 Infixo overwritten because changes are deep inside it
function CityBanner:UpdateReligion()
--print("FUN CityBanner:UpdateReligion()");
local pCity :table = self:GetCity();
local pCityReligion :table = pCity:GetReligion();
local localPlayerID :number = Game.GetLocalPlayer();
local eMajorityReligion :number = pCityReligion:GetMajorityReligion();
self.m_eMajorityReligion = eMajorityReligion;
self:UpdateInfo(pCity);
local cityInst :table = self.m_Instance;
local religionInfo :table = cityInst.ReligionInfo;
local religionsInCity :table = pCityReligion:GetReligionsInCity();
-- Hide the meter and bail out if the religion lens isn't active
if (not m_isReligionLensActive or table.count(religionsInCity) == 0) then
if religionInfo then
religionInfo.ReligionInfoContainer:SetHide(true);
end
return;
end
-- Update religion icon + religious pressure animation
local majorityReligionColor:number = COLOR_RELIGION_DEFAULT;
if (eMajorityReligion >= 0) then
majorityReligionColor = UI.GetColorValue(GameInfo.Religions[eMajorityReligion].Color);
end
-- Preallocate total fill so we can stagger the meters
local totalFillPercent:number = 0;
local iCityPopulation:number = pCity:GetPopulation();
-- Get a list of religions present in this city
local activeReligions:table = {};
local numOfActiveReligions:number = 0;
local pReligionsInCity:table = pCityReligion:GetReligionsInCity();
for _, cityReligion in pairs(pReligionsInCity) do
local religion:number = cityReligion.Religion;
if religion == -1 then religion = 0; end -- #59 Infixo include a pantheon
--if (religion >= 0) then
local followers:number = cityReligion.Followers;
local fillPercent:number = followers / iCityPopulation;
totalFillPercent = totalFillPercent + fillPercent;
table.insert(activeReligions, {
Religion=religion,
Followers=followers,
Pressure=pCityReligion:GetTotalPressureOnCity(religion),
LifetimePressure=cityReligion.Pressure,
FillPercent=fillPercent,
Color=GameInfo.Religions[religion].Color });
numOfActiveReligions = numOfActiveReligions + 1;
--end
end
-- Sort religions by largest number of followers
-- #59 Infixo sort by followers, then by lifetime pressure
table.sort(activeReligions,
function(a,b)
if a.Followers ~= b.Followers then
return a.Followers > b.Followers;
else
return a.LifetimePressure > b.LifetimePressure;
end
end
);
-- After sort update accumulative fill percent
local accumulativeFillPercent = 0.0;
for i, religion in ipairs(activeReligions) do
accumulativeFillPercent = accumulativeFillPercent + religion.FillPercent;
religion.AccumulativeFillPercent = accumulativeFillPercent;
end
if (table.count(activeReligions) > 0) then
local localPlayerVis:table = PlayersVisibility[localPlayerID];
if (localPlayerVis ~= nil) then
-- Holy sites get a different color and texture
local holySitePlotIDs:table = {};
local cityDistricts:table = pCity:GetDistricts();
local playerDistricts:table = self.m_Player:GetDistricts();
for i, district in cityDistricts:Members() do
local districtType:string = GameInfo.Districts[district:GetType()].DistrictType;
if (districtType == "DISTRICT_HOLY_SITE") then
local locX:number = district:GetX();
local locY:number = district:GetY();
if localPlayerVis:IsVisible(locX, locY) then
local plot:table = Map.GetPlot(locX, locY);
local holySiteFaithYield:number = district:GetReligionHealRate();
SpawnHolySiteIconAtLocation(locX, locY, "+" .. holySiteFaithYield);
holySitePlotIDs[plot:GetIndex()] = true;
end
break;
end
end
-- Color hexes in this city the same color as religion
local plots:table = Map.GetCityPlots():GetPurchasedPlots(pCity);
if (table.count(plots) > 0) then
UILens.SetLayerHexesColoredArea( m_HexColoringReligion, localPlayerID, plots, majorityReligionColor );
end
end
end
if religionInfo then
-- Create or reset icon instance manager
local iconIM:table = cityInst[DATA_FIELD_RELIGION_ICONS_IM];
if (iconIM == nil) then
iconIM = InstanceManager:new("ReligionIconInstance", "ReligionIconContainer", religionInfo.ReligionInfoIconStack);
cityInst[DATA_FIELD_RELIGION_ICONS_IM] = iconIM;
else
iconIM:ResetInstances();
end
-- Create or reset follower list instance manager
local followerListIM:table = cityInst[DATA_FIELD_RELIGION_FOLLOWER_LIST_IM];
if (followerListIM == nil) then
followerListIM = InstanceManager:new("ReligionFollowerListInstance", "ReligionFollowerListContainer", religionInfo.ReligionFollowerListStack);
cityInst[DATA_FIELD_RELIGION_FOLLOWER_LIST_IM] = followerListIM;
else
followerListIM:ResetInstances();
end
-- Create or reset pop chart instance manager
local popChartIM:table = cityInst[DATA_FIELD_RELIGION_POP_CHART_IM];
if (popChartIM == nil) then
popChartIM = InstanceManager:new("ReligionPopChartInstance", "PopChartMeter", religionInfo.ReligionPopChartContainer);
cityInst[DATA_FIELD_RELIGION_POP_CHART_IM] = popChartIM;
else
popChartIM:ResetInstances();
end
local populationChartTooltip:string = RELIGION_POP_CHART_TOOLTIP_HEADER;
-- Show what religion we will eventually turn into
local nextReligion = pCityReligion:GetNextReligion();
local turnsTillNextReligion:number = pCityReligion:GetTurnsToNextReligion();
if nextReligion and nextReligion ~= -1 and turnsTillNextReligion > 0 then
local pNextReligionDef:table = GameInfo.Religions[nextReligion];
-- Religion icon
if religionInfo.ConvertingReligionIcon then
local religionIcon = "ICON_" .. pNextReligionDef.ReligionType;
religionInfo.ConvertingReligionIcon:SetIcon(religionIcon);
local religionColor = UI.GetColorValue(pNextReligionDef.Color);
religionInfo.ConvertingReligionIcon:SetColor(religionColor);
religionInfo.ConvertingReligionIconBacking:SetColor(religionColor);
religionInfo.ConvertingReligionIconBacking:SetToolTipString(Locale.Lookup(pNextReligionDef.Name));
end
-- Converting text
local convertString = Locale.Lookup("LOC_CITY_BANNER_CONVERTS_IN_X_TURNS", turnsTillNextReligion);
religionInfo.ConvertingReligionLabel:SetText(convertString);
religionInfo.ReligionConversionTurnsStack:SetHide(false);
-- If the turns till conversion are less than 10 play the warning flash animation
religionInfo.ConvertingSoonAlphaAnim:SetToBeginning();
if turnsTillNextReligion <= 10 then
religionInfo.ConvertingSoonAlphaAnim:Play();
else
religionInfo.ConvertingSoonAlphaAnim:Stop();
end
else
religionInfo.ReligionConversionTurnsStack:SetHide(true);
end
-- Add religion icons for each active religion
for i,religionInfo in ipairs(activeReligions) do
local religionDef:table = GameInfo.Religions[religionInfo.Religion];
local icon = "ICON_" .. religionDef.ReligionType;
local religionColor = UI.GetColorValue(religionDef.Color);
-- The first index is the predominant religion. Label it as such.
local religionName = "";
if i == 1 and numOfActiveReligions > 1 then
religionName = Locale.Lookup("LOC_CITY_BANNER_PREDOMINANT_RELIGION", Game.GetReligion():GetName(religionDef.Index));
else
religionName = Game.GetReligion():GetName(religionDef.Index);
end
-- Add icon to main icon list
-- If our only active religion is the same religion we're being converted to don't show an icon for it
--if numOfActiveReligions > 1 or nextReligion ~= religionInfo.Religion then -- #59 Infixo show all religions
local iconInst:table = iconIM:GetInstance();
iconInst.ReligionIconButton:SetIcon(icon);
iconInst.ReligionIconButton:SetColor(religionColor);
iconInst.ReligionIconButtonBacking:SetColor(religionColor);
--iconInst.ReligionIconButtonBacking:SetToolTipString(religionName); -- #59 Infixo new field and tooltip
iconInst.ReligionIconFollowers:SetText(religionInfo.Followers);
iconInst.ReligionIconContainer:SetToolTipString(
Locale.Lookup("LOC_CITY_BANNER_FOLLOWER_PRESSURE_TOOLTIP", religionName, religionInfo.Followers, Round(religionInfo.LifetimePressure)).."[NEWLINE]"..
Locale.Lookup("LOC_HUD_REPORTS_PER_TURN", "+"..tostring(Round(religionInfo.Pressure, 1))));
--end
-- Add followers to detailed info list
local followerListInst:table = followerListIM:GetInstance();
followerListInst.ReligionFollowerIcon:SetIcon(icon);
followerListInst.ReligionFollowerIcon:SetColor(religionColor);
followerListInst.ReligionFollowerIconBacking:SetColor(religionColor);
followerListInst.ReligionFollowerCount:SetText(religionInfo.Followers);
followerListInst.ReligionFollowerPressure:SetText(Locale.Lookup("LOC_CITY_BANNER_RELIGIOUS_PRESSURE", Round(religionInfo.Pressure)));
-- Add the follower tooltip to the population chart tooltip
local followerTooltip:string = Locale.Lookup("LOC_CITY_BANNER_FOLLOWER_PRESSURE_TOOLTIP", religionName, religionInfo.Followers, Round(religionInfo.LifetimePressure));
followerListInst.ReligionFollowerIconBacking:SetToolTipString(followerTooltip);
populationChartTooltip = populationChartTooltip .. "[NEWLINE][NEWLINE]" .. followerTooltip;
end
religionInfo.ReligionPopChartContainer:SetToolTipString(populationChartTooltip);
religionInfo.ReligionFollowerListStack:CalculateSize();
religionInfo.ReligionFollowerListScrollPanel:CalculateInternalSize();
religionInfo.ReligionFollowerListScrollPanel:ReprocessAnchoring();
-- Add populations to pie chart in reverse order
for i = #activeReligions, 1, -1 do
local religionInfo = activeReligions[i];
local religionColor = UI.GetColorValue(religionInfo.Color);
local popChartInst:table = popChartIM:GetInstance();
popChartInst.PopChartMeter:SetPercent(religionInfo.AccumulativeFillPercent);
popChartInst.PopChartMeter:SetColor(religionColor);
end
-- Update population pie chart majority religion icon
if (eMajorityReligion > 0) then
local iconName : string = "ICON_" .. GameInfo.Religions[eMajorityReligion].ReligionType;
religionInfo.ReligionPopChartIcon:SetIcon(iconName);
religionInfo.ReligionPopChartIcon:SetHide(false);
else
religionInfo.ReligionPopChartIcon:SetHide(true);
end
-- Show how much religion this city is exerting outwards
local outwardReligiousPressure = pCityReligion:GetPressureFromCity();
religionInfo.ExertedReligiousPressure:SetText(Locale.Lookup("LOC_CITY_BANNER_RELIGIOUS_PRESSURE", Round(outwardReligiousPressure)));
-- Reset buttons to default state
religionInfo.ReligionInfoButton:SetHide(false);
religionInfo.ReligionInfoDetailedButton:SetHide(true);
-- Register callbacks to open/close detailed info
religionInfo.ReligionInfoButton:RegisterCallback( Mouse.eLClick, function() OnReligionInfoButtonClicked(religionInfo, pCity); end);
religionInfo.ReligionInfoDetailedButton:RegisterCallback( Mouse.eLClick, function() OnReligionInfoDetailedButtonClicked(religionInfo, pCity); end);
religionInfo.ReligionInfoContainer:SetHide(false);
end
end
-- ===========================================================================
-- CQUI Initialize Function
-- ===========================================================================
function Initialize_CQUI_expansions()
print_debug("CityBannerManager_CQUI_Expansions: Initialize CQUI CityBannerManager")
Events.LensLayerOff.Add(CQUI_OnLensLayerOff);
Events.LensLayerOn.Add(CQUI_OnLensLayerOn);
end
Initialize_CQUI_expansions();
|
local module = ...
local httpdRequestHandler = {
method = nil,
query = { },
path = nil,
contentType = nil,
body = nil
}
local function httpdRequest(data)
local _, _, method, path, query = string.find(data, '([A-Z]+) (.+)?(.+) HTTP')
if method == nil then
_, _, method, path = string.find(data, '([A-Z]+) (.+) HTTP')
end
if query ~= nil then
query = string.gsub(query, '%%(%x%x)', function(x) string.char(tonumber(x, 16)) end)
for k, v in string.gmatch(query, '([^&]+)=([^&]*)&*') do
httpdRequestHandler.query[k] = v
end
end
httpdRequestHandler.method = method
httpdRequestHandler.path = path
httpdRequestHandler.contentType = string.match(data, "Content%-Type: ([%w/-]+)")
httpdRequestHandler.body = string.sub(data, string.find(data, "\r\n\r\n", 1, true), #data)
if httpdRequestHandler.contentType == "application/json" then
httpdRequestHandler.body = sjson.decode(httpdRequestHandler.body)
end
return httpdRequestHandler
end
return function(data)
package.loaded[module] = nil
module = nil
return httpdRequest(data)
end |
local utils = { }
local scopes = {o = vim.o, b = vim.bo, w = vim.wo}
function utils.opt(scope, key, value)
scopes[scope][key] = value
if scope ~= 'o' then scopes['o'][key] = value end
end
function utils.map(mode, lhs, rhs, opts)
local options = {noremap = true}
if opts then options = vim.tbl_extend('force', options, opts) end
vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end
function utils.buf_map(bufnr, mode, lhs, rhs, opts)
local options = {noremap = true}
if opts then options = vim.tbl_extend('force', options, opts) end
vim.api.nvim_buf_set_keymap(bufnr, mode, lhs, rhs, options)
end
-- Stolen from:
-- https://github.com/norcalli/nvim_utils/blob/master/lua/nvim_utils.lua
function utils.create_augroups(definitions)
for group_name, definition in pairs(definitions) do
vim.api.nvim_command('augroup '..group_name)
vim.api.nvim_command('autocmd!')
for _, def in ipairs(definition) do
local command = table.concat(vim.tbl_flatten{'autocmd', def}, ' ')
vim.api.nvim_command(command)
end
vim.api.nvim_command('augroup END')
end
end
return utils
|
---账号角色管理器
--@usage
--redis数据库结构
--角色表: appid:role:角色ID => {roleid=xxx,appid=xxx,account=xxx,create_serverid=xxx,...}
--账号表: account:账号 => {account=xxx,passwd=xxx,sdk=xxx,platform=xxx,...}
--账号已有角色表: appid:roles:账号 => {角色ID列表}
--账号已删除角色表: appid:deleted_roles:账号 => {角色ID列表}
--
--mongo数据库结构
--角色表: role => {roleid=xxx,appid=xxx,account=xxx,create_serverid=xxx,...}
--账号表: account => {account=xxx,passwd=xxx,sdk=xxx,platform=xxx,...}
--账号已有角色表: account_roles => {account=xxx,appid=xxx,roles={角色ID列表}}
--账号已删除角色表: account_deleted_roles => {account=xxx,appid=xxx,roles={角色ID列表}}
accountmgr = accountmgr or {}
function accountmgr.saveaccount(accountobj)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local account = assert(accountobj.account)
local key = string.format("account:%s",account)
db:set(key,cjson.encode(accountobj))
else
local account = assert(accountobj.account)
db.account:update({account=account},accountobj,true,false)
end
end
function accountmgr.getaccount(account)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("account:%s",account)
local retval = db:get(key)
if retval == nil then
return nil
else
return cjson.decode(retval)
end
else
local doc = db.account:findOne({account=account})
if doc == nil then
return nil
else
doc._id = nil
return doc
end
end
end
--/*
-- accountobj: {account=账号,passwd=密码,sdk=sdk,platform=平台,...}
--*/
function accountmgr.addaccount(accountobj)
local account = assert(accountobj.account)
local has_accountobj = accountmgr.getaccount(account)
if has_accountobj then
return httpc.answer.code.ACCT_EXIST
end
accountobj.createtime = os.time()
logger.logf("info","account",string.format("op=addaccount,accountobj=%s",cjson.encode(accountobj)))
accountmgr.saveaccount(accountobj)
return httpc.answer.code.OK
end
function accountmgr.delaccount(account)
local accountobj = accountmgr.getaccount(account)
if accountobj then
logger.logf("info","account",string.format("op=delaccount,account=%s",account))
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
db:del(account)
else
db.player:delete({account=account})
end
return httpc.answer.code.OK
end
return httpc.answer.code.ACCT_NOEXIST
end
-- 返回角色ID列表
function accountmgr.getroles(account,appid)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("%s:roles:%s",appid,account)
local retval = db:get(key)
if retval == nil then
return {}
else
return cjson.decode(retval)
end
else
local doc = db.account_roles:findOne({account=account,appid=appid})
if doc == nil then
return {}
else
return doc.roles
end
end
end
function accountmgr.getrolelist(account,appid)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local roles = accountmgr.getroles(account,appid)
local keys = {}
for i,roleid in ipairs(roles) do
table.insert(keys,string.format("%s:role:%s",appid,roleid))
end
local rolelist = {}
if #keys > 0 then
rolelist = db:mget(table.unpack(keys))
end
for i,data in ipairs(rolelist) do
rolelist[i] = cjson.decode(data)
end
return rolelist
else
local cursor = db.role:find({account=account,appid=appid})
local docs = {}
while cursor:hasNext() do
local doc = cursor:next()
doc._id = nil
table.insert(docs,doc)
end
return docs
end
end
-- roles: 角色ID列表
function accountmgr.saveroles(account,appid,roles)
assert(roles ~= nil)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("%s:roles:%s",appid,account)
db:set(key,cjson.encode(roles))
else
local doc = {account=account,appid=appid,roles=roles}
db.account_roles:update({account=account,appid=appid},doc,true,false)
end
end
-- 保存删除的角色列表
-- roles: 角色ID列表
function accountmgr.save_deleted_roles(account,appid,roles)
assert(roles ~= nil)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("%s:deleted_roles:%s",appid,account)
db:set(key,cjson.encode(roles))
else
local doc = {account=account,appid=appid,roles=roles}
db.account_deleted_roles:update({account=account,appid=appid},doc,true,false)
end
end
-- 返回已删除角色ID列表
function accountmgr.get_deleted_roles(account,appid)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("%s:deleted_roles:%s",appid,account)
local retval = db:get(key)
if retval == nil then
return {}
else
return cjson.decode(retval)
end
else
local doc = db.account_deleted_roles:findOne({account=account,appid=appid})
if doc == nil then
return {}
else
return doc.roles
end
end
end
function accountmgr.checkrole(role)
local role,err = table.check(role,{
roleid = {type="number"},
name = {type="string"},
sex = {type="number",optional=true},
job = {type="string",optional=true},
shapeid = {type="string",optional=true,},
lv = {type="number",optional=true,default=0,},
gold = {type="number",optional=true,default=0,},
})
return role,err
end
function accountmgr.addrole(account,appid,serverid,role)
local role,err = accountmgr.checkrole(role)
if err then
return httpc.answer.code.ROLE_FMT_ERR,err
end
local roleid = assert(role.roleid)
local name = assert(role.name)
if not util.get_app(appid) then
return httpc.answer.code.APPID_NOEXIST
end
if not accountmgr.getaccount(account) then
return httpc.answer.code.ACCT_NOEXIST
end
if not servermgr.getserver(appid,serverid) then
return httpc.answer.code.SERVER_NOEXIST
end
local found = accountmgr.getrole(appid,roleid)
if found then
return httpc.answer.code.ROLE_EXIST
end
local rolelist = accountmgr.getroles(account,appid)
local found = table.find(rolelist,roleid)
if found then
return httpc.answer.code.ROLE_EXIST
end
role.appid = appid
role.account = account
role.create_serverid = serverid
role.now_serverid = serverid
role.createtime = role.createtime or os.time()
logger.logf("info","account",string.format("op=addrole,account=%s,appid=%s,role=%s",account,appid,cjson.encode(role)))
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("%s:role:%s",appid,roleid)
db:set(key,cjson.encode(role))
else
--db.role:update({appid=appid,roleid=roleid},role,true,false)
db.role:insert(role)
end
table.insert(rolelist,roleid)
accountmgr.saveroles(account,appid,rolelist)
return httpc.answer.code.OK
end
function accountmgr.getrole(appid,roleid)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("%s:role:%s",appid,roleid)
local retval = db:get(key)
if retval == nil then
return nil
else
return cjson.decode(retval)
end
else
local doc = db.role:findOne({appid=appid,roleid=roleid})
if doc == nil then
return nil
else
doc._id = nil
return doc
end
end
end
function accountmgr.delrole(appid,roleid,forever)
if not util.get_app(appid) then
return httpc.answer.code.APPID_NOEXIST
end
local role = accountmgr.getrole(appid,roleid)
if not role then
return httpc.answer.code.ROLE_NOEXIST
end
local account = role.account
local rolelist = accountmgr.getroles(account,appid)
local found_pos = table.find(rolelist,roleid)
if not found_pos then
return httpc.answer.code.ROLE_NOEXIST
end
logger.logf("info","account",string.format("op=delrole,account=%s,appid=%s,role=%s,forever=%s",account,appid,cjson.encode(role),forever))
if forever then
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("%s:role:%s",appid,roleid)
db:del(key)
else
db.role:delete({appid=appid,roleid=roleid},true)
end
else
local deleted_rolelist = accountmgr.get_deleted_roles(account,appid)
table.insert(deleted_rolelist,roleid)
accountmgr.save_deleted_roles(account,appid,deleted_rolelist)
end
table.remove(rolelist,found_pos)
accountmgr.saveroles(account,appid,rolelist)
return httpc.answer.code.OK
end
-- 增量更新
function accountmgr.updaterole(appid,syncrole)
local roleid = assert(syncrole.roleid)
if not util.get_app(appid) then
return httpc.answer.code.APPID_NOEXIST
end
local role = accountmgr.getrole(appid,roleid)
if not role then
return httpc.answer.code.ROLE_NOEXIST
end
table.update(role,syncrole)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("%s:role:%s",appid,roleid)
db:set(key,cjson.encode(role))
return httpc.answer.code.OK,role
else
db.role:update({appid=appid,roleid=roleid},role,true,false)
return httpc.answer.code.OK,role
end
end
-- 有效范围: [minroleid,maxroleid)
function accountmgr.genroleid(appid,idkey,minroleid,maxroleid)
minroleid = tonumber(minroleid)
maxroleid = tonumber(maxroleid)
assert(appid)
assert(idkey)
assert(minroleid)
assert(maxroleid)
local db = gg.dbmgr:getdb()
if gg.dbmgr.db_type == "redis" then
local key = string.format("roleid:%s:%s",appid,idkey)
-- roleid in range [minroleid,maxroleid)
local valid_range = maxroleid - minroleid
local range = db:get(key)
range = tonumber(range)
if range and range >= valid_range then
return nil
else
range = db:incr(key)
end
if range > valid_range then
return nil
end
return minroleid+range-1
else
local valid_range = maxroleid - minroleid
local doc = db.roleid:findAndModify({
query = {appid=appid,idkey=idkey},
update = {["$inc"] = {sequence = 1}},
new = true,
upsert = true,
})
local range = doc.value.sequence
if range > valid_range then
return nil
end
return minroleid+range-1
end
end
function accountmgr.gentoken(input)
local prefix = string.format("loginserver.%s.",skynet.hpc())
local token = prefix .. string.randomkey(8)
return token
end
function accountmgr.gettoken(token)
return gg.actor.internal:call(".game","exec","gg.thistemp:get",token)
end
function accountmgr.addtoken(token,data,expire)
expire = expire or 300
return gg.actor.internal:call(".game","exec","gg.thistemp:set",token,data,expire)
end
function accountmgr.deltoken(token)
return gg.actor.internal:call(".game","exec","gg.thistemp:del",token)
end
-- 角色换绑服务器
function accountmgr.rebindserver(account,appid,new_serverid,old_roleid,new_roleid)
if not util.get_app(appid) then
return httpc.answer.code.APPID_NOEXIST
end
if not accountmgr.getaccount(account) then
return httpc.answer.code.ACCT_NOEXIST
end
if not servermgr.getserver(appid,new_serverid) then
return httpc.answer.code.SERVER_NOEXIST
end
local old_role = accountmgr.getrole(appid,old_roleid)
if not old_role then
return httpc.answer.code.ROLE_NOEXIST
end
if old_roleid == new_roleid then
if old_role.create_serverid == new_serverid then
-- unchange
return httpc.answer.code.OK
end
else
local new_role = accountmgr.getrole(appid,new_roleid)
if new_role then
return httpc.answer.code.ROLE_EXIST
end
end
logger.logf("info","account",string.format("op=rebindserver,account=%s,appid=%s,old_serverid=%s,new_serverid=%s,old_roleid=%s,new_roleid=%s",
account,appid,old_role.create_serverid,new_serverid,old_roleid,new_roleid))
if old_roleid == new_roleid then
accountmgr.updaterole(appid,{roleid=new_roleid,create_serverid=new_serverid})
else
accountmgr.delrole(appid,old_roleid,true)
old_role.roleid = new_roleid
accountmgr.addrole(account,appid,new_serverid,old_role)
end
return httpc.answer.code.OK
end
-- 角色换绑帐号
function accountmgr.rebindaccount(new_account,appid,roleid)
if not util.get_app(appid) then
return httpc.answer.code.APPID_NOEXIST
end
local new_accountobj = accountmgr.getaccount(new_account)
if not new_accountobj then
return httpc.answer.code.ACCT_NOEXIST
end
local role = accountmgr.getrole(appid,roleid)
if not role then
return httpc.answer.code.ROLE_NOEXIST
elseif role.account == new_account then
-- nochange
return httpc.answer.code.OK
end
local old_account = role.account
logger.logf("info","account",string.format("op=rebindaccount,appid=%s,roleid=%s,old_account=%s,new_account=%s",appid,roleid,old_account,new_account))
accountmgr.delrole(appid,roleid,true)
role.account = new_account
accountmgr.addrole(new_account,appid,role.create_serverid,role)
return httpc.answer.code.OK
end
-- 恢复角色
function accountmgr.recover_role(appid,roleid)
if not util.get_app(appid) then
return httpc.answer.code.APPID_NOEXIST
end
local role = accountmgr.getrole(appid,roleid)
if not role then
return httpc.answer.code.ROLE_NOEXIST
end
local account = role.account
local deleted_rolelist = accountmgr.get_deleted_roles(account,appid)
local found_pos = table.find(deleted_rolelist,roleid)
if not found_pos then
return httpc.answer.code.ROLE_NOEXIST
end
logger.logf("info","account",string.format("op=recover_role,account=%s,appid=%s,roleid=%s",account,appid,roleid))
local rolelist = accountmgr.getroles(account,roleid)
table.remove(deleted_rolelist,found_pos)
table.insert(rolelist,roleid)
accountmgr.saveroles(account,appid,rolelist)
accountmgr.save_deleted_roles(account,appid,deleted_rolelist)
return httpc.answer.code.OK
end
return accountmgr
|
-----------------------------------
-- PROTOTYPE OBJECT
-----------------------------------
PrototypeDevice = {
bridgeType = "'bridgeType' needs to be set",
bridgeSubtype = "'bridgeSubtype' needs to be set",
bridgeBinary = "'bridgeBinary' needs to be set",
bridgeBinaryProperty = "value",
bridgeMultilevel = "'bridgeMultilevel' needs to be set",
bridgeRead = "'bridgeRead' needs to be set",
bridgeWrite = "'bridgeWrite' needs to be set",
bridgeModes = "'bridgeWrite' needs to be set to an array of modes, e.g. 'heat', 'cool'",
customPropertySetters = nil -- could be optionally set by child class
}
function PrototypeDevice:new(fibaroDevice)
-- clone self, and copy fibaroDevice
local status, device = pcall(clone, self)
shallowCopyTo(fibaroDevice, device)
device.fibaroDevice = fibaroDevice
device.roomName = tostring(fibaro.getRoomNameByDeviceID(device.id))
self:init(device)
return device
end
function PrototypeDevice:init(device)
-- needs to be overriden by subclasses if need to initialize custom parameters
end
function PrototypeDevice:setProperty(propertyName, value)
if isEmptyString(value) then
return
end
local customPropertySetter
if (self.customPropertySetters ~= nil) then
customPropertySetter = self.customPropertySetters[propertyName]
end
if (customPropertySetter == nil) then
-- DEFAULT PROPERTY SETTER
if (propertyName == "state") then
if (value == "true") then
print("Turn ON for device #" .. self.id)
fibaro.call(self.id, "turnOn")
elseif (value == "false") then
print("Turn OFF for device #" .. self.id)
fibaro.call(self.id, "turnOff")
else
print("Unexpected value: " .. json.encode(event))
end
else
local firstPart = string.upper(string.sub(propertyName, 1, 1))
local secondPart = string.sub(propertyName, 2, string.len(propertyName))
local functionName = "set" .. firstPart .. secondPart
print("CALL \"" .. functionName .. "\", with VALUE \"" .. value .. "\" for device #" .. self.id)
fibaro.call(self.id, functionName, value)
end
else
-- CUSTOM PROPERTY SETTER
print("SET \"" .. propertyName .. "\" to \"" .. value .. "\" for device #" .. self.id)
customPropertySetter(propertyName, value)
end
end
function PrototypeDevice.isSupported(fibaroDevice)
print("'isSupported' function is mandatory for implementation")
end
-----------------------------------
-- BINARY SWITCH
-----------------------------------
Switch = inheritFrom(PrototypeDevice)
Switch.bridgeType = "switch"
Switch.bridgeBinary = true
Switch.bridgeMultilevel = false
Switch.bridgeRead = true
Switch.bridgeWrite = true
function Switch.isSupported(fibaroDevice)
if ((fibaroDevice.baseType == "com.fibaro.binarySwitch") or (fibaroDevice.type == "com.fibaro.binarySwitch")) and not table_contains_value(fibaroDevice.interfaces, "light") then
return true
else
return false
end
end
-----------------------------------
-- CentralSceneEvent
-----------------------------------
Scene = inheritFrom(PrototypeDevice)
Scene.bridgeType = "scene"
Scene.bridgeBinary = true
Scene.bridgeMultilevel = false
Scene.bridgeRead = true
Scene.bridgeWrite = true
function Scene.isSupported(fibaroDevice)
if (fibaroDevice.baseType == "com.fibaro.remoteSceneController" or fibaroDevice.type == "com.fibaro.remoteController") then
return true
else
return false
end
end
-----------------------------------
-- BINARY LIGHT
-----------------------------------
Light = inheritFrom(PrototypeDevice)
Light.bridgeType = "light"
Light.bridgeBinary = true
Light.bridgeMultilevel = false
Light.bridgeRead = true
Light.bridgeWrite = true
function Light.isSupported(fibaroDevice)
if ((fibaroDevice.baseType == "com.fibaro.binarySwitch") or (fibaroDevice.type == "com.fibaro.binarySwitch")) and table_contains_value(fibaroDevice.interfaces, "light") then
return true
else
return false
end
end
-----------------------------------
-- MULTILEVEL LIGHT (DIMMERS)
-----------------------------------
Dimmer = inheritFrom(PrototypeDevice)
Dimmer.bridgeType = "light"
Dimmer.bridgeBinary = true
Dimmer.bridgeMultilevel = true
Dimmer.bridgeRead = true
Dimmer.bridgeWrite = true
function Dimmer.isSupported(fibaroDevice)
if (fibaroDevice.baseType == "com.fibaro.multilevelSwitch") and table_contains_value(fibaroDevice.interfaces, "light") then
return true
else
return false
end
end
-----------------------------------
-- BINARY SENSOR (DOOR, MOTION, WATER LEAK, FIRE, SMORE SENSORSMULTILEVEL FOR TEMPERATURE, ETC)
-----------------------------------
BinarySensor = inheritFrom(PrototypeDevice)
BinarySensor.bridgeType = "binary_sensor"
BinarySensor.bridgeBinary = true
BinarySensor.bridgeMultilevel = false
BinarySensor.bridgeRead = true
BinarySensor.bridgeWrite = false
function BinarySensor.isSupported(fibaroDevice)
if (string.find(fibaroDevice.baseType, "Sensor")) or (string.find(fibaroDevice.baseType, "sensor")) then
if (fibaroDevice.baseType ~= "com.fibaro.multilevelSensor") and (fibaroDevice.type ~= "com.fibaro.multilevelSensor") then
return true
end
end
return false
end
function BinarySensor:init(device)
-- set unit of measurement
device.bridgeUnitOfMeasurement = device.properties.unit
-- ToDo: refactor with mappings
if (device.type == "com.fibaro.motionSensor") or (device.baseType == "com.fibaro.motionSensor") then
device.bridgeSubtype = "motion"
elseif (device.baseType == "com.fibaro.floodSensor") then
device.bridgeSubtype = "moisture"
elseif (device.baseType == "com.fibaro.doorWindowSensor") then
if (device.type == "com.fibaro.doorSensor") then
device.bridgeSubtype = "door"
else
print("[BinarySensor.init] Uknown doow/window sensor " .. device.id .. " " .. device.name)
end
elseif (device.baseType == "com.fibaro.lifeDangerSensor") then
device.bridgeSubtype = "safety"
elseif (device.baseType == "com.fibaro.smokeSensor") or (device.type == "com.fibaro.smokeSensor") then
device.bridgeSubtype = "smoke"
else
print("[BinarySensor.init] Unknown binary sensor")
end
end
-----------------------------------
-- MULTILEVEL SENSOR (TEMPERATURE, HUMIDITY, VOLTAGE, ETC)
-----------------------------------
MultilevelSensor = inheritFrom(PrototypeDevice)
MultilevelSensor.bridgeType = "sensor"
MultilevelSensor.bridgeBinary = false
MultilevelSensor.bridgeMultilevel = true
MultilevelSensor.bridgeUnitOfMeasurement = "'unit of measurement' needs to be initialized"
MultilevelSensor.bridgeRead = true
MultilevelSensor.bridgeWrite = false
function MultilevelSensor.isSupported(fibaroDevice)
if (string.find(fibaroDevice.baseType, "Sensor")) or (string.find(fibaroDevice.baseType, "sensor")) then
if (fibaroDevice.baseType == "com.fibaro.multilevelSensor") or (fibaroDevice.type == "com.fibaro.multilevelSensor") then
return true
end
end
return false
end
function MultilevelSensor:init(device)
-- initialize unit of measurement
device.bridgeUnitOfMeasurement = device.properties.unit
-- initialize subtype
-- ToDo: refactor with mappings
if (device.type == "com.fibaro.temperatureSensor") then
device.bridgeSubtype = "temperature"
device.bridgeUnitOfMeasurement = "°" .. device.properties.unit
elseif (device.type == "com.fibaro.lightSensor") then
device.bridgeSubtype = "illuminance"
elseif (device.type == "com.fibaro.humiditySensor") then
device.bridgeSubtype = "humidity"
elseif (device.properties.unit == "V") then
device.bridgeSubtype = "voltage"
elseif (device.properties.unit == "A") then
device.bridgeSubtype = "current"
elseif (device.properties.unit == "W" or device.properties.unit == "kW" or device.properties.unit == "kVA") then
device.bridgeSubtype = "power"
elseif (device.properties.unit == "min(s)") then
device.bridgeSubtype = "battery"
else
print("[MultilevelSensor.init] Unknown multilevel sensor " .. tostring(device.id) .. " " .. tostring(device.name) .. " " .. device.properties.unit)
end
end
-----------------------------------
-- MULTILEVEL SWITCH (COVER)
-----------------------------------
Cover = inheritFrom(PrototypeDevice)
Cover.bridgeType = "cover"
Cover.bridgeBinary = true
Cover.bridgeMultilevel = true
Cover.bridgeRead = true
Cover.bridgeWrite = true
function Cover.isSupported(fibaroDevice)
if (fibaroDevice.baseType == "com.fibaro.baseShutter") then
return true
else
return false
end
end
function Cover:init(device)
device.customPropertySetters = { }
device.customPropertySetters["state"] = function (propertyName, value)
if (value == "open") then
fibaro.call(device.id, "setValue", 99)
elseif (value == "close") then
fibaro.call(device.id, "setValue", 0)
elseif (value == "stop") then
fibaro.call(device.id, "stop")
else
print("Unsupported state")
end
end
end
-----------------------------------
-- THERMOSTAT (MULTILEVEL SWITCH)
-----------------------------------
Thermostat = inheritFrom(PrototypeDevice)
Thermostat.bridgeType = "climate"
Thermostat.bridgeBinary = false
Thermostat.bridgeMultilevel = true
Thermostat.bridgeRead = true
Thermostat.bridgeWrite = true
function Thermostat.isSupported(fibaroDevice)
if (fibaroDevice.type == "com.fibaro.hvacSystem") then
return true
else
return false
end
end
function Thermostat:init(device)
for i, mode in ipairs(device.properties.supportedThermostatModes) do
device.properties.supportedThermostatModes[i] = string.lower(mode)
end
end
function Thermostat:setMode(mode)
fibaro.call(self.id, "setThermostatMode", mode)
end
function Thermostat:setHeatingThermostatSetpoint(targetTemperature)
fibaro.call(self.id, "setHeatingThermostatSetpoint", targetTemperature)
end
function Thermostat:getTemperatureSensor(allDevices)
local device = allDevices[self.id + 1]
if (not Thermostat.isTemperatureSensor(device)) then
-- *** no laughs, to be refactored :)
device = allDevices[self.id + 2]
end
if (Thermostat.isTemperatureSensor(device)) then
return device
else
return nil
end
end
function Thermostat.isTemperatureSensor(device)
if ((device ~= nil) and (MultilevelSensor.isSupported(device)) and (device.bridgeSubtype == "temperature")) then
return true
else
return false
end
end
-----------------------------------
-- HELPER FUNCTIONS - OVERRIDE "WRONG" DEVICE TYPES FROM FIBARO DEVICE API
-----------------------------------
local fibaroBaseTypeOverride = {
["com.fibaro.FGR"] = "com.fibaro.baseShutter",
["com.fibaro.FGMS001"] = "com.fibaro.motionSensor",
["com.fibaro.FGWP"] = "com.fibaro.binarySwitch"
}
local fibaroTypeOverride = {
["com.fibaro.FGKF601"] = "com.fibaro.keyFob",
["com.fibaro.FGD212"] = "com.fibaro.dimmer",
["com.fibaro.FGMS001v2"] = "com.fibaro.motionSensor",
["com.fibaro.FGFS101"] = "com.fibaro.floodSensor",
["com.fibaro.FGWP102"] = "com.fibaro.binarySwitch"
}
function getFibaroDevicesByFilter(filter)
local filterStr = ""
local firstParameter = true
for i, j in pairs(filter) do
if (not firstParameter) then
filterStr = filterStr .. "&"
end
filterStr = filterStr .. i .. "=" .. tostring(j)
firstParameter = false
end
print("Device filter URI '" .. "/devices?" .. filterStr .. "'")
local allDevices = api.get("/devices?" .. filterStr)
for i, j in ipairs(allDevices) do
overrideFibaroDeviceType(j)
end
return allDevices
end
function getFibaroDeviceById(id)
local fibaroDevice = api.get("/devices/" .. id)
return getFibaroDeviceByInfo(fibaroDevice)
end
function getFibaroDeviceByInfo(info)
local fibaroDevice = info
overrideFibaroDeviceType(fibaroDevice)
return fibaroDevice
end
function overrideFibaroDeviceType(fibaroDevice)
if (not fibaroDevice) or (not fibaroDevice.type) then
return
end
local overrideType = fibaroTypeOverride[fibaroDevice.type]
if overrideType then
fibaroDevice.type = overrideType
end
local overrideBaseType = fibaroBaseTypeOverride[fibaroDevice.baseType]
if overrideBaseType then
fibaroDevice.baseType = overrideBaseType
end
end
-----------------------------------
-- HELPER FUNCTIONS - IDENTIFY DEVICE BRIDGE TYPE BY LOOKING AT FIBARO DEVICE TYPE
-----------------------------------
deviceTypeMappings = {
Switch, -- binary switch
Cover, -- multilevel switch
Light, -- binary light
Dimmer, -- multilevel light
BinarySensor,
MultilevelSensor,
Thermostat,
Scene -- scene device
}
function identifyDevice(fibaroDevice)
for i, j in ipairs(deviceTypeMappings) do
if (j.isSupported(fibaroDevice)) then
local device = j:new(fibaroDevice)
if (device.parentId and device.parentId ~= 0) then
device.bridgeParent = getFibaroDeviceById(device.parentId)
end
return device
end
end
return nil
end
|
-- CommandLineF4.lua
-- v1.1.2
-- Editing command line content in the editor
-- Keys: F4 in Panel with not empty command line, F2 in editor for save text to command line
-- originally found at https://github.com/z0hm/far-scripts/blob/master/CommandLineF4.lua
local function fwrite(s,f) local x,h = nil,io.open(f,"wb") if h then x=h:write(s or "") io.close(h) end return x end
local F = far.Flags
local name = "far.xxxxxx.cmd"
local ffi = require'ffi'
local C = ffi.C
Macro {
area="Shell"; key="F4"; flags="NotEmptyCommandLine"; description="Command Line -> Editor";
condition = function() return not(APanel.Visible and PPanel.Visible) end;
action = function()
local pc=ffi.cast("struct PluginStartupInfo*",far.CPluginStartupInfo()).PanelControl
local l,x = "",panel.GetCmdLinePos(-1)
local ln=pc(PANEL_ACTIVE,"FCTL_GETCMDLINE",0,nil)
local cl=ffi.new("wchar_t[?]",ln)
pc(PANEL_ACTIVE,"FCTL_GETCMDLINE",ln,cl)
local cw=ffi.string(cl,(ln-1)*2)
local f = win.GetEnv("TEMP").."\\"..name
fwrite(cw,f)
cw=ffi.string(cl,x*2)
local _,y = regex.gsubW(cw,"\n","\n")
cw=regex.matchW(cw,"(?:^|\n)(.+?)$")
if cw then x=#cw/2 else x=1 end
editor.Editor(f,nil,0,0,-1,-1,bit64.bor(F.EF_NONMODAL,F.EF_IMMEDIATERETURN,F.EF_OPENMODE_USEEXISTING),y+1,x,1200)
end;
}
Macro {
area="Editor"; key="F2"; description="Command Line <- Editor";
condition = function() return editor.GetFileName():match("[^\\]+$")==name end;
action = function()
local text,len,nw,x,l = "",0,"\10\0" -- win.Utf8ToUtf16("\n")
local pc=ffi.cast("struct PluginStartupInfo*",far.CPluginStartupInfo()).PanelControl
local ec=ffi.cast("struct PluginStartupInfo*",far.CPluginStartupInfo()).EditorControl
local ei=ffi.new("struct EditorInfo")
ei.StructSize=ffi.sizeof(ei)
if ec(-1,"ECTL_GETINFO",0,ei) then
local y=tonumber(ei.CurLine)
x=tonumber(ei.CurPos)
l=tonumber(ei.TotalLines)-1
local ss,ln
local egs=ffi.new("struct EditorGetString")
egs.StructSize=ffi.sizeof(egs)
for i=0,l do
if i==y then x=x+len/2+y end
egs.StringNumber=i
if ec(-1,"ECTL_GETSTRING",0,egs) then
ln=egs.StringLength*2
ss=ffi.string(egs.StringText,ln)
len=len+ln
if i<l then text=text..ss..nw else text=text..ss end
end
end
end
editor.Quit(-1)
local cl=ffi.new("wchar_t[?]",len/2+l+1)
ffi.copy(cl,text)
pc(PANEL_ACTIVE,"FCTL_SETCMDLINE",0,cl)
pc(PANEL_ACTIVE,"FCTL_SETCMDLINEPOS",x,nil)
end;
} |
function love.conf(t)
t.title = "Green Jellybean Love Stars"
t.version = "0.9.0"
t.modules.joystick = false
t.modules.physics = false
-- fullscreen the thing
-- t.window.fullscreen = true
end
|
require('utils')
local item = require("../item");
local image = require("../image")
return {
name = "Apple Showdown",
amount = 100,
weight = 1.5,
condition = function (state)
return state.appleFestival > 5
end,
description = "The mysterious old woman has terrorized your apple festival for long enough. You're going to take her down.",
heads = {
effectDescription = "Win (# of 'Red Apple' * 10%), otherwise -25 hp",
effect = function (state)
if love.math.random() <= table.count(state.items, item.apple) * 0.1 then
state.appleFestival = state.appleFestival + 1
return {
description = "After a long, grueling fight, you throw one last apple at the witch and knock her out. The town celebrates and crowns you as the Apple King.",
image = image.apple,
win = true
}
else
state.hp = state.hp - 25
return {
description = "You lose the fight and take 25 hp.",
image = image.stranger
}
end
end
},
tails = {
effectDescription = "Obtain 3 'Red Apple' (50%), obtain 'Red Apple' (50%)",
effect = function (state)
if love.math.random() <= 0.5 then
table.insert(state.items, item.apple)
table.insert(state.items, item.apple)
table.insert(state.items, item.apple)
return {
description = "You scrounge together 3 more apples.",
image = image.apple
}
else
table.insert(state.items, item.apple)
return {
description = "A festival goer generously hands you an apple.",
image = image.apple
}
end
end
},
beg = {
effectDescription = 'Lose 1 "Red Apple" and -1 coin',
effect = function (state)
if table.contains(state.items, item.apple) then
table.delete(state.items, item.apple)
end
state.coins = math.max(0, state.coins - 1)
return {
description = "You lose chicken out and lose an apple and 1 coin while you're dallying around.",
image = image.bad
}
end
}
}
|
-- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local ffi = require("ffi")
local shm = require("core.shm")
-- SHM object type for gauges (double precision float values).
type = shm.register('gauge', getfenv())
local gauge_t = ffi.typeof("struct { double g; }")
function create (name, initval)
local gauge = shm.create(name, gauge_t)
set(gauge, initval or 0)
return gauge
end
function open (name)
return shm.open(name, gauge_t, 'readonly')
end
function set (gauge, value) gauge.g = value end
function read (gauge) return gauge.g end
ffi.metatype(gauge_t,
{__tostring =
function (gauge) return ("%f"):format(read(gauge)) end})
function selftest ()
print('selftest: lib.gauge')
local a = create("lib.gauge/gauge/a", 1.42)
local a2 = open("lib.gauge/gauge/a")
local b = create("lib.gauge/gauge/b")
assert(read(a) == 1.42)
assert(read(a2) == read(a))
assert(read(b) == 0)
assert(read(a) ~= read(b))
set(a, 0.1234)
assert(read(a) == 0.1234)
assert(read(a2) == read(a))
shm.unmap(a)
shm.unmap(a2)
shm.unmap(b)
shm.unlink("link.gauge")
print('selftest: ok')
end
|
LinkLuaModifier("modifier_item_guardian_greaves_arena", "items/item_guardian_greaves_arena.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_guardian_greaves_arena_effect", "items/item_guardian_greaves_arena.lua", LUA_MODIFIER_MOTION_NONE)
item_guardian_greaves_arena = class({
GetIntrinsicModifierName = function() return "modifier_item_guardian_greaves_arena" end,
})
if IsServer() then
function item_guardian_greaves_arena:OnSpellStart()
local caster = self:GetCaster()
caster:EmitSound("Item.GuardianGreaves.Activate")
ParticleManager:CreateParticle("particles/items3_fx/warmage.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
for _,v in ipairs(FindUnitsInRadius(caster:GetTeamNumber(), caster:GetAbsOrigin(), nil, self:GetSpecialValueFor("radius"), self:GetAbilityTargetTeam(), self:GetAbilityTargetType(), self:GetAbilityTargetFlags(), FIND_ANY_ORDER, false)) do
SafeHeal(v, self:GetSpecialValueFor("replenish_health"), self)
v:GiveMana(self:GetSpecialValueFor("replenish_mana"))
ParticleManager:CreateParticle("particles/items3_fx/warmage_recipient.vpcf", PATTACH_ABSORIGIN_FOLLOW, v, caster)
v:EmitSound("Item.GuardianGreaves.Target")
v:Purge(false, true, false, true, false)
end
end
end
modifier_item_guardian_greaves_arena = class({
IsHidden = function() return true end,
GetAttributes = function() return MODIFIER_ATTRIBUTE_MULTIPLE end,
IsPurgable = function() return false end,
})
function modifier_item_guardian_greaves_arena:DeclareFunctions()
return {
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
MODIFIER_PROPERTY_STATS_AGILITY_BONUS,
MODIFIER_PROPERTY_STATS_INTELLECT_BONUS,
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS,
MODIFIER_PROPERTY_HEALTH_BONUS,
MODIFIER_PROPERTY_MANA_BONUS,
MODIFIER_PROPERTY_MOVESPEED_BONUS_UNIQUE
}
end
function modifier_item_guardian_greaves_arena:GetModifierHealthBonus()
return self:GetAbility():GetSpecialValueFor("bonus_health")
end
function modifier_item_guardian_greaves_arena:GetModifierManaBonus()
return self:GetAbility():GetSpecialValueFor("bonus_mana")
end
function modifier_item_guardian_greaves_arena:GetModifierMoveSpeedBonus_Special_Boots()
return self:GetAbility():GetSpecialValueFor("bonus_movement")
end
function modifier_item_guardian_greaves_arena:GetModifierBonusStats_Strength()
return self:GetAbility():GetSpecialValueFor("bonus_all_stats")
end
function modifier_item_guardian_greaves_arena:GetModifierBonusStats_Agility()
return self:GetAbility():GetSpecialValueFor("bonus_all_stats")
end
function modifier_item_guardian_greaves_arena:GetModifierBonusStats_Intellect()
return self:GetAbility():GetSpecialValueFor("bonus_all_stats")
end
function modifier_item_guardian_greaves_arena:GetModifierPhysicalArmorBonus()
return self:GetAbility():GetSpecialValueFor("bonus_armor")
end
function modifier_item_guardian_greaves_arena:GetModifierAura()
return "modifier_item_guardian_greaves_arena_effect"
end
function modifier_item_guardian_greaves_arena:IsAura()
return true
end
function modifier_item_guardian_greaves_arena:GetAuraRadius()
return self:GetAbility():GetSpecialValueFor("radius")
end
function modifier_item_guardian_greaves_arena:GetAuraSearchTeam()
return self:GetAbility():GetAbilityTargetTeam()
end
function modifier_item_guardian_greaves_arena:GetAuraSearchType()
return self:GetAbility():GetAbilityTargetType()
end
function modifier_item_guardian_greaves_arena:GetAuraSearchFlags()
return self:GetAbility():GetAbilityTargetFlags()
end
modifier_item_guardian_greaves_arena_effect = class({})
function modifier_item_guardian_greaves_arena_effect:DeclareFunctions()
return {
MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT,
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS
}
end
function modifier_item_guardian_greaves_arena_effect:GetModifierConstantHealthRegen()
local parent = self:GetParent()
local ability = self:GetAbility()
if ability then
return ability:GetSpecialValueFor(parent:GetHealth() / parent:GetMaxHealth() > ability:GetSpecialValueFor("aura_bonus_threshold_pct") * 0.01 and "aura_health_regen" or "aura_health_regen_bonus")
end
end
function modifier_item_guardian_greaves_arena_effect:GetModifierPhysicalArmorBonus()
local parent = self:GetParent()
local ability = self:GetAbility()
if ability then
local s = parent:GetHealthPercent() >= ability:GetSpecialValueFor("aura_bonus_threshold_pct") and "aura_armor" or "aura_armor_bonus"
return ability:GetSpecialValueFor(s)
end
end
|
-- [0x70..0x7e]
local tags = {
-- standard
TUPLE = 0x70, -- 'p'
BIT = 0x71, -- 'q'
TYPEREF = 0x72, -- 'r'
SPAN = 0x73, -- 's'
TYPE = 0x74, -- 't'
UNION = 0x75, -- 'u'
VOID = 0x76, -- 'v'
OBJECT = 0x77, -- 'w'
ALIGN = 0x78, -- 'x'
LIST = 0x79, -- 'y'
ARRAY = 0x7a, -- 'z'
BUNDLE = 0x7b, -- '{'
CHOICE = 0x7c, -- '|'
DYNAMIC = 0x7d, -- '}'
EMBEDDED = 0x7e, -- '~'
-- custom aliases
UINT = 0x0a,
SINT = 0x1a,
UINTVAR = 0x2a,
SINTVAR = 0x3a,
BOOLEAN = 0x0b,
BITPAD = 0x1b,
-- = 0x2b,
-- = 0x3b,
NULL = 0x0c,
CHAR = 0x1c,
WCHAR = 0x2c,
PADDING = 0x3c,
}
do
-- [0x00..0x3f]
local aliases = {
UINT = 0x00,
SINT = 0x01,
STREAM = 0x02,
STRING = 0x03,
WSTRING = 0x04,
UNION = 0x05,
MAP = 0x06,
SET = 0x07,
ALIGN = 0x08,
LIST = 0x09,
--custom = 0x0a,
--custom = 0x0b,
--custom = 0x0c,
-- = 0x0d,
EMBEDDED = 0x0e,
FLOAT = 0x0f,
}
local suffixfactor = {
ALIGN = 1,
FLOAT = 16,
}
for name, value in pairs(aliases) do
local factor = suffixfactor[name] or 8
for i = 0, 3 do
local suffix = (1<<i)*factor
assert(tags[name..suffix] == nil)
tags[name..suffix] = (i<<4)+value
end
end
tags.FLOAT256 = 0x4f
end
--[[
do
local report = {}
local names = {}
for name, value in pairs(tags) do
if names[value] ~= nil then
error(string.format("%02x %s %s", value, names[value], name))
end
names[value] = name
table.insert(report, string.format("%-12s = %02x", name, value))
end
table.sort(report)
for _, line in ipairs(report) do
print(line)
end
end
--]]
--[[
-- Primitives
VOID = 0x00,
BIT = 0x01,
ALIGN = 0x03, --v:UINTVAR := { PAD n | n=(v-index%v) }
-- Homogeneus compositions
SPAN = 0x0e, --t:TYPE := n:(UINT s) { e[i]:t | 0<i<=n }
LIST = 0x0e, --s:UINTVAR t:TYPE := n:(UINT s) { e[i]:t | 0<i<=n }
ARRAY = 0x0b, --n:UINTVAR t:TYPE := { e[i]:t | 0<i<=n }
-- Heterogeneous compositions
TUPLE = 0x0c, --n:UINTVAR { t[i]:TYPE | 0<i<=n } := { e[1]:t[1]...e[n]:t[n] }
BUNDLE = 0x0d, --n:UINTVAR { t[i]:TYPE | 0<i<=n & t[i]<=t[i+1] } := { e[1]:t[1]...e[n]:t[n] }
UNION = 0x0d, --s:UINTVAR n:UINTVAR { t[i]:TYPE | 0<i<=n & t[i]<=t[i+1] } := i:(UINT s) v:t[i]
-- Embedded compositions
SWITCH = 0x0d, --typeref:UINTVAR n:UINTVAR { k[i]:UINTVAR | 0<i<=n } { t[i]:TYPE | 0<i<=n } d:TYPE := { v:t[i] | k[i]=x:TYPE@typeref }
-- Modifiers
OBJECT = 0x12, --t:TYPE := offset:UINTVAR SWITCH 0x00 0x01 0x00 t VOID
EMBEDDED = 0x13, --s:UINTVAR t:TYPE := n:(UINT s) { t | length(t)=n }
-- Predefined: implict ALIGN 0x08
UINTVAR = 0x02, -- AS_UNSIGNED TUPLE 0x03 BIT (ARRAY 0x07 BIT) SWITCH 0x03 0x01 0x00 VOID TYPEREF 0x0a
SINTVAR = 0x03, -- AS_SIGNED TUPLE 0x03 BIT (ARRAY 0x07 BIT) SWITCH 0x03 0x01 0x00 VOID TYPEREF 0x0a
TYPE = 0x06, -- :=
TYPEREF = 0x07, --
DYNAMIC = 0x08, --
--Alignments
ALIGN1 = 0x17, -- ALIGN 0x08
ALIGN2 = 0x18, -- ALIGN 0x10
ALIGN4 = 0x19, -- ALIGN 0x20
ALIGN8 = 0x1a, -- ALIGN 0x40
--Sub-Byte
SINT = 0x0a, -- AS_SIGNED ARRAY size BIT size
UINT = 0x0a, -- AS_UNSIGNED ARRAY size BIT size
--Common
NULL = 0x01, -- AS_NULL VOID
PAD = 0x02, -- AS_VOID BIT size
--Boleans
BOOLEAN = 0x1b, -- AS_BOOLEAN ALIGN1 ARRAY 0x08 BIT
-- Signed Integers (Two's Complement)
SINT8 = 0x20, -- ALIGN1 SINT 0x08
SINT16 = 0x21, -- ALIGN1 SINT 0x10
SINT32 = 0x22, -- ALIGN1 SINT 0x20
SINT64 = 0x23, -- ALIGN1 SINT 0x40
-- Unsigned Integers
UINT8 = 0x1c, -- ALIGN1 UINT 0x08
UINT16 = 0x1d, -- ALIGN1 UINT 0x10
UINT32 = 0x1e, -- ALIGN1 UINT 0x20
UINT64 = 0x1f, -- ALIGN1 UINT 0x40
-- Floating Point (IEEE 754)
FLOAT16 = 0x24, -- AS_IEEE754 ALIGN1 TUPLE 0x03 BIT ARRAY 0x05 BIT ARRAY 0x0a BIT
FLOAT32 = 0x25, -- AS_IEEE754 ALIGN1 TUPLE 0x03 BIT ARRAY 0x08 BIT ARRAY 0x17 BIT
FLOAT64 = 0x26, -- AS_IEEE754 ALIGN1 TUPLE 0x03 BIT ARRAY 0x0b BIT ARRAY 0x34 BIT
FLOAT128 = 0x27, -- AS_IEEE754 ALIGN1 TUPLE 0x03 BIT ARRAY 0x0f BIT ARRAY 0x70 BIT
FLOAT256 = 0x27, -- AS_IEEE754 ALIGN1 TUPLE 0x03 BIT ARRAY 0x13 BIT ARRAY 0xec BIT
-- Characters
CHAR = 0x04, -- AS_ISO8859_1 ALIGN1 ARRAY 0x08 BIT 0x05 BIT
WCHAR = 0x05, -- AS_UTF16 ALIGN1 ARRAY 0x10 BIT
STRING = 0x29, -- SEMANTIC "nullterm" TUPLE 0x02 LIST size CHAR CHAR
WSTRING = 0x2a, -- SEMANTIC "nullterm" TUPLE 0x02 LIST size WCHAR WCHAR
-- Compositions
STREAM = 0x28, -- LIST size UINT8
SET = 0x0f, -- AS_SET LIST size type
MAP = 0x10, -- AS_MAP LIST size TUPLE 0x02 key value
-- Semantic (>0x7f)
AS_VOID = 0x80,
AS_NULL = 0x81,
AS_BOOLEAN = 0x82,
AS_SIGNED = 0x83,
AS_UNSIGNED = 0x84,
AS_IEEE754 = 0x85,
AS_ISO8859_1 = 0x86,
}
local temp = {}
for name, code in pairs(tags) do
temp[code] = name
end
for code, name in pairs(temp) do
tags[code] = name
end
--]]
return tags
|
position = {x = 29.7733421325684, y = 1.43002331256866, z = -18.0400009155273}
rotation = {x = -0.000122623663628474, y = 269.991760253906, z = 0.00591064570471644}
|
#! /usr/bin/lua
local bcrypt = require( "bcrypt" )
function bcrypt.tune( t )
local SAMPLES = 10
local rounds = 5
while true do
local total = 0
for i = 1, SAMPLES do
local start = os.clock()
bcrypt.digest( "asdf", rounds )
local delta = os.clock() - start
total = total + delta
end
if ( total / SAMPLES ) * 1000 >= t then
return rounds - 1
end
rounds = rounds + 1
end
end
print( bcrypt.tune( 250 ) )
|
local configModule = {}
configModule.MQTT = {}
configModule.MQTT.clientID = "moduleAlpha"
configModule.MQTT.username = "debugDevice" --Cloud MQTT te bu kullanici adli uyeye okuma izni vermeyi unutma.
configModule.MQTT.password = "12345"
configModule.MQTT.server = "m10.cloudmqtt.com"
configModule.MQTT.tlsPort = 38429
configModule.MQTT.unsecurePort = 18429
configModule.MQTT.secureConnection = false
configModule.Wifi = {}
configModule.Wifi.ssid = "Hey-Yo"
configModule.Wifi.password = "710710710"
return configModule |
data:extend(
{
{
type = "recipe",
energy_required = 0.5,
name = "substation-mk2",
enabled = "false",
ingredients =
{
{"substation", 1},
{"advanced-circuit", 10},
{"effectivity-module", 1}
},
result = "substation-mk2"
},
{
type = "recipe",
energy_required = 0.5,
name = "substation-mk3",
enabled = "false",
ingredients =
{
{"substation-mk2", 1},
{"processing-unit", 10},
{"effectivity-module-2", 1}
},
result = "substation-mk3"
}
}) |
-- items
-- unfinished, but will interact with Turtles to store a users items and allow them to send it to others
os.loadAPI("SublarmsOS/conf/Config")
os.loadAPI(Config.rootDir().."/os/utils/ScreenUtils")
while true do
ScreenUtils.drawHF("Home >> Items")
ScreenUtils.drawHomeOptions(4,true)
term.setCursorPos(19,4)
term.write("Not finished. Use Bksp to exit")
e, k = os.pullEvent("key")
if k == 14 then
break
end
end
|
-- translated example1.c
-- convert the first two argument words to decNumber,
-- add them together, and display the result
-- run with: lua example1.lua <num1> <num2>
require "ldecNumber"
local DECNUMDIGITS = 34
local ctx = decNumber.getcontext()
ctx:setdefault(decNumber.INIT_BASE)
ctx:settraps(0) -- no traps (this is the default, and only option!)
ctx:setdigits(DECNUMDIGITS)
local r = decNumber.tonumber(arg[1]) + arg[2]
print (string.format ("%s + %s => %s", arg[1], arg[2], r:tostring()))
|
--------------------------------------------------------------------------------
-- Module Declaration
--
local mod, CL = BigWigs:NewBoss("Dread Captain Lockwood", 1822, 2173)
if not mod then return end
mod:RegisterEnableMob(129208) -- Dread Captain Lockwood
mod.engageId = 2109
mod.respawnTime = 36
--------------------------------------------------------------------------------
-- Locals
--
local withdrawn = 0
--------------------------------------------------------------------------------
-- Locales
--
local L = mod:GetLocale()
if L then
L.ordanance_dropped = "Unstable Ordnance Dropped"
end
--------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
272471, -- Evasive
269029, -- Clear the Deck
273470, -- Gut Shot
268752, -- Withdraw
{268230, "TANK"}, -- Crimson Swipe
268260, -- Broadside
268963, -- Unstable Ordnance
}, {
[272471] = "general",
[268230] = -18230, -- Ashvane Deckhand
[268260] = -18232, -- Ashvane Cannoneer
}
end
function mod:OnBossEnable()
self:RegisterUnitEvent("UNIT_SPELLCAST_START", nil, "boss2", "boss3", "boss4")
self:RegisterUnitEvent("UNIT_SPELLCAST_SUCCEEDED", nil, "boss1", "boss2", "boss3", "boss4")
self:Log("SPELL_AURA_APPLIED", "Evasive", 272471)
self:Log("SPELL_CAST_START", "CleartheDeck", 269029)
self:Log("SPELL_CAST_START", "CrimsonSwipe", 268230)
self:Log("SPELL_CAST_SUCCESS", "GutShot", 273470)
end
function mod:OnEngage()
withdrawn = 0
self:Bar(269029, 3.5) -- Clear the Deck
self:Bar(268752, 12.1) -- Withdraw
end
--------------------------------------------------------------------------------
-- Event Handlers
--
function mod:UNIT_SPELLCAST_START(_, _, _, spellId)
if spellId == 268260 then -- Broadside
self:Message2(spellId, "orange")
self:PlaySound(spellId, "alarm")
self:Bar(268260, 12) -- Broadside
end
end
function mod:UNIT_SPELLCAST_SUCCEEDED(_, _, _, spellId)
if spellId == 268752 then -- Withdraw
withdrawn = 1
self:Message2(spellId, "yellow")
self:PlaySound(spellId, "long")
self:StopBar(269029) -- Clear the Deck
self:StopBar(268752) -- Withdraw
self:Bar(268260, 11.2) -- Broadside
elseif spellId == 268745 then -- Energy Tracker / Jump Back
if withdrawn == 1 then
self:Message2(268752, "green", CL.over:format(self:SpellName(268752)))
self:PlaySound(268752, "long")
self:Bar(269029, 7) -- Clear the Deck
self:Bar(268752, 35.7) -- Withdraw
end
elseif spellId == 268963 then -- Unstable Ordnance (Dropped)
self:Message2(spellId, "cyan", L.ordanance_dropped)
self:PlaySound(spellId, "info")
end
end
function mod:Evasive(args)
self:Message2(args.spellId, "yellow")
self:PlaySound(args.spellId, "alert")
end
function mod:CleartheDeck(args)
self:Message2(args.spellId, "orange")
self:PlaySound(args.spellId, "alarm")
self:Bar(args.spellId, 18)
end
do
local prev = 0
function mod:CrimsonSwipe(args)
local t = args.time
if t-prev > 2 then
prev = t
self:Message2(args.spellId, "purple")
self:PlaySound(args.spellId, "alarm")
end
end
end
function mod:GutShot(args)
self:TargetMessage2(args.spellId, "red", args.destName)
self:PlaySound(args.spellId, "alert", nil, args.destName)
end
|
local mediawiki = {}
function mediawiki.config()
vim.g.mediawiki_wikilang_to_vim_overrides = { sls = "sls" }
vim.g.mediawiki_forced_wikilang = { "bash" }
end
return mediawiki
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by 干冲.
--- DateTime: 2018/4/17 16:44
--- 玩家参数
PlayerSetting = {
UID = "uid",
ServerIP = "serverIP",
ServerID = "serverID",
} |
local addonName, ns = ...
local B, C, L, DB, P = unpack(ns)
local T = P:GetModule("Tooltip")
local NT = B:GetModule("Tooltip")
local format, strsplit, strmatch, strsub = string.format, string.split, string.match, string.sub
local pairs, tonumber = pairs, tonumber
T.MemberCovenants = {}
local covenantMap = {
[1] = "Kyrian",
[2] = "Venthyr",
[3] = "NightFae",
[4] = "Necrolord",
}
-- Credit: OmniCD
local covenantAbilities = {
[324739] = 1,
[323436] = 1,
[312202] = 1,
[306830] = 1,
[326434] = 1,
[338142] = 1,
[338035] = 1,
[338018] = 1,
[327022] = 1,
[327037] = 1,
[327071] = 1,
[308491] = 1,
[307443] = 1,
[310454] = 1,
[304971] = 1,
[325013] = 1,
[323547] = 1,
[324386] = 1,
[312321] = 1,
[307865] = 1,
[300728] = 2,
[311648] = 2,
[317009] = 2,
[323546] = 2,
[324149] = 2,
[314793] = 2,
[326860] = 2,
[316958] = 2,
[323673] = 2,
[323654] = 2,
[320674] = 2,
[321792] = 2,
[317483] = 2,
[317488] = 2,
[310143] = 3,
[324128] = 3,
[323639] = 3,
[323764] = 3,
[328231] = 3,
[314791] = 3,
[327104] = 3,
[328622] = 3,
[328282] = 3,
[328620] = 3,
[328281] = 3,
[327661] = 3,
[328305] = 3,
[328923] = 3,
[325640] = 3,
[325886] = 3,
[319217] = 3,
[324631] = 4,
[315443] = 4,
[329554] = 4,
[325727] = 4,
[325028] = 4,
[324220] = 4,
[325216] = 4,
[328204] = 4,
[324724] = 4,
[328547] = 4,
[326059] = 4,
[325289] = 4,
[324143] = 4,
}
local LibRS
local DCLoaded
local ZT_Prefix = "ZenTracker"
local DC_Prefix = "DCOribos"
local OmniCD_Prefix = "OmniCD"
local MRT_Prefix = "EXRTADD"
local addonPrefixes = {
[ZT_Prefix] = true,
[DC_Prefix] = true,
[OmniCD_Prefix] = true,
[MRT_Prefix] = true,
}
function T:GetCovenantIcon(covenantID, size)
local covenant = covenantMap[covenantID]
if covenant then
return format("|TInterface\\Addons\\"..addonName.."\\Media\\Texture\\Covenants\\%s:%d|t", covenant, size)
end
return ""
end
local covenantIDToName = {}
function T:GetCovenantName(covenantID)
if not covenantIDToName[covenantID] then
local covenantData = C_Covenants.GetCovenantData(covenantID)
covenantIDToName[covenantID] = covenantData and covenantData.name
end
return covenantIDToName[covenantID] or covenantMap[covenantID]
end
function T:GetCovenantID(unit)
local guid = UnitGUID(unit)
if not guid then return end
local covenantID = T.MemberCovenants[guid]
if not covenantID then
local playerInfo = LibRS and LibRS.playerInfoManager.GetPlayerInfo(GetUnitName(unit, true))
return playerInfo and playerInfo.covenantId
end
return covenantID
end
local function msgChannel()
return IsPartyLFG() and "INSTANCE_CHAT" or IsInRaid() and "RAID" or "PARTY"
end
local cache = {}
function T:UpdateRosterInfo()
if not IsInGroup() then return end
for i = 1, GetNumGroupMembers() do
local name = GetRaidRosterInfo(i)
if name and name ~= DB.MyName and not cache[name] then
if not DCLoaded then
C_ChatInfo.SendAddonMessage(DC_Prefix, format("ASK:%s", name), msgChannel())
end
C_ChatInfo.SendAddonMessage(MRT_Prefix, format("inspect\tREQ\tS\t%s", name), msgChannel())
cache[name] = true
end
end
if LibRS then
LibRS.RequestAllPlayersInfo()
end
end
function T:HandleAddonMessage(...)
local prefix, msg, _, sender = ...
sender = Ambiguate(sender, "none")
if sender == DB.MyName then return end
if prefix == ZT_Prefix then
local version, type, guid, _, _, _, _, covenantID = strsplit(":", msg)
version = tonumber(version)
if (version and version > 3) and (type and type == "H") and guid then
covenantID = tonumber(covenantID)
if covenantID and (not T.MemberCovenants[guid] or T.MemberCovenants[guid] ~= covenantID) then
T.MemberCovenants[guid] = covenantID
P:Debug("%s 盟约:%s (by ZenTracker)", sender, covenantMap[covenantID] or "None")
end
end
elseif prefix == OmniCD_Prefix then
local header, guid, body = strmatch(msg, "(.-),(.-),(.+)")
if (header and guid and body) and (header == "INF" or header == "REQ" or header == "UPD") then
local covenantID = select(15, strsplit(",", body))
covenantID = tonumber(covenantID)
if covenantID and (not T.MemberCovenants[guid] or T.MemberCovenants[guid] ~= covenantID) then
T.MemberCovenants[guid] = covenantID
P:Debug("%s 盟约:%s (by OmniCD)", sender, covenantMap[covenantID] or "None")
end
end
elseif prefix == DC_Prefix then
local playerName, covenantID = strsplit(":", msg)
if playerName == "ASK" then return end
local guid = UnitGUID(sender)
covenantID = tonumber(covenantID)
if covenantID and guid and (not T.MemberCovenants[guid] or T.MemberCovenants[guid] ~= covenantID) then
T.MemberCovenants[guid] = covenantID
P:Debug("%s 盟约:%s (by Details_Covenants)", sender, covenantMap[covenantID] or "None")
end
elseif prefix == MRT_Prefix then
local modPrefix, subPrefix, soulbinds = strsplit("\t", msg)
if (modPrefix and modPrefix == "inspect") and (subPrefix and subPrefix == "R") and (soulbinds and strsub(soulbinds, 1, 1) == "S") then
local guid = UnitGUID(sender)
local covenantID = select(2, strsplit(":", soulbinds))
covenantID = tonumber(covenantID)
if covenantID and guid and (not T.MemberCovenants[guid] or T.MemberCovenants[guid] ~= covenantID) then
T.MemberCovenants[guid] = covenantID
P:Debug("%s 盟约:%s (by MRT)", sender, covenantMap[covenantID] or "None")
end
end
end
end
function T:HandleSpellCast(unit, _, spellID)
local covenantID = covenantAbilities[spellID]
if covenantID then
local guid = UnitGUID(unit)
if guid and (not T.MemberCovenants[guid] or T.MemberCovenants[guid] ~= covenantID) then
T.MemberCovenants[guid] = covenantID
P:Debug("%s 盟约:%s (by %s)", GetUnitName(unit, true), covenantMap[covenantID], GetSpellLink(spellID))
end
end
end
function T:AddCovenant()
if not T.db["Covenant"] then return end
local _, unit = GameTooltip:GetUnit()
if not unit or not UnitExists(unit) then return end
local covenantID
if UnitIsUnit(unit, "player") then
covenantID = C_Covenants.GetActiveCovenantID()
else
covenantID = T:GetCovenantID(unit)
end
if covenantID and covenantID ~= 0 then
GameTooltip:AddLine(format(L["Covenant"], T:GetCovenantIcon(covenantID, 14)))
end
end
do
if NT.OnTooltipSetUnit then
hooksecurefunc(NT, "OnTooltipSetUnit", T.AddCovenant)
end
end
function T:Covenant()
LibRS = _G.LibStub and _G.LibStub("LibOpenRaid-1.0", true)
DCLoaded = IsAddOnLoaded("Details_Covenants")
for prefix in pairs(addonPrefixes) do
C_ChatInfo.RegisterAddonMessagePrefix(prefix)
end
T:UpdateRosterInfo()
B:RegisterEvent("GROUP_ROSTER_UPDATE", T.UpdateRosterInfo)
B:RegisterEvent("CHAT_MSG_ADDON", T.HandleAddonMessage)
B:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED", T.HandleSpellCast)
end |
--#region Usings
--#region Framework usings
---@type Array
local Array = EsoAddonFramework_Framework_Array
---@type Color
local Color = EsoAddonFramework_Framework_Color
---@type Console
local Console = EsoAddonFramework_Framework_Console
---@type Event
local Event = EsoAddonFramework_Framework_Eso_Event
---@type EventManager
local EventManager = EsoAddonFramework_Framework_Eso_EventManager
---@type FrameworkMessageType
local FrameworkMessageType = EsoAddonFramework_Framework_MessageType
---@type Log
local Log = EsoAddonFramework_Framework_Log
---@type LogLevel
local LogLevel = EsoAddonFramework_Framework_LogLevel
---@type Map
local Map = EsoAddonFramework_Framework_Map
---@type Messenger
local Messenger = EsoAddonFramework_Framework_Messenger
---@type Pack
local Pack = EsoAddonFramework_Framework_Eso_Pack
---@type Storage
local Storage = EsoAddonFramework_Framework_Storage
---@type StorageScope
local StorageScope = EsoAddonFramework_Framework_StorageScope
---@type String
local String = EsoAddonFramework_Framework_String
---@type StringBuilder
local StringBuilder = EsoAddonFramework_Framework_StringBuilder
---@type Type
local Type = EsoAddonFramework_Framework_Eso_Type
---@type UnitTag
local UnitTag = EsoAddonFramework_Framework_Eso_UnitTag
--#endregion
--#region Addon usings
---@type AddonMessageType
local AddonMessageType = GameplayHelper_Types_MessageType
---@type ItemAssessment
local ItemAssessment = GameplayHelper_Types_ItemAssessment
---@type ItemAssessmentManager
local ItemAssessmentManager = GameplayHelper_Globals_ItemAssessmentManager
---@type ItemAssessmentFilter
local ItemAssessmentFilter = GameplayHelper_Types_ItemAssessmentFilter
local Lang = GameplayHelper_Lang
---@type UnitManager
local Unit = GameplayHelper_Globals_UnitManager
--#endregion
--#endregion
-- Constants
local BladeOfWoeIcon = "darkbrotherhood"
local DefaultSettings = {
IsEnabled = true,
OutputSuppressions = true
}
local MirriAdjectives = {
"amazing",
"awesome",
"beautiful",
"elegant",
"fascinating",
"gorgeous",
"incredible",
"impressive",
"magnificent",
"stunning",
"superb",
"wonderful"
}
local MirriCompanionId = 2
local MirriName = "Mirri"
local MirriVerbs = {
"admires",
"beholds",
"inspects",
"is crazy about",
"looks at",
"marvels at",
"observes",
"studies",
"watches"
}
local Name = "GameplayHelper_Handlers_MirriHandler"
-- Fields
local _companionName
local _log
local _mirriActivated = false
local _settings = DefaultSettings
-- Local functions
local function CreateSettingsControls()
local descriptionBuilder = StringBuilder.CreateInstance()
descriptionBuilder:AppendLine("Suppresses some interactions and synergies when {Mirri} is active.")
descriptionBuilder:AppendLine("Suppressed interactions:")
descriptionBuilder:AppendLine(" - " .. "{butterflies}")
descriptionBuilder:AppendLine(" - " .. "{torch bugs}")
descriptionBuilder:AppendLine(" - " .. "{navigators}")
descriptionBuilder:AppendLine(" - " .. "the {Dark Brotherhood Sanctuary}")
descriptionBuilder:AppendLine("Suppressed synergies:")
descriptionBuilder:Append(" - " .. "{Blade of Woe}")
local description = String.Format(descriptionBuilder:ToString())
local settingsControls = {
{
type = "description",
text = description
},
{
type = "checkbox",
name = "Enabled",
getFunc = function() return _settings.IsEnabled end,
setFunc = function(value) _settings.IsEnabled = value end
},
{
type = "divider"
},
{
type = "checkbox",
name = "Output suppressions to chat",
tooltip = "Outputs why an interaction was suppressed to the chat window",
getFunc = function() return _settings.OutputSuppressions end,
setFunc = function(value) _settings.OutputSuppressions = value end,
disabled = function() return not _settings.IsEnabled end
}
}
return {
DisplayName = "Mirri suppressor",
Controls = settingsControls
}
end
local function EndConversationIfNavigator()
if (not IsInteractionPending() and
not IsInteracting())
then
return
end
if (IsInteractionPending()) then
zo_callLater(EndConversationIfNavigator, 100)
return
end
local name = GetUnitName(UnitTag.Interact)
local caption = GetUnitCaption(UnitTag.Interact)
local isNavigator = caption ~= nil and caption:lower() == "navigator"
if (not isNavigator) then
_log:Debug("Interaction with {1} approved", name)
return
end
local interactionType = GetInteractionType()
EndInteraction(interactionType)
if (_settings.OutputSuppressions) then
Console.Write(String.Format("{1} does not want to travel with {2}", MirriName, name))
end
end
local function OnClientInteractResult(event, result, interactTargetName)
if (not _settings.IsEnabled or not _mirriActivated) then
return false
end
if (result ~= Type.ClientInteractResult.Success) then
return
end
EndConversationIfNavigator()
end
local function OnCompanionActivated(event, companionId)
local companionNameInfo = Unit.GetNameInfo(UnitTag.Companion)
if (companionId ~= MirriCompanionId) then
_log:Debug("Non-Mirri companion {1} [{2}] activated", companionNameInfo.Name, companionId)
return
end
_log:Debug("{1} activated", companionNameInfo.Name)
_mirriActivated = true
_companionName = companionNameInfo.Name
Messenger.Publish(AddonMessageType.InteractionCriteriaChanged)
end
local function OnCompanionDeactivated(event)
_log:Debug("{1} deactivated", _companionName)
if (_mirriActivated) then
_mirriActivated = false
Messenger.Publish(AddonMessageType.InteractionCriteriaChanged)
end
end
local function OnInteractionChangedPreview(message)
if (not _settings.IsEnabled or not _mirriActivated) then
return
end
if (message.ActionInfo.Name == "Torchbug" or
message.ActionInfo.Name == "Butterfly") then
if (_settings.OutputSuppressions) then
Console.Write(String.Format(
"{1} {2:None} the {3:None} {4}",
MirriName,
MirriVerbs[math.random(#MirriVerbs)],
MirriAdjectives[math.random(#MirriAdjectives)],
message.ActionInfo.Name))
end
_log:Debug("Suppressing interaction {1}", message.ActionInfo.Name)
return true
end
if (message.ActionInfo.Name == "Dark Brotherhood Sanctuary") then
if (_settings.OutputSuppressions) then
Console.Write(String.Format("{1} refuses to enter the {2}", MirriName, message.ActionInfo.Name))
end
_log:Debug("Suppressing interaction {1}", message.ActionInfo.Name)
return true
end
end
local function OnSynergyChangedPreview(message)
if (not _settings.IsEnabled or not _mirriActivated) then
return false
end
if (string.find(message.SynergyInfo.IconFilename, BladeOfWoeIcon, 1, true)) then
if (_settings.OutputSuppressions) then
Console.Write(String.Format("{1} cannot accept the use of {2}", MirriName, message.SynergyInfo.SynergyName))
end
_log:Debug("Suppressing synergy {1}", message.SynergyInfo.SynergyName)
return true
end
end
-- Constructor
---@param addonInfo AddonInfo
local function Constructor(addonInfo)
_log = Log.CreateInstance(Name)
if (HasActiveCompanion()) then
local companionNameInfo = Unit.GetNameInfo(UnitTag.Companion)
_companionName = companionNameInfo.Name
local companionId = GetActiveCompanionDefId()
if (companionId == MirriCompanionId) then
_mirriActivated = true
end
end
EventManager:RegisterForEvent(Name, Event.ClientInteractResult, OnClientInteractResult)
EventManager:RegisterForEvent(Name, Event.CompanionActivated, OnCompanionActivated)
EventManager:RegisterForEvent(Name, Event.CompanionDeactivated, OnCompanionDeactivated)
Messenger.Subscribe(FrameworkMessageType.SettingsControlsRequest, CreateSettingsControls)
Messenger.Subscribe(AddonMessageType.InteractionChangedPreview, OnInteractionChangedPreview)
Messenger.Subscribe(AddonMessageType.SynergyChangedPreview, OnSynergyChangedPreview)
_settings = Storage.GetEntry(Name, DefaultSettings, StorageScope.Account)
end
EsoAddonFramework_Framework_Bootstrapper.Register(Constructor) |
-- << event_die.lua
local wesnoth = wesnoth
local addon = creepwars
local is_ai_array = addon.is_ai_array
local defender = wesnoth.get_unit(wesnoth.get_variable("x1") or 0, wesnoth.get_variable("y1") or 0)
local attacker = wesnoth.get_unit(wesnoth.get_variable("x2") or 0, wesnoth.get_variable("y2") or 0)
if defender == nil then
local msg = "Warning: cannot find killed unit. No gold/creep bonus was generated."
print(msg)
wesnoth.message("Creep Wars", msg)
elseif not defender.canrecruit and not defender.variables["creepwars_creep"] then
local msg = "Turn " .. wesnoth.get_variable("turn_number") .. ": " .. defender.type
.. " died, neither Leader nor Creep. Probably plagued. No gold/creep bonus was generated."
print(msg)
-- wesnoth.message("Creep Wars", msg)
else
if not defender.canrecruit then
addon.unit_kill_event(attacker, defender)
elseif not is_ai_array[defender.side] then
addon.unit_kill_event(attacker, defender)
creepwars.leader_died_event(defender)
elseif addon.alive_teams_count() >= 3 then
addon.unit_kill_event(attacker, defender)
addon.guard_killed_event(attacker.side, defender.side)
else
addon.guard_killed_event(attacker.side, defender.side)
end
end
-- >>
|
local GAResourceFlowType = require(script.GAResourceFlowType)
local GAProgressionStatus = require(script.GAProgressionStatus)
local GAErrorSeverity = require(script.GAErrorSeverity)
local ga = {
EGAResourceFlowType = GAResourceFlowType,
EGAProgressionStatus = GAProgressionStatus,
EGAErrorSeverity = GAErrorSeverity,
}
local logger = require(script.Logger)
local threading = require(script.Threading)
local state = require(script.State)
local validation = require(script.Validation)
local store = require(script.Store)
local events = require(script.Events)
local utilities = require(script.Utilities)
local Players = game:GetService("Players")
local MKT = game:GetService("MarketplaceService")
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local LocalizationService = game:GetService("LocalizationService")
local ScriptContext = game:GetService("ScriptContext")
local Postie = require(ReplicatedStorage.Postie)
local OnPlayerReadyEvent
local ProductCache = {}
local ONE_HOUR_IN_SECONDS = 3600
local MaxErrorsPerHour = 10
local ErrorDS = {}
local errorCountCache = {}
local errorCountCacheKeys = {}
local InitializationQueue = {}
local InitializationQueueByUserId = {}
local function addToInitializationQueue(func, ...)
if InitializationQueue ~= nil then
table.insert(InitializationQueue, {
Func = func;
Args = {...};
})
logger:i("Added event to initialization queue")
else
--This should never happen
logger:w("Initialization queue already cleared.")
end
end
local function addToInitializationQueueByUserId(userId, func, ...)
if not ga:isPlayerReady(userId) then
if InitializationQueueByUserId[userId] == nil then
InitializationQueueByUserId[userId] = {}
end
table.insert(InitializationQueueByUserId[userId], {
Func = func;
Args = {...};
})
logger:i("Added event to player initialization queue")
else
--This should never happen
logger:w("Player initialization queue already cleared.")
end
end
-- local functions
local function isSdkReady(options)
local playerId = options["playerId"] or nil
local needsInitialized = options["needsInitialized"] or true
local shouldWarn = options["shouldWarn"] or false
local message = options["message"] or ""
-- Is SDK initialized
if needsInitialized and not state.Initialized then
if shouldWarn then
logger:w(message .. " SDK is not initialized")
end
return false
end
-- Is SDK enabled
if needsInitialized and playerId and not state:isEnabled(playerId) then
if shouldWarn then
logger:w(message .. " SDK is disabled")
end
return false
end
-- Is session started
if needsInitialized and playerId and not state:sessionIsStarted(playerId) then
if shouldWarn then
logger:w(message .. " Session has not started yet")
end
return false
end
return true
end
function ga:configureAvailableCustomDimensions01(customDimensions)
if isSdkReady({needsInitialized = true, shouldWarn = false}) then
logger:w("Available custom dimensions must be set before SDK is initialized")
return
end
state:setAvailableCustomDimensions01(customDimensions)
end
function ga:configureAvailableCustomDimensions02(customDimensions)
if isSdkReady({needsInitialized = true, shouldWarn = false}) then
logger:w("Available custom dimensions must be set before SDK is initialized")
return
end
state:setAvailableCustomDimensions02(customDimensions)
end
function ga:configureAvailableCustomDimensions03(customDimensions)
if isSdkReady({needsInitialized = true, shouldWarn = false}) then
logger:w("Available custom dimensions must be set before SDK is initialized")
return
end
state:setAvailableCustomDimensions03(customDimensions)
end
function ga:configureAvailableResourceCurrencies(resourceCurrencies)
if isSdkReady({needsInitialized = true, shouldWarn = false}) then
logger:w("Available resource currencies must be set before SDK is initialized")
return
end
events:setAvailableResourceCurrencies(resourceCurrencies)
end
function ga:configureAvailableResourceItemTypes(resourceItemTypes)
if isSdkReady({needsInitialized = true, shouldWarn = false}) then
logger:w("Available resource item types must be set before SDK is initialized")
return
end
events:setAvailableResourceItemTypes(resourceItemTypes)
end
function ga:configureBuild(build)
if isSdkReady({needsInitialized = true, shouldWarn = false}) then
logger:w("Build version must be set before SDK is initialized.")
return
end
events:setBuild(build)
end
function ga:configureAvailableGamepasses(availableGamepasses)
if isSdkReady({needsInitialized = true, shouldWarn = false}) then
logger:w("Available gamepasses must be set before SDK is initialized.")
return
end
state:setAvailableGamepasses(availableGamepasses)
end
function ga:startNewSession(player, gaData)
threading:performTaskOnGAThread(function()
if not state:isEventSubmissionEnabled() then
return
end
if not state.Initialized then
logger:w("Cannot start new session. SDK is not initialized yet.")
return
end
state:startNewSession(player, gaData)
end)
end
function ga:endSession(playerId)
threading:performTaskOnGAThread(function()
if not state:isEventSubmissionEnabled() then
return
end
state:endSession(playerId)
end)
end
function ga:filterForBusinessEvent(text)
return string.gsub(text, "[^A-Za-z0-9%s%-_%.%(%)!%?]", "")
end
function ga:addBusinessEvent(playerId, options)
threading:performTaskOnGAThread(function()
if not state:isEventSubmissionEnabled() then
return
end
if not isSdkReady({playerId = playerId, needsInitialized = true, shouldWarn = false, message = "Could not add business event"}) then
if playerId then
addToInitializationQueueByUserId(playerId, ga.addBusinessEvent, ga, playerId, options)
else
addToInitializationQueue(ga.addBusinessEvent, ga, playerId, options)
end
return
end
-- Send to events
local amount = options["amount"] or 0
local itemType = options["itemType"] or ""
local itemId = options["itemId"] or ""
local cartType = options["cartType"] or ""
local USDSpent = math.floor((amount * 0.7) * 0.35)
local gamepassId = options["gamepassId"] or nil
events:addBusinessEvent(playerId, "USD", USDSpent, itemType, itemId, cartType)
if itemType == "Gamepass" and cartType ~= "Website" then
local player = Players:GetPlayerByUserId(playerId)
local playerData = store:GetPlayerData(player)
if not playerData.OwnedGamepasses then
playerData.OwnedGamepasses = {}
end
table.insert(playerData.OwnedGamepasses, gamepassId)
store.PlayerCache[playerId] = playerData
store:SavePlayerData(player)
end
end)
end
function ga:addResourceEvent(playerId, options)
threading:performTaskOnGAThread(function()
if not state:isEventSubmissionEnabled() then
return
end
if not isSdkReady({playerId = playerId, needsInitialized = true, shouldWarn = false, message = "Could not add resource event"}) then
if playerId then
addToInitializationQueueByUserId(playerId, ga.addResourceEvent, ga, playerId, options)
else
addToInitializationQueue(ga.addResourceEvent, ga, playerId, options)
end
return
end
-- Send to events
local flowType = options["flowType"] or 0
local currency = options["currency"] or ""
local amount = options["amount"] or 0
local itemType = options["itemType"] or ""
local itemId = options["itemId"] or ""
events:addResourceEvent(playerId, flowType, currency, amount, itemType, itemId)
end)
end
function ga:addProgressionEvent(playerId, options)
threading:performTaskOnGAThread(function()
if not state:isEventSubmissionEnabled() then
return
end
if not isSdkReady({playerId = playerId, needsInitialized = true, shouldWarn = false, message = "Could not add progression event"}) then
if playerId then
addToInitializationQueueByUserId(playerId, ga.addProgressionEvent, ga, playerId, options)
else
addToInitializationQueue(ga.addProgressionEvent, ga, playerId, options)
end
return
end
-- Send to events
local progressionStatus = options["progressionStatus"] or 0
local progression01 = options["progression01"] or ""
local progression02 = options["progression02"] or nil
local progression03 = options["progression03"] or nil
local score = options["score"] or nil
events:addProgressionEvent(playerId, progressionStatus, progression01, progression02, progression03, score)
end)
end
function ga:addDesignEvent(playerId, options)
threading:performTaskOnGAThread(function()
if not state:isEventSubmissionEnabled() then
return
end
if not isSdkReady({playerId = playerId, needsInitialized = true, shouldWarn = false, message = "Could not add design event"}) then
if playerId then
addToInitializationQueueByUserId(playerId, ga.addDesignEvent, ga, playerId, options)
else
addToInitializationQueue(ga.addDesignEvent, ga, playerId, options)
end
return
end
-- Send to events
local eventId = options["eventId"] or ""
local value = options["value"] or nil
events:addDesignEvent(playerId, eventId, value)
end)
end
function ga:addErrorEvent(playerId, options)
threading:performTaskOnGAThread(function()
if not state:isEventSubmissionEnabled() then
return
end
if not isSdkReady({playerId = playerId, needsInitialized = true, shouldWarn = false, message = "Could not add error event"}) then
if playerId then
addToInitializationQueueByUserId(playerId, ga.addErrorEvent, ga, playerId, options)
else
addToInitializationQueue(ga.addErrorEvent, ga, playerId, options)
end
return
end
-- Send to events
local severity = options["severity"] or 0
local message = options["message"] or ""
events:addErrorEvent(playerId, severity, message)
end)
end
function ga:setEnabledDebugLog(flag)
if RunService:IsStudio() then
if flag then
logger:setDebugLog(flag)
logger:i("Debug logging enabled")
else
logger:i("Debug logging disabled")
logger:setDebugLog(flag)
end
else
logger:i("setEnabledDebugLog can only be used in studio")
end
end
function ga:setEnabledInfoLog(flag)
if flag then
logger:setInfoLog(flag)
logger:i("Info logging enabled")
else
logger:i("Info logging disabled")
logger:setInfoLog(flag)
end
end
function ga:setEnabledVerboseLog(flag)
if flag then
logger:setVerboseLog(flag)
logger:ii("Verbose logging enabled")
else
logger:ii("Verbose logging disabled")
logger:setVerboseLog(flag)
end
end
function ga:setEnabledEventSubmission(flag)
threading:performTaskOnGAThread(function()
if flag then
state:setEventSubmission(flag)
logger:i("Event submission enabled")
else
logger:i("Event submission disabled")
state:setEventSubmission(flag)
end
end)
end
function ga:setCustomDimension01(playerId, dimension)
threading:performTaskOnGAThread(function()
if not validation:validateDimension(state._availableCustomDimensions01, dimension) then
logger:w("Could not set custom01 dimension value to '" .. dimension .. "'. Value not found in available custom01 dimension values")
return
end
if not isSdkReady({playerId = playerId, needsInitialized = true, shouldWarn = true, message = "Could not set custom01 dimension"}) then
return
end
state:setCustomDimension01(playerId, dimension)
end)
end
function ga:setCustomDimension02(playerId, dimension)
threading:performTaskOnGAThread(function()
if not validation:validateDimension(state._availableCustomDimensions02, dimension) then
logger:w("Could not set custom02 dimension value to '" .. dimension .. "'. Value not found in available custom02 dimension values")
return
end
if not isSdkReady({playerId = playerId, needsInitialized = true, shouldWarn = true, message = "Could not set custom02 dimension"}) then
return
end
state:setCustomDimension02(playerId, dimension)
end)
end
function ga:setCustomDimension03(playerId, dimension)
threading:performTaskOnGAThread(function()
if not validation:validateDimension(state._availableCustomDimensions03, dimension) then
logger:w("Could not set custom03 dimension value to '" .. dimension .. "'. Value not found in available custom03 dimension values")
return
end
if not isSdkReady({playerId = playerId, needsInitialized = true, shouldWarn = true, message = "Could not set custom03 dimension"}) then
return
end
state:setCustomDimension03(playerId, dimension)
end)
end
function ga:setEnabledReportErrors(flag)
threading:performTaskOnGAThread(function()
state.ReportErrors = flag
end)
end
function ga:setEnabledCustomUserId(flag)
threading:performTaskOnGAThread(function()
state.UseCustomUserId = flag
end)
end
function ga:setEnabledAutomaticSendBusinessEvents(flag)
threading:performTaskOnGAThread(function()
state.AutomaticSendBusinessEvents = flag
end)
end
function ga:addGameAnalyticsTeleportData(playerIds, teleportData)
local gameAnalyticsTeleportData = {}
for _, playerId in ipairs(playerIds) do
local PlayerData = store:GetPlayerDataFromCache(playerId)
PlayerData.PlayerTeleporting = true
local data = {
["SessionID"] = PlayerData.SessionID,
["Sessions"] = PlayerData.Sessions,
["SessionStart"] = PlayerData.SessionStart,
}
gameAnalyticsTeleportData[tostring(playerId)] = data
end
teleportData["gameanalyticsData"] = gameAnalyticsTeleportData
return teleportData
end
function ga:getRemoteConfigsValueAsString(playerId, options)
local key = options["key"] or ""
local defaultValue = options["defaultValue"] or nil
return state:getRemoteConfigsStringValue(playerId, key, defaultValue)
end
function ga:isRemoteConfigsReady(playerId)
return state:isRemoteConfigsReady(playerId)
end
function ga:getRemoteConfigsContentAsString(playerId)
return state:getRemoteConfigsContentAsString(playerId)
end
function ga:PlayerJoined(Player)
local joinData = Player:GetJoinData()
local teleportData = joinData.TeleportData
local gaData = nil
--Variables
local PlayerData = store:GetPlayerData(Player)
if teleportData then
gaData = teleportData.gameanalyticsData and teleportData.gameanalyticsData[tostring(Player.UserId)]
end
local pd = store:GetPlayerDataFromCache(Player.UserId)
if pd then
if gaData then
pd.SessionID = gaData.SessionID
pd.SessionStart = gaData.SessionStart
end
pd.PlayerTeleporting = false
return
end
local PlayerPlatform = "unknown"
local isSuccessful, platform = Postie.InvokeClient("getPlatform", Player, 5)
if isSuccessful then
PlayerPlatform = platform
end
--Fill Data
for key, value in pairs(store.BasePlayerData) do
PlayerData[key] = PlayerData[key] or value
end
local countryCodeResult, countryCode = pcall(function()
return LocalizationService:GetCountryRegionForPlayerAsync(Player)
end)
if countryCodeResult then
PlayerData.CountryCode = countryCode
end
store.PlayerCache[Player.UserId] = PlayerData
PlayerData.Platform = (PlayerPlatform == "Console" and "uwp_console") or (PlayerPlatform == "Mobile" and "uwp_mobile") or (PlayerPlatform == "Desktop" and "uwp_desktop") or "uwp_desktop"
PlayerData.OS = PlayerData.Platform .. " 0.0.0"
if not countryCodeResult then
events:addSdkErrorEvent(Player.UserId, "event_validation", "player_joined", "string_empty_or_null", "country_code", "")
end
local PlayerCustomUserId = ""
if state.UseCustomUserId then
local isSuccessful, customUserId = Postie.InvokeClient("getCustomUserId", Player, 5)
if isSuccessful then
PlayerCustomUserId = customUserId
end
end
if not utilities:isStringNullOrEmpty(PlayerCustomUserId) then
logger:i("Using custom id: " .. PlayerCustomUserId)
PlayerData.CustomUserId = PlayerCustomUserId
end
ga:startNewSession(Player, gaData)
OnPlayerReadyEvent = OnPlayerReadyEvent or ReplicatedStorage:WaitForChild("OnPlayerReadyEvent")
OnPlayerReadyEvent:Fire(Player)
--Validate
if state.AutomaticSendBusinessEvents then
--Website gamepasses
if PlayerData.OwnedGamepasses == nil then --player is new (or is playing after SDK update)
PlayerData.OwnedGamepasses = {}
for _, id in ipairs(state._availableGamepasses) do
if MKT:UserOwnsGamePassAsync(Player.UserId, id) then
table.insert(PlayerData.OwnedGamepasses, id)
end
end
--Player's data is now up to date. gamepass purchases on website can now be tracked in future visits
store.PlayerCache[Player.UserId] = PlayerData
store:SavePlayerData(Player)
else
--build a list of the game passes a user owns
local currentlyOwned = {}
for _, id in ipairs(state._availableGamepasses) do
if MKT:UserOwnsGamePassAsync(Player.UserId, id) then
table.insert(currentlyOwned, id)
end
end
--make a table so it's easier to compare to stored game passes
local storedGamepassesTable = {}
for _, id in ipairs(PlayerData.OwnedGamepasses) do
storedGamepassesTable[id] = true
end
--compare stored game passes to currently owned game passses
for _, id in ipairs(currentlyOwned) do
if not storedGamepassesTable[id] then
table.insert(PlayerData.OwnedGamepasses, id)
local gamepassInfo = ProductCache[id]
--Cache
if not gamepassInfo then
--Get
gamepassInfo = MKT:GetProductInfo(id, Enum.InfoType.GamePass)
ProductCache[id] = gamepassInfo
end
ga:addBusinessEvent(Player.UserId, {
amount = gamepassInfo.PriceInRobux,
itemType = "Gamepass",
itemId = ga:filterForBusinessEvent(gamepassInfo.Name),
cartType = "Website",
})
end
end
store.PlayerCache[Player.UserId] = PlayerData
store:SavePlayerData(Player)
end
end
local playerEventQueue = InitializationQueueByUserId[Player.UserId]
if playerEventQueue then
InitializationQueueByUserId[Player.UserId] = nil
for _, queuedFunction in ipairs(playerEventQueue) do
queuedFunction.Func(unpack(queuedFunction.Args))
end
logger:i("Player initialization queue called #" .. #playerEventQueue .. " events")
end
end
function ga:PlayerRemoved(Player)
--Save
store:SavePlayerData(Player)
local PlayerData = store:GetPlayerDataFromCache(Player.UserId)
if PlayerData then
if not PlayerData.PlayerTeleporting then
ga:endSession(Player.UserId)
else
store.PlayerCache[Player.UserId] = nil
end
end
end
function ga:isPlayerReady(playerId)
if store:GetPlayerDataFromCache(playerId) then
return true
else
return false
end
end
function ga:ProcessReceiptCallback(Info)
--Variables
local ProductInfo = ProductCache[Info.ProductId]
--Cache
if not ProductInfo then
--Get
pcall(function()
ProductInfo = MKT:GetProductInfo(Info.ProductId, Enum.InfoType.Product)
ProductCache[Info.ProductId] = ProductInfo
end)
end
if ProductInfo then
ga:addBusinessEvent(Info.PlayerId, {
amount = Info.CurrencySpent,
itemType = "DeveloperProduct",
itemId = ga:filterForBusinessEvent(ProductInfo.Name),
})
end
end
--customGamepassInfo argument to optinaly provide our own name or price
function ga:GamepassPurchased(player, id, customGamepassInfo)
local gamepassInfo = ProductCache[id]
--Cache
if not gamepassInfo then
--Get
gamepassInfo = MKT:GetProductInfo(id, Enum.InfoType.GamePass)
ProductCache[id] = gamepassInfo
end
local amount = 0
local itemId = "GamePass"
if customGamepassInfo then
amount = customGamepassInfo.PriceInRobux
itemId = customGamepassInfo.Name
elseif gamepassInfo then
amount = gamepassInfo.PriceInRobux
itemId = gamepassInfo.Name
end
ga:addBusinessEvent(player.UserId, {
amount = amount or 0,
itemType = "Gamepass",
itemId = ga:filterForBusinessEvent(itemId),
gamepassId = id,
})
end
local requiredInitializationOptions = {"gameKey", "secretKey"}
function ga:initialize(options)
threading:performTaskOnGAThread(function()
for _, option in ipairs(requiredInitializationOptions) do
if options[option] == nil then
logger:e("Initialize '"..option.."' option missing")
return
end
end
if options.enableInfoLog ~= nil and options.enableInfoLog then
ga:setEnabledInfoLog(options.enableInfoLog)
end
if options.enableVerboseLog ~= nil and options.enableVerboseLog then
ga:setEnabledVerboseLog(options.enableVerboseLog)
end
if options.availableCustomDimensions01 ~= nil and #options.availableCustomDimensions01 > 0 then
ga:configureAvailableCustomDimensions01(options.availableCustomDimensions01)
end
if options.availableCustomDimensions02 ~= nil and #options.availableCustomDimensions02 > 0 then
ga:configureAvailableCustomDimensions02(options.availableCustomDimensions02)
end
if options.availableCustomDimensions03 ~= nil and #options.availableCustomDimensions03 > 0 then
ga:configureAvailableCustomDimensions03(options.availableCustomDimensions03)
end
if options.availableResourceCurrencies ~= nil and #options.availableResourceCurrencies > 0 then
ga:configureAvailableResourceCurrencies(options.availableResourceCurrencies)
end
if options.availableResourceItemTypes ~= nil and #options.availableResourceItemTypes > 0 then
ga:configureAvailableResourceItemTypes(options.availableResourceItemTypes)
end
if options.build ~= nil and #options.build > 0 then
ga:configureBuild(options.build)
end
if options.availableGamepasses ~= nil and #options.availableGamepasses > 0 then
ga:configureAvailableGamepasses(options.availableGamepasses)
end
if options.enableDebugLog ~= nil then
ga:setEnabledDebugLog(options.enableDebugLog)
end
if options.automaticSendBusinessEvents ~= nil then
ga:setEnabledAutomaticSendBusinessEvents(options.automaticSendBusinessEvents)
end
if options.reportErrors ~= nil then
ga:setEnabledReportErrors(options.reportErrors)
end
if options.useCustomUserId ~= nil then
ga:setEnabledCustomUserId(options.useCustomUserId)
end
if isSdkReady({needsInitialized = true, shouldWarn = false}) then
logger:w("SDK already initialized. Can only be called once.")
return
end
local gameKey = options["gameKey"]
local secretKey = options["secretKey"]
if not validation:validateKeys(gameKey, secretKey) then
logger:w("SDK failed initialize. Game key or secret key is invalid. Can only contain characters A-z 0-9, gameKey is 32 length, secretKey is 40 length. Failed keys - gameKey: " .. gameKey .. ", secretKey: " .. secretKey)
return
end
events.GameKey = gameKey
events.SecretKey = secretKey
state.Initialized = true
-- New Players
Players.PlayerAdded:Connect(function(Player)
ga:PlayerJoined(Player)
end)
-- Players leaving
Players.PlayerRemoving:Connect(function(Player)
ga:PlayerRemoved(Player)
end)
-- Fire for players already in game
for _, Player in ipairs(Players:GetPlayers()) do
coroutine.wrap(ga.PlayerJoined)(ga, Player)
end
for _, queuedFunction in ipairs(InitializationQueue) do
spawn(queuedFunction.Func, unpack(queuedFunction.Args))
end
logger:i("Server initialization queue called #" .. #InitializationQueue .. " events")
InitializationQueue = nil
events:processEventQueue()
end)
end
if not ReplicatedStorage:FindFirstChild("GameAnalyticsRemoteConfigs") then
--Create
local f = Instance.new("RemoteEvent")
f.Name = "GameAnalyticsRemoteConfigs"
f.Parent = ReplicatedStorage
end
if not ReplicatedStorage:FindFirstChild("OnPlayerReadyEvent") then
--Create
local f = Instance.new("BindableEvent")
f.Name = "OnPlayerReadyEvent"
f.Parent = ReplicatedStorage
end
spawn(function()
local currentHour = math.floor(os.time() / 3600)
ErrorDS = store:GetErrorDataStore(currentHour)
while wait(ONE_HOUR_IN_SECONDS) do
currentHour = math.floor(os.time() / 3600)
ErrorDS = store:GetErrorDataStore(currentHour)
errorCountCache = {}
errorCountCacheKeys = {}
end
end)
spawn(function()
while wait(store.AutoSaveData) do
for _, key in pairs(errorCountCacheKeys) do
local errorCount = errorCountCache[key]
local step = errorCount.currentCount - errorCount.countInDS
errorCountCache[key].countInDS = store:IncrementErrorCount(ErrorDS, key, step)
errorCountCache[key].currentCount = errorCountCache[key].countInDS
end
end
end)
local function ErrorHandler(message, trace, scriptName, player)
local m = scriptName .. ": message=" .. message .. ", trace=" .. trace
if #m > 8192 then
m = string.sub(m, 1, 8192)
end
local userId = nil
if player then
userId = player.UserId
m = m:gsub(player.Name, "[LocalPlayer]") -- so we don't flood the same errors with different player names
end
local key = m
if #key > 50 then
key = string.sub(key, 1, 50)
end
if errorCountCache[key] == nil then
errorCountCacheKeys[#errorCountCacheKeys + 1] = key
errorCountCache[key] = {}
errorCountCache[key].countInDS = 0
errorCountCache[key].currentCount = 0
end
-- don't report error if limit has been exceeded
if errorCountCache[key].currentCount > MaxErrorsPerHour then
return
end
ga:addErrorEvent(userId, {
severity = ga.EGAErrorSeverity.error,
message = m,
})
-- increment error count
errorCountCache[key].currentCount = errorCountCache[key].currentCount + 1
end
local function ErrorHandlerFromServer(message, trace, Script)
--Validate
if not state.ReportErrors then
return
end
if not Script then -- don't remember if this check is necessary but must have added it for a reason
return
end
local scriptName = nil
local ok, _ = pcall(function()
scriptName = Script:GetFullName() -- CoreGui.RobloxGui.Modules.PlayerList error, can't get name because of security permission
end)
if not ok then
return
end
return ErrorHandler(message, trace, scriptName)
end
local function ErrorHandlerFromClient(message, trace, scriptName, player)
--Validate
if not state.ReportErrors then
return
end
return ErrorHandler(message, trace, scriptName, player)
end
--Error Logging
ScriptContext.Error:Connect(ErrorHandlerFromServer)
if not ReplicatedStorage:FindFirstChild("GameAnalyticsError") then
--Create
local f = Instance.new("RemoteEvent")
f.Name = "GameAnalyticsError"
f.Parent = ReplicatedStorage
end
ReplicatedStorage.GameAnalyticsError.OnServerEvent:Connect(function(player, message, trace, scriptName)
ErrorHandlerFromClient(message, trace, scriptName, player)
end)
--Record Gamepasses.
MKT.PromptGamePassPurchaseFinished:Connect(function(Player, ID, Purchased)
--Validate
if not state.AutomaticSendBusinessEvents or not Purchased then
return
end
ga:GamepassPurchased(Player, ID)
end)
return ga
|
function showBlood(attacker, weapon, bodypart)
local health = getElementHealth(source)
if (health<=20) then
local x, y, z = getElementPosition(source)
fxAddBlood(x, y, z, 0, 0, 0, 1000, 1.0)
end
-- Realistic blood from bodypart
if (attacker) then
if (bodypart==3) then -- torso
local x, y, z = getPedBonePosition(source, 3)
fxAddBlood(x, y, z, 0, 0, 0, 500, 1.0)
elseif (bodypart==4) then -- ass
local x, y, z = getPedBonePosition(source, 1)
fxAddBlood(x, y, z, 0, 0, 0, 500, 1.0)
elseif (bodypart==5) then -- left arm
local x, y, z = getPedBonePosition(source, 32)
fxAddBlood(x, y, z, 0, 0, 0, 500, 1.0)
elseif (bodypart==6) then -- right arm
local x, y, z = getPedBonePosition(source, 22)
fxAddBlood(x, y, z, 0, 0, 0, 500, 1.0)
elseif (bodypart==7) then -- left leg
local x, y, z = getPedBonePosition(source, 42)
fxAddBlood(x, y, z, 0, 0, 0, 500, 1.0)
elseif (bodypart==8) then -- right leg
local x, y, z = getPedBonePosition(source, 52)
fxAddBlood(x, y, z, 0, 0, 0, 500, 1.0)
elseif (bodypart==9) then -- head
local x, y, z = getPedBonePosition(source, 6)
fxAddBlood(x, y, z, 0, 0, 0, 500, 1.0)
end
end
end
addEventHandler("onClientPedDamage", getRootElement(), showBlood) |
local speed = i2c.setup(0, 3, 4, i2c.SLOW)
if speed == 0 then
log('i2c setup error')
return
end
log('i2c setup successful @', speed)
if pcall(si7021.setup) then
log('si7021 setup successful')
else
log('si7021 setup failed - no device?')
return
end
if cfg.debug then
local sna, snb = si7021.serial()
log(string.format("Device: Si70%d\nSN: 0x%08X 0x%08X", bit.rshift(snb, 24), sna, snb))
local fwrev = si7021.firmware()
log(string.format("FW: %1.1f", fwrev == 0x20 and 2 or 1))
end
function sensor_get_data(callback)
local humidity, temperature = si7021.read()
if not humidity or not temperature then
log('si7021 data read failed')
return callback()
end
local sna, snb = si7021.serial()
if not sna or not snb then
log('si7021 serial read failed')
return callback()
end
result = {}
local model = 'si70' .. string.format('%d', bit.rshift(snb, 24))
local sn = string.format('%08x', sna)
result[model .. '-' .. sn] = {
temperature = temperature,
humidity = humidity,
updated = rtctime.get() * 1000,
}
callback(result)
end
log('si7021 sensor module loaded');
|
getglobal game
getfield -1 Players
getfield -1 LocalPlayer
getfield -1 Character
getfield -1 Head
getglobal Instance
getfield -1 new
pushstring PointLight
pushvalue -4
pcall 2 1 0 |
return {
name = 'FilterType',
description = 'Types of filters for Sources.',
constants = {
{
name = 'lowpass',
description = 'Low-pass filter. High frequency sounds are attenuated.',
},
{
name = 'highpass',
description = 'High-pass filter. Low frequency sounds are attenuated.',
},
{
name = 'bandpass',
description = 'Band-pass filter. Both high and low frequency sounds are attenuated based on the given parameters.',
},
},
} |
local Modules = game:GetService("Players").LocalPlayer.PlayerGui.AvatarEditorInGame.Modules
local Action = require(Modules.Common.Action)
local ArgCheck = require(Modules.Packages.ArgCheck)
return Action(script.Name, function(userAssets)
ArgCheck.isType(userAssets, "table", "userAssets")
return {
userAssets = userAssets,
}
end) |
--[[
Project: SA Memory (Available from https://blast.hk/)
Developers: LUCHARE, FYP
Special thanks:
plugin-sdk (https://github.com/DK22Pac/plugin-sdk) for the structures and addresses.
Copyright (c) 2018 BlastHack.
]]
local shared = require 'SAMemory.shared'
shared.require 'RenderWare'
shared.require 'vector2d'
shared.require 'vector3d'
shared.ffi.cdef[[
typedef enum e2dEffectType
{
EFFECT_LIGHT,
EFFECT_PARTICLE,
EFFECT_ATTRACTOR = 3,
EFFECT_SUN_GLARE,
EFFECT_FURNITUR,
EFFECT_ENEX,
EFFECT_ROADSIGN,
EFFECT_SLOTMACHINE_WHEEL,
EFFECT_COVER_POINT,
EFFECT_ESCALATOR,
} e2dEffectType;
typedef enum ePedAttractorType
{
PED_ATTRACTOR_ATM = 0,
PED_ATTRACTOR_SEAT = 1,
PED_ATTRACTOR_STOP = 2,
PED_ATTRACTOR_PIZZA = 3,
PED_ATTRACTOR_SHELTER = 4,
PED_ATTRACTOR_TRIGGER_SCRIPT = 5,
PED_ATTRACTOR_LOOK_AT = 6,
PED_ATTRACTOR_SCRIPTED = 7,
PED_ATTRACTOR_PARK = 8,
PED_ATTRACTOR_STEP = 9
} ePedAttractorType;
typedef struct tEffectLight
{
RwColor color;
float fCoronaFarClip;
float fPointlightRange;
float fCoronaSize;
float fShadowSize;
unsigned short nFlags;
unsigned char nCoronaFlashType;
bool bCoronaEnableReflection;
unsigned char nCoronaFlareType;
unsigned char nShadowColorMultiplier;
char nShadowZDistance;
char offsetX;
char offsetY;
char offsetZ;
char _pad2E[2];
RwTexture *pCoronaTex;
RwTexture *pShadowTex;
int field_38;
int field_3C;
} tEffectLight;
typedef struct tEffectParticle
{
char szName[24];
} tEffectParticle;
typedef struct tEffectPedAttractor
{
vector3d vecQueueDir;
vector3d vecUseDir;
vector3d vecForwardDir;
unsigned char nAttractorType;
unsigned char nPedExistingProbability;
char field_36;
unsigned char nFlags;
char szScriptName[8];
} tEffectPedAttractor;
typedef struct tEffectEnEx
{
float fEnterAngle;
vector3d vecSize;
vector3d vecExitPosn;
float fExitAngle;
short nInteriorId;
unsigned char nFlags1;
unsigned char nSkyColor;
char szInteriorName[8];
unsigned char nTimeOn;
unsigned char nTimeOff;
unsigned char nFlags2;
} tEffectEnEx;
typedef struct tEffectRoadsign
{
vector2d vecSize;
float afRotation[3];
unsigned short nFlags;
char _pad26[2];
char *pText;
RpAtomic *pAtomic;
} tEffectRoadsign;
typedef struct tEffectCoverPoint
{
vector2d vecDirection;
unsigned char nType;
char _pad19[3];
} tEffectCoverPoint;
typedef struct tEffectEscalator
{
vector3d vecBottom;
vector3d vecTop;
vector3d vecEnd;
unsigned char nDirection;
char _pad35[3];
} tEffectEscalator;
typedef struct C2dEffect
{
vector3d vecPosn;
unsigned int nType;
union
{
tEffectLight light;
tEffectParticle particle;
tEffectPedAttractor pedAttractor;
tEffectEnEx enEx;
tEffectRoadsign roadsign;
tEffectCoverPoint coverPoint;
tEffectEscalator escalator;
};
} C2dEffect;
]]
shared.validate_size('C2dEffect', 0x40)
|
stEnd = {}
local bg = require "utils.background"
local fonts = require "assets.fonts"
local utils = require "utils.utils"
function stEnd:enter(game, result)
self.result = result
self.dogeism = utils.getDogeism() --new one each time we pause
end
function stEnd:update(dt)
--gui updates
Gui.group.push{ grow = "down",
pos = { love.window.getWidth()/2 - Gui.group.size[1]/2, love.graphics.getHeight()/2 + 50 } }
if Gui.Button{text = "Play Again"} then
Gamestate.switch(stGame)
end
if Gui.Button{text = "Quit to Menu"} then
Gamestate.switch(stMenu)
end
if Gui.Button{text = "Quit to Desktop"} then
love.event.quit()
end
Gui.group.pop{}
bg:update(dt)
end
function stEnd:draw()
bg:draw()
--draw the text
local w, h = love.window.getWidth(), love.graphics.getHeight()
if(self.result == "lose") then
love.graphics.setFont(fonts[72])
love.graphics.setColor(0,0,0,255)
love.graphics.printf("wow " .. self.dogeism .. " fail", 4, (h / 2 - love.graphics.getFont():getHeight())+4, w, "center")
love.graphics.setColor(255,255,255,255)
love.graphics.printf("wow " .. self.dogeism .. " fail", 0, h / 2 - love.graphics.getFont():getHeight(), w, "center")
else
love.graphics.setFont(fonts[72])
love.graphics.setColor(0,0,0,255)
love.graphics.printf("wow " .. self.dogeism .. " " .. self.result .. " victory", 4, (h / 2 - love.graphics.getFont():getHeight())+4, w, "center")
love.graphics.setColor(255,255,255,255)
love.graphics.printf("wow " .. self.dogeism .. " " .. self.result .. " victory", 0, h / 2 - love.graphics.getFont():getHeight(), w, "center")
end
love.graphics.setFont(fonts.default)
Gui.core.draw()
end
function stEnd:keyreleased(key)
if(key == "escape") then
love.audio.resume()
Gamestate.pop()
end
end
|
require("nebulous").setup {
variant = "fullmoon",
disable = {
background = true,
endOfBuffer = false,
},
italic = {
comments = true,
keywords = true,
functions = true,
variables = false,
},
custom_colors = { -- this table can hold any group of colors with their respective values
CursorLineNr = { fg = "#E1CD6C", bg = "NONE", style = "NONE" },
Comment = { fg = "#696f7a", bg = "NONE", style = "NONE" },
-- it is possible to specify only the element to be changed
--[[ TelescopePreviewBorder = { fg = "#A13413" },
LspDiagnosticsDefaultError = { bg = "#E11313" },
TSTagDelimiter = { style = "bold,italic" }, ]]
}
}
|
return function()
local liter = require(game:GetService('ReplicatedStorage').liter)
it('should unpack the array around the returned value', function()
local iter = liter.array({ { 1, 2 }, { 3, 4 } }):unbox()
local a, b = iter:after()
expect(a).to.equal(1)
expect(b).to.equal(2)
local c, d = iter:after()
expect(c).to.equal(3)
expect(d).to.equal(4)
expect(iter:after()).to.never.be.ok()
end)
end
|
function RunStartupStuffEsx(msg)
-- NOTE: If not using legacy then comment out the '@es_extended/imports.lua' line in fxmanifest.lua
-- Legacy provides a definition for ESX object so this should overwrite the global, but
-- better to not let it load if not required
if Config.UsingEsxLegacy == false then
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj)
ESX = obj
end)
end
end
function GetAllPlayerNamesEsx()
-- If you don't have this function in your es_extended, add it. I won't accomodate for
-- not having this as without it there's MAJOR potential for server killing. Find it in ESX Legacy
local xPlayers = ESX.GetExtendedPlayers()
local playerNames = {}
for _, playerIdStr in pairs(GetPlayers()) do
local playerId = tonumber(playerIdStr)
if xPlayers[playerId] ~= nil then
playerNames[playerId] = xPlayers[playerId].name
end
end
return playerNames
end
|
function GlobalLuaFunction()
print "nvim-example-lua-plugin.luamodule.init GlobalLuaFunction: hello"
end
function CurrentLineInfo()
local linenr = vim.api.nvim_win_get_cursor(0)[1]
local curline = vim.api.nvim_buf_get_lines(0, linenr, linenr + 1, false)[1]
print(string.format("current line [%d] has %d bytes", linenr, #curline))
end
function ShowBuffs()
print(vim.api.nvim_list_bufs())
end
|
return {'zeken','zeker','zekere','zekeren','zekerheid','zekerheidshalve','zekerheidsmaatregel','zekerheidsrecht','zekerheidsregeling','zekerheidsstelsel','zekerheidssysteem','zekerheidstelling','zekerheidstelsel','zekerheidsuitgaven','zekerheidswetgeving','zekering','zekeringhouder','zekeringkast','zekerlijk','zekers','zekerstelling','zekerheidsstelling','zekerheidssteller','zekerheidsnemer','zekerheidsovereenkomst','zekeringenkast','zekeringskast','zekerde','zekerden','zekerder','zekergesteld','zekerheden','zekerheidsbijdragen','zekerheidsmaatregelen','zekerheidstellingen','zekeringen','zekerst','zekert','zekerheidsrechten','zekerste','zekerheidsregelingen','zekerheidsstelsels','zekeringenkastje','zekerheidssystemen'} |
-- // Name: getFollowings.lua
-- // Description: Gets the list of people the specified user is following
-- // Author: @Jumpathy
local pageObject = require(script.Parent.Parent.Parent:WaitForChild("objects"):WaitForChild("page"));
return {
authentication_required = false,
call = function(client,api,endpoints,cookie,userId)
local args = {userId}
return api.promiseModule.async(function(resolve,reject)
local key = "getFollowings";
local pageInitiator = api.request(true,key,{
["urlExtension"] = "?sortOrder=Desc&limit=100";
},nil,unpack(args)):andThen(function(response)
resolve(pageObject.new(
response,
args,
key,
api
));
end):catch(function(err)
reject(err);
end)
end)
end
} |
---@class CS.UnityEngine.Matrix4x4 : CS.System.ValueType
---@field public m00 number
---@field public m10 number
---@field public m20 number
---@field public m30 number
---@field public m01 number
---@field public m11 number
---@field public m21 number
---@field public m31 number
---@field public m02 number
---@field public m12 number
---@field public m22 number
---@field public m32 number
---@field public m03 number
---@field public m13 number
---@field public m23 number
---@field public m33 number
---@field public rotation CS.UnityEngine.Quaternion
---@field public lossyScale CS.UnityEngine.Vector3
---@field public isIdentity boolean
---@field public determinant number
---@field public decomposeProjection CS.UnityEngine.FrustumPlanes
---@field public inverse CS.UnityEngine.Matrix4x4
---@field public transpose CS.UnityEngine.Matrix4x4
---@field public Item number
---@field public Item number
---@field public zero CS.UnityEngine.Matrix4x4
---@field public identity CS.UnityEngine.Matrix4x4
---@type CS.UnityEngine.Matrix4x4
CS.UnityEngine.Matrix4x4 = { }
---@return CS.UnityEngine.Matrix4x4
---@param column0 CS.UnityEngine.Vector4
---@param column1 CS.UnityEngine.Vector4
---@param column2 CS.UnityEngine.Vector4
---@param column3 CS.UnityEngine.Vector4
function CS.UnityEngine.Matrix4x4.New(column0, column1, column2, column3) end
---@return boolean
function CS.UnityEngine.Matrix4x4:ValidTRS() end
---@return number
---@param m CS.UnityEngine.Matrix4x4
function CS.UnityEngine.Matrix4x4.Determinant(m) end
---@return CS.UnityEngine.Matrix4x4
---@param pos CS.UnityEngine.Vector3
---@param q CS.UnityEngine.Quaternion
---@param s CS.UnityEngine.Vector3
function CS.UnityEngine.Matrix4x4.TRS(pos, q, s) end
---@param pos CS.UnityEngine.Vector3
---@param q CS.UnityEngine.Quaternion
---@param s CS.UnityEngine.Vector3
function CS.UnityEngine.Matrix4x4:SetTRS(pos, q, s) end
---@return CS.UnityEngine.Matrix4x4
---@param m CS.UnityEngine.Matrix4x4
function CS.UnityEngine.Matrix4x4.Inverse(m) end
---@return CS.UnityEngine.Matrix4x4
---@param m CS.UnityEngine.Matrix4x4
function CS.UnityEngine.Matrix4x4.Transpose(m) end
---@return CS.UnityEngine.Matrix4x4
---@param left number
---@param right number
---@param bottom number
---@param top number
---@param zNear number
---@param zFar number
function CS.UnityEngine.Matrix4x4.Ortho(left, right, bottom, top, zNear, zFar) end
---@return CS.UnityEngine.Matrix4x4
---@param fov number
---@param aspect number
---@param zNear number
---@param zFar number
function CS.UnityEngine.Matrix4x4.Perspective(fov, aspect, zNear, zFar) end
---@return CS.UnityEngine.Matrix4x4
---@param from CS.UnityEngine.Vector3
---@param to CS.UnityEngine.Vector3
---@param up CS.UnityEngine.Vector3
function CS.UnityEngine.Matrix4x4.LookAt(from, to, up) end
---@overload fun(fp:CS.UnityEngine.FrustumPlanes): CS.UnityEngine.Matrix4x4
---@return CS.UnityEngine.Matrix4x4
---@param left number
---@param optional right number
---@param optional bottom number
---@param optional top number
---@param optional zNear number
---@param optional zFar number
function CS.UnityEngine.Matrix4x4.Frustum(left, right, bottom, top, zNear, zFar) end
---@return number
function CS.UnityEngine.Matrix4x4:GetHashCode() end
---@overload fun(other:CS.System.Object): boolean
---@return boolean
---@param other CS.UnityEngine.Matrix4x4
function CS.UnityEngine.Matrix4x4:Equals(other) end
---@overload fun(lhs:CS.UnityEngine.Matrix4x4, rhs:CS.UnityEngine.Matrix4x4): CS.UnityEngine.Matrix4x4
---@return CS.UnityEngine.Matrix4x4
---@param lhs CS.UnityEngine.Matrix4x4
---@param vector CS.UnityEngine.Vector4
function CS.UnityEngine.Matrix4x4.op_Multiply(lhs, vector) end
---@return boolean
---@param lhs CS.UnityEngine.Matrix4x4
---@param rhs CS.UnityEngine.Matrix4x4
function CS.UnityEngine.Matrix4x4.op_Equality(lhs, rhs) end
---@return boolean
---@param lhs CS.UnityEngine.Matrix4x4
---@param rhs CS.UnityEngine.Matrix4x4
function CS.UnityEngine.Matrix4x4.op_Inequality(lhs, rhs) end
---@return CS.UnityEngine.Vector4
---@param index number
function CS.UnityEngine.Matrix4x4:GetColumn(index) end
---@return CS.UnityEngine.Vector4
---@param index number
function CS.UnityEngine.Matrix4x4:GetRow(index) end
---@param index number
---@param column CS.UnityEngine.Vector4
function CS.UnityEngine.Matrix4x4:SetColumn(index, column) end
---@param index number
---@param row CS.UnityEngine.Vector4
function CS.UnityEngine.Matrix4x4:SetRow(index, row) end
---@return CS.UnityEngine.Vector3
---@param point CS.UnityEngine.Vector3
function CS.UnityEngine.Matrix4x4:MultiplyPoint(point) end
---@return CS.UnityEngine.Vector3
---@param point CS.UnityEngine.Vector3
function CS.UnityEngine.Matrix4x4:MultiplyPoint3x4(point) end
---@return CS.UnityEngine.Vector3
---@param vector CS.UnityEngine.Vector3
function CS.UnityEngine.Matrix4x4:MultiplyVector(vector) end
---@return CS.UnityEngine.Plane
---@param plane CS.UnityEngine.Plane
function CS.UnityEngine.Matrix4x4:TransformPlane(plane) end
---@return CS.UnityEngine.Matrix4x4
---@param vector CS.UnityEngine.Vector3
function CS.UnityEngine.Matrix4x4.Scale(vector) end
---@return CS.UnityEngine.Matrix4x4
---@param vector CS.UnityEngine.Vector3
function CS.UnityEngine.Matrix4x4.Translate(vector) end
---@return CS.UnityEngine.Matrix4x4
---@param q CS.UnityEngine.Quaternion
function CS.UnityEngine.Matrix4x4.Rotate(q) end
---@overload fun(): string
---@return string
---@param optional format string
function CS.UnityEngine.Matrix4x4:ToString(format) end
return CS.UnityEngine.Matrix4x4
|
---@class icp.main:cc.ViewBase
local M = class('icp.main', require('cc.ViewBase'))
assert(imgui)
local im = imgui
local wi = require('imgui.Widget')
function M:ctor()
require('cc.ViewBase').ctor(self)
self:showWithScene()
local la = im.on(self:getParent())
local window_flags = bit.bor(
--im.WindowFlags.MenuBar,
im.WindowFlags.NoDocking,
im.WindowFlags.NoTitleBar,
im.WindowFlags.NoCollapse,
im.WindowFlags.NoResize,
im.WindowFlags.NoMove,
im.WindowFlags.NoBringToFrontOnFocus,
im.WindowFlags.NoNavFocus,
im.WindowFlags.NoBackground
)
la:addChild(function()
local viewport = im.getMainViewport()
im.setNextWindowPos(viewport.Pos)
im.setNextWindowSize(viewport.Size)
im.setNextWindowViewport(viewport.ID)
im.pushStyleVar(im.StyleVar.WindowRounding, 0)
im.pushStyleVar(im.StyleVar.WindowBorderSize, 0)
im.pushStyleVar(im.StyleVar.WindowPadding, im.p(0, 0))
im.begin('Dock Space', nil, window_flags)
im.popStyleVar(3)
im.dockSpace(im.getID('icp.dock_space'), im.p(0, 0), im.DockNodeFlags.PassthruCentralNode)
im.endToLua()
end)
local assetManager = require('icp.AssetManager'):getInstance()
la:addChild(assetManager)
local editor = require('icp.Editor'):getInstance()
la:addChild(editor)
local property = require('icp.Property'):getInstance()
la:addChild(property)
assetManager:addImage('D:/图片/表情/贴吧表情/43.png')
--la:addChild(im.showDemoWindow)
--la:addChild(im.showStyleEditor)
--im.styleColorsLight()
require('imgui.style').AdobeDark()
require('imgui.lstg.util').loadFont()
self:_loadIcons()
self:scheduleUpdateWithPriorityLua(function()
local key = require('keycode')
if lstg.GetKeyState(key.CTRL) and lstg.GetLastKey() == key.R then
for i, v in ipairs(table.keys(package.loaded)) do
package.loaded[v] = nil
end
im.off()
local dir = cc.Director:getInstance()
dir:purgeCachedData()
dir:replaceScene(nil)
lstg.FrameReset()
end
end, 1)
end
function M:_loadIcons()
local names = {
"ActualSize",
"AdjustWindowSize",
"AutoZoom",
"Checkerboard",
"Convert",
"Delete",
"Edit",
"FlipHorz",
"FlipVert",
"FullScreen",
"GoToFirst",
"GoToImage",
"GotoLast",
"LockRatio",
"Menu",
"OpenFile",
"Print",
"Refresh",
"RotateLeft",
"RotateRight",
"ScaleToFill",
"ScaleToFit",
"ScaleToHeight",
"ScaleToWidth",
"Slideshow",
"ThumbnailBar",
"ViewNextImage",
"ViewPreviousImage",
"ZoomIn",
"ZoomOut",
}
local cache = cc.Director:getInstance():getTextureCache()
for i, v in ipairs(names) do
local path = ('icp/icon/%s.png'):format(v)
local img = cc.Image()
local ok = img:initWithImageFile(path)
assert(ok)
local tex = cache:addImage(img, path)
assert(tex)
img:release()
end
end
return M
|
--The Direction of the file (made by NoNameDude)
local ip_file = minetest.get_worldpath().."/ip_file.txt"
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
local ip = minetest.get_player_ip(name)
--If its an ip then it gets saved (made by NoNameDude)
if ip then
local logFile = io.open(ip_file, 'a')
logFile:write("Player ",name," has the ip [",ip,"].\n")
logFile:close()
--shows you if something went wrong (made by NoNameDude)
else
print("There was an error with "..name..". ")
end
end)
|
local image = nil
local dungeonWindow = nil
local dungeon1 = nil
function init()
connect(g_game, { onGameEnd = onGameEnd })
dungeonWindow = g_ui.displayUI('dungeon')
dungeonWindow:hide()
-- lootWindow:addAnchor(AnchorLeft, 'gameLeftPanel', AnchorRight)
-- lootWindow:addAnchor(AnchorLeft, "gameMapPanel", AnchorRight)
--lootWindow:addAnchor(AnchorTop, 'topMenu', AnchorBottom)
--lootWindow:addAnchor(AnchorBottom, 'topMenu', AnchorBottom + 70)
dungeonWindow:setHeight(475)
dungeonWindow:setWidth(700)
ProtocolGame.registerExtendedOpcode(68, function(protocol, opcode, buffer)
local strings = string.explode(buffer, '-')
show(strings[1], strings[2])--, strings[3], strings[4], strings[5], strings[6], strings[7], strings[8], strings[9], strings[10], strings[11])--, strings[12], strings[13], strings[14], strings[15], strings[16], strings[17], strings[18], strings[19])
end)
end
function terminate()
disconnect(g_game, { onGameEnd = onGameEnd })
ProtocolGame.unregisterExtendedOpcode(68)
dungeonWindow:destroy()
end
function onGameEnd()
if dungeonWindow:isVisible() then
dungeonWindow:hide()
end
end
function show(image)
addEvent(function() g_effects.fadeIn(dungeonWindow, 350) end)
--fernanda = "/images/dungeons/Shiny Charizard"
--scheduleEvent(function() dungeonWindow:setPhantom(false) end, 250)
-- addEvent(lootWindow:setPhantom(false), 250)
dungeonWindow:show()
dungeonWindow:raise()
dungeonWindow:focus()
dungeonWindow:setImageSource('/images/dungeons/'..image..'.png')
-- dungeonWindow:getChildById('dungeon1'):setImage("/images/dungeons/teste.png")
--lootWindow:getChildById('loot1'):setParent(center)
--catchWindow:getChildById('maguBall'):setItemId(15324)
--catchWindow:getChildById('soraBall'):setItemId(15325)
--catchWindow:getChildById('yumeBall'):setItemId(15326)
--catchWindow:getChildById('duskBall'):setItemId(15327)
--catchWindow:getChildById('taleBall'):setItemId(15330)
--catchWindow:getChildById('moonBall'):setItemId(15331)
--catchWindow:getChildById('netBall'):setItemId(15332)
-- catchWindow:getChildById('premierBall'):setItemId(15334)
-- catchWindow:getChildById('tinkerBall'):setItemId(15335)
-- catchWindow:getChildById('fastBall'):setItemId(15328)
-- catchWindow:getChildById('heavyBall'):setItemId(15329)
-- catchWindow:getChildById('text'):setText(tr('Congratulations!\nYou caught a %s!\nXP: %s', doCorrectString(pokemon), exp))
-- catchWindow:getChildById('pokeballsLabel'):setText(n)
--catchWindow:getChildById('greatballsLabel'):setText(g)
-- catchWindow:getChildById('superballsLabel'):setText(s)
-- catchWindow:getChildById('utraballsLabel'):setText(u)
-- catchWindow:getChildById('saffariballsLabel'):setText(s2)
--addEvent(function() g_effects.fadeOut(lootWindow,7000) end)
scheduleEvent(function() g_effects.fadeOut(dungeonWindow, 500) end, 3000)
-- scheduleEvent(function() lootWindow:setPhantom(true) end, 5000)
-- scheduleEvent(function() lootWindow:hide() end, 6000)
-- catchWindow:getChildById('maguBallsLabel'):setText(magu)
-- catchWindow:getChildById('soraBallsLabel'):setText(sora)
-- catchWindow:getChildById('yumeBallsLabel'):setText(yume)
-- catchWindow:getChildById('duskBallsLabel'):setText(dusk)
-- catchWindow:getChildById('taleBallsLabel'):setText(tale)
-- catchWindow:getChildById('moonBallsLabel'):setText(moon)
-- catchWindow:getChildById('netBallsLabel'):setText(net)
-- catchWindow:getChildById('premierBallsLabel'):setText(premier)
-- catchWindow:getChildById('tinkerBallsLabel'):setText(tinker)
-- catchWindow:getChildById('fastBallsLabel'):setText(fast)
-- catchWindow:getChildById('heavyBallsLabel'):setText(heavy)
-- lootWindow:show()
end
function hide()
addEvent(function() g_effects.fadeOut(dungeonWindow, 250) end)
scheduleEvent(function() dungeonWindow:hide() end, 250)
end
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local common = ReplicatedStorage.common
local lib = ReplicatedStorage.lib
local event = ReplicatedStorage.event
local eAttackActor = event.eAttackActor
local Projectiles = require(common.Projectiles)
local PizzaAlpaca = require(lib.PizzaAlpaca)
local ProjectileCreator = PizzaAlpaca.GameModule:extend("ProjectileCreator")
function ProjectileCreator:fireProjectile(owner, id, origin, direction, metadata)
if not self.recsCore then return end
local model = Projectiles.getModelForId(id)
local projectile = Projectiles.byId[id]
if not model then return end
if not projectile then return end
local newBullet = model:clone()
newBullet.Parent = self.bulletBin
newBullet.CFrame = CFrame.new(origin,origin+(direction.Unit))
self.recsCore:addComponent(newBullet,self.recsCore:getComponentClass("Projectile"), {
id = id,
position = origin,
velocity = direction.Unit * projectile.speed,
gravityScale = projectile.gravityScale,
owner = owner,
fireTime = tick(),
metadata = metadata
})
end
function ProjectileCreator:preInit()
local bulletBin = Instance.new("Folder")
bulletBin.Name = "bullets"
bulletBin.Parent = workspace
self.bulletBin = bulletBin
end
function ProjectileCreator:postInit()
local recsContainer = self.core:getModule("ClientRECSContainer")
recsContainer:getCore():andThen(function(newCore)
self.recsCore = newCore
end)
end
return ProjectileCreator |
return {
title = "Example Blog",
baseUrl = "http://myblog.example/",
languageCode = "en",
}
|
WUMA = WUMA or {}
local WUMADebug = WUMADebug
local WUMALog = WUMALog
WUMA.Files = WUMA.Files or {}
function WUMA.Files.Initialize()
--Create Data folder
WUMA.Files.CreateDir(WUMA.DataDirectory)
--Create userfiles folder
WUMA.Files.CreateDir(WUMA.DataDirectory..WUMA.UserDataDirectory)
end
function WUMA.Files.CreateDir(dir)
dir = string.lower(dir)
if not file.IsDir(dir, "DATA") then
file.CreateDir(dir)
end
end
function WUMA.Files.Append(path, text)
path = string.lower(path)
local f = file.Exists(WUMA.DataDirectory..path, "DATA")
if (not f) then
Files.Write(WUMA.DataDirectory..path, text)
return
end
file.Append(path, text)
end
function WUMA.Files.Exists(path)
path = string.lower(path)
return file.Exists(path, "DATA")
end
function WUMA.Files.Delete(path)
path = string.lower(path)
file.Delete(path)
end
function WUMA.Files.Write(path, text)
path = string.lower(path)
file.Write(path, text)
end
function WUMA.Files.Read(path)
path = string.lower(path)
local f = file.Open(path, "r", "DATA")
if not f then return "" end
local str = f:Read(f:Size())
f:Close()
return str or ""
end
|
--主要用于组件的获取 组件的测试
--LuaComponent
LuaComponent = {};
local GameObject = UnityEngine.GameObject;
function LuaComponent:new()
print("LuaComponent:new");
return setmetatable({ set = {} }, { __index = self} );
end
function LuaComponent:getComponent(Obj)
print("LuaComponent:getComponent");
print(Obj);
--添加绑定组件
--Obj:AddComponent(typeof(AudioSource));
Obj:AddComponent(typeof(UnityEngine.AudioSource));
end
return LuaComponent; |
if SERVER then
for _, f in pairs(file.Find("scalar/*", "LUA")) do
AddCSLuaFile("scalar/" .. f)
end
else
Scalar = Scalar or {Data = {}, SCALEFACTOR = {}}
for _, f in pairs(file.Find("scalar/*", "LUA")) do
include("scalar/" .. f)
end
end
|
-- Initialization
vim.cmd("hi clear")
vim.cmd("syntax reset")
vim.g.colors_name = "monokai"
vim.opt.termguicolors = true
require("monokai.theme")
|
function newDirectionButton(x, y, rotation, onHeld, onRelease)
local directionButton = {}
directionButton.x = x
directionButton.y = y
local width, height = 32, 16
if rotation == math.pi / 2 or rotation == math.pi * 3 / 2 then
width, height = 16, 32
directionButton.sides = true
end
directionButton.width = width
directionButton.height = height
directionButton.button = button
directionButton.rotation = rotation
directionButton.held = false
directionButton.onHeld = onHeld
directionButton.onRelease = onRelease
function directionButton:draw()
local graphic = directionalButtonGraphic
if self.held then
graphic = directionalButtonGraphicPressed
end
love.graphics.draw(graphic, self.x + (self:getWidth() / 2), self.y + (self:getHeight() / 2), self.rotation, 1, 1, self:getWidth() / 2, self.getHeight() / 2)
end
function directionButton:touchPressed(id, x, y, pressure)
local offsetX, offsetY = 0, 0
if self.sides then
offsetX, offsetY = self.width / 2, -8
end
return lovia.insideElement(self.x + offsetX, self.y + offsetY, self.width, self.height, x, y)
end
function directionButton:setHeld(id, isHeld, isReleased)
if isHeld then
self.held = id
end
if self.held == id then
if isHeld then
if self.onHeld then
self.onHeld()
end
else
if self.onRelease then
self.onRelease()
end
end
if isReleased then
if self.onRelease then
self.onRelease()
end
end
if not isHeld then
self.held = false
end
end
end
function directionButton:getWidth()
return directionalButtonGraphic:getWidth()
end
function directionButton:getHeight()
return directionalButtonGraphic:getHeight()
end
return directionButton
end |
function print_node (node)
print (string.format ("Node position = [%.2f %.2f %.2f]", node.WorldPosition.x, node.WorldPosition.y, node.WorldPosition.z))
end
function print_bind (bind)
print ("Bind anchor = " .. tostring (bind.Anchor) .. " axis = " .. tostring (bind.Axis))
end
function collision_filter (body1, body2)
print ("Collision filter called")
return true
end
function collision_event_name (event)
if event == Physics.CollisionEventType.Begin then
return "Begin"
elseif event == Physics.CollisionEventType.Process then
return "Process"
elseif event == Physics.CollisionEventType.End then
return "End"
else
return "Unknown"
end
end
function collision_callback (event, body1, body2, point)
print ("Collision callback called for event " .. collision_event_name (event) .. " at point " .. string.format ("[%.2f %.2f %.2f]", point.x, point.y, point.z))
end
function body_collision_callback (event, body1, body2, point)
print ("Body collision callback called for event " .. collision_event_name (event) .. " at point " .. string.format ("[%.2f %.2f %.2f]", point.x, point.y, point.z))
end
function print_material (material)
print (string.format ("Material linear damping = %.2f, angular damping = %.2f, friction = %.2f, anisotropic friction = %.2f %.2f %.2f, restitution = %.2f", material.LinearDamping, material.AngularDamping, material.Friction,
material.AnisotropicFriction.x, material.AnisotropicFriction.y, material.AnisotropicFriction.z, material.Restitution))
end
function print_shape_list_shape_info (list, index)
print (string.format ("Shape list %d shape margin = %.2f position is %s orientation is %s", index, list:Shape (index).Margin, tostring (list:ShapePosition (index)), tostring (list:ShapeOrientation (index))))
end
function body_update_transform_callback (body)
print ("body transform updated")
end
function print_rigid_body (body)
print ("Rigid body:")
print (string.format (" mass %.2f", body.Mass))
print (" mass space inertia tensor " .. tostring (body.MassSpaceInertiaTensor))
print (" world position " .. tostring (body.WorldPosition))
print (" world orientation " .. tostring (body.WorldOrientation))
print (string.format (" sleep linear velocity %.2f", body.SleepLinearVelocity))
print (string.format (" sleep angular velocity %.2f", body.SleepAngularVelocity))
print (string.format (" ccd motion threshold %.2f", body.CcdMotionThreshold))
print (string.format (" shape margin %.2f", body.Shape.Margin))
print (string.format (" material linear damping %.2f", body.Material.LinearDamping))
print (" collision group '" .. body.CollisionGroup .. "'")
print (" linear velocity " .. tostring (body.LinearVelocity))
print (" angular velocity " .. tostring (body.AngularVelocity))
print (" flags:")
print (" frozen position x = " .. tostring (body:GetFlag (Physics.RigidBodyFlag.FrozenPositionX)))
print (" frozen position y = " .. tostring (body:GetFlag (Physics.RigidBodyFlag.FrozenPositionY)))
print (" frozen position z = " .. tostring (body:GetFlag (Physics.RigidBodyFlag.FrozenPositionZ)))
print (" frozen position = " .. tostring (body:GetFlag (Physics.RigidBodyFlag.FrozenPosition)))
print (" frozen rotation x = " .. tostring (body:GetFlag (Physics.RigidBodyFlag.FrozenRotationX)))
print (" frozen rotation y = " .. tostring (body:GetFlag (Physics.RigidBodyFlag.FrozenRotationY)))
print (" frozen rotation z = " .. tostring (body:GetFlag (Physics.RigidBodyFlag.FrozenRotationZ)))
print (" frozen rotation = " .. tostring (body:GetFlag (Physics.RigidBodyFlag.FrozenRotation)))
print (" kinematic = " .. tostring (body:GetFlag (Physics.RigidBodyFlag.Kinematic)))
end
function test_physics()
print "Physics test"
local manager = Engine.PhysicsManagers.Get ("PhysicsManager")
print ("Manager description is '" .. manager.Description .. "'")
local scene = manager:CreateScene ()
local material = manager:CreateMaterial ()
local box_shape = manager:CreateBoxShape (vec3 (1, 2, 3))
local sphere_shape = manager:CreateSphereShape (1)
local capsule_shape = manager:CreateCapsuleShape (1, 2)
local plane_shape = manager:CreatePlaneShape (vec3 (0, 1, 0), 10)
local shape_list = Physics.ShapeList.Create ()
print ("Shape list size = " .. shape_list.Size)
shape_list:Add (box_shape)
shape_list:Add (sphere_shape, vec3 (1, 2, 3))
shape_list:Add (capsule_shape, quat (1, 2, 3, 4))
shape_list:Add (plane_shape, vec3 (5, 6, 7), quat (1, 2, 3, 4))
local compound_shape = manager:CreateCompoundShape (shape_list)
print ("Shape list size = " .. shape_list.Size)
print_shape_list_shape_info (shape_list, 0)
print_shape_list_shape_info (shape_list, 1)
print_shape_list_shape_info (shape_list, 2)
print_shape_list_shape_info (shape_list, 3)
shape_list:Remove (1)
print ("Shape list size = " .. shape_list.Size)
shape_list:Clear ()
print ("Shape list size = " .. shape_list.Size)
print_material (material)
material.LinearDamping = 1
material.AngularDamping = 2
material.Friction = 3
material.AnisotropicFriction = vec3 (4, 5, 6)
material.Restitution = 7
print_material (material)
print (string.format ("box_shape margin = %.2f", box_shape.Margin))
box_shape.Margin = 5
print ("new box_shape margin = " .. box_shape.Margin)
print ("Scene gravity = " .. tostring (scene.Gravity))
print (string.format ("Scene simulation step = %0.2f", scene.SimulationStep))
scene.Gravity = vec3 (0, -8, 0)
scene.SimulationStep = 0.1
print ("Scene gravity = " .. tostring (scene.Gravity))
print (string.format ("Scene simulation step = %0.2f", scene.SimulationStep))
local body1 = scene:CreateRigidBody (box_shape, 1)
local body2 = scene:CreateRigidBody (plane_shape, 2)
print_rigid_body (body1)
print_rigid_body (body2)
body1.Mass = 4
body1.MassSpaceInertiaTensor = vec3 (1, 2, 3)
body1.WorldPosition = vec3 (2, 3, 4)
body1.WorldOrientation = quat (1, 2, 3, 4)
body1.SleepLinearVelocity = 5
body1.SleepAngularVelocity = 6
body1.CcdMotionThreshold = 7
body1.CollisionGroup = "object"
body1.LinearVelocity = vec3 (7, 8, 9)
body1.AngularVelocity = vec3 (8, 9, 10)
body1.Material = material
body1:SetFlag (Physics.RigidBodyFlag.FrozenPositionX, true)
body1:SetFlag (Physics.RigidBodyFlag.FrozenRotationY, true)
body1:SetFlag (Physics.RigidBodyFlag.Kinematic, true)
body2.CollisionGroup = "ground"
print_rigid_body (body1)
body1:SetFlag (Physics.RigidBodyFlag.FrozenPositionX, true)
body1:SetFlag (Physics.RigidBodyFlag.FrozenPositionY, true)
body1:SetFlag (Physics.RigidBodyFlag.FrozenPositionZ, true)
body1:SetFlag (Physics.RigidBodyFlag.FrozenRotation, true)
body1:SetFlag (Physics.RigidBodyFlag.FrozenRotationY, false)
print_rigid_body (body1)
body1:SetFlag (Physics.RigidBodyFlag.FrozenPosition, false)
body1:SetFlag (Physics.RigidBodyFlag.FrozenRotation, false)
body1:SetFlag (Physics.RigidBodyFlag.Kinematic, false)
local joint_bind_1 = Physics.JointBind.Create (body1)
local joint_bind_2 = Physics.JointBind.Create (body1, vec3 (1, 2, 3))
local joint_bind_3 = Physics.JointBind.Create (body2, vec3 (2, 3, 4), vec3 (1, 0, 0))
print_bind (joint_bind_1)
print_bind (joint_bind_2)
print_bind (joint_bind_3)
joint_bind_1.Body = body2
joint_bind_1.Anchor = vec3 (3, 4, 5)
joint_bind_1.Axis = vec3 (0, 1, 0)
print_bind (joint_bind_1)
local spherical_joint = scene:CreateSphericalJoint (joint_bind_1, joint_bind_2)
local cone_twist_joint_1 = scene:CreateConeTwistJoint (joint_bind_1, joint_bind_2)
local cone_twist_joint_2 = scene:CreateConeTwistJoint (joint_bind_1, joint_bind_2, 10)
local cone_twist_joint_3 = scene:CreateConeTwistJoint (joint_bind_1, joint_bind_2, 20, 30)
local hinge_joint = scene:CreateHingeJoint (joint_bind_1, joint_bind_2)
local prismatic_joint = scene:CreatePrismaticJoint (joint_bind_1, joint_bind_2)
print ("hinge joint bodies count = " .. hinge_joint.BodiesCount)
local filter1 = scene:AddCollisionFilter ("*", "*", true)
local filter2 = scene:AddCollisionFilter ("*", "ground", false, Physics.Scene.CreateCollisionFilter (collision_filter))
scene:RemoveCollisionFilter (filter1)
scene:RemoveAllCollisionFilters ()
local filter3 = scene:AddCollisionFilter ("*", "*", true, Physics.Scene.CreateCollisionFilter (collision_filter))
local callback_connection = scene:RegisterCollisionCallback ("*", "*", Physics.CollisionEventType.Begin, Physics.Scene.CreateCollisionCallback (collision_callback))
local body_transform_connection = body1:RegisterTransformUpdateCallback (Physics.RigidBody.CreateTransformUpdateCallback (body_update_transform_callback))
local body_collision_connection = body1:RegisterCollisionCallback ("*", Physics.CollisionEventType.Begin, Physics.RigidBody.CreateCollisionCallback (body_collision_callback))
local node = Scene.Node.Create ()
print_node (node)
scene:PerformSimulation (1)
local node_controller = Scene.Controllers.SyncPhysicsToNode.Create (node, body1)
print_node (node)
node:Update (Xtl.Rational.LongLong.Create (1, 10))
print_node (node)
end
function test ()
test_physics ()
end
|
local Tunnel = module("vrp", "lib/Tunnel")
local Proxy = module("vrp", "lib/Proxy")
MySQL = module("vrp_mysql", "MySQL")
cfg = module("vrp", "cfg/garages")
vehicles = cfg.garage_types
vRP = Proxy.getInterface("vRP")
vRPclient = Tunnel.getInterface("vRP","vRP_carcrusher")
vRPcc = {}
Tunnel.bindInterface("vRP_carcrusher",vRPcc)
Proxy.addInterface("vRP_carcrusher",vRPcc)
vRPccC = Tunnel.getInterface("vRP_carcrusher","vRP_carcrusher")
MySQL.createCommand("vRP/del_vehicle","DELETE FROM vrp_user_vehicles WHERE user_id = @user_id AND vehicle = @vehicle")
AddEventHandler("vRP:playerSpawn",function(user_id,source,first_spawn)
vRPclient.addBlip(source,{-421.03393554688, -1710.8310546875, 19.439516067504, 68, 49, "Vehicle Crusher"})
end)
RegisterServerEvent("crushVehicle")
AddEventHandler("crushVehicle", function(vtype, vname, vehPrice)
local user_id = vRP.getUserId({source})
vRPclient.despawnGarageVehicle(source,{vtype,15})
MySQL.execute("vRP/del_vehicle", {user_id = user_id, vehicle = vname})
vRPclient.notify(source, {"~w~[CRUSHER] ~g~You scrapped the vehicle and received ~r~$"..vehPrice})
vRP.giveMoney({user_id, vehPrice})
end)
function vRPcc.getVehiclesPrices(vname)
thePrice = 0
vehName = ""
for i, v in pairs(vehicles) do
for ix, vx in pairs(v) do
if(tostring(ix) ~= "_config") and (tostring(ix) == vname)then
vehName = tostring(vx[1])
thePrice = tonumber(vx[2])
if(thePrice == nil) or (thePrice <= 0)then
thePrice = 0
else
thePrice = math.ceil(thePrice*0.50)
end
end
end
end
return thePrice, vehName
end |
local api, time, delay, fn = ...
local stamp = time.stamp + delay
api.log(2, 'scheduling timer %.2f %s', stamp, tostring(fn))
time.timers:push(stamp, fn)
|
local items = { }
items.scrap1 = {
type = 'scrap1',
itemType = 'corpse',
name = 'Scrap',
img = 'scrap1',
color = {0.85, 0.85, 0.85},
stats = {weight = 55},
stackable = true,
desc = 'A pile of damaged scrap.'
}
items.corpse1 = {
type = 'corpse1',
itemType = 'corpse',
name = 'Corpse',
img = 'corpse1',
color = {0.88, 0, 0},
stats = {weight = 55},
stackable = true,
desc = 'A mangled corpse.',
}
items.chest1 = {
type = 'chest1',
itemType = 'container',
name = 'Chest',
img = 'chest1',
color = {0.89, 0.87, 0.5},
stats = {weight = 15, container = true},
container = { },
stackable = false,
desc = 'A simple chest.',
}
items.woodenbuckler = {
type = 'woodenbuckler',
itemType = 'shield',
name = 'Wooden Buckler',
img = 'buckler1',
color = {0.5, 0.3, 0.2},
stats = {weight = 3, shield = true, blockChance = 10},
stackable = false,
desc = 'A small buckler carved from wood. Common in the slums.\n\nBlock Chance: 10%\nWeight: 3',
getDisplayName = function (self)
return ' [10%]'
end
}
items.simpleshield = {
type = 'simpleshield',
itemType = 'shield',
name = 'Simple Shield',
img = 'shield1',
color = {0.75, 0.75, 0.75},
stats = {weight = 5, shield = true, blockChance = 15},
stackable = false,
desc = 'A simple shield constructed from scrap metal.\n\nBlock Chance: 15%\nWeight: 5',
getDisplayName = function (self)
return ' [15%]'
end,
}
items.bullet = {
type = 'bullet',
itemType = 'ammo',
name = 'Depleted Uranium Round',
img = 'bullet1',
color = {0, 1, 0.25},
stats = {weight = 0},
stackable = true,
desc = 'A 9mm depleted uranium round inteded for use in an old fashioned ballistics weapon.\n\nWeight: 1',
getDisplayName = function (self)
return ''
end,
}
items.ballisticrifle = {
type = 'ballisticrifle',
itemType = 'ranged',
name = 'Ballistic Rifle',
img = 'rifle2',
color = {0.85, 0.85, 0.85},
stats = {weight = 15, damage = {1,6,0}, equipSlot = 'ranged', rangedWeapon = {penetration = 11, inaccuracy = 0.16, maxAmmo = 15, currentAmmo = 0, ammoType = 'bullet'}},
stackable = false,
desc = 'A standard ballistics rifle. Fires depleted uranium bullets.\n\nDamage: 1d6+0\nWeight: 15',
getDisplayName = function (self)
return ' [1d6+0] [' .. self.item.stats.rangedWeapon.currentAmmo .. ' / ' .. self.item.stats.rangedWeapon.maxAmmo ..']'
end,
}
items.huntingrifle = {
type = 'huntingrifle',
itemType = 'ranged',
name = 'Hunting Rifle',
img = 'rifle1',
color = {0.85, 0.85, 0.85},
stats = {weight = 15, damage = {2,3,0}, equipSlot = 'ranged', rangedWeapon = {penetration = 13, inaccuracy = 0.12, maxAmmo = 1, currentAmmo = 0, ammoType = 'bullet'}},
stackable = false,
desc = 'An old hunting rifle. Fires depleted uranium bullets.\n\nDamage: 2d3+0\nWeight: 15',
getDisplayName = function (self)
return ' [2d3+0] [' .. self.item.stats.rangedWeapon.currentAmmo .. ' / ' .. self.item.stats.rangedWeapon.maxAmmo ..']'
end,
}
items.ballisticpistol = {
type = 'ballisticpistol',
itemType = 'ranged',
name = 'Ballistics Pistol',
img = 'pistol1',
color = {0.85, 0.85, 0.85},
stats = {weight = 5, damage = {1,3,1}, equipSlot = 'ranged', rangedWeapon = {penetration = 9, inaccuracy = 0.22, maxAmmo = 6, currentAmmo = 0, ammoType = 'bullet'}},
stackable = false,
desc = 'An old ballistics pistol. Fires depleted uranium bullets.\n\nDamage: 1d3+0\nWeight: 5',
getDisplayName = function (self)
return ' [1d3+0] [' .. self.item.stats.rangedWeapon.currentAmmo .. ' / ' .. self.item.stats.rangedWeapon.maxAmmo ..']'
end,
}
items.hoe = {
type = 'hoe',
itemType = 'weapon',
name = 'Hoe',
img = 'hoe1',
color = {0.56, 0.62, 0.63},
stats = {weight = 6, damage = {2,3,0}},
stackable = false,
desc = 'A simple hoe used for farming.\n\nDamage: 2d3+0\nWeight: 6',
getDisplayName = function (self)
return ' [2d3+0]'
end,
}
items.plasteelsaber = {
type = 'plasteelsaber',
itemType = 'weapon',
name = 'Plasteel Saber',
img = 'longblade2',
color = {0.56, 0.62, 0.63},
stats = {weight = 3, damage = {2,5,0}},
stackable = false,
desc = 'A molded plasteel blade modeled after a traditional saber.\n\nDamage: 2d5+0\nWeight: 3',
getDisplayName = function (self)
return ' [2d5+0]'
end,
}
items.longsword = {
type = 'longsword',
itemType = 'weapon',
name = 'Longsword',
img = 'longblade1',
color = {0.71, 0.87, 1},
stats = {weight = 3, damage = {1,8,0}},
stackable = false,
desc = 'An older style longsword, fashioned by hand in the slums.\n\nDamage: 1d8+0\nWeight: 1',
getDisplayName = function (self)
return ' [1d8+0]'
end,
}
items.cryoblade = {
type = 'cryoblade',
itemType = 'weapon',
name = 'Cryoblade',
img = 'shortblade2',
color = {0.25, 1, 1},
stats = {weight = 1, damage = {3,2,0}, toHit = 2},
mods = {'balanced'},
stackable = false,
desc = 'A short cryo forged blade.\n\nDamage: 3d2+0\nTo Hit: +2\nWeight: 1',
getDisplayName = function (self)
return ' [3d2+0]'
end,
}
items.switchblade = {
type = 'switchblade',
itemType = 'weapon',
name = 'Switchblade',
img = 'shortblade1',
color = {0.6, 0.67, 0.71},
stats = {weight = 1, damage = {1,5,0}, toHit = 2},
mods = {'balanced'},
stackable = false,
desc = 'A simple switchblade. Easy to use, and even easier to conceal.\n\nDamage: 1d5+0\nTo Hit: +2\nWeight: 1',
getDisplayName = function (self)
return ' [1d5+0]'
end,
}
items.cleatedboots = {
type = 'cleatedboots',
itemType = 'armor',
name = 'Cleated Boots',
img = 'shoe2',
color = {0.5, 0.3, 0.2},
stats = {weight = 1, av = 1, dv = -1, equipSlot = 'feet'},
stackable = false,
desc = 'A pair of cleated boots. Offers great traction.\n\nAV: 1\nDV: -1\nWeight: 1',
getDisplayName = function (self)
return ' [1AV -1DV]'
end,
}
items.sneakers = {
type = 'sneakers',
itemType = 'armor',
name = 'Sneakers',
img = 'shoe1',
color = {0.8, 0.8, 0.3},
stats = {weight = 1, av = 0, dv = 1, equipSlot = 'feet'},
stackable = false,
desc = 'A pair of well fitting sneakers.\n\nAV: 0\nDV: 1\nWeight: 1',
getDisplayName = function (self)
return ' [0AV 1DV]'
end,
}
items.denimjeans = {
type = 'denimjeans',
itemType = 'armor',
name = 'Denim Jeans',
img = 'leggings1',
color = {0.2, 0.4, 0.6},
stats = {weight = 3, av = 0, dv = 1, equipSlot = 'legs'},
stackable = false,
desc = 'A pair of worn denim jeans. Frayed near the ankles.\n\nAV: 0\nDV: 1\nWeight: 3',
getDisplayName = function (self)
return ' [0AV 1DV]'
end,
}
items.leathergloves = {
type = 'leathergloves',
itemType = 'armor',
name = 'Leather Gloves',
img = 'gloves1',
color = {0.79, 0.56, 0.39},
stats = {weight = 1, av = 1, dv = 0, equipSlot = 'gloves'},
stackable = false,
desc = 'A pair of leather gloves made for hard labor.\n\nAV: 1\nnDV: 0\nWeight: 1',
getDisplayName = function (self)
return ' [1AV 0DV]'
end,
}
items.worncloak = {
type = 'worncloak',
itemType = 'armor',
name = 'Worn Cloak',
img = 'cloak1',
color = {0.89, 0.66, 0.49},
stats = {weight = 1, av = 0, dv = 1, equipSlot = 'back'},
stackable = false,
desc = 'An old cloak that\'s been worn out and left to gather dust.\n\nAV: 0\nnDV: 1\nWeight: 1',
getDisplayName = function (self)
return ' [0AV 1DV]'
end,
}
items.leatherjacket = {
type = 'leatherjacket',
itemType = 'armor',
name = 'Leather Jacket',
img = 'leatherjacket1',
color = {0.81, 0.58, 0.41},
stats = {weight = 5, av = 1, dv = 0, equipSlot = 'overshirt'},
stackable = false,
desc = 'A battered leather jacket. Popular among street punks and laborers.\n\nAV: 1\nDV: 0\nWeight: 5',
getDisplayName = function (self)
return ' [1AV 0DV]'
end,
}
items.kevlarvest = {
type = 'kevlarvest',
itemType = 'armor',
name = 'Kevlar Vest',
img = 'kevlar1',
color = {0.46, 0.47, 0.61},
stats = {weight = 15, av = 3, dv = -1, equipSlot = 'overshirt'},
stackable = false,
desc = 'A thick vest made from woven kevlar. Offers significant protection.\n\nAV: 3\nDV: -1\nWeight: 15',
getDisplayName = function (self)
return ' [3AV -1DV]'
end,
}
items.polyestershirt = {
type = 'polyestershirt',
itemType = 'armor',
name = 'Polyester Shirt',
img = 'shirt1',
color = {0.61, 0.46, 0.46},
stats = {weight = 1, av = 0, dv = 1, equipSlot = 'undershirt'},
stackable = false,
desc = 'A mass produced polyester shirt sporting a logo near the collar.\n\nAV: 0\nDV: 1\nWeight: 1',
getDisplayName = function (self)
return ' [0AV 1DV]'
end,
}
items.clothshirt = {
type = 'clothshirt',
itemType = 'armor',
name = 'Cloth Shirt',
img = 'shirt1',
color = {0.76, 0.68, 0.46},
stats = {weight = 1, av = 0, dv = 2, equipSlot = 'undershirt'},
stackable = false,
desc = 'An authentic cloth shirt. Comfortable, and conforming.\n\nAV: 0\nDV: 2\nWeight: 1',
getDisplayName = function (self)
return ' [0AV 2DV]'
end,
}
items.healthneedle = {
type = 'healthneedle',
itemType = 'drug',
name = 'Hypodermic Needle',
img = 'needle1',
color = {1, 0.19, 0.19},
stats = {weight = 0, fluid = 'morphine'},
stackable = true,
applicable = true,
amountUsedPerApplication = 1,
applicationMessage = {
player = ' stuck the needle into ',
other = ' sticks the needle into ',
},
effectMessage = {
player = ' chest feels numb and the pain begins to fade. ',
other = ' begins to feel better. '
},
desc = 'A clean hypodermic needle filled with Morphine. Can be injected into the skin, the effects of which will take place immediately.\n\nExample Effect\nExample Effect\nExample Effect',
getDisplayName = function (self)
return ' [Morphine]'
end,
application = function (self, appliedBy, target)
target.ReferenceStateGame.getCreature().addCurrentHealth(target, 25)
end,
aiCheck = function (self, creature, targetself)
if targetself and creature.currentHealth <= creature.ReferenceStateGame.getCreature().getMaxHealth(creature) * 0.5 then
if love.math.random(1, 100) <= 25 then
return true
end
end
return false
end
}
items.staminaneedle = {
type = 'staminaneedle',
itemType = 'drug',
name = 'Hypodermic Needle',
img = 'needle1',
color = {0.19, 1, 0.19},
stats = {weight = 0, fluid = 'adrenaline'},
stackable = true,
applicable = true,
amountUsedPerApplication = 1,
applicationMessage = {
player = ' stuck the needle into ',
other = ' sticks the needle into ',
},
effectMessage = {
player = ' chest heats up as your muscles fill with energy. ',
other = ' begins to frantically shake. '
},
desc = 'A clean hypodermic needle filled with Adrenaline. Can be injected into the skin, the effects of which will take place immediately.\n\nExample Effect\nExample Effect\nExample Effect',
getDisplayName = function (self)
return ' [Adrenaline]'
end,
application = function (self, appliedBy, target)
end,
}
items.deathneedle = {
type = 'deathneedle',
itemType = 'drug',
name = 'Hypodermic Needle',
img = 'needle1',
color = {1, 1, 1},
stats = {weight = 0, fluid = 'fentanyl'},
stackable = true,
applicable = true,
amountUsedPerApplication = 1,
applicationMessage = {
player = ' stuck the needle into ',
other = ' sticks the needle into ',
},
effectMessage = {
player = ' chest chills as your heart begins to ache. ',
other = ' begins to look sick. '
},
desc = 'A clean hypodermic needle filled with Fentanyl. Can be injected into the skin, the effects of which will take place immediately.\n\nExample Effect\nExample Effect\nExample Effect',
getDisplayName = function (self)
return ' [Fentanyl]'
end,
application = function (self, appliedBy, target)
if appliedBy ~= target then
target.target = appliedBy
end
target.ReferenceStateGame.getCreature().takeDamage(target, 25, 'internal')
end,
aiCheck = function (self, creature, targetself)
if not targetself and creature.target then
local targets = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}
for i = 1, # targets do
if creature.target.x == creature.x + targets[i][1] and creature.target.y == creature.y + targets[i][2] then
if love.math.random(1, 100) <= 20 then
return true
end
end
end
end
return false
end
}
return items |
-- 转码到URL。注意特殊字符"="等
local function escape(s)
local str = string.gsub(s, "[&=+%%%c]", function(c)
return string.format("%%%02X", string.byte(c))
end)
str = string.gsub(str, " ", "+")
return str
end
-- 从URL转码
local function unescape(s)
local str = string.gsub(s, "+", " ")
str = string.gsub(str, "%%(%x%x)", function(h)
return string.char(tonumber(h, 16))
end)
return str
end
-- 解码参数
local function decode(s)
local cgi = {}
for k, v in string.gmatch(s, "([^&=]+)=([^&=]+)") do
k = unescape(k)
v = unescape(v)
cgi[k] = v
end
return cgi
end
-- 编码参数
local function encode(t)
local b = {}
for k, v in pairs(t) do
b[#b + 1] = string.format("%s=%s", escape(k), escape(v))
end
return table.concat(b, "&")
end
local function test()
local js = require("cjson.safe")
local s = "name=al&query=a%2Bb+%3D+c&q=yes+or+no"
local ns = unescape(s)
local ens = escape(ns)
io.write("原字符串:", s, "\n")
io.write("解码后 = ", ns, "\n")
io.write("解码后再编码 = ", ens, "\n")
io.write(s, " != ", ens, "\n")
local t = decode(s)
print(js.encode(t))
print(encode(t))
end
test()
return {
decode = decode,
encode = encode,
} |
-- See LICENSE for terms
local Resources = Resources
local T = T
local table = table
local properties = {}
local c = 0
local resources = table.icopy(UniversalStorageDepot.storable_resources)
resources[#resources+1] = "WasteRock"
if g_AvailableDlc.armstrong and not table.find(resources, "Seeds") then
resources[#resources+1] = "Seeds"
end
for i = 1, #resources do
local res = resources[i]
c = c + 1
properties[c] = PlaceObj("ModItemOptionNumber", {
"name", "MinResourceAmount_" .. res,
"DisplayName", table.concat(T(302535920011754, "Min Resource Amount") .. ": " .. T(Resources[res].display_name)),
"Help", T(302535920011755, "If stored resource is below this amount then don't remove resource from depot."),
"DefaultValue", 0,
"MinValue", 0,
"MaxValue", 10000,
"StepSize", 10,
})
end
local CmpLower = CmpLower
local _InternalTranslate = _InternalTranslate
table.sort(properties, function(a, b)
return CmpLower(_InternalTranslate(a.DisplayName), _InternalTranslate(b.DisplayName))
end)
return properties
|
Constraint =
{
Properties=
{
radius = 0.03, --[0,1,0.1,"Attachment sphere radius"]
damping = 0,
bNoSelfCollisions = 1, --[0,1,1,"Ignore collisions between attached objects"]
bUseEntityFrame=1, --[0,1,1,"Use the first (lightest) entity coordinate frame instead of the constraint's"]
max_pull_force=0, --[0,1000000,0.1,"Linear force limit, 0=no limit"]
max_bend_torque=0, --[0,1000000,0.1,"Rotational force limit, 0=no limit"]
bConstrainToLine=0, --[0,1,1,"Mutually exclusive with constrain to plane and fully"]
bConstrainToPlane=0, --[0,1,1,"Mutually exclusive with constraint to line and fully"]
bConstrainFully=1, --[0,1,1,"Translation is fully disabled; mutually exclusive with line and plane"]
bNoRotation=0, --[0,1,1,"Rotation is fully disabled"]
Limits = {
x_min = 0, --[-180,180,0.1,"Minimal twist angle or linear offset if constrained to line. If x_min and x_max are 0, twist is locked, unless yz is also 0, which disables limits"]
x_max = 0, --[-180,180,0.1,"Maximal twist angle or linear offset if constrained to line. If x_min and x_max are 0, twist is locked, unless yz is also 0, which disables limits"]
yz_max = 0, --[0,90,0.1,"Maximal bend angle (minimal is always 0). If 0, bending is locked, unless x_min and x_max are also 0, which disables limits"]
}
},
numUpdates = 0,
Editor=
{
Icon="Magnet.bmp",
ShowBounds = 1,
},
}
function Constraint:OnReset()
--Log("%s:OnReset() idEnt: %s idConstr: %s broken: %s", self:GetName(), tostring(self.idEnt),
-- tostring(self.idConstr), tostring(self.broken))
--if (self.idConstr) then
--System.GetEntity(self.idEnt):SetPhysicParams(PHYSICPARAM_REMOVE_CONSTRAINT, { id=self.idConstr })
--end
self.idEnt = nil
self.idConstr = nil
self.broken = nil
self.numUpdates = 0
self:SetFlags(ENTITY_FLAG_CLIENT_ONLY,0);
end
function Constraint:Apply()
--Log("%s:Apply() idEnt: %s idConstr: %s broken: %s", self:GetName(), tostring(self.idEnt),
-- tostring(self.idConstr), tostring(self.broken))
local ConstraintParams = {pivot={},frame0={},frame1={}};
if self.idEnt then
elseif (not self.broken) then
local ents = Physics.SamplePhysEnvironment(self:GetPos(), self.Properties.radius);
if (ents[1] and ents[6]) then
CopyVector(ConstraintParams.pivot, self:GetPos());
if self.Properties.bUseEntityFrame==1 then
CopyVector(ConstraintParams.frame1, ents[1]:GetAngles());
else
CopyVector(ConstraintParams.frame1, self:GetAngles());
end
CopyVector(ConstraintParams.frame0, ConstraintParams.frame1);
ConstraintParams.entity_part_id_1 = ents[2];
ConstraintParams.phys_entity_id = ents[6];
ConstraintParams.entity_part_id_2 = ents[5];
ConstraintParams.xmin = self.Properties.Limits.x_min;
ConstraintParams.xmax = self.Properties.Limits.x_max;
ConstraintParams.yzmin = 0;
ConstraintParams.yzmax = self.Properties.Limits.yz_max;
ConstraintParams.ignore_buddy = self.Properties.bNoSelfCollisions;
ConstraintParams.damping = self.Properties.damping;
ConstraintParams.sensor_size = self.Properties.radius;
ConstraintParams.max_pull_force = self.Properties.max_pull_force;
ConstraintParams.max_bend_torque = self.Properties.max_bend_torque;
ConstraintParams.line = self.Properties.bConstrainToLine;
ConstraintParams.plane = self.Properties.bConstrainToPlane;
ConstraintParams.no_rotation = self.Properties.bNoRotation;
ConstraintParams.full = self.Properties.bConstrainFully;
self.idConstr = ents[1]:SetPhysicParams(PHYSICPARAM_CONSTRAINT, ConstraintParams);
self.idEnt = ents[1].id;
else
self:SetTimer(1,1);
end
end
end
function Constraint:OnTimer()
if (self.numUpdates < 10) then
self:Apply();
self.numUpdates = self.numUpdates+1;
end
end
function Constraint:OnLevelLoaded()
--Log("%s:OnLevelLoaded() idEnt: %s idConstr: %s broken: %s", self:GetName(), tostring(self.idEnt),
-- tostring(self.idConstr), tostring(self.broken))
if ((not self.broken) and (not self.idConstr)) then
self.numUpdates = 0
self.idEnt = nil
self.idConstr = nil
self:Apply()
end
end
function Constraint:OnPropertyChange()
self:OnReset()
end
function Constraint:OnSpawn()
self:OnReset()
end
function Constraint:Event_ConstraintBroken(sender)
--Log("%s:Event_ConstraintBroken() idEnt: %s idConstr: %s broken: %s", self:GetName(), tostring(self.idEnt),
-- tostring(self.idConstr), tostring(self.broken))
if self.idEnt then
System.GetEntity(self.idEnt):SetPhysicParams(PHYSICPARAM_REMOVE_CONSTRAINT, { id=self.idConstr });
self.idEnt = nil
self.idConstr = nil
end
self.broken = true
self:KillTimer(1)
BroadcastEvent(self, "ConstraintBroken")
end
function Constraint:OnSave( props )
--Log("%s:OnSave() idEnt: %s idConstr: %s broken: %s", self:GetName(), tostring(self.idEnt),
-- tostring(self.idConstr), tostring(self.broken))
props.broken = self.broken
props.idEnt = self.idEnt
props.idConstr = self.idConstr
end
function Constraint:OnLoad( props )
self.broken = props.broken
self.idEnt = props.idEnt
self.idConstr = props.idConstr
--Log("%s:OnLoad() idEnt: %s idConstr: %s broken: %s", self:GetName(), tostring(self.idEnt),
-- tostring(self.idConstr), tostring(self.broken))
end
function Constraint:OnDestroy()
end
Constraint.FlowEvents =
{
Inputs =
{
ConstraintBroken = { Constraint.Event_ConstraintBroken, "bool" },
},
Outputs =
{
ConstraintBroken = "bool",
},
}
|
local a
a = d and e and f and a and g and h and i
a = d or e or f or a or g or h or i
|
local module = {}
function module.nill()
return nil
end
function module.cons(x,xs)
return {head = x, tail = xs}
end
function module.case(xs,f,g)
if not xs then
return nil
else
return g(xs.head, xs.tail)
end
end
function module.show(xs)
if not xs then
return "[]"
else
return tostring(xs.head) .. ":" .. module.show(xs.tail)
end
end
function module.map(f,xs)
module.case(xs,
nill,
function(y,ys)
module.cons(f(y), module.map(f,ys))
end
)
end
local function f(x)
return 3 * x + 1
end
print(module.show({head=1,tail={head=2,tail={head=3,tail=nil}}}))
print(module.show(module.map(f, {head=1,tail={head=2,tail={head=3,tail=nil}}})))
return module
|
--[[
docs:
https://github.com/minetest/minetest/blob/master/doc/lua_api.txt#L1683
]]--
-- this stuff will be seperate from the rest when the seperate files are put into one
local data = { -- window size
width = 15,
height = 10,
}
local form_esc = minetest.formspec_escape -- shorten the function
local modstorage = core.get_mod_storage()
local function create_tabs(selected)
return "tabheader[0,0;_option_tabs_;" ..
" LUA EDITOR ,FORMSPEC EDITOR, LUA CONSOLE , FILES , STARTUP , FUNCTIONS , HELP ;"..selected..";;]"
end
local function copy_table(table)
local new = {}
for i, v in pairs(table) do
if type(v) == "table" then
v = copy_table(v)
end
new[i] = v
end
return new
end
---------- ----------
-- FORMSPEC EDITOR START --
---------- ----------
local widg_list = {"Button", "DropDown", "CheckBox", "Slider", "Tabs", "TextList", "Table", "Field", "TextArea", "InvList", "Label", "Image", "Box", "Tooltip", "Container"} -- all widget options
local widgets = nil -- stores all widget data for the current file
local selected_widget = 1 -- the widget/tab currently being edited
local new_widg_tab = false -- so the new widget tab can be displayed without moving the selection
local main_ui_form -- make this function global to the rest of the program
local current_ui_file = modstorage:get_string("_GUI_editor_selected_file") -- file name of last edited file
if current_ui_file == "" then -- for first ever load
current_ui_file = "new"
modstorage:set_string("_GUI_editor_selected_file", current_ui_file)
modstorage:set_string("_GUI_editor_file_"..current_ui_file, dump({{type="Display", name="", width=5, height=5, width_param=false, height_param=false, left=0.5, top=0.5,
position=false, background=false, colour="#000000aa", fullscreen=false, colour_tab=false,
col={col=false, bg_normal="#f0fa", bg_hover="#f0fa", set_border=false, border="#f0fa", set_tool=false, tool_bg="#f0fa", tool_font="#f0fa"}}}))
end
local function reload_ui() -- update the display, and save the file
modstorage:set_string("_GUI_editor_file_"..current_ui_file, dump(widgets))
minetest.show_formspec("ui_editor:main", main_ui_form())
end
local function load_UI(name) -- open/create a ui file
current_ui_file = name
modstorage:set_string("_GUI_editor_selected_file", current_ui_file)
_, widgets = pcall(loadstring("return "..modstorage:get_string("_GUI_editor_file_"..current_ui_file)))
if widgets == nil then
widgets = {{type="Display", name="", width=5, height=5, width_param=false, height_param=false, left=0.5, top=0.5,
position=false, background=false, colour="#000000aa", fullscreen=false, colour_tab=false,
col={col=false, bg_normal="#f0fa", bg_hover="#f0fa", set_border=false, border="#f0fa", set_tool=false, tool_bg="#f0fa", tool_font="#f0fa"}}}
end
end
load_UI(current_ui_file)
--widgets = {{type="Display", name="", width=5, height=5, width_param=false, height_param=false, left=0.5, top=0.5, position=false, background=false, colour="#000000aa", fullscreen=false, colour_tab=false, col={col=false, bg_normal="#f0fa", bg_hover="#f0fa", set_border=false, border="#f0fa", set_tool=false, tool_bg="#f0fa", tool_font="#f0fa"}} }
----------
-- UI DISPLAY
----------
-- generates the preview of the UI being edited
local function generate_ui()
local width = data.width-5 -- the size that is needed for the final formspec size, so large formspecs can be previewed
local height = data.height
-- data for calculating positions
local left = {0.1}
local top = {0.1}
local fwidth = {1}
local fheight = {1}
local form = ""
local boxes = "" -- because I can't add to form in get_rect() function
local depth = 1 -- container depth
-- calculates the positions of widgets, and creates the position syntax from a widget def
local function get_rect(widget, real, full)
local wleft = 0 -- widget top (etc)
if widget.left_type == "R-" then -- right is value from right side
wleft = left[depth]+fwidth[depth]-widget.left
elseif widget.left_type == "W/" then -- right is width/value from left side
wleft = left[depth]+fwidth[depth]/widget.left
else -- right is value from left side
wleft = left[depth]+widget.left
end
if full then -- container only takes whole numbers as positions.
wleft = math.floor(wleft-left[depth])+left[depth]
end
local wtop = 0
if widget.top_type == "B-" then -- value from bottom
wtop = top[depth]+fheight[depth]-widget.top
elseif widget.top_type == "H/" then -- height/value from top
wtop = top[depth]+(fheight[deformpth]/widget.top)
else -- value from top
wtop = top[depth]+widget.top
end
if full then
wtop = math.floor(wtop-top[depth])+top[depth]
end
if widget.right == nil then -- for widgets with no size option
return wleft..","..wtop..";"
else
local wright = 0
if widget.right_type == "R-" then
wright = left[depth]+fwidth[depth]-widget.right-wleft
elseif widget.right_type == "W/" then
wright = left[depth]+fwidth[depth]/widget.right-wleft
elseif widget.right_type == "R" then -- relative to left
wright = widget.right
else
wright = left[depth]+widget.right-wleft
end
local wbottom = 0
if widget.bottom_type == "B-" then
wbottom = top[depth]+fheight[depth]-widget.bottom-wtop
elseif widget.bottom_type == "H/" then
wbottom = top[depth]+fheight[depth]/widget.bottom-wtop
elseif widget.bottom_type == "R" then
wbottom = widget.bottom
else
wbottom = top[depth]+widget.bottom-wtop
end
if wleft+wright > width then -- stops widgets covering the controlls
boxes = boxes.."box["..width ..","..wtop ..";"..wleft+wright-width..","..wbottom..";#ff0000]" -- shows where it would go
wright = width-wleft
end
if real then
return {left=wleft, top=wtop, width=wright, height=wbottom} -- table uses the calculated values for other things
end
return wleft..","..wtop..";"..wright..","..wbottom..";"
end
end
-- iterate all widgets
for i, v in pairs(widgets) do
if v.type == "Display" then -- defines the size
if v.width < data.width-5.2 then
left = {math.floor(((data.width-5)/2 - v.width/2)*10)/10} -- place the form in the center
else
width = math.floor((v.width+0.2)*10)/10 -- resize for large forms
end
if v.height < data.height-0.2 then -- ^
top = {data.height/2 - v.height/2}
else
height = v.height+0.2
end
fwidth = {v.width}
fheight = {v.height}
form = form ..
-- "box["..left[1]..","..top[1]..";"..v.width..","..v.height..";#000000]" -- this adds it to the form
"box["..left[1]-0.28 ..","..top[1]-0.3 ..";"..v.width+0.38 ..",".. 0.32 ..";#000000]" ..
"box["..left[1]-0.28 ..","..top[1]+v.height..";"..v.width+0.38 ..",".. 0.4 ..";#000000]" ..
"box["..left[1]-0.28 ..","..top[1]..";".. 0.3 ..","..v.height..";#000000]" ..
"box["..left[1]+v.width..","..top[1]..";".. 0.1 ..","..v.height..";#000000]"
if v.background then
form = form .. "bgcolor["..v.colour..";"..tostring(v.fullscreen).."]"
end
if v.col.col then
form = form.."listcolors["..v.col.bg_normal..";"..v.col.bg_hover
if v.col.set_border then
form = form..";"..v.col.border
if v.col.set_tool then
form = form..";"..v.col.tool_bg..";"..v.col.tool_font
end
end
form = form.."]"
end
elseif v.type == "Button" then
if v.image then -- image option
if v.item and not v.exit then
form = form .. "item_image_button["..get_rect(v)..form_esc(v.texture)..";"..i.."_none;"..form_esc(v.label).."]"
else
form = form .. "image_button["..get_rect(v)..form_esc(v.texture)..";"..i.."_none;"..form_esc(v.label).."]"
end
else
form = form .. "button["..get_rect(v)..i.."_none;"..form_esc(v.label).."]"
end
elseif v.type == "Field" then
if v.password then -- password option
form = form .. "pwdfield["..get_rect(v)..i.."_none;"..form_esc(v.label).."]"
else
form = form .. "field["..get_rect(v)..i.."_none;"..form_esc(v.label)..";"..form_esc(v.default).."]"
end
form = form .. "field_close_on_enter["..i.."_none;false]"
elseif v.type == "TextArea" then
form = form .. "textarea["..get_rect(v)..i.."_none;"..form_esc(v.label)..";"..form_esc(v.default).."]"
elseif v.type == "Label" then
if v.vertical then -- vertical option
form = form .. "vertlabel["..get_rect(v)..form_esc(v.label).."]"
else
form = form .. "label["..get_rect(v)..form_esc(v.label).."]"
end
elseif v.type == "TextList" then
local item_str = "" -- convert the list to a sting
for i, item in pairs(v.items) do
item_str = item_str .. form_esc(item)..","
end
if v.transparent then -- transparent option
form = form .. "textlist["..get_rect(v)..i.."_none;"..item_str..";1;True]"
else
form = form .. "textlist["..get_rect(v)..i.."_none;"..item_str.."]"
end
elseif v.type == "DropDown" then
local item_str = "" -- convert the list to a string
for i, item in pairs(v.items) do
item_str = item_str .. form_esc(item)..","
end
form = form .. "dropdown["..get_rect(v)..i.."_none;"..item_str..";"..v.select_id.."]"
elseif v.type == "CheckBox" then
form = form .. "checkbox["..get_rect(v)..i.."_none;"..v.label..";"..tostring(v.checked).."]"
elseif v.type == "Box" then -- a coloured square
form = form .. "box["..get_rect(v)..form_esc(v.colour).."]"
elseif v.type == "Image" then
if v.item then
form = form .. "item_image["..get_rect(v)..form_esc(v.image).."]"
elseif v.background then
if v.fill then
form = form .. "background["..left[1]-0.18 ..","..top[1]-0.22 ..";"..fwidth[1]+0.37 ..","..fheight[1]+0.7 ..";"..form_esc(v.image).."]"
else
form = form .. "background["..get_rect(v)..form_esc(v.image).."]"
end
else
form = form .. "image["..get_rect(v)..form_esc(v.image).."]"
end
elseif v.type == "Slider" then
orientation = "horizontal"
if v.vertical then
orientation = "vertical"
end
form = form .. "scrollbar["..get_rect(v)..orientation..";"..i.."_none;"..v.value.."]"
elseif v.type == "InvList" then
local extras = {["player:"]=1, ["nodemeta:"]=1, ["detached:"]=1} -- locations that need extra info (v.data)
if extras[v.location] then
form = form .. "list["..v.location..form_esc(v.data)..";"..form_esc(v.name)..";"..get_rect(v)..v.start.."]"
if v.ring then -- items can be shift clicked between ring items
form = form .. "listring["..v.location..form_esc(v.data)..";"..form_esc(v.name).."]"
end
else
form = form .. "list["..v.location..";"..form_esc(v.name)..";"..get_rect(v)..v.start.."]"
if v.ring then
form = form .. "listring["..v.location..";"..form_esc(v.name).."]"
end
end
elseif v.type == "Table" then
local cell_str = ""
local column_str = ""
local most_items = 0 -- the amount of rows needed = the most items in a column
for i, c in pairs(v.columns) do
if #c.items > most_items then -- get max length
most_items = #c.items
end
if i > 1 then
column_str = column_str..";"
end
column_str = column_str .. c.type -- add column types
if c.type == "image" then -- add list of available images
for n, t in pairs(c.images) do
column_str = column_str..","..n .."="..form_esc(t)
end
elseif c.type == "color" and c.distance ~= "infinite" then -- add distance that coloures affect
column_str = column_str..",span="..c.distance
end
end
for i=1, most_items do -- create a list from all column's lists
for n, c in pairs(v.columns) do -- create a row from column's items
if n > 1 or i > 1 then
cell_str = cell_str..","
end
local item = c.items[i]
if item == nil then -- blank item if this column doesn't exend as far
item = ""
end
cell_str = cell_str..form_esc(item)
end
end
if column_str:len() > 0 then
form = form .. "tablecolumns["..column_str.."]"
end
form = form .. "table["..get_rect(v)..i.."_none;"..cell_str..";-1]"
elseif v.type == "Tooltip" then
for n, w in pairs(widgets) do
if w.name == v.name and w.type ~= "Tooltip" then
if v.colours then
form = form .. "tooltip["..n.."_none;"..v.text..";"..v.bg..";"..v.fg.."]"
else
form = form .. "tooltip["..n.."_none;"..v.text.."]"
end
end
end
elseif v.type == "Container - Start" then
local rect = get_rect(v, true, true)
left[depth+1] = rect.left -- register the new area
top[depth+1] = rect.top
fwidth[depth+1] = rect.width
fheight[depth+1] = rect.height
depth = depth+1
elseif v.type == "Container - End" then
depth = depth-1 -- go back to the parent area
elseif v.type == "Tabs" then
local capt_str = ""
for i, capt in pairs(v.captions) do
if i > 1 then capt_str = capt_str.."," end
capt_str = capt_str .. form_esc(capt)
end
form = form .. "tabheader["..get_rect(v)..i.."_none;"..capt_str..";"..v.tab..";"..tostring(v.transparent)..";"..tostring(v.border).."]"
end
end
return form..boxes, width+5, height
end
----------
-- Compiling
----------
-- generates a function to create the UI, with parameters
local function generate_function()
local form_esc = function(str) -- escape symbols need to be escaped
return string.gsub(minetest.formspec_escape(str), "\\", "\\\\") -- which have to be escaped...
end
local parameters = {} -- these store info which will be put together at the end
local before_str = ""
local display = {}
local form = ""
local table_items = false
local function name(v) -- converts the name into something that can be used in parameters
n = v.name
if v.type == "InvList" then -- the name of inv lists is used differently
n = v.location.."_"..v.name
end
local new = ""
chars = "abcdefghijklmnopqrstuvwxyz"
chars = chars..string.upper(chars)
for i=1, #n do
local c = n:sub(i,i)
if string.find(chars, c, 1, true) or (string.find("1234567890", c, 1, true) and i ~= 1) then -- numbers only allowed after first char
new = new..c
else
new = new.."_"
end
end
return new
end
local width = {widgets[1].width}
if widgets[1].width_param then -- if size defined from parameters
width = {"width"}
end
local height = {widgets[1].height}
if widgets[1].height_param then
height = {"height"}
end
local dep = 1 -- depth into containers
-- returns a string containing the position and size of a widget, or (hopefully) the most efficient calculation
local function get_rect(widget, real, l, t)
local fwidth = width[dep]
local fheight = height[dep]
local wleft = "0"
if type(fwidth) == "string" or l then -- if the area width (window or continer) will be changed with a parameter
local l_ = l -- if the left of the widget comes from a parameter
if l_ == nil then
l_ = widget.left
end
if widget.left_type == "R-" then -- different position types
wleft = fwidth..'- '..l_
elseif widget.left_type == "W/" then
wleft = fwidth..'/'..l_
else
wleft = l_
end
if type(wleft) == "string" and not real then
wleft = '"..'..wleft..' .."'
end
else
if widget.left_type == "R-" then -- calculation made now if nothing comes from a parameter
wleft = fwidth-widget.left
elseif widget.left_type == "W/" then
wleft = fwidth/widget.left
else
wleft = widget.left
end
end
local wtop = "0" --top
if type(fheight) == "string" or t then
local t_ = t
if t_ == nil then
t_ = widget.top
end
if widget.top_type == "B-" then
wtop = fheight..'- '..t_
elseif widget.left_type == "H/" then
wtop = fheight..'/'..t_
else
wtop = t_
end
if type(wtop) == "string" and not real then
wtop = '"..'..wtop..' .."'
end
else
if widget.top_type == "B-" then
wtop = fheight-widget.top
elseif widget.left_type == "H/" then
wtop = fheight/widget.top
else
wtop = widget.top
end
end
if widget.right == nil then -- for widgets with no size option
return wleft..","..wtop
else
local wright = 0
if type(fwidth) == "string" then -- if the width is changed by a parameter
local l_ = l
if l_ == nil then
l_ = widget.left
end
-- goes through all right types, and for eacg, goes through all left types to get the best calculation.
if widget.right_type == "R-" then -- (I know there is a better way of doing this)
if widget.left_type == "R-" then
wright = fwidth..'- '..widget.right..'-('..fwidth..'- '..l_..')'
elseif widget.left_type == "W/" then
wright = fwidth..'- '..widget.right..'-('..fwidth..'/'..l_..')'
elseif type(l_) == "string" then
wright = fwidth..'- '..widget.right.."- "..l_
else
wright = fwidth..'- '..widget.right+l_
end
elseif widget.right_type == "W/" then
if widget.left_type == "R-" then
wright = fwidth..'/'..widget.right..'-('..fwidth..'- '..l_..')'
elseif widget.left_type == "W/" then
wright = fwidth..'/'..widget.right..'-('..fwidth..'/'..l_..')'
else
wright = fwidth..'/'..widget.right.."- "..l_
end
elseif widget.right_type == "R" then
wright = widget.right
else
if widget.left_type == "R-" then
wright = widget.right..'-('..fwidth..'- '..l_..')'
elseif widget.left_type == "W/" then
wright = widget.right..'-('..fwidth..'/'..l_..')'
elseif type(l) == "string" then
wright = widget.right.."- "..l_
else
wright = widget.right-l_
end
end
if type(wright) == "string" and not real then
wright = '"..'..wright..' .."'
end
elseif l then -- if there is a parameter for the left, but not the width
if widget.right_type == "R-" then
if widget.left_type == "R-" then
wright = fwidth-widget.right..'-('..fwidth..'- '..l..')'
elseif widget.left_type == "W/" then
wright = fwidth-widget.right..'-('..fwidth..'/'..l..')'
else
wright = fwidth-widget.right.."- "..l
end
elseif widget.right_type == "W/" then
if widget.left_type == "R-" then
wright = fwidth..'/'..widget.right..'-('..fwidth..'- '..l..')'
elseif widget.left_type == "W/" then
wright = fwidth..'/'..widget.right..'-('..fwidth..'/'..l..')'
else
wright = fwidth..'/'..widget.right.."- "..l
end
elseif widget.right_type == "R" then
wright = widget.right
else
if widget.left_type == "R-" then
wright = widget.right..'-('..fwidth..'- '..l..')'
elseif widget.left_type == "W/" then
wright = widget.right..'-('..fwidth..'/'..l..')'
else
wright = widget.right.."- "..l
end
end
if type(wright) == "string" and not real then
wright = '"..'..wright..' .."'
end
else -- if all values are known now
if widget.right_type == "R-" then
wright = fwidth-widget.right-wleft
elseif widget.right_type == "W/" then
wright = fwidth/widget.right-wleft
elseif widget.right_type == "R" then
wright = widget.right
else
wright = widget.right-wleft
end
end
local wbottom = 0 -- similar for bottom
if type(fheight) == "string" then
local t_ = t
if t_ == nil then -- if widget's top comes from a parameter (container)
t_ = widget.top
end
if widget.bottom_type == "B-" then
if widget.top_type == "B-" then
wbottom = fheight..'- '..widget.bottom..'-('..fheight..'- '..t_..')'
elseif widget.left_type == "W/" then
wbottom = fheight..'- '..widget.bottom..'-('..fheight..'/'..t_..')'
elseif type(t_) == "string" then
wbottom = fheight..'- '..widget.bottom.."- "..t_
else
wbottom = fheight..'- '..widget.bottom+t_
end
elseif widget.bottom_type == "H/" then
if widget.top_type == "B-" then
wbottom = fheight..'/'..widget.bottom..'-('..fheight..'- '..t_..')'
elseif widget.left_type == "W/" then
wbottom = fheight..'/'..widget.bottom..'-('..fheight..'/'..t_..')'
else
wbottom = fheight..'/'..widget.bottom.."- "..t_
end
elseif widget.bottom_type == "R" then
wbottom = widget.bottom
else
if widget.top_type == "B-" then
wbottom = widget.bottom..'-('..fheight..'- '..t_..')'
elseif widget.left_type == "W/" then
wbottom = widget.bottom..'-('..fheight..'/'..t_..')'
elseif type(t_) == "string" then
wbottom = widget.bottom.."- "..t_
else
wbottom = widget.bottom-t_
end
end
if type(wbottom) == "string" and not real then
wbottom = '"..'..wbottom..' .."'
end
elseif t then
if widget.bottom_type == "B-" then
if widget.top_type == "B-" then
wbottom = fheight-widget.bottom-fheight..'- '..t
elseif widget.left_type == "W/" then
wbottom = fheight-widget.bottom-fheight..'/'..t
else
wbottom = fheight-widget.bottom.."+"..t
end
elseif widget.bottom_type == "H/" then
if widget.top_type == "B-" then
wbottom = fheight/widget.bottom-fheight..'- '..t
elseif widget.left_type == "W/" then
wbottom = fheight/widget.bottom-fheight..'/'..t
else
wbottom = fheight/widget.bottom.."- "..t
end
elseif widget.bottom_type == "R" then
wbottom = widget.bottom
else
if widget.top_type == "B-" then
wbottom = widget.bottom-fheight..'- '..t
elseif widget.left_type == "W/" then
wbottom = widget.bottom-fheight..'/'..t
elseif type(t) == "string" then
wbottom = widget.bottom.."- "..t
else
wbottom = widget.bottom-t
end
end
if type(wbottom) == "string" and not real then
wbottom = '"..'..wbottom..' .."'
end
else
if widget.bottom_type == "B-" then
wbottom = fheight-widget.bottom-wtop
elseif widget.bottom_type == "H/" then
wbottom = fheight/widget.bottom-wtop
elseif widget.bottom_type == "R" then
wbottom = widget.bottom
else
wbottom = widget.bottom-wtop
end
end
if real then
return {left=wleft, top=wtop, width=wright, height=wbottom} -- container needs the values seperate
end
return wleft..","..wtop..";"..wright..","..wbottom
end
end
local w, h = 0, 0
-- go through all the widgets, and add their code
for i, v in pairs(widgets) do
if v.type == "Display" then
local w, h
if v.width_param then -- things like this are for parameters
table.insert(parameters, "width")
w = '"..width.."'
else
w = tostring(v.width)
end
if v.height_param then
table.insert(parameters, "height")
h = '"..height.."'
else
h = tostring(v.height)
end
table.insert(display, '"size['..w..','..h..']"')
if v.position then -- for non-default position
table.insert(display, '"position['..v.left..','..v.top..']"')
end
if v.background then
table.insert(display, '"bgcolor['..v.colour..';'..tostring(v.fullscreen)..']"')
end
if v.col.col then
local cols = '"listcolors['..v.col.bg_normal..";"..v.col.bg_hover
if v.col.set_border then
cols = cols..";"..v.col.border
if v.col.set_tool then
cols = cols..";"..v.col.tool_bg..";"..v.col.tool_font
end
end
cols = cols..']"'
table.insert(display, cols)
end
elseif v.type == "Button" then
if v.image then
local tex = ""
if v.image_param then -- image texture param
table.insert(parameters, name(v).."_image")
tex = '"..'..name(v)..'_image.."'
else
tex = form_esc(v.texture)
end
if v.item and not v.exit then -- quit on click
table.insert(display, '"item_image_button['..get_rect(v)..';'..tex..';'..form_esc(v.name)..';'..form_esc(v.label)..']"')
else
if v.exit then -- quit on click - image
table.insert(display, '"image_button_exit['..get_rect(v)..';'..tex..';'..form_esc(v.name)..';'..form_esc(v.label)..']"')
else -- normal image
table.insert(display, '"image_button['..get_rect(v)..';'..tex..';'..form_esc(v.name)..';'..form_esc(v.label)..']"')
end
end
else
if v.exit then -- quit on click
table.insert(display, '"button_exit['..get_rect(v)..';'..form_esc(v.name)..';'..form_esc(v.label)..']"')
else -- basic button
table.insert(display, '"button['..get_rect(v)..';'..form_esc(v.name)..';'..form_esc(v.label)..']"')
end
end
elseif v.type == "Field" then
if v.password then -- password field
table.insert(display, '"pwdfield['..get_rect(v)..';'..form_esc(v.name)..';'..form_esc(v.label)..']"')
else
local default = ""
if v.default_param then -- default param
table.insert(parameters, name(v).."_default")
default = '"..minetest.formspec_escape('..name(v)..'_default).."'
else
default = form_esc(v.default)
end
table.insert(display, '"field['..get_rect(v)..';'..form_esc(v.name)..';'..form_esc(v.label)..';'..default..']"')
end
if v.enter_close == false then
table.insert(display, '"field_close_on_enter['..form_esc(v.name)..';false]"')
end
elseif v.type == "TextArea" then
local default = ""
if v.default_param then
table.insert(parameters, name(v).."_default")
default = '"..minetest.formspec_escape('..name(v)..'_default).."'
else
default = form_esc(v.default)
end
table.insert(display, '"textarea['..get_rect(v)..';'..form_esc(v.name)..';'..form_esc(v.label)..';'..form_esc(default)..']"')
elseif v.type == "Label" then
local label = form_esc(v.label)
if v.label_param then
table.insert(parameters, name(v).."_label")
label = '"..minetest.formspec_escape('..name(v)..'_label).."'
end
if v.vertical then -- vertical label
table.insert(display, '"vertlabel['..get_rect(v)..';'..label..']"')
else
table.insert(display, '"label['..get_rect(v)..';'..label..']"')
end
elseif v.type == "TextList" then
local items = ""
if v.items_param then
table.insert(parameters, name(v).."_items")
before_str = before_str.. -- add code for converting the list from a parameter to a string
' local '..name(v)..'_item_str = ""\n' ..
' for i, item in pairs('..name(v)..'_items) do\n' ..
' if i ~= 1 then '..name(v)..'_item_str = '..name(v)..'_item_str.."," end\n' ..
' '..name(v)..'_item_str = '..name(v)..'_item_str .. minetest.formspec_escape(item)\n' ..
' end\n\n'
items = '"..'..name(v)..'_item_str.."'
else
items = ""
for i, item in pairs(v.items) do
if i ~= 1 then items = items.."," end
items = items .. form_esc(item)
end
end
if v.item_id_param or v.transparent then
if v.item_id_param then -- selected item parameter
table.insert(parameters, name(v).."_selected_item")
table.insert(display, '"textlist['.. get_rect(v)..';'..form_esc(v.name)..';'..items..';"..'..name(v)..'_selected_item..";'..tostring(v.transparent)..']"')
else
table.insert(display, '"textlist['..get_rect(v)..';'..form_esc(v.name)..';'..items..';1;'..tostring(v.transparent)..']"')
end
else
table.insert(display, '"textlist['..get_rect(v)..';'..form_esc(v.name)..';'..items..']"')
end
elseif v.type == "DropDown" then
local items = ""
if v.items_param then
table.insert(parameters, name(v).."_items")
before_str = before_str.. -- add code for converting the list from a parameter to a string
' local '..name(v)..'_item_str = ""\n' ..
' for i, item in pairs('..name(v)..'_items) do\n' ..
' if i ~= 1 then '..name(v)..'_item_str = '..name(v)..'_item_str.."," end\n' ..
' '..name(v)..'_item_str = '..name(v)..'_item_str .. minetest.formspec_escape(item)\n' ..
' end\n\n'
items = '"..'..name(v)..'_item_str.."'
else
items = ""
for i, item in pairs(v.items) do
if i ~= 1 then items = items.."," end
items = items .. form_esc(item)
end
end
local item_id = ""
if v.item_id_param then -- selected item parameter
table.insert(parameters, name(v).."_selected_item")
item_id = '"..'..name(v)..'_selected_item.."'
else
item_id = tostring(v.select_id)
end
table.insert(display, '"dropdown['..get_rect(v)..';'..form_esc(v.name)..';'..items..';'..item_id..']"')
elseif v.type == "CheckBox" then
local checked = tostring(v.checked)
if v.checked_param then
table.insert(parameters, name(v).."_checked")
checked = '"..tostring('..name(v)..'_checked).."'
end
table.insert(display, '"checkbox['..get_rect(v)..';'..form_esc(v.name)..";"..form_esc(v.label)..';'..checked..']"')
elseif v.type == "Box" then
local colour = form_esc(v.colour)
if v.colour_param then
table.insert(parameters, name(v).."_colour")
colour = '"..'..name(v)..'_colour.."'
end
table.insert(display, '"box['..get_rect(v)..';'..colour..']"')
elseif v.type == "Image" then
local image = form_esc(v.image)
if v.image_param then -- texture
table.insert(parameters, name(v).."_image")
image = '"..'..name(v)..'_image.."'
end
if v.item then
table.insert(display, '"item_image['..get_rect(v)..';'..image..']"')
elseif v.background then
table.insert(display, '"background['..get_rect(v)..';'..image..';'..tostring(v.fill)..']"')
else
table.insert(display, '"image['..get_rect(v)..';'..image..']"')
end
elseif v.type == "Slider" then
local value = form_esc(v.value)
if v.value_param then
table.insert(parameters, name(v).."_value")
value = '"..'..name(v)..'_value.."'
end
local orientation = "horizontal"
if v.vertical then
orientation = "vertical"
end
table.insert(display, '"scrollbar['..get_rect(v)..';'..orientation..";"..form_esc(v.name)..";"..value..']"')
elseif v.type == "InvList" then
local extras = {["player:"]=1, ["nodemeta:"]=1, ["detached:"]=1}
local data = ""
if v.data_param then -- extra location data needed in some locations
table.insert(parameters, name(v).."_data")
data = '"..minetest.formspec_escape('..name(v)..'_data).."'
elseif extras[v.location] then
data = form_esc(v.data)
end
local start = v.start
if v.page_param then
table.insert(parameters, name(v).."_start_idx")
start = '"..'..name(v)..'_start_idx.."'
end
table.insert(display, '"list['..v.location..data..';'..form_esc(v.name)..';'..get_rect(v)..';'..start..']"')
if v.ring then -- shift clicking between item lists
table.insert(display, '"listring['..v.location..data..';'..form_esc(v.name)..']"')
end
elseif v.type == "Table" then
local cell_str = ""
local column_str = ""
local item_param = false
local most_items = 0
for i, c in pairs(v.columns) do
if #c.items > most_items then -- find how many columns are needed
most_items = #c.items
end
if c.items_param then -- find out if any parameters are needed
item_param = true
end
if i > 1 then -- create a column string
column_str = column_str..";"
end
column_str = column_str .. c.type
if c.type == "image" then -- add list of images
for n, t in pairs(c.images) do
column_str = column_str..","..n .."="..t
end
elseif c.type == "color" and c.distance ~= "infinite" then -- and distance affected by colour
column_str = column_str..",span="..c.distance
end
end
if not item_param then -- calculate item list if none come from parameters
for i=1, most_items do
for n, c in pairs(v.columns) do
if n > 1 or i > 1 then
cell_str = cell_str..","
end
local item = c.items[i]
if item == nil then
item = ""
end
cell_str = cell_str..item
end
end
else -- or add the code to convert the items from the parameters into a string
local items = " local "..name(v).."_cells = {"
for i, c in pairs(v.columns) do
if c.items_param then
table.insert(parameters, name(v).."_col_"..i.."_items")
items = items.."\n ["..i.."]="..name(v).."_col_"..i.."_items,"
else
local item_str = "{" -- create a string table with the items
for n, item in pairs(c.items) do
item_str = item_str..'"'..item..'", '
end
item_str = item_str.."}"
items = items.."\n ["..i.."]="..item_str..","
end
end
items = items.."\n }\n"
table_items = true -- this makes it add the function onto the start of the function
before_str = before_str..items ..
' local '..name(v)..'_cell_str = table_item_str('..name(v)..'_cells)\n\n'
cell_str = '"..'..name(v)..'_cell_str.."'
end
if column_str:len() > 0 then -- tablecolumns without columns gives an error
table.insert(display, '"tablecolumns['..column_str..']"')
end
local selected = ""
if v.select_param then -- selected item parameter
table.insert(parameters, name(v).."_selected_item")
selected = '"..'..name(v)..'_selected_item.."'
end
table.insert(display, '"table['..get_rect(v)..";"..form_esc(v.name)..';'..cell_str..';'..selected..']"')
elseif v.type == "Tooltip" then
if v.colours then
table.insert(display, '"tooltip['..form_esc(v.name)..';'..form_esc(v.text)..';'..form_esc(v.bg)..';'..form_esc(v.fg)..']"')
else
table.insert(display, '"tooltip['..form_esc(v.name)..';'..form_esc(v.text)..']"')
end
elseif v.type == "Container - Start" then -- container has 2 sections
local l = v.left
if v.left_param then -- the only widget which can hve position parameters
table.insert(parameters, name(v).."_left")
l = name(v)..'_left'
end
local t = v.top
if v.top_param then
table.insert(parameters, name(v).."_top")
t = name(v)..'_top'
end
local rect = get_rect(v, true, l, t) -- the area is returned as a table this time
dep = dep+1
if type(rect.width) == "string" then -- if it is a calculation, and not the calculated value
width[dep] = "("..rect.width..")"
else
width[dep] = rect.width
end
if type(rect.height) == "string" then
height[dep] = "("..rect.height..")"
else
height[dep] = rect.height
end
if type(rect.left) == "string" then
rect.left = '"..'..rect.left..' .."'
end
if type(rect.top) == "string" then
rect.top = '"..'..rect.top..' .."'
end
table.insert(display, '"container['..rect.left..','..rect.top..']"')
elseif v.type == "Container - End" then -- only exits the table
dep = dep-1
table.insert(display, '"container_end[]"')
elseif v.type == "Tabs" then
local capt_str = ""
for i, capt in pairs(v.captions) do
if i > 1 then capt_str = capt_str.."," end
capt_str = capt_str .. form_esc(capt)
end
table.insert(display, '"tabheader['..get_rect(v)..';'..form_esc(v.name)..';'..capt_str..';'..v.tab..';'.. tostring(v.transparent)..';'..tostring(v.border)..']"')
end
end
if table_items then -- the function generating a string from a list of column items
before_str = '' .. -- added if a table uses parameters
' local function table_item_str(cells)\n' ..
' local most_items = 0\n' ..
' for i, v in pairs(cells) do\n' ..
' if #v > most_items then\n' ..
' most_items = #v\n' ..
' end\n' ..
' end\n' ..
' local cell_str = ""\n' ..
' for i=1, most_items do\n' ..
' for n=1, #cells do\n' ..
' if n > 1 or i > 1 then ' ..
'cell_str = cell_str.."," ' ..
'end\n' ..
' local item = cells[n][i]\n' ..
' if item == nil then ' ..
'item = "" ' ..
'end\n' ..
' cell_str = cell_str..minetest.formspec_escape(item)\n' ..
' end\n' ..
' end\n' ..
' return cell_str\n' ..
' end\n\n' ..
before_str
end
param_str = "" -- creates the parameter string --> "param1, param2, paramN"
for i, v in pairs(parameters) do
if i ~= 1 then
param_str = param_str .. ", "
end
param_str = param_str .. v
end
-- puts the first part of the function together
form = form .. "function generate_form("..param_str..")\n" .. before_str .. '\n local form = "" ..\n'
for i, v in pairs(display) do -- adds the widget strings
form = form .. " "..v.." ..\n"
end
form = form .. ' ""\n\n return form\nend' -- completes it
return form
end
-- generates a string for a static UI
local function generate_string()
local form_esc = function(str) -- escape symbols need to be escaped with escaped escape symbols ;p
return string.gsub(minetest.formspec_escape(str), "\\", "\\\\")
end
local fwidth = {0}
local fheight = {0}
local dep = 1
local function get_rect(widget, real) -- can't be bothered commenting this. see function on line 73, it is basically the same...
local wleft = 0
if widget.left_type == "R-" then
wleft = fwidth[dep]-widget.left
elseif widget.left_type == "W/" then
wleft = fwidth[dep]/widget.left
else
wleft = widget.left
end
local wtop = 0
if widget.top_type == "B-" then
wtop = fheight[dep]-widget.top
elseif widget.left_type == "H/" then
wtop = fheight[dep]/widget.top
else
wtop = widget.top
end
if widget.right == nil then -- for widgets with no size option
return wleft..","..wtop..";"
else
local wright = 0
if widget.right_type == "R-" then
wright = fwidth[dep]-widget.right-wleft
elseif widget.right_type == "W/" then
wright = fwidth[dep]/widget.right-wleft
elseif widget.right_type == "R" then
wright = widget.right
else
wright = widget.right-wleft
end
local wbottom = 0
if widget.bottom_type == "B-" then
wbottom = fheight[dep]-widget.bottom-wtop
elseif widget.bottom_type == "H/" then
wbottom = fheight[dep]/widget.bottom-wtop
elseif widget.bottom_type == "R" then
wbottom = widget.bottom
else
wbottom = widget.bottom-wtop
end
if real then
return {left=wleft, top=wtop, width=wright, height=wbottom}
end
return wleft..","..wtop..";"..wright..","..wbottom..";"
end
end
local output = ""
for i, v in pairs(widgets) do -- go through all the widgets and create their strings
if v.type == "Display" then
fwidth = {v.width}
fheight = {v.height}
output = output .. "\"size["..v.width..","..v.height.."]\" ..\n"
if v.position then
output = output .. "\"position["..v.left..","..v.top.."]\" ..\n"
end
if v.background then
output = output .. "\"bgcolor["..v.colour..";"..tostring(v.fullscreen).."]\" ..\n"
end
if v.col.col then
output = output.."\"listcolors["..v.col.bg_normal..";"..v.col.bg_hover
if v.col.set_border then
output = output..";"..v.col.border
if v.col.set_tool then
output = output..";"..v.col.tool_bg..";"..v.col.tool_font
end
end
output = output.."]\" ..\n"
end
elseif v.type == "Button" then
if v.image then
local ending = get_rect(v)..form_esc(v.texture)..";"..form_esc(v.name)..";"..form_esc(v.label).."]\" ..\n"
if v.item and not v.exit then
output = output .. "\"item_image_button["..ending
else
if v.exit then
output = output .. "\"image_button_exit["..ending
else
output = output .. "\"image_button["..ending
end
end
else
if v.exit then
output = output .. "\"button_exit["..get_rect(v)..form_esc(v.name)..";"..form_esc(v.label).."]\" ..\n"
else
output = output .. "\"button["..get_rect(v)..form_esc(v.name)..";"..form_esc(v.label).."]\" ..\n"
end
end
elseif v.type == "Field" then
if v.password then
output = output .. "\"pwdfield["..get_rect(v)..form_esc(v.name)..";"..form_esc(v.label).."]\" ..\n"
else
output = output .. "\"field["..get_rect(v)..form_esc(v.name)..";"..form_esc(v.label)..";"..form_esc(v.default).."]\" ..\n"
end
if v.enter_close == false then
output = output .. "\"field_close_on_enter["..form_esc(v.name)..";false]\" ..\n"
end
elseif v.type == "TextArea" then
output = output .. "\"textarea["..get_rect(v)..form_esc(v.name)..";"..form_esc(v.label)..";"..form_esc(v.default).."]\" ..\n"
elseif v.type == "Label" then
if v.vertical then
output = output .. "\"vertlabel["..get_rect(v)..form_esc(v.label).."]\" ..\n"
else
output = output .. "\"label["..get_rect(v)..form_esc(v.label).."]\" ..\n"
end
elseif v.type == "TextList" then
local item_str = ""
for i, item in pairs(v.items) do
item_str = item_str .. form_esc(item)..","
end
if not v.transparent then
output = output .. "\"textlist["..get_rect(v)..form_esc(v.name)..";"..item_str:sub(0,-2).."]\" ..\n"
else
output = output .. "\"textlist["..get_rect(v)..form_esc(v.name)..";"..item_str:sub(0,-2)..";1;true]\" ..\n"
end
elseif v.type == "DropDown" then
local item_str = ""
for i, item in pairs(v.items) do
item_str = item_str .. form_esc(item)..","
end
output = output .. "\"dropdown["..get_rect(v)..form_esc(v.name)..";"..item_str:sub(0,-2)..";"..v.select_id.."]\" ..\n"
elseif v.type == "CheckBox" then
output = output .. "\"checkbox["..get_rect(v)..form_esc(v.name)..";"..form_esc(v.label)..";"..tostring(v.checked).."]\" ..\n"
elseif v.type == "Box" then
output = output .. "\"box["..get_rect(v)..form_esc(v.colour).."]\" ..\n"
elseif v.type == "Image" then
if v.item then
output = output .. "\"item_image["..get_rect(v)..form_esc(v.image).."]\" ..\n"
elseif v.background then
output = output .. "\"background["..get_rect(v)..form_esc(v.image)..";"..tostring(v.fill).."]\" ..\n"
else
output = output .. "\"image["..get_rect(v)..form_esc(v.image).."]\" ..\n"
end
elseif v.type == "Slider" then
orientation = "horizontal"
if v.vertical then
orientation = "vertical"
end
output = output .. "\"scrollbar["..get_rect(v)..orientation..";"..form_esc(v.name)..";"..v.value.."]\" ..\n"
elseif v.type == "InvList" then
local extras = {["player:"]=1, ["nodemeta:"]=1, ["detached:"]=1}
if extras[v.location] then
output = output .. "\"list["..v.location..form_esc(v.data)..";"..form_esc(v.name)..";"..get_rect(v)..v.start.."]\" ..\n"
if v.ring then
output = output .. "\"listring["..v.location..form_esc(v.data)..";"..form_esc(v.name).."]\" ..\n"
end
else
output = output .. "\"list["..v.location..";"..form_esc(v.name)..";"..get_rect(v)..v.start.."]\" ..\n"
if v.ring then
output = output .. "\"listring["..v.location..";"..form_esc(v.name).."]\" ..\n"
end
end
elseif v.type == "Table" then
local cell_str = ""
local column_str = ""
-- this converts the column's individual item lists into a string
local most_items = 0
for i, c in pairs(v.columns) do
if #c.items > most_items then
most_items = #c.items -- gets the largest size
end
if i > 1 then
column_str = column_str..";"
end
column_str = column_str .. c.type -- creates the column list
-- adds column parameters \/
if c.type == "image" then
for n, t in pairs(c.images) do
column_str = column_str..","..n .."="..t
end
elseif c.type == "color" and c.distance ~= "infinite" then
column_str = column_str..",span="..c.distance
end
end
for i=1, most_items do -- adds all the items together
for n, c in pairs(v.columns) do
if n > 1 or i > 1 then
cell_str = cell_str..","
end
local item = c.items[i]
if item == nil then -- columns with less items get blank items to make them the same length
item = ""
end
cell_str = cell_str..item
end
end
if column_str:len() > 0 then
output = output .. "\"tablecolumns["..column_str.."]\" ..\n"
end
output = output .. "\"table["..get_rect(v)..form_esc(v.name)..";"..cell_str..";]\" ..\n"
elseif v.type == "Tooltip" then
if v.colours then
output = output .. "\"tooltip["..form_esc(v.name)..";"..form_esc(v.text)..";"..form_esc(v.bg)..";"..form_esc(v.fg).."]\" ..\n"
else
output = output .. "\"tooltip["..form_esc(v.name)..";"..form_esc(v.text).."]\" ..\n"
end
elseif v.type == "Container - Start" then
local rect = get_rect(v, true)
fwidth[dep+1] = rect.width -- set the width and height that widgets in the container use
fheight[dep+1] = rect.height
dep = dep+1
output = output .. "\"container["..rect.left..","..rect.top.."]\" ..\n"
elseif v.type == "Container - End" then
dep = dep-1 -- close container
output = output .. "\"container_end[]\" ..\n"
elseif v.type == "Tabs" then
local capt_str = ""
for i, capt in pairs(v.captions) do
if i > 1 then capt_str = capt_str.."," end
capt_str = capt_str .. form_esc(capt)
end
output = output .. "\"tabheader["..get_rect(v)..form_esc(v.name)..";"..capt_str..";"..v.tab..";"..tostring(v.transparent)..";"..tostring(v.border).."]\" ..\n"
end
end
return output .. '""'
end
----------
-- UI Editors
----------
-- creates a position chooser with << and >> buttons, text box, and position type (if needed)
local function ui_position(name, value, left, top, typ, typ_id)
name = form_esc(name)
local form = ""..
"label["..left+0.1 ..","..top-0.3 ..";"..name.."]" ..
"button["..left+0.1 ..","..top..";1,1;"..name.."_size_down;<<]" ..
"field["..left+1.3 ..","..top+0.3 ..";1,1;"..name.."_size;;"..form_esc(value).."]" ..
"field_close_on_enter["..name.."_size;false]" ..
"button["..left+1.9 ..","..top..";1,1;"..name.."_size_up;>>]"
local typ_ids = {["L+"]=1, ["T+"]=1, ["R-"]=2, ["B-"]=2, ["W/"]=3, ["H/"]=3, ["R"]=4}
if typ == "LEFT" then -- left and right sides use this type
if name == "RIGHT" then -- but right has a relative option (I should make it right type, but I decided much later to include it)
form = form .."dropdown["..left+3 ..","..top+0.1 ..";1.1,1;"..name.."_type;LEFT +,RIGHT -,WIDTH /,RELATIVE;"..typ_ids[typ_id].."]"
else
form = form .. "dropdown["..left+3 ..","..top+0.1 ..";1.1,1;"..name.."_type;LEFT +,RIGHT -,WIDTH /;"..typ_ids[typ_id].."]"
end
elseif typ == "TOP" then
if name == "BOTTOM" then
form = form.."dropdown["..left+3 ..","..top+0.1 ..";1.1,1;"..name.."_type;TOP +,BOTTOM -,HEIGHT /,RELATIVE;"..typ_ids[typ_id].."]"
else
form = form .. "dropdown["..left+3 ..","..top+0.1 ..";1.1,1;"..name.."_type;TOP +,BOTTOM -,HEIGHT /;"..typ_ids[typ_id].."]"
end
end
return form
end
-- handles position ui functionality
local function handle_position_changes(id, fields, range)
local pos_names = {"width", "height", "left", "top", "right", "bottom", "value"} -- the only names it will check
for i, v in pairs(pos_names) do
if fields[string.upper(v).."_size_down"] then -- down button
if range and range[v] then
widgets[id][v] = widgets[id][v] - range[v]/10 -- slider uses a different step
else
widgets[id][v] = widgets[id][v] - 0.1
end
if widgets[id][v] < 0.0001 and widgets[id][v] > -0.0001 then widgets[id][v] = 0 end -- weird number behaviour
elseif fields[string.upper(v).."_size_up"] then -- up button
if range and range[v] then
widgets[id][v] = widgets[id][v] + range[v]/10
else
widgets[id][v] = widgets[id][v] + 0.1
end
if widgets[id][v] < 0.0001 and widgets[id][v] > -0.0001 then widgets[id][v] = 0 end -- weird number behaviour
elseif fields.key_enter_field == string.upper(v).."_size" then -- size edit box/displayer
local value = tonumber(fields[string.upper(v).."_size"])
if value ~= nil then
widgets[id][v] = value
end
elseif fields[string.upper(v).."_type"] then -- type selector
local typ_trans = {["LEFT +"]="L+", ["RIGHT -"]="R-", ["WIDTH /"]="W/", ["TOP +"]="T+", ["BOTTOM -"]="B-", ["HEIGHT /"]="H/", ["RELATIVE"]="R"}
widgets[id][v.."_type"] = typ_trans[fields[string.upper(v).."_type"]]
end
if range then -- sometimes the number must be within a range
if range[v] then
if widgets[id][v] < 0 then
widgets[id][v] = 0
elseif widgets[id][v] > range[v] then
widgets[id][v] = range[v]
end
end
end
end
end
-- creates a field to edit name or other attributes, and a parameter checkbox (if needed)
local function ui_field(name, value, left, top, param)
name = form_esc(name)
local field = "" ..
"field["..left+0.2 ..","..top..";2.8,1;"..name.."_input_box;"..name..";"..form_esc(value).."]" ..
"field_close_on_enter["..name.."_input_box;false]"
if param ~= nil then
field = field .. "checkbox["..left+2.8 ..","..top-0.3 ..";"..name.."_param_box;parameter;"..tostring(param).."]"
end
return field
end
-- handles field functionality
local function handle_field_changes(names, id, fields)
for i, v in pairs(names) do -- names are supplied this time, so only nececary ones are checked
if fields.key_enter_field == string.upper(v).."_input_box" then
widgets[id][v] = fields[string.upper(v).."_input_box"]
elseif fields[string.upper(v).."_param_box"] then
widgets[id][v.."_param"] = fields[string.upper(v).."_param_box"] == "true"
end
end
end
----------
-- individual widget definitions
-- functions for widget's custom editing UIs at the side
local widget_editor_uis = {
Display = { -- type can be seen here, etc, extra tabs (options, new widget) are at the end
ui = function(id, left, top, width) -- function for creating the form
local form = "label["..left+1.7 ..","..top ..";- DISPLAY -]"
if not widgets[id].colour_tab then
form = form ..
"button["..left+width-3 ..","..top+6.7 ..";3.1,1;col_page;INVENTORY COLOURS >]" ..
ui_position("WIDTH", widgets[id].width, left, top+0.7) ..
ui_position("HEIGHT", widgets[id].height, left, top+1.7) ..
"checkbox["..left+3 ..","..top+0.7 ..";WIDTH_param_box;parameter;"..tostring(widgets[id].width_param).."]" ..
"checkbox["..left+3 ..","..top+1.7 ..";HEIGHT_param_box;parameter;"..tostring(widgets[id].height_param).."]"
if widgets[id].position then -- this part only gets displayed if the position checkbox is checked
form = form ..
ui_position("LEFT", widgets[id].left, left, top+2.7) ..
ui_position("TOP", widgets[id].top, left, top+3.7) ..
"checkbox["..left+0.1 ..","..top+4.3 ..";pos_box;position;true]" ..
"checkbox["..left+2 ..","..top+4.3 ..";back_box;background;"..tostring(widgets[id].background).."]"
if widgets[id].background then
form = form..
ui_field("COLOUR", widgets[id].colour, left+0.2, top+5.5) ..
"checkbox["..left+3 ..","..top+5.2 ..";full;fullscreen;"..tostring(widgets[id].fullscreen).."]"
end
else
form = form .. "checkbox["..left+0.1 ..","..top+2.3 ..";pos_box;position;false]" ..
"checkbox["..left+2 ..","..top+2.3 ..";back_box;background;"..tostring(widgets[id].background).."]"
if widgets[id].background then
form = form..
ui_field("COLOUR", widgets[id].colour, left+0.2, top+3.5) ..
"checkbox["..left+3 ..","..top+3.2 ..";full;fullscreen;"..tostring(widgets[id].fullscreen).."]"
end
end
else
form = form ..
"checkbox["..left+0.1 ..","..top+0.3 ..";do_col;COLOURS;"..tostring(widgets[id].col.col).."]" ..
"button["..left+width-1.2 ..","..top+6.7 ..";1.3,1;dat_page;BACK <]"
if widgets[id].col.col then
form = form ..
"field["..left+0.4 ..","..top+1.5 ..";2.8,1;bg_main;BACKGROUND;"..widgets[id].col.bg_normal.."]" ..
"field_close_on_enter[bg_main;false]" ..
"field["..left+0.4 ..","..top+2.5 ..";2.8,1;bg_hover;HOVER BACKGROUND;"..widgets[id].col.bg_hover.."]" ..
"field_close_on_enter[bg_hover;false]" ..
"checkbox["..left+0.1 ..","..top+2.8 ..";do_border;BORDER;"..tostring(widgets[id].col.set_border).."]"
if widgets[id].col.set_border then
form = form ..
"field["..left+0.4 ..","..top+4 ..";2.8,1;border;BORDER;"..widgets[id].col.border.."]" ..
"field_close_on_enter[border;false]" ..
"checkbox["..left+0.1 ..","..top+4.3 ..";do_tool;TOOLTIP;"..tostring(widgets[id].col.set_tool).."]"
if widgets[id].col.set_tool then
form = form ..
"field["..left+0.4 ..","..top+5.5 ..";2.8,1;bg_tool;BACKGROUND;"..widgets[id].col.tool_bg.."]" ..
"field_close_on_enter[bg_tool;false]" ..
"field["..left+0.4 ..","..top+6.5 ..";2.8,1;tool_text;TEXT;"..widgets[id].col.tool_font.."]" ..
"field_close_on_enter[tool_text;false]"
end
end
end
end
return form
end,
func = function(id, fields) -- function for handling the form
handle_position_changes(id, fields, {left=1, top=1})
handle_field_changes({"colour"}, id, fields)
if fields.WIDTH_param_box then
widgets[id].width_param = fields.WIDTH_param_box == "true"
elseif fields.HEIGHT_param_box then
widgets[id].height_param = fields.HEIGHT_param_box == "true"
elseif fields.pos_box then
widgets[id].position = fields.pos_box == "true"
elseif fields.back_box then
widgets[id].background = fields.back_box == "true"
elseif fields.full then
widgets[id].fullscreen = fields.full == "true"
elseif fields.col_page then -- colour tab
widgets[id].colour_tab = true
elseif fields.dat_page then
widgets[id].colour_tab = false
elseif fields.do_col then
widgets[id].col.col = fields.do_col == "true"
elseif fields.do_border then
widgets[id].col.set_border = fields.do_border == "true"
elseif fields.do_tool then
widgets[id].col.set_tool = fields.do_tool == "true"
elseif fields.key_enter_field == "bg_main" then
widgets[id].col.bg_normal = fields.bg_main
elseif fields.key_enter_field == "bg_hover" then
widgets[id].col.bg_hover = fields.bg_hover
elseif fields.key_enter_field == "border" then
widgets[id].col.border = fields.border
elseif fields.key_enter_field == "bg_tool" then
widgets[id].col.tool_bg = fields.bg_tool
elseif fields.key_enter_field == "tool_text" then
widgets[id].col.tool_font = fields.tool_text
end
reload_ui() -- refresh the display and save the file
end
},
Button = {
ui = function(id, left, top, width)
local form = "label["..left+1.8 ..","..top ..";- BUTTON -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+0.7) .. -- all have a name box
ui_position("LEFT", widgets[id].left, left, top+1.4, "LEFT", widgets[id].left_type) .. -- and an area or position
ui_position("TOP", widgets[id].top, left, top+2.4, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+3.4, "LEFT", widgets[id].right_type) ..
ui_position("BOTTOM", widgets[id].bottom, left, top+4.4, "TOP", widgets[id].bottom_type) ..
ui_field("LABEL", widgets[id].label, left+0.2, top+5.7) .. -- then extra things
""
if widgets[id].image then
form = form ..
ui_field("TEXTURE", widgets[id].texture, left+0.2, top+6.7) ..
"checkbox["..left+3 ..","..top+6.4 ..";image_param_box;parameter;"..tostring(widgets[id].image_param).."]" ..
"checkbox["..left+1.8 ..","..top+7 ..";image_box;image;true]" ..
"checkbox["..left+0.1 ..","..top+7 ..";close_box;exit form;"..tostring(widgets[id].exit).."]"
if not widgets[id].exit then
form = form .. "checkbox["..left+3 ..","..top+7 ..";item_box;item;"..tostring(widgets[id].item).."]"
end
else
form = form .. "checkbox["..left+1.8 ..","..top+6 ..";image_box;image;false]" ..
"checkbox["..left+0.1 ..","..top+6 ..";close_box;exit form;"..tostring(widgets[id].exit).."]"
end
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name", "label", "texture"}, id, fields)
if fields.image_box then
widgets[id].image = fields.image_box == "true"
elseif fields.image_param_box then
widgets[id].image_param = fields.image_param_box == "true"
elseif fields.item_box then
widgets[id].item = fields.item_box == "true"
elseif fields.close_box then
widgets[id].exit = fields.close_box == "true"
end
reload_ui()
end
},
Field = {
ui = function(id, left, top, width)
local form = "label["..left+1.8 ..","..top ..";- FIELD -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+3.7, "LEFT", widgets[id].right_type) ..
ui_field("LABEL", widgets[id].label, left+0.2, top+5) ..
""
if widgets[id].password then
form = form.."checkbox["..left+0.1 ..","..top+5.3 ..";password_box;password;true]" ..
"checkbox["..left+0.1 ..","..top+5.7 ..";enter_close_box;close form on enter;"..tostring(widgets[id].enter_close).."]"
else
form = form..
ui_field("DEFAULT", widgets[id].default, left+0.2, top+6, widgets[id].default_param) ..
"checkbox["..left+0.1 ..","..top+6.3 ..";password_box;password;false]" ..
"checkbox["..left+0.1 ..","..top+6.7 ..";enter_close_box;close form on enter;"..tostring(widgets[id].enter_close).."]"
end
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name", "label", "default"}, id, fields)
if fields.password_box then
widgets[id].password = fields.password_box == "true"
elseif fields.enter_close_box then
widgets[id].enter_close = fields.enter_close_box == "true"
end
reload_ui()
end
},
TextArea = {
ui = function(id, left, top, width)
local form = "label["..left+1.8 ..","..top ..";- TextArea -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+3.7, "LEFT", widgets[id].right_type) ..
ui_position("BOTTOM", widgets[id].bottom, left, top+4.7, "TOP", widgets[id].bottom_type) ..
ui_field("LABEL", widgets[id].label, left+0.2, top+6) ..
ui_field("DEFAULT", widgets[id].default, left+0.2, top+7, widgets[id].default_param) ..
""
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name", "label", "default"}, id, fields)
reload_ui()
end
},
Label = {
ui = function(id, left, top, width)
local form = "label["..left+2 ..","..top ..";- Label -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
ui_field("LABEL", widgets[id].label, left+0.2, top+4, widgets[id].label_param) ..
"checkbox["..left+0.1 ..","..top+4.3 ..";vert_box;vertical;"..tostring(widgets[id].vertical).."]"
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name", "label"}, id, fields)
if fields.vert_box then
widgets[id].vertical = fields.vert_box == "true"
end
reload_ui()
end
},
TextList = {
ui = function(id, left, top, width)
local item_str = ""
for i, v in pairs(widgets[id].items) do
item_str = item_str .. form_esc(v) .. ","
end
local form = "label["..left+1.8 ..","..top ..";- TextList -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+3.7, "LEFT", widgets[id].right_type) ..
ui_position("BOTTOM", widgets[id].bottom, left, top+4.7, "TOP", widgets[id].bottom_type) ..
"label["..left+0.1 ..","..top+5.4 ..";ITEMS]" ..
"textlist["..left+0.1 ..","..top+5.75 ..";2.6,0.7;item_list;"..item_str.."]" ..
"field["..left+3.3 ..","..top+6 ..";1.8,1;item_input;;]" ..
"field_close_on_enter[item_input;false]" ..
"checkbox["..left+0.1 ..","..top+6.3 ..";items_param_box;items parameter;"..tostring(widgets[id].items_param).."]" ..
"checkbox["..left+0.1 ..","..top+6.7 ..";item_id_param_box;selected item id parameter;"..tostring(widgets[id].item_id_param).."]" ..
"checkbox["..left+3 ..","..top+6.7 ..";transparent_box;transparent;"..tostring(widgets[id].transparent).."]" ..
""
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name"}, id, fields)
if fields.item_list then -- common (lazy) way I make editable lists
if string.sub(fields.item_list, 1, 3) == "DCL" then -- remove
table.remove(widgets[id].items, tonumber(string.sub(fields.item_list, 5)))
end
elseif fields.key_enter_field == "item_input" then -- add
table.insert(widgets[id].items, fields.item_input)
elseif fields.items_param_box then
widgets[id].items_param = fields.items_param_box == "true"
elseif fields.item_id_param_box then
widgets[id].item_id_param = fields.item_id_param_box == "true"
elseif fields.transparent_box then
widgets[id].transparent = fields.transparent_box == "true"
end
reload_ui()
end
},
DropDown = {
ui = function(id, left, top, width)
local item_str = ""
for i, v in pairs(widgets[id].items) do
item_str = item_str .. form_esc(v) .. ","
end
local form = "label["..left+1.8 ..","..top ..";- DropDown -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+3.7, "LEFT", widgets[id].right_type) ..
"label["..left+0.1 ..","..top+4.4 ..";ITEMS]" ..
"label["..left+1.8 ..","..top+4.4 ..";selected: "..widgets[id].select_id.."]" ..
"textlist["..left+0.1 ..","..top+4.75 ..";2.6,0.7;item_list;"..item_str.."]" ..
"field["..left+3.3 ..","..top+5 ..";1.8,1;item_input;;]" ..
"field_close_on_enter[item_input;false]" ..
"checkbox["..left+0.1 ..","..top+5.3 ..";items_param_box;items parameter;"..tostring(widgets[id].items_param).."]" ..
"checkbox["..left+0.1 ..","..top+5.7 ..";item_id_param_box;selected item id parameter;"..tostring(widgets[id].item_id_param).."]" ..
""
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name"}, id, fields)
if fields.item_list then
if string.sub(fields.item_list, 1, 3) == "DCL" then
table.remove(widgets[id].items, tonumber(string.sub(fields.item_list, 5)))
else
widgets[id].select_id = tonumber(string.sub(fields.item_list, 5))
end
elseif fields.key_enter_field == "item_input" then
table.insert(widgets[id].items, fields.item_input)
elseif fields.items_param_box then
widgets[id].items_param = fields.items_param_box == "true"
elseif fields.item_id_param_box then
widgets[id].item_id_param = fields.item_id_param_box == "true"
end
reload_ui()
end
},
CheckBox = {
ui = function(id, left, top, width)
local form = "label["..left+2 ..","..top ..";- Label -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
ui_field("LABEL", widgets[id].label, left+0.2, top+4) ..
"checkbox["..left+0.1 ..","..top+4.3 ..";checked_box;checked;"..tostring(widgets[id].checked).."]" ..
"checkbox["..left+0.1 ..","..top+4.7 ..";checked_param_box;checked parameter;"..tostring(widgets[id].checked_param).."]"
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name", "label"}, id, fields)
if fields.checked_box then
widgets[id].checked = fields.checked_box == "true"
elseif fields.checked_param_box then
widgets[id].checked_param = fields.checked_param_box == "true"
end
reload_ui()
end
},
Box = {
ui = function(id, left, top, width)
local form = "label["..left+1.8 ..","..top ..";- Box -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+3.7, "LEFT", widgets[id].right_type) ..
ui_position("BOTTOM", widgets[id].bottom, left, top+4.7, "TOP", widgets[id].bottom_type) ..
ui_field("COLOUR", widgets[id].colour, left+0.2, top+6, widgets[id].colour_param) ..
""
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name", "colour"}, id, fields)
reload_ui()
end
},
Image = {
ui = function(id, left, top, width)
local form = "label["..left+1.8 ..","..top ..";- Image -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+3.7, "LEFT", widgets[id].right_type) ..
ui_position("BOTTOM", widgets[id].bottom, left, top+4.7, "TOP", widgets[id].bottom_type) ..
ui_field("IMAGE", widgets[id].image, left+0.2, top+6, widgets[id].image_param) ..
"checkbox["..left+0.1 ..","..top+6.3 ..";item_box;item;"..tostring(widgets[id].item).."]" ..
""
if not widgets[id].item then
form = form .. "checkbox["..left+1.5 ..","..top+6.3 ..";back_box;background;"..tostring(widgets[id].background).."]"
if widgets[id].background then
form = form .. "checkbox["..left+1.5 ..","..top+6.7 ..";fill_box;fill;"..tostring(widgets[id].fill).."]"
end
end
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name", "image"}, id, fields)
if fields.item_box then
widgets[id].item = fields.item_box == "true"
elseif fields.back_box then
widgets[id].background = fields.back_box == "true"
elseif fields.fill_box then
widgets[id].fill = fields.fill_box == "true"
end
reload_ui()
end
},
Slider = {
ui = function(id, left, top, width)
local form = "label["..left+1.8 ..","..top ..";- Slider -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+3.7, "LEFT", widgets[id].right_type) ..
ui_position("BOTTOM", widgets[id].bottom, left, top+4.7, "TOP", widgets[id].bottom_type) ..
ui_position("VALUE", widgets[id].value, left, top+5.7) ..
"checkbox["..left+3 ..","..top+5.7 ..";value_param_box;parameter;"..tostring(widgets[id].value_param).."]" ..
"dropdown["..left+0.1 ..","..top+6.7 ..";2,1;orientation;horizontal,vertical;"..(widgets[id].vertical and 2 or 1).."]" ..
""
return form
end,
func = function(id, fields)
handle_position_changes(id, fields, {value=1000})
handle_field_changes({"name"}, id, fields)
if fields.value_param_box then
widgets[id].value_param = fields.value_param_box == "true"
elseif fields.orientation then
local new = fields.orientation == "vertical"
if widgets[id].vertical ~= new then -- swaps the width and height to make it nicer to edit
widgets[id].vertical = new
widgets[id].right, widgets[id].bottom = widgets[id].bottom, widgets[id].right
end
end
reload_ui()
end
},
InvList = {
ui = function(id, left, top, width)
local location_values = {context=1, current_player=2, ["player:"]=3, ["nodemeta:"]=4, ["detached:"]=5}
local form = "label["..left+1.4 ..","..top ..";- Inventory List -]" ..
ui_position("LEFT", widgets[id].left, left, top+0.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+1.7, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+2.7, "LEFT", widgets[id].right_type) ..
ui_position("BOTTOM", widgets[id].bottom, left, top+3.7, "TOP", widgets[id].bottom_type) ..
"label["..left+0.1 ..","..top+4.4 ..";LOCATION]" ..
"dropdown["..left+0.1 ..","..top+4.75 ..";2.8;location_select;context,current_player,player:,nodemeta:,detached:;" .. location_values[widgets[id].location].."]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+6) ..
"field["..left+0.4 ..","..top+7 ..";1,1;start;START;"..widgets[id].start.."]" ..
"field_close_on_enter[start;false]" ..
"checkbox["..left+1.5 ..","..top+6.7 ..";start_box;param;"..tostring(widgets[id].start_param).."]" ..
"checkbox["..left+3 ..","..top+5.9 ..";ring_box;ring;"..tostring(widgets[id].ring).."]"
local extras = {["player:"]=1, ["nodemeta:"]=1, ["detached:"]=1} -- these locations need extra data
if extras[widgets[id].location] then
form = form .. "field["..left+3.3 ..","..top+5 ..";1.7,1;data;DATA;"..form_esc(widgets[id].data).."]" ..
"field_close_on_enter[data;false]" ..
"checkbox["..left+3 ..","..top+5.5 ..";data_box;data param;"..tostring(widgets[id].data_param).."]"
end
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name"}, id, fields)
if fields.ring_box then
widgets[id].ring= fields.ring_box == "true"
elseif fields.start_box then
widgets[id].start_param = fields.start_box == "true"
elseif fields.data_box then
widgets[id].data_param = fields.data_box == "true"
elseif fields.key_enter_field == "data" then
widgets[id].data = fields.data
elseif fields.key_enter_field == "start" then
widgets[id].start = tonumber(fields.start)
if widgets[id].start == nil then
widgets[id].start = 0
end
elseif fields.location_select then
widgets[id].location = fields.location_select
end
reload_ui()
end
},
Tooltip = {
ui = function(id, left, top, width)
local form = "label["..left+1.7 ..","..top ..";- Tooltip -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_field("TEXT", widgets[id].text, left+0.2, top+2) ..
""
if widgets[id].colours then
form = form .. "field["..left+0.4 ..","..top+3 ..";2.8,1;bg;BACKGROUND;"..form_esc(widgets[id].bg).."]" ..
"field_close_on_enter[bg;false]" ..
"field["..left+0.4 ..","..top+4 ..";2.8,1;fg;TEXT COLOUR;"..form_esc(widgets[id].fg).."]" ..
"field_close_on_enter[fg;false]" ..
"checkbox["..left+0.12 ..","..top+4.4 ..";col_box;colours;true]"
else
form = form .. "checkbox["..left+0.12 ..","..top+2.4 ..";col_box;colours;false]"
end
return form
end,
func = function(id, fields)
handle_field_changes({"name", "text"}, id, fields)
if fields.key_enter_field == "bg" then
widgets[id].bg = fields.bg
elseif fields.key_enter_field == "fg" then
widgets[id].fg = fields.fg
elseif fields.col_box then
widgets[id].colours = fields.col_box == "true"
end
reload_ui()
end
},
Table = {
ui = function(id, left, top, width)
local column_str = ""
for i, v in pairs(widgets[id].columns) do
column_str = column_str..","..i..": "..v.type
end
local form = "label["..left+1.8 ..","..top ..";- Table -]" ..
"textlist["..left+0.1 ..","..top+0.4 ..";2.5,1.5;column_select;#ffff00DATA,#ffff00- columns: "..column_str..";"..widgets[id].selected_column+2 ..";]" ..
"button["..left+2.7 ..","..top+0.3 ..";0.5,1;column_up;/\\\\]" ..
"button["..left+2.7 ..","..top+1.15 ..";0.5,1;column_down;\\\\/]" ..
"button["..left+3.1 ..","..top+0.3 ..";0.8,1;column_add;+]" ..
"button["..left+3.1 ..","..top+1.15 ..";0.8,1;column_remove;-]"
if widgets[id].selected_column == -1 then -- the data tab (size, name, etc)
form = form .. ui_field("NAME", widgets[id].name, left+0.2, top+2.5) ..
ui_position("LEFT", widgets[id].left, left, top+3.2, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+4.2, "TOP", widgets[id].top_type) ..
ui_position("RIGHT", widgets[id].right, left, top+5.2, "LEFT", widgets[id].right_type) ..
ui_position("BOTTOM", widgets[id].bottom, left, top+6.2, "TOP", widgets[id].bottom_type) ..
"checkbox["..left+0.1 ..","..top+6.9 ..";select_param_box;selected item param;"..tostring(widgets[id].select_param).."]"
elseif widgets[id].selected_column > 0 then -- item controller
local c = widgets[id].columns[widgets[id].selected_column]
typ_convt = {text=1, image=2, color=3, indent=4, tree=5}
local items_str = ""
for i, v in pairs(c.items) do
items_str = items_str..i..": "..v..","
end
form = form .. "label["..left+0.1 ..","..top+1.9 ..";TYPE]" ..
"dropdown["..left+0.1 ..","..top+2.3 ..";2.7,1;column_type;text,image,color,indent,tree;"..typ_convt[c.type].."]" ..
"label["..left+0.1 ..","..top+2.9 ..";ITEMS]" ..
"textlist["..left+0.1 ..","..top+3.3 ..";2.5,1.5;item_lst;"..items_str..";".. c.selected_item..";]" ..
"button["..left+2.7 ..","..top+3.2 ..";0.5,1;item_up;/\\\\]" ..
"button["..left+2.7 ..","..top+4.05 ..";0.5,1;item_down;\\\\/]" ..
"button["..left+3.1 ..","..top+3.2 ..";0.8,1;item_add;+]" ..
"button["..left+3.1 ..","..top+4.05 ..";0.8,1;item_remove;-]" ..
"checkbox["..left+2.7 ..","..top+4.6 ..";item_param_box;items parameter;"..tostring(c.items_param).."]"
if #c.items > 0 then -- item editor
form = form .. "field["..left+0.4 ..","..top+5.4 ..";2.5,1;item_edit;ITEM;"..c.items[c.selected_item].."]" ..
"field_close_on_enter[item_edit;false]"
-- some column types need extra stuff
if c.type == "image" then -- image
local img_str = ""
for i, v in pairs(c.images) do
img_str = img_str..i ..": "..v..","
end
form = form .. "label["..left+0.1 ..","..top+5.8 ..";IMAGES]" ..
"textlist["..left+0.1 ..","..top+6.2 ..";2.5,1.4;image_lst;"..img_str.."]" ..
"field["..left+3 ..","..top+6.4 ..";2,1;image_add;;]" ..
"field_close_on_enter[image_add;false]"
elseif c.type == "color" then -- colour
form = form .. "field["..left+0.4 ..","..top+6.4 ..";2.5,1;colour_len;DISTANCE;"..c.distance.."]" ..
"field_close_on_enter[colour_len;false]"
end
end
end
return form
end,
func = function(id, fields)
-- basic stuff
handle_position_changes(id, fields)
handle_field_changes({"name"}, id, fields)
local number_usrs = {indent=1, tree=1, image=1}
local c = widgets[id].columns[widgets[id].selected_column]
-- column selector and editor
if fields.column_select then
widgets[id].selected_column = tonumber(string.sub(fields.column_select, 5))-2
elseif fields.column_add then -- column def
table.insert(widgets[id].columns, {type="text", items={}, images={}, selected_item=1, items_param=false, distance="infinite"})
widgets[id].selected_column = #widgets[id].columns
elseif fields.column_remove and widgets[id].selected_column > 0 then
table.remove(widgets[id].columns, widgets[id].selected_column)
widgets[id].selected_column = widgets[id].selected_column-1
elseif fields.column_down and widgets[id].selected_column < #widgets[id].columns and widgets[id].selected_column > 0 then
table.insert(widgets[id].columns, widgets[id].selected_column+1, table.remove(widgets[id].columns, widgets[id].selected_column))
widgets[id].selected_column = widgets[id].selected_column+1
elseif fields.column_up and widgets[id].selected_column > 1 then
table.insert(widgets[id].columns, widgets[id].selected_column-1, table.remove(widgets[id].columns, widgets[id].selected_column))
widgets[id].selected_column = widgets[id].selected_column-1
elseif fields.select_param_box then
widgets[id].select_param = fields.select_param_box == "true"
-- item editor
elseif fields.item_lst then
c.selected_item = tonumber(string.sub(fields.item_lst, 5))
if c.selected_item > #c.items then
c.selected_item = #c.items
end
elseif fields.item_add then
if number_usrs[c.type] then
table.insert(c.items, 0)
else
table.insert(c.items, "-")
end
c.selected_item = #c.items
elseif fields.item_remove then
table.remove(c.items, c.selected_item)
if c.selected_item > 1 then
c.selected_item = c.selected_item-1
end
elseif fields.item_down and c.selected_item < #c.items then
table.insert(c.items, c.selected_item+1, table.remove(c.items, c.selected_item))
c.selected_item = c.selected_item+1
elseif fields.item_up and c.selected_item > 1 then
table.insert(c.items, c.selected_item-1, table.remove(c.items, c.selected_item))
c.selected_item = c.selected_item-1
elseif fields.item_param_box then
c.items_param = fields.item_param_box == "true"
elseif fields.key_enter_field == "item_edit" then
c.items[c.selected_item] = fields.item_edit
if number_usrs[c.type] then
c.items[c.selected_item] = tonumber(fields.item_edit)
if c.items[c.selected_item] == nil then
c.items[c.selected_item] = 0
end
c.items[c.selected_item] = math.floor(c.items[c.selected_item])
end
-- extra things for column types
elseif fields.key_enter_field == "image_add" then
table.insert(c.images, fields.image_add)
elseif fields.image_lst and string.sub(fields.image_lst, 1, 3) == "DCL" then
table.remove(c.images, tonumber(string.sub(fields.image_lst, 5)))
elseif fields.colour_len then
c.distance = tonumber(fields.colour_len)
if c.distance == nil or c.distance <= 0 then
c.distance = "infinite"
else
c.distance = math.floor(c.distance)
end
elseif fields.column_type then
c.type = fields.column_type
if number_usrs[c.type] then
for i, v in pairs(c.items) do
c.items[i] = tonumber(v)
if c.items[i] == nil then
c.items[i] = 0
end
end
end
end
reload_ui()
end
},
["Container - Start"] = {
ui = function(id, left, top, width)
local form = "label["..left+1.8 ..","..top ..";- Container -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
"label["..left+3.8 ..","..top+1.4 ..";parameter]" ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
"checkbox["..left+4.2 ..","..top+1.7 ..";left_param_box;;"..tostring(widgets[id].left_param).."]" ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
"checkbox["..left+4.2 ..","..top+2.7 ..";top_param_box;;"..tostring(widgets[id].top_param).."]" ..
ui_position("RIGHT", widgets[id].right, left, top+3.7, "LEFT", widgets[id].right_type) ..
ui_position("BOTTOM", widgets[id].bottom, left, top+4.7, "TOP", widgets[id].bottom_type) ..
""
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name"}, id, fields)
if fields.left_param_box then
widgets[id].left_param = fields.left_param_box == "true"
elseif fields.top_param_box then
widgets[id].top_param = fields.top_param_box == "true"
end
reload_ui()
end,
del = function(id)
table.remove(widgets, id)
local depth = 0
while id <= #widgets and depth > -1 do -- find which container end belongs to this container and delete it too
if widgets[id].type == "Container - Start" then
depth = depth+1
elseif widgets[id].type == "Container - End" then
if depth == 0 then
table.remove(widgets, id)
end
depth = depth-1
end
id = id+1
end
end
},
["Container - End"] = {
ui = function(id, left, top, width)
local name = ""
local depth = 0
local pos = id-1
while pos > 0 and depth > -1 do -- find which container start belongs to this container and display it's name
if widgets[pos].type == "Container - Start" then
if depth == 0 then
name = widgets[pos].name
end
depth = depth-1
elseif widgets[pos].type == "Container - End" then
depth = depth+1
end
pos = pos-1
end
local form = "label["..left+0.1 ..","..top+1 ..";- End of Container \""..form_esc(name).."\" -]" ..
""
return form
end,
func = function(id, fields)
-- ehem?
end
},
Tabs = {
ui =function(id, left, top, width)
local item_str = ""
for i, v in pairs(widgets[id].captions) do
item_str = item_str .. form_esc(v) .. ","
end
local form = "label["..left+1.9 ..","..top ..";- Tabs -]" ..
ui_field("NAME", widgets[id].name, left+0.2, top+1) ..
ui_position("LEFT", widgets[id].left, left, top+1.7, "LEFT", widgets[id].left_type) ..
ui_position("TOP", widgets[id].top, left, top+2.7, "TOP", widgets[id].top_type) ..
"label["..left+0.1 ..","..top+3.4 ..";TABS]" ..
"label["..left+1.8 ..","..top+3.4 ..";selected: "..widgets[id].tab.."]" ..
"textlist["..left+0.1 ..","..top+3.75 ..";2.6,0.7;item_list;"..item_str.."]" ..
"field["..left+3.3 ..","..top+4 ..";1.8,1;item_input;;]" ..
"field_close_on_enter[item_input;false]" ..
"checkbox["..left+0.1 ..","..top+4.3 ..";transparent_box;transparent;"..tostring(widgets[id].transparent).."]" ..
"checkbox["..left+0.1 ..","..top+4.7 ..";border_box;border;"..tostring(widgets[id].border).."]" ..
""
return form
end,
func = function(id, fields)
handle_position_changes(id, fields)
handle_field_changes({"name"}, id, fields)
if fields.item_list then
if string.sub(fields.item_list, 1, 3) == "DCL" then
table.remove(widgets[id].captions, tonumber(string.sub(fields.item_list, 5)))
else
widgets[id].tab = tonumber(string.sub(fields.item_list, 5))
end
elseif fields.key_enter_field == "item_input" then
table.insert(widgets[id].captions, fields.item_input)
elseif fields.transparent_box then
widgets[id].transparent = fields.transparent_box == "true"
elseif fields.border_box then
widgets[id].border = fields.border_box == "true"
end
reload_ui()
end
},
Options = {
ui = function(id, left, top, width)
local form = "label["..left+1.8 ..","..top ..";- Options -]" ..
"button["..left+0.1 ..","..top+1 ..";2,1;func_create;generate function]" ..
"button["..left+2.1 ..","..top+1 ..";2,1;string_create;generate string]" ..
""
return form
end,
func = function(id, fields)
if fields.string_create then -- display the formspec to output the generated string (and generate it)
minetest.show_formspec("ui_editor:output",
"size[10,8]" ..
"textarea[1,1;9,7;_;Generated Code;"..form_esc(generate_string()).."]" ..
"button[8.8,0;1,1;back;back]")
elseif fields.func_create then -- display the (same) formspec to output the generated function (and generate it)
minetest.show_formspec("ui_editor:output",
"size[10,8]" ..
"textarea[1,1;9,7;_;Generated Code;"..form_esc(generate_function()).."]" ..
"button[8.8,0;1,1;back;back]")
end
end
},
New = {
ui = function(id, left, top, width)
local widg_str = "" -- convert the list of widget types to a string
for i, v in pairs(widg_list) do
widg_str = widg_str..v..","
end
local form = "label["..left+1.6 ..","..top ..";- NEW WIDGET -]" ..
"textlist["..left+0.1 ..","..top+0.4 ..";"..width-0.2 ..",6;new_widg_selector;"..widg_str.."]"
return form
end,
func = function(id, fields)
if fields.new_widg_selector then
if string.sub(fields.new_widg_selector, 1, 3) == "DCL" then
local name = widg_list[tonumber(string.sub(fields.new_widg_selector, 5))]
selected_widget = #widgets +1
-- widget defaults --
-- create widgets with the correct and default data
if name == "Button" then
table.insert(widgets, {type="Button", name="New Button", label="New", image=false, image_param=false, texture="default_cloud.png", item=false,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="L+", bottom=1, bottom_type="R"})
elseif name == "Field" then
table.insert(widgets,
{type="Field", name="New Field", label="", default="", default_param=false, password=false, enter_close=true,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="L+", bottom=1, bottom_type="R"})
elseif name == "TextArea" then
table.insert(widgets, {type="TextArea", name="New TextArea", label="", default="", default_param=false,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="L+", bottom=2, bottom_type="T+"})
elseif name == "Label" then
table.insert(widgets, {type="Label", name="New Label", label="New Label", label_param=false, vertical=false,
left=1, left_type="L+", top=1, top_type="T+"})
elseif name == "TextList" then
table.insert(widgets,
{type="TextList", name="New TextList", items={}, items_param=false, item_id_param=false, transparent=false,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="L+", bottom=2, bottom_type="T+"})
elseif name == "DropDown" then
table.insert(widgets,
{type="DropDown", name="New DropDown", items={}, items_param=false, item_id_param=false, select_id=1,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="L+", bottom=1, bottom_type="R"})
elseif name == "CheckBox" then
table.insert(widgets, {type="CheckBox", name="New CheckBox", label="New CheckBox", checked=false, checked_param=false,
left=1, left_type="L+", top=1, top_type="T+"})
elseif name == "Box" then
table.insert(widgets, {type="Box", name="New Box", colour="#ffffff", colour_param=false,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="L+", bottom=2, bottom_type="T+"})
elseif name == "Image" then
table.insert(widgets, {type="Image", name="New Image", image="default_cloud.png", image_param=false, item=false,
background=false, fill=false,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="L+", bottom=2, bottom_type="T+"})
elseif name == "Slider" then
table.insert(widgets, {type="Slider", name="New Slider", vertical=false, value=0, value_param=false,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="R", bottom=0.3, bottom_type="R"})
elseif name == "Table" then
table.insert(widgets, {selected_column=-1, type="Table", name="New Table", selected_param=false, columns = {},
select_param=false,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="L+", bottom=2, bottom_type="T+"})
elseif name == "InvList" then
table.insert(widgets, {type="InvList", name="main", location="current_player", start_param=false, data="",
data_param=false, ring=false, colour_tab=false, start=0,
left=1, left_type="L+", top=1, top_type="T+", right=2, right_type="L+", bottom=2, bottom_type="T+"})
elseif name == "Tooltip" then
table.insert(widgets, {type="Tooltip", name="widget", text="New Tooltip", colours=false, bg="#00cc00", fg="#000000"})
elseif name == "Container" then
table.insert(widgets, {type="Container - Start", name="New container", left_param=false, top_param=false,
left=1, left_type="L+", top=1, top_type="T+", right=4, right_type="L+", bottom=4, bottom_type="T+"})
table.insert(widgets, {type="Container - End", name=""})
elseif name == "Tabs" then
table.insert(widgets, {type="Tabs", name="New Tabs", captions={}, tab=1, transparent=false, border=false,
left=0, left_type="L+", top=0, top_type="T+"})
end
new_widg_tab = false
reload_ui()
end
end
end
},
}
----------
-- GENERAL
----------
-- handles formspec input, or sends to correct places
minetest.register_on_formspec_input(function(formname, fields)
if formname == "ui_editor:main" then
if fields.widg_select then -- select a widget
selected_widget = tonumber(string.sub(fields.widg_select, 5))-4
new_widg_tab = false
minetest.show_formspec("ui_editor:main", main_ui_form())
elseif fields.widg_mov_up then -- move a widget up
if selected_widget > 2 then
if widgets[selected_widget].type == "Container - End" and widgets[selected_widget-1].type == "Container - Start" then
local pos = selected_widget-2 -- containers must always make sence. each start must have an end after it,
local count = 0 -- -- so they can't move past eachother in some cases
while pos > 0 do
if widgets[pos].type == "Container - End" then
count = count-1
elseif widgets[pos].type == "Container - Start" then
count = count+1
end
pos = pos-1
end
if count <= 0 then return true end
end
table.insert(widgets, selected_widget-1, table.remove(widgets, selected_widget)) -- move it
selected_widget = selected_widget-1
new_widg_tab = false
reload_ui()
end
elseif fields.widg_mov_dwn then --move a widget down
if selected_widget < #widgets and selected_widget > 1 then
if widgets[selected_widget].type == "Container - Start" and widgets[selected_widget+1].type == "Container - End" then
local pos = selected_widget+2 -- containers must have an end after them (and can't share an end)
local count = 0
while pos <= #widgets do
if widgets[pos].type == "Container - End" then
count = count+1
elseif widgets[pos].type == "Container - Start" then
count = count-1
end
pos = pos+1
end
if count <= 0 then return true end
end
table.insert(widgets, selected_widget+1, table.remove(widgets, selected_widget))
selected_widget = selected_widget+1
new_widg_tab = false
reload_ui()
end
elseif fields.widg_duplicate then -- duplicate a widget
table.insert(widgets, copy_table(widgets[selected_widget]))
new_widg_tab = false
reload_ui()
elseif fields.widg_new then -- switch to the NEW WIDGET tab
new_widg_tab = not new_widg_tab
reload_ui()
elseif fields.widg_delete then -- delete a widget
if widgets[selected_widget].type == "Container - Start" then
widget_editor_uis["Container - Start"].del(selected_widget)
else
table.remove(widgets, selected_widget)
end
selected_widget = selected_widget-1
new_widg_tab = false
reload_ui()
elseif fields.quit == nil then -- send update to widget editors
if selected_widget == -2 or new_widg_tab then
widget_editor_uis["New"].func(selected_widget, fields)
elseif selected_widget > 0 then
widget_editor_uis[widgets[selected_widget].type].func(selected_widget, fields)
new_widg_tab = false
elseif selected_widget == -3 then
widget_editor_uis["Options"].func(selected_widget, fields)
new_widg_tab = false
end
end
elseif formname == "ui_editor:output" then -- the display for outputting generated code
if fields.back then
reload_ui()
end
end
end)
-- loads the correct widget editor
local function widget_editor(left, height)
local form = "box["..left+0.1 ..",2.2;4.8,"..height-2.3 ..";#000000]"
if selected_widget == -1 or selected_widget == 0 or (selected_widget > 1 and widgets[selected_widget] == nil) then
selected_widget = -2 -- blank items in the list can be used for adding new widgets
end
if selected_widget == -2 or new_widg_tab then -- the new widget tab can be displayed without moving the selection
form = form .. widget_editor_uis["New"].ui(selected_widget, left+0.1, 2.2, 4.8)
elseif selected_widget > 0 then -- load correct editor for current selected widget
form = form .. widget_editor_uis[widgets[selected_widget].type].ui(selected_widget, left+0.1, 2.2, 4.8)
elseif selected_widget == -3 then
form = form .. widget_editor_uis["Options"].ui(selected_widget, left+0.1, 2.2, 4.8)
end
return form
end
-- creates the widget selector
local function widget_chooser(left)
local widget_str = "OPTIONS,NEW WIDGET,,.....," -- options at the top of the list
local depth = 0
for i, v in pairs(widgets) do
if v.type == "Container - End" then -- the order of end and start are because they do not need indenting
depth = depth-1
end
widget_str = widget_str .. string.rep("- ", depth) .. form_esc(v.type .. ": " .. v.name) .. ","
if v.type == "Container - Start" then -- container contents gets indented
depth = depth+1
end
end
local form = ""..
"textlist["..left+0.1 ..",0.1;3.4,2;widg_select;"..widget_str..";"..selected_widget+4 .."]" ..
"button["..left+3.6 ..",0.1;0.5,1;widg_mov_up;"..form_esc("/\\").."]" ..
"button["..left+3.6 ..",1.2;0.5,1;widg_mov_dwn;"..form_esc("\\/").."]"
if selected_widget > 1 and selected_widget <= #widgets and widgets[selected_widget].type ~= "Container - End" then
form = form .. "button["..left+4 ..",0;1,1;widg_duplicate;DUPLICATE]" ..
"button["..left+4 ..",0.7;1,1;widg_delete;DELETE]" ..
"button["..left+4 ..",1.4;1,1;widg_new;NEW]"
end
return form
end
-- puts the whole formspec together
main_ui_form = function ()
local ui, width, height = generate_ui() -- the preview
local w_selector = widget_chooser(width-5) -- the widget selector
local w_editor = widget_editor(width-5, height) -- the widget editor
local form = "".. -- add everything together
"size["..width..","..height.."]" ..
"box["..width-5 ..",0;5,"..height..";#ffffff]" ..
ui .. w_selector .. w_editor .. create_tabs(2) -- add the global tabs
return form
end
---------- ----------
-- END FORM EDITOR --
---------- ----------
-- register the chat command
minetest.register_chatcommand("gui", {
description = core.gettext("UI editor"),
func = function()
minetest.show_formspec("ui_editor:main", main_ui_form())
end,
})
|
function Steelbreaker_OnEnterCombat(unit, event)
Unit:PlaySoundToSet(15674)
Unit:SendChatMessage(14, 0, "You will not defeat the Assembly of Iron so easily, invaders!")
Unit:RegisterEvent("Steelbreaker_Highvoltage", 30000, 4)
Unit:RegisterEvent("Steelbreaker_Fusion", 30000, 2)
Unit:RegisterEvent("Steelbreaker_Meltdown", 25000, 4)
Unit:RegisterEvent("Steelbreaker_Phase1", 60000, 0)
Unit:RegisterEvent("Steelbreaker_Phase2", 1000, 1)
Unit:RegisterEvent("Steelbreaker_Phase3", 1000, 1)
end
function Steelbreaker_Highvoltage(unit, event)
Unit:PlaySoundToSet(15675)
Unit:SendChatMessage("So fragile and weak!")
Unit:CastSpell(61890)
end
function Steelbreaker_Fusion(unit,event)
Unit:PlaySoundToSet(15677)
Unit:SendChatMessage(14, 0, "You seek the secrets of Ulduar? Then take them!")
Unit:CastSpellOnTarger(61902, Unit:GetMainTank())
end
--choice=math.random(1, 4)
function Steelbreaker_Phase1(unit, event)
if unit:GetHealthPct() <= 95 then
if choice==1 then
Unit:CastSpellOnTarget(61903)
end
end
end
function Steelbreaker_Meltdown(unit, event)
if choice==2 then
Unit:CastSpell(61889)
end
end
function Steelbreaker_Phase2(unit, event)
if unit:GetHealthPct() <= 40 then
Unit:CastSpellOnTarget(63494, Unit:GetRandomPlayer(2))
end
end
function Steelbreaker_Phase3(unit, event)
if unit:GetHealthPct() <= 35 then
Unit:CastSpellOnTarget(61889, unit:GetRandomPlayer(0))
end
end
function Steelbreaker_OnKilledTarget(unit, event)
Unit:PlaySoundToSet(15676)
Unit:SendChatMessage(14, 0, "Flesh, HAH! Such a hindrence!")
end
function Steelbreaker_OnLeaveCombat(unit, event)
Unit:PlaySoundToSet(15680)
Unit:SendChatMessage(14, 0, "This meeting of the Assembly of Iron is adjourned!")
Unit:RemoveEvents()
end
function Steelbreaker_OnDeath(unit, event)
Unit:PlaySoundToSet(15678)
Unit:SendChatMessage(14, 0, "My death only serves to hasten your demise.")
Unit:CastSpell(61920)
end
RegisterUnitEvent(32867, 1, "Steelbreaker_OnEnterCombat")
RegisterUnitEvent(32867, 2, "Steelbreaker_OnLeaveCombat")
RegisterUnitEvent(32867, 3, "Steelbreaker_OnKilledTarget")
RegisterUnitEvent(32867, 4, "Steelbreaker_OnDeath")
---------STORMCALLER BRUNDIR------------
function StormcallerBrundir_OnEnterCombat(unit, event)
Unit:PlaySoundToSet(15684)
Unit:SendChatMessage(14, 0, "Whether the world's greatest gnats or the world's greatest heroes, you're still only mortal!")
Unit:RegisterEvent("StormcallerBrundir_ChainLightning", 30000, 0)
Unit:RegisterEvent("StormcallerBrundir_LightningWhirl", 25000, 0)
Unit:RegisterEvent("StormcallerBrundir_LightningTendrils", 15000, 0)
Unit:RegisterEvent("StormcallerBrundir", 60000, 0)
Unit:RegisterEvent("StormcallerBrundir", 60000, 0)
end
function StormcallerBrundir_ChainLightning(unit, event)
Unit:PlaySoundToSet(15685)
Unit:SendChatMessage(14, 0, "A merciful kill!")
Unit:CastSpellOnTarget(63479, Unit:GetRandomPlayer(0))
end
--Choice=math.random(1, 2)
function StormcallerBrundir_Phase1(unit, event)
if Unit:GetHealthPct() <= 90 then
if choice==1 then
Unit:CastSpell(63481)
end
end
end
function StormcallerBrundir_LightningWhirl(unit, event)
Unit:PlaySoundToSet(15686)
Unit:SendChatMessage(14, 0, "HAH")
if choice==2 then
Unit:CastSpellOnTarget(63483, Unit:GetRandomPlayer(0))
end
end
Choice=math.random(1, 2)
function StormcallerBrundir_Phase2(unit, event)
if Unit:GetHealthPct() <= 50 then
Unit:PlaySoundToSet(15687)
Unit:SendChatMessage(14, 0, "Stand still and stare into the light!")
Unit:CastSpell(64187)
end
end
function StormcallerBrundir_LightningTendrils(unit, event)
if choice==2 then
Unit:CastSpellOnTarget(63485, Unit:GetRandomPlayer(4))
Unit:PlaySoundToSet(15688)
Unit:SendChatMessage(14, 0, "Let the storm clouds rise and rain down death from above!")
end
end
function StormcallerBrundir_OnLeaveCombat(unit, event)
Unit:PlaySoundToSet(15689)
Unit:SendChatMessage(14, 0, "The power of the storm lives on...")
Unit:RemoveEvents()
end
function StormcallerBrundir_Death(unit, event)
Unit:PlaySoundToSet(15690)
Unit:SendChatMessage(14, 0, "You rush headlong into the maw of madness!")
Unit:RemoveEvents()
end
function StormcallerBrundir_OnKilledTarget(unit, event)
end
RegisterUnitEvent(32857, 1, "StormcallerBrundir_OnEnterCombat")
RegisterUnitEvent(32857, 2, "StormcallerBrundir_OnLeaveCombat")
RegisterUnitEvent(32857, 3, "StormcallerBrundir_OnKilledTarget")
RegisterUnitEvent(32857, 4, "StormcallerBrundir_Death")
------------RUNEMASTER MOLGEIN-------------
function RunemasterMolgein_OnEnterCombat(unit, event)
Unit:PlaySoundToSet(15657)
Unit:SendChatMessage(12, 0, "Nothing short of total decimation will suffice")
Unit:RegisterEvent("RunemasterMolgein_Shieldofrunes", 1000, 1)
Unit:RegisterEvent("RunemasterMolgein_Elemental", 10, 20000)
Unit:RegisterEvent("RunemasterMolgein_LightningBlast", 1000, 1)
end
function RunemasterMolgein_Shieldofrunes(unit, event)
Unit:CastSpell(63489)
end
--choice=math.random(1, 4)
function RunemasterMolgein_Phase1(unit, event)
if unit:GetHealthPct() <= 90 then
if choice==1 then
Unit:CastSpell(61974)
Unit:PlaySoundToSet(15658)
Unit:SendChatMessage(14, 0, "The world suffers yet another insignificant loss.")
end
end
end
function RunemasterMolgein_Runeofdeath(unit, event)
if choice==2 then
Unit:CastSpell(63490)
Unit:PlaySoundToSet(15660)
Unit:SendChatMessage(14, 0, "Decipher this!")
end
end
function RunemasterMolgein_Elemental(unit, event)
if unit:GetHealthPct() <= 70 then
Unit:SpawnCreature(34147, x, y, z, o, 10, 20000)
Unit:PlaySoundToSet(15661)
Unit:SendChatMessage(14, 0, "Face the lightning surge!")
end
end
function RunemasterMolgein_LightningBlast(unit, event)
if unit:GetHealthPct() <= 10 then
Unit:CastSpell(63491)
Unit:PlaySoundToSet(15664)
Unit:SendChatMessage(14, 0, "This meeting of the Assembly of Iron is adjourned!")
end
end
function RunemasterMolgein_OnLeaveCombat(unit, event)
Unit:PlaySoundToSet(15662)
Unit:SendChatMessage(14, 0, "The legacy of storms shall not be undone.")
Unit:Despawn(1000, 0)
Unit:RemoveEvents()
end
function RunemasterMolgein_Death(unit, event)
Unit:PlaySoundToSet(15663)
Unit:SendChatMessage(14, 0, "What have you gained from my defeat? You are no less doomed, mortals!")
Unit:Despawn(1000, 0)
Unit:RemoveEvents()
end
function RunemasterMolgein_OnKilledTarget(pUnit, Event)
end
RegisterUnitEvent(32927, 1, "RunemasterMolgein_OnEnterCombat")
RegisterUnitEvent(32927, 2, "RunemasterMolgein_OnLeaveCombat")
RegisterUnitEvent(32927, 3, "RunemasterMolgein_OnKilledTarget")
RegisterUnitEvent(32927, 4, "RunemasterMolgein_Death") |
--
-- Anti-Cheat Control Panel
--
-- _common.lua
--
_version = "0.1.8"
MIN_CLIENT_VERSION_FOR_MOD_BLOCKS = "1.3.1-9.04818"
function outputDebug(msg)
msg = getTickCount() .. " " .. msg
outputDebugString(msg)
end
function stripColorCodes ( text )
return string.gsub ( text, '#%x%x%x%x%x%x', '' )
end
function table.find(t, ...)
local args = { ... }
if #args == 0 then
for k,v in pairs(t) do
if v then
return k, v
end
end
return false
end
local value = table.remove(args)
if value == '[nil]' then
value = nil
end
for k,v in pairs(t) do
for i,index in ipairs(args) do
if type(index) == 'function' then
v = index(v)
else
if index == '[last]' then
index = #v
end
v = v[index]
end
end
if v == value then
return k, t[k]
end
end
return false
end
function math.bit(p)
return 2 ^ (p - 1) -- 1-based indexing
end
-- Typical call: if hasbit(x, bit(3)) then ...
function math.hasbit(x, p)
return x % (p + p) >= p
end
newline = "\n"
colorYellow = {255,255,0}
colorGreen = {128,255,128}
colorRed = {255,128,128}
colorGrey = {128,128,128}
colorLtGrey = {192,192,192}
colorWhite = {255,255,255}
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
aBlockModsTab_presets = {
none = "",
all = "*",
modelsAnims = ".ifp" .. newline ..
".dff",
weaponModels = "grenade.dff" .. newline ..
"teargas.dff" .. newline ..
"molotov.dff" .. newline ..
"colt45.dff" .. newline ..
"silenced.dff" .. newline ..
"desert_eagle.dff" .. newline ..
"chromegun.dff" .. newline ..
"sawnoff.dff" .. newline ..
"shotgspa.dff" .. newline ..
"micro_uzi.dff" .. newline ..
"mp5lng.dff" .. newline ..
"ak47.dff" .. newline ..
"m4.dff" .. newline ..
"cuntgun.dff" .. newline ..
"rocketla.dff" .. newline ..
"heatseek.dff" .. newline ..
"flame.dff" .. newline ..
"minigun.dff" .. newline ..
"satchel.dff" .. newline ..
"tec9.dff" .. newline ..
"sniper.dff",
playerModels =
[[cj.dff
truth.dff
maccer.dff
andre.dff
bbthin.dff
bb.dff
emmet.dff
male01.dff
janitor.dff
bfori.dff
bfost.dff
vbfycrp.dff
bfyri.dff
bfyst.dff
bmori.dff
bmost.dff
bmyap.dff
bmybu.dff
bmybe.dff
bmydj.dff
bmyri.dff
bmycr.dff
bmyst.dff
wmybmx.dff
wbdyg1.dff
wbdyg2.dff
wmybp.dff
wmycon.dff
bmydrug.dff
wmydrug.dff
hmydrug.dff
dwfolc.dff
dwmolc1.dff
dwmolc2.dff
dwmylc1.dff
hmogar.dff
wmygol1.dff
wmygol2.dff
hfori.dff
hfost.dff
hfyri.dff
hfyst.dff
jethro.dff
hmori.dff
hmost.dff
hmybe.dff
hmyri.dff
hmycr.dff
hmyst.dff
omokung.dff
wmymech.dff
bmymoun.dff
wmymoun.dff
ofost.dff
ofyri.dff
ofyst.dff
omori.dff
omost.dff
omyri.dff
omyst.dff
wmyplt.dff
wmopj.dff
bfypro.dff
hfypro.dff
kendl.dff
bmypol1.dff
bmypol2.dff
wmoprea.dff
sbfyst.dff
wmosci.dff
wmysgrd.dff
swmyhp1.dff
swmyhp2.dff
swfopro.dff
wfystew.dff
swmotr1.dff
wmotr1.dff
bmotr1.dff
vbmybox.dff
vwmybox.dff
vhmyelv.dff
vbmyelv.dff
vimyelv.dff
vwfypro.dff
ryder3.dff
vwfyst1.dff
wfori.dff
wfost.dff
wfyjg.dff
wfyri.dff
wfyro.dff
wfyst.dff
wmori.dff
wmost.dff
wmyjg.dff
wmylg.dff
wmyri.dff
wmyro.dff
wmycr.dff
wmyst.dff
ballas1.dff
ballas2.dff
ballas3.dff
fam1.dff
fam2.dff
fam3.dff
lsv1.dff
lsv2.dff
lsv3.dff
maffa.dff
maffb.dff
mafboss.dff
vla1.dff
vla2.dff
vla3.dff
triada.dff
triadb.dff
sindaco.dff
triboss.dff
dnb1.dff
dnb2.dff
dnb3.dff
vmaff1.dff
vmaff2.dff
vmaff3.dff
vmaff4.dff
dnmylc.dff
dnfolc1.dff
dnfolc2.dff
dnfylc.dff
dnmolc1.dff
dnmolc2.dff
sbmotr2.dff
swmotr2.dff
sbmytr3.dff
swmotr3.dff
wfybe.dff
bfybe.dff
hfybe.dff
sofybu.dff
sbmyst.dff
sbmycr.dff
bmycg.dff
wfycrk.dff
hmycm.dff
wmybu.dff
bfybu.dff
smokev.dff
wfybu.dff
dwfylc1.dff
wfypro.dff
wmyconb.dff
wmybe.dff
wmypizz.dff
bmobar.dff
cwfyhb.dff
cwmofr.dff
cwmohb1.dff
cwmohb2.dff
cwmyfr.dff
cwmyhb1.dff
bmyboun.dff
wmyboun.dff
wmomib.dff
bmymib.dff
wmybell.dff
bmochil.dff
sofyri.dff
somyst.dff
vwmybjd.dff
vwfycrp.dff
sfr1.dff
sfr2.dff
sfr3.dff
bmybar.dff
wmybar.dff
wfysex.dff
wmyammo.dff
bmytatt.dff
vwmycr.dff
vbmocd.dff
vbmycr.dff
vhmycr.dff
sbmyri.dff
somyri.dff
somybu.dff
swmyst.dff
wmyva.dff
copgrl3.dff
gungrl3.dff
mecgrl3.dff
nurgrl3.dff
crogrl3.dff
gangrl3.dff
cwfofr.dff
cwfohb.dff
cwfyfr1.dff
cwfyfr2.dff
cwmyhb2.dff
dwfylc2.dff
dwmylc2.dff
omykara.dff
wmykara.dff
wfyburg.dff
vwmycd.dff
vhfypro.dff
suzie.dff
omonood.dff
omoboat.dff
wfyclot.dff
vwmotr1.dff
vwmotr2.dff
vwfywai.dff
sbfori.dff
swfyri.dff
wmyclot.dff
sbfost.dff
sbfyri.dff
sbmocd.dff
sbmori.dff
sbmost.dff
shmycr.dff
sofori.dff
sofost.dff
sofyst.dff
somobu.dff
somori.dff
somost.dff
swmotr5.dff
swfori.dff
swfost.dff
swfyst.dff
swmocd.dff
swmori.dff
swmost.dff
shfypro.dff
sbfypro.dff
swmotr4.dff
swmyri.dff
smyst.dff
smyst2.dff
sfypro.dff
vbfyst2.dff
vbfypro.dff
vhfyst3.dff
bikera.dff
bikerb.dff
bmypimp.dff
swmycr.dff
wfylg.dff
wmyva2.dff
bmosec.dff
bikdrug.dff
wmych.dff
sbfystr.dff
swfystr.dff
heck1.dff
heck2.dff
bmycon.dff
wmycd1.dff
bmocd.dff
vwfywa2.dff
wmoice.dff
tenpen.dff
pulaski.dff
Hernandez.dff
dwayne.dff
smoke.dff
sweet.dff
ryder.dff
forelli.dff
tbone.dff
laemt1.dff
lvemt1.dff
sfemt1.dff
lafd1.dff
lvfd1.dff
sffd1.dff
lapd1.dff
sfpd1.dff
lvpd1.dff
csher.dff
lapdm1.dff
swat.dff
fbi.dff
army.dff
dsher.dff
zero.dff
rose.dff
paul.dff
cesar.dff
ogloc.dff
wuzimu.dff
torino.dff
jizzy.dff
maddogg.dff
cat.dff
claude.dff]]
}
aBlockModsTab = {
radioButtons = {
{ type="none", desc="None", color=colorRed, button=false, custom=false, text=aBlockModsTab_presets.none },
{ type="all", desc="All", color=colorGreen, button=false, custom=false, text=aBlockModsTab_presets.all },
{ type="models_anims", desc="Models+Anims", color=colorWhite, button=false, custom=false, text=aBlockModsTab_presets.modelsAnims },
{ type="weapons", desc="Some weapons", color=colorWhite, button=false, custom=false, text=aBlockModsTab_presets.weaponModels },
{ type="players", desc="Player Models", color=colorWhite, button=false, custom=false, text=aBlockModsTab_presets.playerModels },
{ type="custom", desc="Custom", color=colorWhite, button=false, custom=true, text="" },
}
}
function aBlockModsTab.getInfoForType(type)
for _,info in ipairs(aBlockModsTab.radioButtons) do
if info.type == type then
return info
end
end
end
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
aServerConfigTab_presets = {
none = "",
maxMinClient = "1.3.1-9.04835",
release = "1.3.1-9.04709",
}
aServerConfigTab = {
radioButtons = {
{ type="none", desc="None", color=colorRed, button=false, custom=false, text=aServerConfigTab_presets.none },
{ type="latest", desc="Latest anti-cheat defs", color=colorGreen, button=false, custom=false, text=aServerConfigTab_presets.maxMinClient },
{ type="release", desc="Current release version", color=colorWhite, button=false, custom=false, text=aServerConfigTab_presets.release },
{ type="custom", desc="Custom", color=colorWhite, button=false, custom=true, text="" },
}
}
function aServerConfigTab.getInfoForType(type)
for _,info in ipairs(aServerConfigTab.radioButtons) do
if info.type == type then
return info
end
end
end
|
game = {
timePlayed = 0,
timeRequired = 0,
displayHint = 0,
triggerHint = false,
modes = {
beginner = {
timeRequired = 15 * 60,
hints = {
"have some tea",
"clean up your room",
"do your laundry",
"take a short walk",
"call your mother",
"read a newspaper"
}
},
advanced = {
timeRequired = 1 * 3600,
hints = {
"work out",
"read a book",
"take a long walk",
"cook yourself some nice meal"
}
},
expert = {
timeRequired = 24 * 3600,
hints = {
"go hiking",
"hang out in the park",
"meet some old friends"
}
}
}
}
function game:enter()
love.mouse.setVisible(false)
self.timeRequired = self.modes[self.mode].timeRequired
self.displayHint = 0
self.mouseX, self.mouseY = love.mouse.getPosition()
end
function game:update(timeElapsed)
self.timePlayed = self.timePlayed + timeElapsed
if self.timePlayed >= self.timeRequired then
switchState("win")
end
if self.displayHint > 0 then
self.displayHint = self.displayHint - timeElapsed
end
local mX, mY = love.mouse.getPosition()
if mX ~= self.mouseX and mX ~= self.mouseX then
self.mouseX, self.mouseY = mX, mY
self.triggerHint = true
end
if self.triggerHint then
self.triggerHint = false
if self.displayHint <= 0 then
-- somehow the randomness is broken and we have to seed it
math.randomseed(timeElapsed)
self.hint = self.modes[self.mode].hints[math.random(#self.modes[self.mode].hints)]
end
self.displayHint = 10
end
end
function game:draw()
local timeLeft = self.timeRequired - self.timePlayed
local textual = secondsToCountdown(timeLeft)
local countdownX = (love.graphics.getWidth() * 0.5) - (fonts.countdown:getWidth(textual) * 0.5)
local countdownY = (love.graphics.getHeight() * 0.5) - (fonts.countdown:getHeight() * 0.5)
love.graphics.setFont(fonts.countdown)
love.graphics.print(textual, countdownX, countdownY)
if self.displayHint > 0 and self.hint ~= nil then
local hintOffsetY = countdownY + (fonts.countdown:getHeight())
local text = {
"Don't know what to do?",
"How about you ...",
"",
self.hint.."?"
}
love.graphics.setFont(fonts.text)
for index, line in pairs(text) do
local hintY = hintOffsetY + (fonts.text:getHeight() * (index - 1))
local hintX = (love.graphics.getWidth() * 0.5) - (fonts.text:getWidth(line) * 0.5)
love.graphics.print(line, hintX, hintY)
end
end
end
function game:mousepressed()
self.triggerHint = true
end
function game:keypressed(key)
if key == "escape" then
switchState("lost")
else
self.triggerHint = true
end
end
function game:focus()
switchState("lost")
end |
-- This Library is just for PAC3 Integration.
-- You must install PAC3 to make this library works.
PLUGIN.name = "PAC3 Integration"
PLUGIN.author = "Black Tea"
PLUGIN.desc = "More Upgraded, More well organized PAC3 Integration made by Black Tea"
PLUGIN.partData = {}
if (not pac) then
return
end
nut.util.include("sh_permissions.lua")
nut.util.include("sh_pacoutfit.lua")
nut.util.include("sv_parts.lua")
nut.util.include("cl_parts.lua")
nut.util.include("cl_ragdolls.lua")
|
local Collapse, parent = torch.class('rnn2d.Collapse', 'nn.Module')
function Collapse:__init(op, dimension, narrow)
parent.__init(self)
self.op = op
self.dimension = dimension
self.narrow = narrow or nil
assert(self.op == 'sum' or self.op == 'mean',
('Collapse operation %q is not implemented!'):format(op))
assert(self.dimension ~= nil)
self.output = torch.Tensor():type(self:type())
self.gradInput = torch.Tensor():type(self:type())
end
function Collapse:updateOutput(input)
local dim = self.dimension < 0 and input:dim() + self.dimension + 1 or self.dimension
local len = self.narrow or input:size(dim)
local n = input:size(dim) / len
assert(math.floor(n) == n, ('Input dimension %d is not divisible by %d!'):format(dim, len))
-- Initialize output to zeros
self.output = self.output:resizeAs(input:narrow(dim, 1, len)):zero()
-- Compute output
for i=1,n do
if self.op == 'sum' then
self.output:add(input:narrow(dim, (i - 1) * len + 1, len))
elseif self.op == 'mean' then
self.output:add(1.0 / n, input:narrow(dim, (i - 1) * len + 1, len))
else
error(('Collapse operation %q not implemented!'):format(self.op))
end
end
return self.output
end
function Collapse:updateGradInput(input, gradOutput)
local dim = self.dimension < 0 and input:dim() + self.dimension + 1 or self.dimension
local len = self.narrow or input:size(dim)
local n = input:size(dim) / len
assert(math.floor(n) == n, ('Input dimension %d is not divisible by %d!'):format(dim, len))
-- Initialize gradInput to zeros
self.gradInput = self.gradInput:resizeAs(input):zero()
-- Compute gradInput
for i=1,n do
if self.op == 'sum' then
self.gradInput:narrow(dim, (i - 1) * len + 1, len):copy(gradOutput)
elseif self.op == 'mean' then
self.gradInput:narrow(dim, (i - 1) * len + 1, len):copy(gradOutput):div(n)
else
error(('Collapse operation %q not implemented!'):format(self.op))
end
end
return self.gradInput
end
return Collapse
|
--[[
cargBags: An inventory framework addon for World of Warcraft
Copyright (C) 2010 Constantin "Cargor" Schomburg <[email protected]>
cargBags is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
cargBags is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cargBags; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
DESCRIPTION
This file holds a list of default layouts
DEPENDENCIES
mixins/api-common.lua
]]
----------------------------------------------------------
-- Load RayUI Environment
----------------------------------------------------------
RayUI:LoadEnv("Bags")
local layouts = _cargBags.classes.Container.layouts
function layouts.grid(self, columns, spacing, xOffset, yOffset)
columns, spacing = columns or 8, spacing or 5
xOffset, yOffset = xOffset or 0, yOffset or 0
local width, height = 0, 0
local col, row = 0, 0
for i, button in ipairs(self.buttons) do
if(i == 1) then -- Hackish, I know
width, height = button:GetSize()
end
col = i % columns
if(col == 0) then col = columns end
row = math.ceil(i/columns)
local xPos = (col-1) * (width + spacing)
local yPos = -1 * (row-1) * (height + spacing)
button:ClearAllPoints()
button:SetPoint("TOPLEFT", self, "TOPLEFT", xPos+xOffset, yPos+yOffset)
end
return columns * (width+spacing)-spacing, row * (height+spacing)-spacing
end
--[[!
Places the buttons in a circle [experimental]
@param radius <number> radius of the circle [optional]
@param xOffset <number> x-offset of the whole layout [default: 0]
@param yOffset <number> y-offset of the whole layout [default: 0]
]]
function layouts.circle(self, radius, xOffset, yOffset)
radius = radius or (#self.buttons*50)/math.pi/2
xOffset, yOffset = xOffset or 0, yOffset or 0
local a = 360/#self.buttons
for i, button in ipairs(self.buttons) do
local x = radius*cos(a*i)
local y = -radius*sin(a*i)
button:ClearAllPoints()
button:SetPoint("TOPLEFT", self, "TOPLEFT", radius+x+xOffset, y-radius+yOffset)
end
return radius*2, radius*2
end
|
local Court = {}
-- The top edge of the court
Court.TOP = 0
-- The bottom edge of the court
Court.BOTTOM = love.graphics.getHeight()
return Court
|
function menu.information()
if imgui.BeginTabItem("Information") then
gui.title("Help", true)
function helpItem(item, text)
imgui.BulletText(item)
gui.helpMarker(text)
end
helpItem("Linear SV", "Creates an SV gradient based on two points in time")
helpItem("Stutter SV", "Creates a normalized stutter effect with start, equalize and end SV")
helpItem("Cubic Bezier", "Creates velocity points for a path defined by a cubic bezier curve")
helpItem("Range Editor", "Edit SVs/Notes/BPM points in the map in nearly limitless ways")
gui.title("About", false, "Hyperlinks have been removed so copy-able links have been provided to paste into your browser")
function listItem(text, url)
imgui.TextWrapped(text)
gui.hyperlink(url)
end
listItem("iceSV Wiki (in progress)", "https://github.com/IceDynamix/iceSV/wiki")
listItem("Github Repository", "https://github.com/IceDynamix/iceSV")
listItem("Heavily inspired by Evening's re:amber", "https://github.com/Eve-ning/reamber")
gui.tooltip("let's be real this is basically a direct quaver port")
imgui.EndTabItem()
end
end
function menu.linearSV()
local menuID = "linear"
if imgui.BeginTabItem("Linear") then
-- Initialize variables
local vars = {
startSV = 1,
endSV = 1,
intermediatePoints = 16,
startOffset = 0,
endOffset = 0,
skipEndSV = false,
lastSVs = {}
}
util.retrieveStateVariables(menuID, vars)
-- Create UI Elements
gui.title("Offset", true)
gui.startEndOffset(vars)
gui.title("Velocities")
local velocities = { vars.startSV, vars.endSV }
imgui.PushItemWidth(style.CONTENT_WIDTH)
_, velocities = imgui.DragFloat2("Start/End Velocity", velocities, 0.01, -10.0, 10.0, "%.2fx")
imgui.PopItemWidth()
vars.startSV, vars.endSV = table.unpack(velocities)
gui.helpMarker("Ctrl+Click to enter as text!")
local widths = util.calcAbsoluteWidths({0.7,0.3})
if imgui.Button("Swap start and end velocity", {widths[1], style.DEFAULT_WIDGET_HEIGHT}) then
vars.startSV, vars.endSV = vars.endSV, vars.startSV
end
gui.sameLine()
if imgui.Button("Reset", {widths[2], style.DEFAULT_WIDGET_HEIGHT}) then
vars.startSV = 1
vars.endSV = 1
end
gui.title("Utilities")
gui.intermediatePoints(vars)
gui.title("Calculate")
if gui.insertButton() then
vars.lastSVs = sv.linear(
vars.startSV,
vars.endSV,
vars.startOffset,
vars.endOffset,
vars.intermediatePoints,
vars.skipEndSV
)
editor.placeElements(vars.lastSVs)
end
if imgui.Button("Cross multiply in map", style.FULLSIZE_WIDGET_SIZE) then
baseSV = util.filter(
map.ScrollVelocities,
function (k, v)
return v.StartTime >= vars.startOffset
and v.StartTime <= vars.endOffset
end
)
crossSV = sv.linear(
vars.startSV,
vars.endSV,
vars.startOffset,
vars.endOffset,
500, -- used for more accurate linear values when looking up
vars.skipEndSV
)
newSV = sv.crossMultiply(baseSV, crossSV)
actions.RemoveScrollVelocityBatch(baseSV)
editor.placeElements(newSV)
end
gui.tooltip("Multiplies all SVs in the map between the given start and end offset linearly with the given parameters")
-- Save variables
util.saveStateVariables(menuID, vars)
imgui.EndTabItem()
end
end
function menu.stutterSV()
if imgui.BeginTabItem("Stutter") then
local menuID = "stutter"
local vars = {
skipEndSV = false,
skipFinalEndSV = false,
startSV = 1.5,
duration = 0.5,
averageSV = 1.0,
lastSVs = {},
allowNegativeValues = false,
effectDurationMode = 0,
effectDurationValue = 1
}
util.retrieveStateVariables(menuID, vars)
gui.title("Note", true)
imgui.Text("Select some hitobjects and play around!")
gui.title("Settings")
local modes = {
"Distance between notes",
"BPM/measure snap",
"Absolute length"
}
imgui.PushItemWidth(style.CONTENT_WIDTH)
_, vars.effectDurationMode = imgui.Combo("Effect duration mode", vars.effectDurationMode, modes, #modes)
imgui.PopItemWidth()
gui.helpMarker("This determines the effect duration of a single stutter. Hover over the help marker input box in each mode to find out more.")
local helpMarkerText = ""
imgui.PushItemWidth(style.CONTENT_WIDTH)
-- scale with distance between notes
if vars.effectDurationMode == 0 then
_, vars.effectDurationValue = imgui.SliderFloat("Duration Scale", vars.effectDurationValue, 0, 1, "%.2f")
helpMarkerText = "Scales the effect duration together with the distance between two offsets. If left on 1, then all stutters will seamlessly connect to each other."
-- snap
elseif vars.effectDurationMode == 1 then
_, vars.effectDurationValue = imgui.DragFloat("Duration Length", vars.effectDurationValue, 0.01, 0, 10e10, "%.2f")
helpMarkerText = "Input as a fraction of a beat, e.g. 0.25 would represent an interval of 1/4."
-- absolute
elseif vars.effectDurationMode == 2 then
_, vars.effectDurationValue = imgui.DragFloat("Duration Length", vars.effectDurationValue, 0.01, 0, 10e10, "%.2f")
helpMarkerText = "Fixed length, based on a millisecond value."
end
imgui.PopItemWidth()
gui.helpMarker(helpMarkerText)
gui.spacing()
local startSVBounds = {}
imgui.PushItemWidth(style.CONTENT_WIDTH)
if vars.allowNegativeValues then
startSVBounds = {-1000, 1000}
_, vars.startSV = imgui.DragFloat("Start velocity", vars.startSV, 0.01, startSVBounds[1], startSVBounds[2], "%.2fx")
else
startSVBounds = {0, vars.averageSV/vars.duration}
_, vars.startSV = imgui.SliderFloat("Start velocity", vars.startSV, startSVBounds[1], startSVBounds[2], "%.2fx")
end
gui.helpMarker(string.format("Current bounds: %.2fx - %.2fx", startSVBounds[1], startSVBounds[2]))
imgui.PopItemWidth()
imgui.PushItemWidth(style.CONTENT_WIDTH)
_, vars.duration = imgui.SliderFloat("Start SV Duration", vars.duration, 0.0, 1.0, "%.2f")
imgui.PopItemWidth()
-- Update limits after duration has changed
vars.startSV = mathematics.clamp(vars.startSV, startSVBounds[1], startSVBounds[2])
gui.spacing()
gui.averageSV(vars)
if not (vars.effectDurationMode == 0 and vars.effectDurationValue == 1) then
_, vars.skipEndSV = imgui.Checkbox("Skip end SV of individual stutters?", vars.skipEndSV)
gui.helpMarker("If you use any other mode than \"Distance between notes\" and Scale = 1, then the stutter SVs won't directy connect to each other anymore. This adjust the behavior for the end SV of each individual stutter.")
end
_, vars.skipFinalEndSV = imgui.Checkbox("Skip the final end SV?", vars.skipFinalEndSV)
_, vars.allowNegativeValues = imgui.Checkbox("Allow negative Values?", vars.allowNegativeValues)
gui.helpMarker(
"Unexpected things can happen with negative SV, so I do not recommend " ..
"turning on this option unless you are an expert. This will remove the " ..
"limits for start SV. It can then be negative and also exceed the " ..
"value, where the projected equalize SV would be start to become negative."
)
gui.title("Calculate")
if gui.insertButton() then
local offsets = {}
for i, hitObject in pairs(state.SelectedHitObjects) do
offsets[i] = hitObject.StartTime
end
if #offsets == 0 then
statusMessage = "No hitobjects selected!"
elseif #offsets == 1 then
statusMessage = "Needs hitobjects on different offsets selected!"
else
offsets = util.uniqueBy(offsets)
vars.lastSVs = sv.stutter(
table.sort(offsets),
vars.startSV,
vars.duration,
vars.averageSV,
vars.skipEndSV,
vars.skipFinalEndSV,
vars.effectDurationMode,
vars.effectDurationValue
)
editor.placeElements(vars.lastSVs)
end
end
imgui.Text("Projected equalize SV: " .. string.format("%.2fx", (vars.duration*vars.startSV-vars.averageSV)/(vars.duration-1)))
gui.helpMarker("This represents the velocity of the intermediate SV that is used to balance out the initial SV")
util.saveStateVariables(menuID, vars)
imgui.EndTabItem()
end
end
function menu.cubicBezierSV()
local menuID = "cubicBezier"
if imgui.BeginTabItem("Cubic Bezier") then
local vars = {
startOffset = 0,
endOffset = 0,
x1 = 0.35,
y1 = 0.00,
x2 = 0.65,
y2 = 1.00,
averageSV = 1.0,
intermediatePoints = 16,
skipEndSV = false,
lastSVs = {},
lastPositionValues = {},
stringInput = "cubic-bezier(.35,.0,.65,1)"
}
local xBounds = { 0.0, 1.0}
local yBounds = {-1.0, 2.0}
util.retrieveStateVariables(menuID, vars)
gui.title("Note", true)
gui.hyperlink("https://cubic-bezier.com/", "Create a cubic bezier here first!")
gui.title("Offset")
gui.startEndOffset(vars)
gui.title("Values")
local widths = util.calcAbsoluteWidths(style.BUTTON_WIDGET_RATIOS)
if imgui.Button("Parse", {widths[1], style.DEFAULT_WIDGET_HEIGHT}) then
local regex = "(-?%d*%.?%d+)"
captures = {}
for capture, _ in string.gmatch(vars.stringInput, regex) do
statusMessage = statusMessage .. "," .. capture
table.insert(captures, tonumber(capture))
end
if #captures >= 4 then
vars.x1, vars.y1, vars.x2, vars.y2 = table.unpack(captures)
statusMessage = "Copied values"
else
statusMessage = "Invalid string"
end
end
gui.sameLine()
imgui.PushItemWidth(widths[2])
_, vars.stringInput = imgui.InputText("String", vars.stringInput, 50, 4112)
imgui.PopItemWidth()
imgui.SameLine()
imgui.TextDisabled("(?)")
if imgui.IsItemHovered() then
imgui.BeginTooltip()
imgui.TextWrapped("Examples:")
gui.bulletList({
"cubic-bezier(.35,.0,.65,1)",
".17,.67,.83,.67",
"https://cubic-bezier.com/#.76,-0.17,.63,1.35"
})
imgui.TextWrapped("Or anything else that has 4 numbers")
imgui.EndTooltip()
end
imgui.PushItemWidth(style.CONTENT_WIDTH)
local coords = {}
_, coords = imgui.DragFloat4("x1, y1, x2, y2", {vars.x1, vars.y1, vars.x2, vars.y2}, 0.01, -5, 5, "%.2f")
vars.y2, vars.x1, vars.y1, vars.x2 = table.unpack(coords) -- the coords returned are in this order for some stupid reason??
imgui.PopItemWidth()
gui.helpMarker("x: 0.0 - 1.0\ny: -1.0 - 2.0")
-- Set limits here instead of in the DragFloat4, since this also covers the parsed string
vars.x1, vars.x2 = table.unpack(util.mapFunctionToTable({vars.x1, vars.x2}, mathematics.clamp, xBounds))
vars.y1, vars.y2 = table.unpack(util.mapFunctionToTable({vars.y1, vars.y2}, mathematics.clamp, yBounds))
gui.spacing()
gui.averageSV(vars, widths)
gui.title("Utilities")
gui.intermediatePoints(vars)
gui.title("Calculate")
if gui.insertButton() then
statusMessage = "pressed"
vars.lastSVs, vars.lastPositionValues = sv.cubicBezier(
vars.x1,
vars.y1,
vars.x2,
vars.y2,
vars.startOffset,
vars.endOffset,
vars.averageSV,
vars.intermediatePoints,
vars.skipEndSV
)
editor.placeElements(vars.lastSVs)
end
if #vars.lastSVs > 0 then
gui.title("Plots")
gui.plot(vars.lastPositionValues, "Position Data", "y")
gui.plot(vars.lastSVs, "Velocity Data", "Multiplier")
end
util.saveStateVariables(menuID, vars)
imgui.EndTabItem()
end
end
function menu.rangeEditor()
if imgui.BeginTabItem("Range Editor") then
local menuID = "range"
local vars = {
startOffset = 0,
endOffset = 0,
selections = {
[0] = {},
[1] = {},
[2] = {}
},
type = 0,
windowSelectedOpen = false,
selectionFilters = {
StartTime = {active = false, operator = 0, value = 0},
Multiplier = {active = false, operator = 0, value = 0},
EndTime = {active = false, operator = 0, value = 0},
Lane = {active = false, operator = 0, value = 0},
EditorLayer = {active = false, operator = 0, value = 0},
Bpm = {active = false, operator = 0, value = 0}
},
arithmeticActions = {
StartTime = {active = false, operator = 0, value = 0},
Multiplier = {active = false, operator = 0, value = 0},
EndTime = {active = false, operator = 0, value = 0},
Lane = {active = false, operator = 0, value = 0},
EditorLayer = {active = false, operator = 0, value = 0},
Bpm = {active = false, operator = 0, value = 0}
}
}
util.retrieveStateVariables(menuID, vars)
gui.title("Note", true)
imgui.TextWrapped("This is a very powerful tool and " ..
"can potentially erase hours of work, so please be careful and work on a " ..
"temporary difficulty if necessary! Please keep in mind that the selection " ..
"is cleared once you leave the editor (including testplaying).")
gui.title("Range")
gui.startEndOffset(vars)
gui.title("Selection", false, "You can think of the selection as your second clipboard. Once elements are in your selection, you can edit the element's values and/or paste them at different points in the map. Or just delete it, it's up to you.\n\nFilters limit SVs/Notes/BPM Points in the given range to be added/removed. Every active condition must be true (AND). A (OR) can be simulated by adding a range multiple times with different filters.")
local selectableTypes = {
"SVs",
"Notes",
"BPM Points"
}
imgui.PushItemWidth(style.CONTENT_WIDTH)
_, vars.type = imgui.Combo("Selection Type", vars.type, selectableTypes, #selectableTypes)
imgui.PopItemWidth()
local buttonWidths = util.calcAbsoluteWidths({0.5, 0.5})
local addRangeButtonWidth
if #vars.selections[vars.type] > 0 then addRangeButtonWidth = buttonWidths[1]
else addRangeButtonWidth = style.CONTENT_WIDTH end
gui.spacing()
local widths = util.calcAbsoluteWidths({0.25, 0.75}, style.CONTENT_WIDTH - style.DEFAULT_WIDGET_HEIGHT - style.SAMELINE_SPACING)
for i, attribute in pairs(editor.typeAttributes[vars.type]) do
if attribute == "StartTime" then goto continue end -- imagine a conitnue
_, vars.selectionFilters[attribute].active = imgui.Checkbox(
"##ActiveCheckbox" .. attribute, vars.selectionFilters[attribute].active
)
gui.sameLine()
if vars.selectionFilters[attribute].active then
imgui.PushItemWidth(widths[1])
_, vars.selectionFilters[attribute].operator = imgui.Combo(
"##comparisonOperator" .. attribute,
vars.selectionFilters[attribute].operator,
mathematics.comparisonOperators,
#mathematics.comparisonOperators
)
imgui.PopItemWidth()
gui.sameLine()
imgui.PushItemWidth(widths[2])
_, vars.selectionFilters[attribute].value = imgui.InputFloat(attribute, vars.selectionFilters[attribute].value)
imgui.PopItemWidth()
else
imgui.Text(attribute .. " Filter")
end
::continue::
end
gui.spacing()
if imgui.Button("Add range", {addRangeButtonWidth, style.DEFAULT_WIDGET_HEIGHT}) then
local elements = {
[0] = map.ScrollVelocities,
[1] = map.HitObjects,
[2] = map.TimingPoints
}
local previousCount = #vars.selections[vars.type]
-- Find
-- Range filter
local newElements = util.filter(
elements[vars.type],
function(i, element)
return element.StartTime >= vars.startOffset
and element.StartTime <= vars.endOffset
end
)
-- attribute filter
for attribute, filter in pairs(vars.selectionFilters) do
if filter.active then
newElements = util.filter(
newElements,
function(i, element)
return mathematics.evaluateComparison(
mathematics.comparisonOperators[filter.operator + 1],
element[attribute],
filter.value
) end
)
end
end
-- Add
newElements = util.mergeUnique(
vars.selections[vars.type],
newElements,
editor.typeAttributes[vars.type]
)
-- Sort
newElements = table.sort(
newElements,
function(a,b) return a.StartTime < b.StartTime end
)
vars.selections[vars.type] = newElements
if #vars.selections[vars.type] - previousCount == 0 then
statusMessage = string.format("No %s in range!", selectableTypes[vars.type + 1])
else
statusMessage = string.format(
"Added %s %s",
#vars.selections[vars.type] - previousCount,
selectableTypes[vars.type + 1]
)
end
end
if #vars.selections[vars.type] > 0 then
gui.sameLine()
if imgui.Button("Remove range", {buttonWidths[2], style.DEFAULT_WIDGET_HEIGHT}) then
local previousCount = #vars.selections[vars.type]
-- attribute filter
for attribute, filter in pairs(vars.selectionFilters) do
if filter.active then
vars.selections[vars.type] = util.filter(
vars.selections[vars.type],
function(i, element)
return not (mathematics.evaluateComparison(
mathematics.comparisonOperators[filter.operator + 1],
element[attribute],
filter.value
) and (
element.StartTime >= vars.startOffset and
element.StartTime <= vars.endOffset
))
end
)
end
end
if #vars.selections[vars.type] - previousCount == 0 then
statusMessage = string.format("No %s in range!", selectableTypes[vars.type + 1])
else
statusMessage = string.format(
"Removed %s %s",
previousCount - #vars.selections[vars.type],
selectableTypes[vars.type + 1]
)
end
end
gui.sameLine()
imgui.Text(string.format("%s %s in selection", #vars.selections[vars.type], selectableTypes[vars.type + 1]))
if imgui.Button("Clear selection", {buttonWidths[1], style.DEFAULT_WIDGET_HEIGHT}) then
vars.selections[vars.type] = {}
statusMessage = "Cleared selection"
end
gui.sameLine()
if imgui.Button("Toggle window", {buttonWidths[2], style.DEFAULT_WIDGET_HEIGHT}) then
vars.windowSelectedOpen = not vars.windowSelectedOpen
end
if vars.windowSelectedOpen then
window.selectedRange(vars)
end
-- TODO: Crossedit (add, multiply)
-- TODO: Subdivide by n or to time
-- TODO: Delete nth with offset
-- TODO: Plot (not for hitobjects)
-- TODO: Export as CSV/YAML
local undoHelpText = "If you decide to undo a value edit via the editor Ctrl+Z shortcut, then please keep in mind that you have to undo twice to get back to the original state, since the plugin essentially removes and then pastes the edited points. You'll need to redo your selection, since restoring the previous selection isn't doable right now. Also, editing editor layer doesn't work right now, but filtering does."
gui.title("Edit Values", false, undoHelpText)
widths = util.calcAbsoluteWidths({0.35, 0.25, 0.40}, style.CONTENT_WIDTH - style.DEFAULT_WIDGET_HEIGHT - style.SAMELINE_SPACING*2)
for i, attribute in pairs(editor.typeAttributes[vars.type]) do
if attribute == "EditorLayer" then goto continue end
_, vars.arithmeticActions[attribute].active = imgui.Checkbox(
"##activeCheckbox" .. attribute, vars.arithmeticActions[attribute].active
)
gui.sameLine()
if vars.arithmeticActions[attribute].active then
if imgui.Button("Apply##" .. attribute, {widths[1], style.DEFAULT_WIDGET_HEIGHT}) then
local newElements = editor.createNewTableOfElements(
vars.selections[vars.type],
vars.type,
{
[attribute] = function (value)
return mathematics.evaluateArithmetics(
mathematics.arithmeticOperators[vars.arithmeticActions[attribute].operator + 1],
value,
vars.arithmeticActions[attribute].value
)
end
}
)
editor.removeElements(vars.selections[vars.type], vars.type)
editor.placeElements(newElements, vars.type)
vars.selections[vars.type] = newElements
end
gui.sameLine()
imgui.PushItemWidth(widths[2])
_, vars.arithmeticActions[attribute].operator = imgui.Combo(
"##arithmeticOperator" .. attribute,
vars.arithmeticActions[attribute].operator,
mathematics.arithmeticOperators,
#mathematics.arithmeticOperators
)
imgui.PopItemWidth()
gui.sameLine()
imgui.PushItemWidth(widths[3])
_, vars.arithmeticActions[attribute].value = imgui.InputFloat(
attribute .. "##arithmeticValue" .. attribute,
vars.arithmeticActions[attribute].value
)
imgui.PopItemWidth()
else
imgui.Text(attribute)
end
::continue::
end
gui.title("Editor Actions")
if imgui.Button("Paste at current timestamp", style.FULLSIZE_WIDGET_SIZE) then
local delta = state.SongTime - vars.selections[vars.type][1].StartTime
local newTable = editor.createNewTableOfElements(
vars.selections[vars.type],
vars.type,
{
StartTime = function (startTime) return startTime + delta end,
EndTime = function (endTime) -- used for notes, ignored for svs/bpms
if endTime == 0 then return 0
else return endTime + delta end
end
}
)
editor.placeElements(newTable, vars.type)
end
if imgui.Button("Paste at all selected notes", style.FULLSIZE_WIDGET_SIZE) then
for _, hitObject in pairs(state.SelectedHitObjects) do
local delta = hitObject.StartTime - vars.selections[vars.type][1].StartTime
local newTable = editor.createNewTableOfElements(
vars.selections[vars.type],
vars.type,
{
StartTime = function (startTime) return startTime + delta end,
EndTime = function (endTime) -- used for notes, ignored for svs/bpms
if endTime == 0 then return 0
else return endTime + delta end
end
}
)
editor.placeElements(newTable, vars.type)
end
end
if imgui.Button("Delete selection from map", style.FULLSIZE_WIDGET_SIZE) then
editor.removeElements(vars.selections[vars.type], vars.type)
end
if imgui.Button("Select in editor", style.FULLSIZE_WIDGET_SIZE) and vars.type == 1 then
actions.SetHitObjectSelection(vars.selections[1])
end
end
util.saveStateVariables(menuID, vars)
imgui.EndTabItem()
end
end
|
--[[
-- added by wsh @ 2017-12-11
-- UILogin模块UILoginView窗口中服务器列表的可复用Item
--]]
local ExamTitleSlot = BaseClass("ExamTitleSlot", UIWrapComponent)
local base = UIWrapComponent
-- 创建
local function OnCreate(self)
base.OnCreate(self)
-- 组件初始化
self.examTitleItem = self:AddComponent(require("UI.ExamRoleTitle.View.ExamTitleItem"), "TitileItem");
end
-- 组件被复用时回调该函数,执行组件的刷新
local function OnRefresh(self, real_index, check)
self.cfgdata = self.view.server_list[real_index + 1]; -- 无限滑动刷新数据拿到服务器发来的背包数据
self.serverdata=self.view.model.titleList;
self.examTitleItem:SetData(self.cfgdata,self.serverdata);
end
ExamTitleSlot.OnCreate = OnCreate
ExamTitleSlot.OnRefresh = OnRefresh
return ExamTitleSlot
|
return {
ScrollBarSize = 16,
ScrollStep = 70,
}
|
--- Path and filename handling functions.
-- All paths are configured in this module, making it a single
-- point where the layout of the local installation is defined in LuaRocks.
module("luarocks.path", package.seeall)
local dir = require("luarocks.dir")
local cfg = require("luarocks.cfg")
--- Infer rockspec filename from a rock filename.
-- @param rock_name string: Pathname of a rock file.
-- @return string: Filename of the rockspec, without path.
function rockspec_name_from_rock(rock_name)
assert(type(rock_name) == "string")
local base_name = dir.base_name(rock_name)
return base_name:match("(.*)%.[^.]*.rock") .. ".rockspec"
end
function rocks_dir(repo)
if type(repo) == "string" then
return dir.path(repo, "lib", "luarocks", "rocks")
else
assert(type(repo) == "table")
return repo.rocks_dir or dir.path(repo.root, "lib", "luarocks", "rocks")
end
end
function deploy_bin_dir(repo)
if type(repo) == "string" then
return dir.path(repo, "bin")
else
assert(type(repo) == "table")
return repo.bin_dir or dir.path(repo.root, "bin")
end
end
function deploy_lua_dir(repo)
if type(repo) == "string" then
return dir.path(repo, "share", "lua", "5.1")
else
assert(type(repo) == "table")
return repo.lua_dir or dir.path(repo.root, "share", "lua", "5.1")
end
end
function deploy_lib_dir(repo)
if type(repo) == "string" then
return dir.path(repo, "lib", "lua", "5.1")
else
assert(type(repo) == "table")
return repo.lib_dir or dir.path(repo.root, "lib", "lua", "5.1")
end
end
function manifest_file(repo)
if type(repo) == "string" then
return dir.path(repo, "lib", "luarocks", "rocks", "manifest")
else
assert(type(repo) == "table")
return (repo.rocks_dir and dir.path(repo.rocks_dir, "manifest")) or dir.path(repo.root, "lib", "luarocks", "rocks", "manifest")
end
end
--- Get the repository directory for all versions of a package.
-- @param name string: The package name.
-- @return string: The resulting path -- does not guarantee that
-- @param rocks_dir string or nil: If given, specifies the local repository to use.
-- the package (and by extension, the path) exists.
function versions_dir(name, repo)
assert(type(name) == "string")
repo = repo or cfg.root_dir
return dir.path(rocks_dir(repo), name)
end
--- Get the local installation directory (prefix) for a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param rocks_dir string or nil: If given, specifies the local repository to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function install_dir(name, version, repo)
assert(type(name) == "string")
assert(type(version) == "string")
repo = repo or cfg.root_dir
return dir.path(rocks_dir(repo), name, version)
end
--- Get the local filename of the rockspec of an installed rock.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param rocks_dir string or nil: If given, specifies the local repository to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the file) exists.
function rockspec_file(name, version, repo)
assert(type(name) == "string")
assert(type(version) == "string")
repo = repo or cfg.root_dir
return dir.path(rocks_dir(repo), name, version, name.."-"..version..".rockspec")
end
--- Get the local filename of the rock_manifest file of an installed rock.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param rocks_dir string or nil: If given, specifies the local repository to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the file) exists.
function rock_manifest_file(name, version, repo)
assert(type(name) == "string")
assert(type(version) == "string")
repo = repo or cfg.root_dir
return dir.path(rocks_dir(repo), name, version, "rock_manifest")
end
--- Get the local installation directory for C libraries of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param rocks_dir string or nil: If given, specifies the local repository to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function lib_dir(name, version, repo)
assert(type(name) == "string")
assert(type(version) == "string")
repo = repo or cfg.root_dir
return dir.path(rocks_dir(repo), name, version, "lib")
end
--- Get the local installation directory for Lua modules of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param rocks_dir string or nil: If given, specifies the local repository to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function lua_dir(name, version, repo)
assert(type(name) == "string")
assert(type(version) == "string")
repo = repo or cfg.root_dir
return dir.path(rocks_dir(repo), name, version, "lua")
end
--- Get the local installation directory for documentation of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param rocks_dir string or nil: If given, specifies the local repository to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function doc_dir(name, version, repo)
assert(type(name) == "string")
assert(type(version) == "string")
repo = repo or cfg.root_dir
return dir.path(rocks_dir(repo), name, version, "doc")
end
--- Get the local installation directory for configuration files of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param rocks_dir string or nil: If given, specifies the local repository to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function conf_dir(name, version, repo)
assert(type(name) == "string")
assert(type(version) == "string")
repo = repo or cfg.root_dir
return dir.path(rocks_dir(repo), name, version, "conf")
end
--- Get the local installation directory for command-line scripts
-- of a package.
-- @param name string: The package name.
-- @param version string: The package version.
-- @param rocks_dir string or nil: If given, specifies the local repository to use.
-- @return string: The resulting path -- does not guarantee that
-- the package (and by extension, the path) exists.
function bin_dir(name, version, repo)
assert(type(name) == "string")
assert(type(version) == "string")
repo = repo or cfg.root_dir
return dir.path(rocks_dir(repo), name, version, "bin")
end
--- Extract name, version and arch of a rock filename.
-- @param rock_file string: pathname of a rock
-- @return (string, string, string) or nil: name, version and arch
-- of rock, or nil if name could not be parsed
function parse_rock_name(rock_file)
assert(type(rock_file) == "string")
return dir.base_name(rock_file):match("(.*)-([^-]+-%d+)%.([^.]+)%.rock$")
end
--- Extract name and version of a rockspec filename.
-- @param rockspec_file string: pathname of a rockspec
-- @return (string, string) or nil: name and version
-- of rockspec, or nil if name could not be parsed
function parse_rockspec_name(rockspec_file)
assert(type(rockspec_file) == "string")
return dir.base_name(rockspec_file):match("(.*)-([^-]+-%d+)%.(rockspec)")
end
--- Make a rockspec or rock URL.
-- @param pathname string: Base URL or pathname.
-- @param name string: Package name.
-- @param version string: Package version.
-- @param arch string: Architecture identifier, or "rockspec" or "installed".
-- @return string: A URL or pathname following LuaRocks naming conventions.
function make_url(pathname, name, version, arch)
assert(type(pathname) == "string")
assert(type(name) == "string")
assert(type(version) == "string")
assert(type(arch) == "string")
local filename = name.."-"..version
if arch == "installed" then
filename = dir.path(name, version, filename..".rockspec")
elseif arch == "rockspec" then
filename = filename..".rockspec"
else
filename = filename.."."..arch..".rock"
end
return dir.path(pathname, filename)
end
--- Convert a pathname to a module identifier.
-- In Unix, for example, a path "foo/bar/baz.lua" is converted to
-- "foo.bar.baz"; "bla/init.lua" returns "bla"; "foo.so" returns "foo".
-- @param file string: Pathname of module
-- @return string: The module identifier, or nil if given path is
-- not a conformant module path (the function does not check if the
-- path actually exists).
function path_to_module(file)
assert(type(file) == "string")
local name = file:match("(.*)%."..cfg.lua_extension.."$")
if name then
name = name:gsub(dir.separator, ".")
local init = name:match("(.*)%.init$")
if init then
name = init
end
else
name = file:match("(.*)%."..cfg.lib_extension.."$")
if name then
name = name:gsub(dir.separator, ".")
end
end
if not name then name = file end
name = name:gsub("^%.+", ""):gsub("%.+$", "")
return name
end
--- Obtain the directory name where a module should be stored.
-- For example, on Unix, "foo.bar.baz" will return "foo/bar".
-- @param mod string: A module name in Lua dot-separated format.
-- @return string: A directory name using the platform's separator.
function module_to_path(mod)
assert(type(mod) == "string")
return (mod:gsub("[^.]*$", ""):gsub("%.", dir.separator))
end
--- Set up path-related variables for a given rock.
-- Create a "variables" table in the rockspec table, containing
-- adjusted variables according to the configuration file.
-- @param rockspec table: The rockspec table.
function configure_paths(rockspec)
assert(type(rockspec) == "table")
local vars = {}
for k,v in pairs(cfg.variables) do
vars[k] = v
end
local name, version = rockspec.name, rockspec.version
vars.PREFIX = install_dir(name, version)
vars.LUADIR = lua_dir(name, version)
vars.LIBDIR = lib_dir(name, version)
vars.CONFDIR = conf_dir(name, version)
vars.BINDIR = bin_dir(name, version)
vars.DOCDIR = doc_dir(name, version)
rockspec.variables = vars
end
function versioned_name(file, prefix, name, version)
assert(type(file) == "string")
assert(type(name) == "string")
assert(type(version) == "string")
local rest = file:sub(#prefix+1):gsub("^/*", "")
local name_version = (name.."_"..version):gsub("%-", "_"):gsub("%.", "_")
return dir.path(prefix, name_version.."-"..rest)
end
|
include("shared.lua")
function ENT:Draw()
self.BaseClass.Draw(self)
if self:IsDroneWorkable() and not DRONES_REWRITE.ClientCVars.NoGlows:GetBool() then
local dlight = DynamicLight(self:EntIndex())
if dlight then
dlight.pos = self:LocalToWorld(Vector(34, 0, -8))
dlight.r = 0
dlight.g = 255
dlight.b = 255
dlight.brightness = 1
dlight.Decay = 1000
dlight.Size = 80
dlight.DieTime = CurTime() + 0.1
end
render.SetMaterial(Material("particle/particle_glow_04_additive"))
render.DrawSprite(self:LocalToWorld(Vector(34, 0, -8)), 30, 30, Color(0, 255, 255, 30))
end
end |
AddCSLuaFile();
SWEP.Base = "weapon_cc_base";
SWEP.PrintName = "Shotgun";
SWEP.Slot = 2;
SWEP.SlotPos = 6;
SWEP.UseHands = true;
SWEP.ViewModel = "models/weapons/c_shotgun.mdl";
SWEP.WorldModel = "models/weapons/w_shotgun.mdl";
SWEP.Firearm = true;
SWEP.Primary.ClipSize = 6;
SWEP.Primary.DefaultClip = 6;
SWEP.Primary.Ammo = "cc_shotgun";
SWEP.Primary.InfiniteAmmo = true;
SWEP.Primary.Automatic = false;
SWEP.Primary.Sound = "Weapon_Shotgun.Single";
SWEP.Primary.Damage = 8;
SWEP.Primary.Force = 2;
SWEP.Primary.NumBullets = 7;
SWEP.Primary.Accuracy = 0.08716;
SWEP.Primary.Delay = 0.7;
SWEP.Primary.ViewPunch = Angle( -10, 0, 0 );
SWEP.Primary.ReloadSound = "Weapon_Shotgun.Reload";
SWEP.HoldType = "shotgun";
SWEP.HoldTypeHolster = "passive";
SWEP.Holsterable = true;
SWEP.HolsterUseAnim = true;
SWEP.HolsterPos = Vector();
SWEP.HolsterAng = Vector();
SWEP.AimPos = Vector( -8.95, 4.19, -6.76 );
SWEP.AimAng = Vector( 0, 0, 0 );
SWEP.Itemize = true;
SWEP.ItemDescription = "The SPAS-12 shotgun has become the Combine Overwatch Transhuman Arm's crowd-control method of choice. It functions using an internal tube magazine loaded with 6 rounds of deadly buckshot.";
SWEP.ItemWeight = 10;
SWEP.ItemFOV = 37;
SWEP.ItemCamPos = Vector( -0.79, 50, 5.13 );
SWEP.ItemLookAt = Vector( 0, 0, 0 );
function SWEP:Reload()
if( self.NeedPump ) then return false end
if( !self.Owner or !self.Owner:IsValid() ) then return false end
if( self.InReload ) then return false end
if( self.Owner:Holstered() ) then return false end
local j = self.Primary.ClipSize - self:Clip1();
if( j <= 0 ) then return false end
self.Weapon:SendWeaponAnim( ACT_SHOTGUN_RELOAD_START );
-- animation event
self.Owner:SetAnimation( PLAYER_RELOAD );
self.Weapon:SetBodygroup( 1, 0 );
self:SetNextPrimaryFire( CurTime() + self:SequenceDuration() );
self.InReload = true;
return true;
end
function SWEP:FillClip()
if( !self.Owner or !self.Owner:IsValid() ) then return end
if( self:Clip1() < self.Primary.ClipSize ) then
self:SetClip1( self:Clip1() + 1 );
end
end
function SWEP:ReloadProgress()
if( !self.Owner or !self.Owner:IsValid() ) then return end
if( self:Clip1() >= self.Primary.ClipSize ) then return end
self:FillClip();
self.Weapon:EmitSound( "Weapon_Shotgun.Reload" );
self.Weapon:SendWeaponAnim( ACT_VM_RELOAD );
self:SetNextPrimaryFire( CurTime() + self:SequenceDuration() );
end
function SWEP:FinishReload()
self.Weapon:SetBodygroup( 1, 1 );
if( !self.Owner or !self.Owner:IsValid() ) then return end
self.InReload = false;
self.Weapon:SendWeaponAnim( ACT_SHOTGUN_RELOAD_FINISH );
self:SetNextPrimaryFire( CurTime() + self:SequenceDuration() );
self:Idle();
end
function SWEP:Pump()
if( !self.Owner or !self.Owner:IsValid() ) then return end
self.NeedPump = false;
self.Weapon:EmitSound( "Weapon_Shotgun.Special1" );
self.Weapon:SendWeaponAnim( ACT_SHOTGUN_PUMP );
self:SetNextPrimaryFire( CurTime() + self:SequenceDuration() );
self:Idle();
end
function SWEP:ThinkChild()
if( !self.Owner or !self.Owner:IsValid() ) then return end
if( self.InReload ) then
if( self.Owner:Holstered() ) then
self.Weapon:SetBodygroup( 1, 1 );
self.InReload = false;
return;
end
if( self:GetNextPrimaryFire() <= CurTime() ) then
if( self:Clip1() < self.Primary.ClipSize ) then
self:ReloadProgress();
else
self:FinishReload();
end
end
else
self:SetBodygroup( 1, 1 );
end
if( self.NeedPump and self:GetNextPrimaryFire() <= CurTime() ) then
self:Pump();
return;
end
if( !self.InReload ) then
--self:Idle();
end
end
function SWEP:PrimaryUnholstered()
if( self:CanPrimaryAttack( true ) ) then
self.Weapon:EmitSound( self.Primary.Sound );
self:ShootEffects();
self:SetNextPrimaryFire( CurTime() + self.Weapon:SequenceDuration() );
if( IsFirstTimePredicted() ) then
self:ShootBullet( self.Primary.Damage, self.Primary.Force, self.Primary.NumBullets, self.Primary.Accuracy * self:BulletAccuracyModifier( 0.4 ) );
end
self:TakePrimaryAmmo( 1 );
if( self.AddViewKick ) then
self:AddViewKick();
else
if( type( self.Primary.ViewPunch ) == "Angle" ) then
self.Owner:ViewPunch( Angle( self.Primary.ViewPunch.p, math.random( -self.Primary.ViewPunch.y, self.Primary.ViewPunch.y ), math.random( -self.Primary.ViewPunch.r, self.Primary.ViewPunch.r ) ) );
else
self:DoMachineGunKick( self.Primary.ViewPunch.x, self.Primary.ViewPunch.y, self.Primary.Delay, self.Primary.ViewPunch.z );
end
end
self.NeedPump = true;
end
end
function SWEP:AddViewKick()
self.Owner:ViewPunch( Angle( math.Rand( -12, -15 ), math.Rand( -1, 1 ), 0 ) );
end
|
function lure.dom.createCharacterDataNodeObj(pData)
--INHERIT FROM DOM NODE
local self = lure.dom.nodeObj.new(4)
--===================================================================
-- PROPERTIES =
--===================================================================
self.nodeName = "#CDATASECTION"
---------------------------------------------------------------------
self.nodeValue = pData
---------------------------------------------------------------------
self.attributes = nil --property not allowed
---------------------------------------------------------------------
self.parentNode = nil --property not allowed
---------------------------------------------------------------------
self.childNodes = nil --property not allowed
---------------------------------------------------------------------
--===================================================================
-- MUTATORS =
--===================================================================
self.mutators.getData = function()
return self.nodeValue
end
---------------------------------------------------------------------
self.mutators.getLength = function()
return self.nodeValue:len()
end
---------------------------------------------------------------------
self.mutators.setData = function(pText)
self.nodeValue = pText
end
self.mutators.setLength = function()
return "LURE ERROR:: You cannot set the lengh property"
end
---------------------------------------------------------------------
self.mutators.getId = nil --mutator not allowed
---------------------------------------------------------------------
self.mutators.getClass = nil --mutator not allowed
---------------------------------------------------------------------
self.mutators.getFirstChild = nil --mutator not allowed
---------------------------------------------------------------------
self.mutators.getLastChild = nil --mutator not allowed
---------------------------------------------------------------------
self.mutators.getNextSibling = nil --mutator not allowed
---------------------------------------------------------------------
self.mutators.getPreviousSilbing = nil --mutator not allowed
---------------------------------------------------------------------
self.mutators.setId = nil --mutator not allowed
---------------------------------------------------------------------
self.mutators.setClass = nil --mutator not allowed
---------------------------------------------------------------------
--===================================================================
-- METHODS =
--===================================================================
self.appendData = function(pString)
if type(pString) == "string" then
self.nodeValue = self.nodeValue + pString
else
print("LURE:ERROR: appendData only accepts parameter of type 'string'")
end
end
---------------------------------------------------------------------
self.deleteData = function(pStart, pLength)
end
---------------------------------------------------------------------
self.appendChild = nil --method not allowed
---------------------------------------------------------------------
self.getElementById = nil --method not allowed
---------------------------------------------------------------------
self.getElementsByTagName = nil --method not allowed
---------------------------------------------------------------------
self.getElementsByClassName = nil --method not allowed
---------------------------------------------------------------------
self.removeChild = nil --method not allowed
---------------------------------------------------------------------
self.setAttribute = nil --method not allowed
---------------------------------------------------------------------
self.getAttribute = nil --method not allowed
---------------------------------------------------------------------
self.removeAttribute = nil --method not allowed
---------------------------------------------------------------------
self.hasChildNodes = function() return false end
---------------------------------------------------------------------
self.hasAttributes = function() return false end
---------------------------------------------------------------------
self.replaceChild = nil --method not allowed
---------------------------------------------------------------------
self.isEqualNode = nil --method not allowed
---------------------------------------------------------------------
self.isSameNode = nil --method not allowed
---------------------------------------------------------------------
return self
end |
basestate=Class{}
function basestate:init() end
function basestate:enter() end
function basestate:exit() end
function basestate:update(dt) end
function basestate:render(o) end
|
require 'CLRPackage'
import "System.Windows.Forms"
import "System.Drawing"
form = Form()
form.Text = "Hello, World!"
button = Button()
button.Text = "Click Me!"
button.Location = Point(20,20)
button.Click:Add(function()
MessageBox.Show("We wuz clicked!",arg[0],MessageBoxButtons.OK)
end)
form.Controls:Add(button)
form:ShowDialog()
|
ENT.Base = "swvr_base"
ENT.Category = "CIS"
ENT.Class = "Interceptor"
ENT.PrintName = "Droid Tri-Fighter"
ENT.Author = "Servius"
if SERVER then
AddCSLuaFile()
function ENT:SpawnFunction(ply, tr, ClassName)
if not tr.Hit then
return
end
local ent = ents.Create(ClassName)
ent:SetPos(tr.HitPos + tr.HitNormal * 5)
ent:SetAngles(Angle(0, ply:GetAimVector():Angle().Yaw, 0))
ent:Spawn()
ent:Activate()
return ent
end
function ENT:Initialize()
self:Setup({
Model = "models/swbf3/vehicles/cis_tri-fighter.mdl",
Health = 750,
Speed = 1500,
BoostSpeed = 2250,
VerticalSpeed = 550,
Acceleration = 9,
Roll = true,
})
self:AddWeaponGroup("Pilot", "ls1_cannon", {
Delay = 0.1,
Damage = 25,
Color = "red",
CanOverheat = true,
MaxOverheat = 20
})
self:AddWeapon("Pilot", "MainT", Vector(102, 0, 154)) -- distance from center, left right, up down.
self:AddWeapon("Pilot", "MainR", Vector(102, 73, 20))
self:AddWeapon("Pilot", "MainL", Vector(102, -73, 20))
self:AddWeaponGroup("Center", "gn40_cannon", {
Delay = 0.5,
Damage = 80,
CanOverheat = true,
MaxOverheat = 10,
Cooldown = 10
})
self:AddWeapon("Center", "Center", Vector(130, 0, 65))
self:AddWeaponGroup("Torpedo", "swvr_base_missile", {
Delay = 2,
Callback = function()
local group = self:GetBodygroup(1) == 1 and 2 or 1
self:SetBodygroup(group, 1)
timer.Simple(4.1, function()
if not IsValid(self) then return end
self:SetBodygroup(group, 0)
end)
end
})
self:AddWeapon("Torpedo", "Missile1", Vector(170, 3, 30))
self:AddPilot(nil, nil, {
FPVPos = Vector(80, 0, 80),
Weapons = { "Pilot", "Center", "Torpedo" }
})
self.BaseClass.Initialize(self)
end
end
if CLIENT then
function ENT:Initialize()
self:Setup({
Cockpit = "vgui/droid_cockpit",
AlwaysDraw = true,
EngineSound = "vehicles/droid/droid_fly.wav",
ViewDistance = 700,
ViewHeight = 200
})
self:SetupDefaults()
self:AddEngine(Vector(-140, 30, 47), { -- distance from center, left right, up down.
StartSize = 15,
EndSize = 13.5,
Lifetime = 2.7,
Color = Color(150, 100, 0),
Sprite = "sprites/orangecore1"
})
self:AddEngine(Vector(-140, 0, 96), {
StartSize = 15,
EndSize = 13.5,
Lifetime = 2.7,
Color = Color(150, 100, 0),
Sprite = "sprites/orangecore1"
})
self:AddEngine(Vector(-140, -30, 47), {
StartSize = 15,
EndSize = 13.5,
Lifetime = 2.7,
Color = Color(150, 100, 0),
Sprite = "sprites/orangecore1"
})
self.BaseClass.Initialize(self)
end
end
|
trash_common = {
description = "",
minimumLevel = 0,
maximumLevel = 0,
lootItems = {
{itemTemplate = "junk", weight = 5000000},
{itemTemplate = "collectiontierone", weight = 2000000},
{itemTemplate = "clothing_attachments", weight = 1500000},
{itemTemplate = "armor_attachments", weight = 1500000}
}
}
addLootGroupTemplate("trash_common", trash_common) |
local uv = require('luv')
local function wrapEmitter(emitter)
local read, write
local queue = {}
-- Pipe data from chain to emitter
do
local paused = false
local waiting
function emitter:pause() paused = true end
function emitter:resume()
if not paused then return end
paused = false
if not waiting then return end
local thread = waiting
waiting = nil
assert(coroutine.resume(thread))
end
function write(data)
if paused then
waiting = coroutine.running()
coroutine.yield()
end
if data then
emitter:emit("data", data)
else
emitter:emit("end")
end
end
end
-- Pipe data from emitter to chain
do
local waiting
local ended = false
function emitter:write(data)
if waiting then
local thread = waiting
waiting = nil
assert(coroutine.resume(thread, data))
return true
end
queue[#queue + 1] = data
return false
end
function emitter:shutdown()
ended = true
if waiting then
local thread = waiting
waiting = nil
assert(coroutine.resume(thread))
end
end
function read()
if ended then return end
if #queue > 0 then
local data = table.remove(queue)
if #queue == 0 then emitter:emit("drain") end
return data
end
waiting = coroutine.running()
return coroutine.yield()
end
end
return read, write
end
-- Given a raw uv_stream_t userdara, return coro-friendly read/write functions.
local function wrapStream(socket)
local paused = true
local queue = {}
local waiting
local reading = true
local writing = true
local onRead
local function read()
if #queue > 0 then return unpack(table.remove(queue, 1)) end
if paused then
paused = false
uv.read_start(socket, onRead)
end
waiting = coroutine.running()
return coroutine.yield()
end
function onRead(err, chunk)
local data = err and {nil, err} or {chunk}
if waiting then
local thread = waiting
waiting = nil
assert(coroutine.resume(thread, unpack(data)))
else
queue[#queue + 1] = data
if not paused then
paused = true
uv.read_stop(socket)
end
end
if not chunk then
reading = false
-- Close the whole socket if the writing side is also closed already.
if not writing and not uv.is_closing(socket) then
uv.close(socket)
end
end
end
local function write(chunk)
if chunk == nil then
-- Shutdown our side of the socket
writing = false
if not uv.is_closing(socket) then
uv.shutdown(socket)
-- Close if we're done reading too
if not reading and not uv.is_closing(socket) then
uv.close(socket)
end
end
else
-- TODO: add backpressure by pausing and resuming coroutine
-- when write buffer is full.
uv.write(socket, chunk)
end
end
return read, write
end
local function chain(...)
local args = {...}
local nargs = select("#", ...)
return function(read, write)
local threads = {} -- coroutine thread for each item
local waiting = {} -- flag when waiting to pull from upstream
local boxes = {} -- storage when waiting to write to downstream
for i = 1, nargs do
threads[i] = coroutine.create(args[i])
waiting[i] = false
local r, w
if i == 1 then
r = read
else
function r()
local j = i - 1
if boxes[j] then
local data = boxes[j]
boxes[j] = nil
assert(coroutine.resume(threads[j]))
return unpack(data)
else
waiting[i] = true
return coroutine.yield()
end
end
end
if i == nargs then
w = write
else
function w(...)
local j = i + 1
if waiting[j] then
waiting[j] = false
assert(coroutine.resume(threads[j], ...))
else
boxes[i] = {...}
coroutine.yield()
end
end
end
assert(coroutine.resume(threads[i], r, w))
end
end
end
return {wrapEmitter = wrapEmitter, wrapStream = wrapStream, chain = chain}
|
ElementManager = {}
local instance = nil
function ElementManager:Instance()
if instance == nil then
instance = {}
setmetatable(instance, self)
self.__index = self
instance.Core = nil
instance.Screen = {}
instance.Container = {}
instance.Switch = {}
instance.Button = {}
instance.Emitter = {}
instance.Receiver = {}
instance.Light = {}
instance.Industry = {}
instance.Databank = {}
instance.Emitter = {}
instance.slots = {slot1, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9, slot10}
instance.linked = false
end
instance:link()
return instance
end
function ElementManager:link()
if not self.linked then
for i = 1, #self.slots do
local slot = self.slots[i]
if slot ~= nil then
local elementClass = slot.getElementClass()
if elementClass == 'CoreUnitStatic'
or elementClass == 'CoreUnitSpace'
or elementClass == 'CoreUnitDynamic' then
self.Core = slot
elseif (elementClass == 'ScreenUnit') then
table.insert(self.Screen, #self.Screen + 1, slot)
elseif (elementClass == 'ItemContainer') then
table.insert(self.Container, #self.Container + 1, slot)
elseif (elementClass == 'ManualSwitchUnit') then
table.insert(self.Switch, #self.Switch + 1, slot)
elseif (elementClass == 'ManualButtonUnit') then
table.insert(self.Button, #self.Button + 1, slot)
elseif (elementClass == 'EmitterUnit') then
table.insert(self.Emitter, #self.Emitter + 1, slot)
elseif (elementClass == 'ReceiverUnit') then
table.insert(self.Receiver, #self.Receiver + 1, slot)
elseif (elementClass == 'LightUnit') then
table.insert(self.Light, #self.Light + 1, slot)
elseif (elementClass == 'IndustryUnit') then
table.insert(self.Industry, #self.Industry + 1, slot)
elseif (elementClass == 'DataBankUnit') then
table.insert(self.Databank, #self.Databank + 1, slot)
elseif (elementClass == 'Emitter') then
table.insert(self.Emitter, #self.Emitter + 1, slot)
else
system.print(elementClass)
end
end
end
--[[ system.print("Found elements:")
system.print("Core: " .. tostring(self.Core ~= nil))
system.print("Screen: " .. #self.Screen)
system.print("Container: " .. #self.Container)
system.print("Switch: " .. #self.Switch)
system.print("Button: " .. #self.Button)
system.print("Emitter: " .. #self.Emitter)
system.print("Receiver: " .. #self.Receiver)
system.print("Light: " .. #self.Light)
system.print("Industry: " .. #self.Industry)
system.print("Databank: " .. #self.Databank)
]]
linked = true
end
end
function ElementManager:GetElementNameOfSlot(slot)
return self.Core.getElementNameById(slot.getId())
end
-- Gets a linked element by the name
function ElementManager:GetElementByName(name)
local element = nil
for i, s in ipairs(self.slots) do
if s ~= nil then
if name == self:GetElementNameOfSlot(s) then
element = s
break
end
end
end
return element
end
function ElementManager:IsDatabank(slot)
local elementClass = slot.getElementClass()
return elementClass == "DataBankUnit"
end
function ElementManager:IsScreen(slot)
local elementClass = slot.getElementClass()
return elementClass == "ScreenUnit"
end |
io.write(string.format("Hello from %s\n", _VERSION))
io.write("Calling howdy\n")
local value = howdy(10, 2, 5)
io.write(string.format("howdy() returned: %s\n", tostring(value)))
|
jun = script.Parent.Parent
Stuff = false
--password
function ssj()
if Stuff == false then
Stuff = true
for u, c in pairs (jun.Character:GetChildren()) do
if c.className == "Hat" and c.Name ~= "Swordpack" and c.Name ~= "GlassesBlackFrame" then
c.Handle.Transparency = 1
end
end
Hair22 = Instance.new("Part")
Hair22.Parent = jun.Character
Hair22.Name = "Hair"
Hair22.formFactor = "Symmetric"
Hair22.Size = Vector3.new(1, 1, 1)
Hair22.CFrame = jun.Character.Head.CFrame
Hair22:BreakJoints()
Hair22.CanCollide = false
Hair22.TopSurface = "Smooth"
Hair22.BottomSurface = "Smooth"
Hair22.BrickColor = BrickColor.new("1003")
Weld = Instance.new("Weld")
Weld.Part0 = jun.Character.Head
Weld.Part1 = Hair22
Weld.Parent = jun.Character.Head
Weld.C0 = CFrame.new(-0.12, 0, 0.11)*CFrame.fromEulerAnglesXYZ(0, 0, 0)
Mesh = Instance.new("SpecialMesh")
Mesh.Parent = Hair22
Mesh.MeshType = "FileMesh"
Mesh.Scale = Vector3.new(1, 1, 1)
Mesh.MeshId = "http://www.roblox.com/asset/?id=76056263"
Hair4 = Instance.new("Part")
Hair4.Parent = jun.Character
Hair4.Name = "Hair"
Hair4.CanCollide = false
Hair4.Locked = true
Hair4.TopSurface = "Smooth"
Hair4.BottomSurface = "Smooth"
Hair4.formFactor = "Symmetric"
Hair4.BrickColor = BrickColor.new("1004")
Hair4.CFrame = jun.Character.Torso.CFrame
Hair4.Size = Vector3.new(1, 1, 1)
Weld = Instance.new("Weld")
Weld.Parent = jun.Character.Head
Weld.Part0 = jun.Character.Head
Weld.Part1 = Hair4
Weld.C0 = CFrame.new(0, 1, 0)
Mesh = Instance.new("SpecialMesh")
Mesh.Parent = Hair4
Mesh.Scale = Vector3.new(1.15, 1.9, 1.26)
Mesh.MeshType = "FileMesh"
Mesh.MeshId = "http://www.roblox.com/asset/?id=12212520"
Mesh.TextureId = ""
Effect = Instance.new("Part")
Effect.Parent = jun.Character
Effect.Anchored = true
Effect.CanCollide = false
Effect.Size = Vector3.new(1, 1, 1)
Effect.formFactor = "Symmetric"
Effect.Transparency = 0.5
Effect.BrickColor = BrickColor.new("New Yeller")
Effect.TopSurface = "Smooth"
Effect.BottomSurface = "Smooth"
EffectMesh = Instance.new("SpecialMesh")
EffectMesh.Parent = Effect
EffectMesh.MeshType = "Sphere"
EffectMesh.Scale = Vector3.new(10, 10, 10)
ex2 = Instance.new("Explosion")
ex2.Position = jun.Character.Torso.Position
ex2.BlastPressure = 0
ex2.Parent = workspace
jun.Character.Torso.CFrame = jun.Character.Torso.CFrame * CFrame.new(0, 0.1, 0)
for i = 1 , 20 do
Effect.CFrame = CFrame.new(jun.Character.Torso.Position)
EffectMesh.Scale = EffectMesh.Scale + Vector3.new(2, 2, 2)
Effect.Transparency = Effect.Transparency + 0.025
wait(0.06)
end
Effect:Remove()
if jun.Character.Torso:findFirstChild("PwnFire") == nil then
pie = Instance.new("Fire")
pie.Name = "PwnFire"
pie.Parent = jun.Character.Torso
pie.Size = 9
pie.Color = BrickColor.new("1004")
end
if jun.Character.Torso:findFirstChild("PwnSparkles") == nil then
pie = Instance.new("Sparkles")
pie.Name = "PwnSparkles"
pie.Parent = jun.Character.Torso
end
jun.Character.Humanoid.MaxHealth = jun.Character.Humanoid.MaxHealth*1
wait(0.3)
jun.Character.Humanoid.Health = jun.Character.Humanoid.Health*1
end
end
function nossj()
if Stuff == true then
Stuff = false
if jun.Character.Torso:findFirstChild("PwnFire") ~= nil then
jun.Character.Torso:findFirstChild("PwnFire"):Remove()
end
if jun.Character.Torso:findFirstChild("PwnSparkles") ~= nil then
jun.Character.Torso:findFirstChild("PwnSparkles"):Remove()
end
p = Instance.new("Part")
p.Parent = jun.Character
p.Anchored = true
p.CanCollide = false
p.Transparency = 0.1
p.formFactor = "Symmetric"
p.Size = Vector3.new(22, 22, 22)
p.TopSurface = "Smooth"
p.BottomSurface = "Smooth"
p.Name = "Sharingan"
p.Shape = "Ball"
p.CFrame = jun.Character.Torso.CFrame
p.BrickColor = BrickColor.new("White")
for i = 1 , 10 do
wait(0.05)
p.Size = p.Size + Vector3.new(-4, -4, -4)
p.Transparency = p.Transparency + 0.1
p.CFrame = jun.Character.Torso.CFrame
end
p:Remove()
for u, c in pairs (jun.Character:GetChildren()) do
if c.className == "Hat" and c.Name ~= "Swordpack" and c.Name ~= "GlassesBlackFrame" then
c.Handle.Transparency = 0
end
if c.Name == "Hair" then
c:Remove()
end
end
jun.Character.Humanoid.Health = jun.Character.Humanoid.Health/1
wait(0.3)
jun.Character.Humanoid.MaxHealth = jun.Character.Humanoid.MaxHealth/1
end
end
jun.Chatted:connect(function(Msg)
msg = Msg:lower()
if string.sub(msg, 1, 7) == "bssj" then
wait(0.1)
ssj()
end
if string.sub(msg, 1, 13) == "bloody super saiyan" then
wait(0.1)
ssj()
end
if string.sub(msg, 1, 10) == "offb" then
wait(0.1)
nossj()
end
if string.sub(msg, 1, 3) == "calmb" then
wait(0.1)
nossj()
end
end)
function OnDeath()
wait()
nossj()
end
jun.Character.Humanoid.Died:connect(OnDeath)
jun = script.Parent.Parent
if script.Parent.Parent.Name == "" then
wait(1)
ssj()
end
Stuff = false
--mediafire--- |
--[[
Project: SA Memory (Available from https://blast.hk/)
Developers: LUCHARE, FYP
Special thanks:
plugin-sdk (https://github.com/DK22Pac/plugin-sdk) for the structures and addresses.
Copyright (c) 2018 BlastHack.
]]
local shared = require 'SAMemory.shared'
shared.ffi.cdef[[
typedef struct CColTriangle
{
unsigned short nVertA;
unsigned short nVertB;
unsigned short nVertC;
unsigned char nMaterial;
unsigned char nLight;
} CColTriangle;
]]
shared.validate_size('CColTriangle', 8)
|
phantom_assassin_phantom_strike_nb2017 = class({})
LinkLuaModifier( "modifier_phantom_assassin_phantom_strike_nb2017", "modifiers/modifier_phantom_assassin_phantom_strike_nb2017", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
function phantom_assassin_phantom_strike_nb2017:OnSpellStart()
local hTarget = self:GetCursorTarget()
if hTarget == nil or hTarget:IsInvulnerable() then
return
end
local vForward = self:GetCaster():GetForwardVector()
vForward = vForward:Normalized()
local nFXIndex = ParticleManager:CreateParticle( "particles/units/heroes/hero_phantom_assassin/phantom_assassin_phantom_strike_start.vpcf", PATTACH_CUSTOMORIGIN, nil )
ParticleManager:SetParticleControl( nFXIndex, 0, self:GetCaster():GetOrigin() )
ParticleManager:SetParticleControlForward( nFXIndex, 0, vForward )
ParticleManager:SetParticleControlEnt( nFXIndex, 1, self:GetCaster(), PATTACH_CUSTOMORIGIN, nil, self:GetCaster():GetOrigin(), true )
ParticleManager:ReleaseParticleIndex( nFXIndex )
local vStartLocation = self:GetCaster():GetOrigin()
local vDestination = hTarget:GetOrigin() - vForward * ( hTarget:GetPaddedCollisionRadius() + self:GetCaster():GetPaddedCollisionRadius() + 2.0 )
FindClearSpaceForUnit( self:GetCaster(), vDestination, true )
EmitSoundOnLocationWithCaster( vStartLocation, "Hero_PhantomAssassin.Strike.Start", self:GetCaster() )
self:GetCaster():AddNewModifier( self:GetCaster(), self, "modifier_phantom_assassin_phantom_strike_nb2017", { duration = self:GetSpecialValueFor( "duration" ) } )
EmitSoundOn( "Hero_PhantomAssassin.Strike.End", self:GetCaster() )
local nFXIndex2 = ParticleManager:CreateParticle( "particles/units/heroes/hero_phantom_assassin/phantom_assassin_phantom_strike_end.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetCaster() )
ParticleManager:ReleaseParticleIndex( nFXIndex2)
end
--------------------------------------------------------------------------------
function phantom_assassin_phantom_strike_nb2017:CastFilterResultTarget( hTarget )
local nResult = UnitFilter( hTarget, DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, self:GetCaster():GetTeamNumber() )
if nResult ~= UF_SUCCESS then
return nResult
end
if self:GetCaster() == hTarget then
return UF_FAIL_CUSTOM
end
return UF_SUCCESS
end
--------------------------------------------------------------------------------
function phantom_assassin_phantom_strike_nb2017:GetCustomCastErrorTarget( hTarget )
if self:GetCaster() == hTarget then
return "#dota_hud_error_cant_cast_on_self"
end
return ""
end
|
function init()
if msoak.verbose then
msoak.log(msoak.luascript .. " starting up")
end
end
function greet(topic, _type, d)
s = string.format("Hello %s -> now=%s", d.name,
msoak.strftime("%TZ"))
return s
end
function exit()
msoak.log("Hasta la vista, baby!")
end
|
vim.cmd [[nmap <buffer> h -]]
vim.cmd [[nmap <buffer> l <cr>]]
|
require("__5dim_core__.lib.nuclear.generation-steam-turbine")
local speed = 1
local modules = 2
local energy = 1
local emisions = 30
local techCount = 500
-- Electric furnace 01
genSteamTurbines {
number = "01",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = false,
order = "a",
ingredients = {
{"iron-gear-wheel", 50},
{"copper-plate", 50},
{"pipe", 20}
},
pollution = emisions,
nextUpdate = "5d-steam-turbine-02",
tech = nil
}
speed = speed + 0.15
modules = modules + 1
energy = energy + 0.5
emisions = emisions + 15
-- Electric furnace 02
genSteamTurbines {
number = "02",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = true,
order = "b",
ingredients = {
{"steam-turbine", 1},
{"iron-gear-wheel", 50},
{"copper-plate", 50},
{"electronic-circuit", 50},
{"pipe", 20}
},
pollution = emisions,
nextUpdate = "5d-steam-turbine-03",
tech = {
number = 1,
count = techCount * 1,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
prerequisites = {
"nuclear-power",
}
}
}
speed = speed + 0.15
energy = energy + 0.5
emisions = emisions + 15
-- Electric furnace 03
genSteamTurbines {
number = "03",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "c",
ingredients = {
{"5d-steam-turbine-02", 1},
{"steel-plate", 15},
{"copper-plate", 50},
{"electronic-circuit", 50},
{"pipe", 20}
},
pollution = emisions,
nextUpdate = "5d-steam-turbine-04",
tech = {
number = 2,
count = techCount * 2,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
prerequisites = {
"5d-nuclear-reactor-1",
"5d-steam-turbine-1",
"5d-heat-pipe-1",
"5d-heat-exchanger-1"
}
}
}
speed = speed + 0.15
modules = modules + 1
energy = energy + 0.5
emisions = emisions + 15
-- Electric furnace 04
genSteamTurbines {
number = "04",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = true,
order = "d",
ingredients = {
{"5d-steam-turbine-03", 1},
{"steel-plate", 15},
{"copper-plate", 50},
{"advanced-circuit", 30},
{"pipe", 20}
},
pollution = emisions,
nextUpdate = "5d-steam-turbine-05",
tech = {
number = 3,
count = techCount * 3,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
{"space-science-pack", 1}
},
prerequisites = {
"5d-nuclear-reactor-2",
"5d-steam-turbine-2",
"5d-heat-pipe-2",
"5d-heat-exchanger-2",
"space-science-pack"
}
}
}
speed = speed + 0.15
energy = energy + 0.5
emisions = emisions + 15
-- Electric furnace 05
genSteamTurbines {
number = "05",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "e",
ingredients = {
{"5d-steam-turbine-04", 1},
{"steel-plate", 15},
{"copper-plate", 50},
{"advanced-circuit", 20},
{"pipe", 20},
{"speed-module", 1}
},
pollution = emisions,
nextUpdate = "5d-steam-turbine-06",
tech = {
number = 4,
count = techCount * 4,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
{"space-science-pack", 1}
},
prerequisites = {
"5d-nuclear-reactor-3",
"5d-steam-turbine-3",
"5d-heat-pipe-3",
"5d-heat-exchanger-3"
}
}
}
speed = speed + 0.15
modules = modules + 1
energy = energy + 0.5
emisions = emisions + 15
-- Electric furnace 06
genSteamTurbines {
number = "06",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = true,
order = "f",
ingredients = {
{"5d-steam-turbine-05", 1},
{"steel-plate", 15},
{"copper-plate", 50},
{"advanced-circuit", 20},
{"pipe", 20},
{"productivity-module", 1}
},
pollution = emisions,
nextUpdate = "5d-steam-turbine-07",
tech = {
number = 5,
count = techCount * 5,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
{"space-science-pack", 1}
},
prerequisites = {
"5d-nuclear-reactor-4",
"5d-steam-turbine-4",
"5d-heat-pipe-4",
"5d-heat-exchanger-4"
}
}
}
speed = speed + 0.15
energy = energy + 0.5
emisions = emisions + 15
-- Electric furnace 07
genSteamTurbines {
number = "07",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "g",
ingredients = {
{"5d-steam-turbine-06", 1},
{"steel-plate", 15},
{"copper-plate", 50},
{"advanced-circuit", 20},
{"pipe", 20},
{"speed-module-2", 1}
},
pollution = emisions,
nextUpdate = "5d-steam-turbine-08",
tech = {
number = 6,
count = techCount * 6,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1},
{"space-science-pack", 1}
},
prerequisites = {
"5d-nuclear-reactor-5",
"5d-steam-turbine-5",
"5d-heat-pipe-5",
"5d-heat-exchanger-5"
}
}
}
speed = speed + 0.15
modules = modules + 1
energy = energy + 0.5
emisions = emisions + 15
-- Electric furnace 08
genSteamTurbines {
number = "08",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules,
energyUsage = energy,
new = true,
order = "h",
ingredients = {
{"5d-steam-turbine-07", 1},
{"steel-plate", 15},
{"copper-plate", 50},
{"advanced-circuit", 20},
{"pipe", 20},
{"productivity-module-2", 1}
},
pollution = emisions,
nextUpdate = "5d-steam-turbine-09",
tech = {
number = 7,
count = techCount * 7,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
prerequisites = {
"5d-nuclear-reactor-6",
"5d-steam-turbine-6",
"5d-heat-pipe-6",
"5d-heat-exchanger-6"
}
}
}
speed = speed + 0.15
energy = energy + 0.5
emisions = emisions + 15
-- Electric furnace 09
genSteamTurbines {
number = "09",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "i",
ingredients = {
{"5d-steam-turbine-08", 1},
{"steel-plate", 15},
{"copper-plate", 50},
{"advanced-circuit", 20},
{"pipe", 20},
{"speed-module-3", 1}
},
pollution = emisions,
nextUpdate = "5d-steam-turbine-10",
tech = {
number = 8,
count = techCount * 8,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
prerequisites = {
"5d-nuclear-reactor-7",
"5d-steam-turbine-7",
"5d-heat-pipe-7",
"5d-heat-exchanger-7"
}
}
}
speed = speed + 0.15
modules = modules + 1
energy = energy + 0.5
emisions = emisions + 15
-- Electric furnace 10
genSteamTurbines {
number = "10",
subgroup = "nuclear-turbine",
craftingSpeed = speed,
moduleSlots = modules + 1,
energyUsage = energy,
new = true,
order = "j",
ingredients = {
{"5d-steam-turbine-09", 1},
{"steel-plate", 15},
{"copper-plate", 50},
{"advanced-circuit", 20},
{"pipe", 20},
{"productivity-module-3", 1}
},
pollution = emisions,
tech = {
number = 9,
count = techCount * 9,
packs = {
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
{"chemical-science-pack", 1},
{"production-science-pack", 1},
{"utility-science-pack", 1}
},
prerequisites = {
"5d-nuclear-reactor-8",
"5d-steam-turbine-8",
"5d-heat-pipe-8",
"5d-heat-exchanger-8"
}
}
}
|
local M = {}
local function noop()
-- no operation.
end
local function create_metatable(name, prototype, extend_class)
local super_metatable = getmetatable(extend_class) or {}
local super_prototype = super_metatable.__prototype
setmetatable(prototype, {
__index = super_prototype -- Constructing prototype chains.
})
local ret = {
__new = noop
}
for k, v in pairs(super_metatable) do
ret[k] = v
end
ret.__type = name
ret.__prototype = prototype
ret.__super_prototype = super_prototype
ret.__extend = extend_class
ret.__index = prototype -- Assign a prototype to instances.
for k, v in pairs(prototype) do
if k:sub(1, 2) == "__" then
ret[k] = v
end
end
return ret
end
local function create_instance(class_object, ...)
local mt = getmetatable(class_object)
local ret = {}
setmetatable(ret, mt)
mt.__new(ret, ...)
return ret
end
function M.class(name, prototype, static, extend_class)
static = static or {}
setmetatable(static, {
__call = create_instance,
-- Overrides the metatable returned by getmetatable(class_object).
__metatable = create_metatable(name, prototype, extend_class),
})
return static -- Return as class_object.
end
function M.class_type(value)
local mt = getmetatable(value)
return mt and mt.__type
end
function M.prototype(value)
local mt = getmetatable(value)
return mt and mt.__prototype
end
function M.super(value)
local mt = getmetatable(value)
return mt and mt.__super_prototype
end
function M.resetup(plain_table, class_object)
local mt = getmetatable(class_object)
setmetatable(plain_table, mt)
return plain_table
end
return M |
--- === WindowGrid ===
---
--- Configure and assign hotkey for `hs.grid`
---
--- Download: [https://github.com/Hammerspoon/Spoons/raw/master/Spoons/WindowGrid.spoon.zip](https://github.com/Hammerspoon/Spoons/raw/master/Spoons/WindowGrid.spoon.zip)
local obj={}
obj.__index = obj
-- Metadata
obj.name = "WindowGrid"
obj.version = "0.1"
obj.author = "Diego Zamboni <[email protected]>"
obj.homepage = "https://github.com/Hammerspoon/Spoons"
obj.license = "MIT - https://opensource.org/licenses/MIT"
-- Internal variable: Key binding for showing the grid
obj.key_show_grid = nil
--- WindowGrid.logger
--- Variable
--- Logger object used within the Spoon. Can be accessed to set the default log level for the messages coming from the Spoon.
obj.logger = hs.logger.new('WindowGrid')
--- WindowGrid.gridGeometries
--- Variable
--- Table containing a list of arguments to be passed to grid.setGrid(). Each element in the table is itself a table with 1-3 arguments as defined for [hs.grid.setGrid()](http://www.hammerspoon.org/docs/hs.grid.html#setGrid). Defaults to an empty list, which results in the default 3x3 grid for all screen from `hs.grid`.
obj.gridGeometries = {}
--- WindowGrid:bindHotkeys(mapping)
--- Method
--- Binds hotkeys for WindowGrid
---
--- Parameters:
--- * mapping - A table containing hotkey objifier/key details for the following items:
--- * show_grid - show the grid overlay
function obj:bindHotkeys(mapping)
if mapping["show_grid"] then
if (self.key_show_grid) then
self.key_show_grid:delete()
end
self.key_show_grid = hs.hotkey.bindSpec(mapping["show_grid"], hs.grid.toggleShow)
end
end
--- WindowGrid:start()
--- Method
--- Sets the grid configuration according to `WindowGrid.gridGeometries`.
function obj:start()
for i,v in ipairs(self.gridGeometries) do
self.logger.df("setGrid(%s, %s)", v[1], v[2], v[3])
hs.grid.ui.textSize = 50
hs.grid.ui.cellColor = {0.34,0.46,0.65,0.1}
hs.grid.ui.cellStrokeColor = {0.34, 0.46, 0.65}
-- hs.grid.ui.textColor = {1,1,1}
-- hs.grid.ui.cellColor = {0,0,0,0.25}
-- hs.grid.ui.cellStrokeColor = {0,0,0}
hs.grid.ui.selectedColor = {0.34,0.46,0.65,0.4} -- for the first selected cell during a modal resize
hs.grid.ui.highlightColor = {0.34,0.46,0.65,0.5} -- to highlight the frontmost window behind the grid
hs.grid.ui.highlightStrokeColor = {0.14,0.79,0.66,1} -- 36, 201, 168
hs.grid.ui.cyclingHighlightColor = {0,0.8,0.8,0.5} -- to highlight the window to be resized, when cycling among windows
hs.grid.ui.cyclingHighlightStrokeColor = {0,0.8,0.8,1}
hs.grid.setGrid(v[1], v[2], v[3])
end
end
return obj
|
object_tangible_food_generic_dessert_vagnerian_canape = object_tangible_food_generic_shared_dessert_vagnerian_canape:new {
}
ObjectTemplates:addTemplate(object_tangible_food_generic_dessert_vagnerian_canape, "object/tangible/food/generic/dessert_vagnerian_canape.iff")
|
Ryan.Session = {
ExplodeAll = function(with_earrape)
if with_earrape then -- Credit: Bed Sound
for _, coords in pairs(Ryan.Globals.BedSoundCoords) do
Ryan.Audio.PlayAtCoords(coords, "WastedSounds", "Bed", 999999999)
coords.z = 2000.0
Ryan.Audio.PlayAtCoords(coords, "WastedSounds", "Bed", 999999999)
coords.z = -2000.0
Ryan.Audio.PlayAtCoords(coords, "WastedSounds", "Bed", 999999999)
end
end
for _, player_id in pairs(players.list()) do
Ryan.Player.Explode(player_id, with_earrape)
end
end,
SpamChat = function(message, as_other_players, time_between, wait_for)
local sent = 0
while sent < 32 do
if as_other_players then
for _, player_id in pairs(players.list()) do
local name = players.get_name(player_id)
menu.trigger_commands("chatas" .. name .. " on")
chat.send_message(message, false, true, true)
menu.trigger_commands("chatas" .. name .. " off")
util.yield(time_between)
sent = sent + 1
end
else
chat.send_message(message, false, true, true)
util.yield(time_between)
sent = sent + 1
end
end
util.yield(wait_for)
end,
-- Sorting Types --
ListHighestAndLowest = function(get_value)
local highest_amount = 0
local highest_player = -1
local lowest_amount = 2100000000
local lowest_player = -1
for _, player_id in pairs(players.list()) do
amount = get_value(player_id)
if amount > highest_amount and amount < 2100000000 then
highest_amount = amount
highest_player = player_id
end
if amount < lowest_amount and amount > 0 then
lowest_amount = amount
lowest_player = player_id
end
end
return {highest_player, highest_amount, lowest_player, lowest_amount}
end,
ListByBoolean = function(get_value)
local player_names = ""
for _, player_id in pairs(players.list()) do
if get_value(player_id) then
player_names = player_names .. PLAYER.GET_PLAYER_NAME(player_id) .. ", "
end
end
if player_names ~= "" then
player_names = string.sub(player_names, 1, -3)
end
return player_names
end,
-- Sorting Modes --
ListByMoney = function()
data = Ryan.Session.ListHighestAndLowest(Ryan.Player.GetMoney)
message = ""
if data[1] ~= -1 then
message = PLAYER.GET_PLAYER_NAME(data[1]) .. " is the richest player here ($" .. Ryan.Basics.FormatNumber(data[2]) .. ")."
end
if data[1] ~= data[3] then
message = message .. " " .. PLAYER.GET_PLAYER_NAME(data[3]) .. " is the poorest ($" .. Ryan.Basics.FormatNumber(data[4]) .. ")."
end
if message ~= "" then
chat.send_message(message, false, true, true)
return
end
end,
ListByKD = function()
data = Ryan.Session.ListHighestAndLowest(players.get_kd)
message = ""
if data[1] ~= -1 then
message = PLAYER.GET_PLAYER_NAME(data[1]) .. " has the highest K/D here (" .. string.format("%.1f", data[2]) .. ")."
end
if data[1] ~= data[3] then
message = message .. " " .. PLAYER.GET_PLAYER_NAME(data[3]) .. " has the lowest (" .. string.format("%.1f", data[4]) .. ")."
end
if message ~= "" then
chat.send_message(message, false, true, true)
return
end
end,
ListByInGodmode = function()
local player_names = Ryan.Session.ListByBoolean(Ryan.Player.IsInGodmode)
if player_names ~= "" then
chat.send_message("Players likely in godmode: " .. player_names .. ".", false, true, true)
return
end
chat.send_message("No players are in godmode.", false, true, true)
end,
ListByOffRadar = function()
local player_names = Ryan.Session.ListByBoolean(Ryan.Player.IsOffRadar)
if player_names ~= "" then
chat.send_message("Players off-the-radar: " .. player_names .. ".", false, true, true)
return
end
chat.send_message("No players are off-the-radar.", false, true, true)
end,
ListByOnOppressor2 = function()
local player_names = Ryan.Session.ListByBoolean(Ryan.Player.IsOnOppressor2)
if player_names ~= "" then
chat.send_message("Players on Oppressors: " .. player_names .. ".", false, true, true)
return
end
chat.send_message("No players are on Oppressors.", false, true, true)
end,
WatchVehicleTakeover = function(player_id, action, wait_for)
local player_name = players.get_name(player_id)
menu.trigger_commands("tpveh" .. player_name)
util.yield(750)
local vehicle = PED.GET_VEHICLE_PED_IS_IN(Ryan.Player.GetPed(player_id), false)
if vehicle ~= 0 then
Ryan.Entity.RequestControlLoop(vehicle)
if ENTITY.IS_ENTITY_A_VEHICLE(vehicle) then
action(vehicle)
util.yield(wait_for)
end
end
end,
-- Mass Trolling --
MassTrollingInProgress = false,
CancelMassTrolling = function()
if Ryan.Session.MassTrollingInProgress then
Ryan.Session.MassTrollingInProgress = false
Ryan.Basics.ShowTextMessage(Ryan.Globals.Color.Purple, "Session Trolling", "The mass troll has been cancelled, and will end after this player.")
else
Ryan.Basics.ShowTextMessage(Ryan.Globals.Color.Red, "Session Trolling", "There is no mass troll to cancel.")
end
end,
WatchMassVehicleTakeover = function(action, include_modders, wait_for)
if Ryan.Session.MassTrollingInProgress then
Ryan.Basics.ShowTextMessage(Ryan.Globals.Color.Red, "Session Trolling", "Mass trolling is already in progress. Wait for it to end or stop it.")
return
end
Ryan.Session.MassTrollingInProgress = true
Ryan.Basics.ShowTextMessage(Ryan.Globals.Color.Purple, "Session Trolling", "Mass trolling has begun. Sit tight and enjoy the show!")
menu.trigger_commands("otr on")
menu.trigger_commands("invisibility on")
local starting_coords = ENTITY.GET_ENTITY_COORDS(Ryan.Player.GetPed(), true)
for _, player_id in pairs(players.list()) do
if not Ryan.Session.MassTrollingInProgress then break end
if player_id ~= players.user() and not players.is_in_interior(player_id) then
if include_modders or not players.is_marked_as_modder(player_id) then
Ryan.Session.WatchVehicleTakeover(player_id, action, wait_for)
end
end
end
Ryan.Player.Teleport(starting_coords)
menu.trigger_commands("otr off")
menu.trigger_commands("invisibility off")
Ryan.Session.MassTrollingInProgress = false
Ryan.Basics.ShowTextMessage(Ryan.Globals.Color.Purple, "Session Trolling", "Mass trolling has finished trying all players.")
end,
WatchMassCommands = function(commands, include_modders, wait_for)
if Ryan.Session.MassTrollingInProgress then
Ryan.Basics.ShowTextMessage(Ryan.Globals.Color.Red, "Session Trolling", "Mass trolling is already in progress. Wait for it to end or stop it.")
return
end
Ryan.Session.MassTrollingInProgress = true
Ryan.Basics.ShowTextMessage(Ryan.Globals.Color.Purple, "Session Trolling", "Session trolling has begun. Sit tight and enjoy the show!")
menu.trigger_commands("otr on")
menu.trigger_commands("invisibility on")
menu.trigger_commands("levitation on")
local starting_coords = ENTITY.GET_ENTITY_COORDS(Ryan.Player.GetPed(), true)
for _, player_id in pairs(players.list()) do
if not Ryan.Session.MassTrollingInProgress then break end
if player_id ~= players.user() and not players.is_in_interior(player_id) then
if include_modders or not players.is_marked_as_modder(player_id) then
local player_name = players.get_name(player_id)
menu.trigger_commands("tp" .. player_name)
util.yield(1250)
if player_name ~= "**invalid**" then
for i = 1, #commands do
menu.trigger_commands(commands[i]:gsub("{name}", player_name))
end
end
util.yield(wait_for)
end
end
end
Ryan.Player.Teleport(starting_coords)
menu.trigger_commands("otr off")
menu.trigger_commands("invisibility off")
menu.trigger_commands("levitation off")
Ryan.Session.MassTrollingInProgress = false
end,
WatchMassAction = function(action, include_modders, wait_for)
if Ryan.Session.MassTrollingInProgress then
Ryan.Basics.ShowTextMessage(Ryan.Globals.Color.Red, "Session Trolling", "Mass trolling is already in progress. Wait for it to end or stop it.")
return
end
Ryan.Session.MassTrollingInProgress = true
Ryan.Basics.ShowTextMessage(Ryan.Globals.Color.Purple, "Session Trolling", "Session trolling has begun. Sit tight and enjoy the show!")
menu.trigger_commands("otr on")
menu.trigger_commands("invisibility on")
menu.trigger_commands("levitation on")
local starting_coords = ENTITY.GET_ENTITY_COORDS(Ryan.Player.GetPed(), true)
for _, player_id in pairs(players.list()) do
if not Ryan.Session.MassTrollingInProgress then break end
if player_id ~= players.user() and not players.is_in_interior(player_id) then
if include_modders or not players.is_marked_as_modder(player_id) then
local player_name = players.get_name(player_id)
menu.trigger_commands("tp" .. player_name)
util.yield(1250)
if player_name ~= "**invalid**" then
action(player_id)
end
util.yield(wait_for)
end
end
end
Ryan.Player.Teleport(starting_coords)
menu.trigger_commands("otr off")
menu.trigger_commands("invisibility off")
menu.trigger_commands("levitation off")
Ryan.Session.MassTrollingInProgress = false
end
} |
--[[
@Title: Local Game Setup Controller
@Author: Dr_K4rma aka Alexander Karpov
@Date: 5 Feb. 2021
@Package: ServerScriptService.RovaFramework.Client.Controllers
@Provides: Responsible for initial setup of the game on the client. This is the first thing that should be called.
]]
_G()
local public = {}
----------------------------------
-- DEPENDENCIES
----------------------------------
----------------------------------
-- SERVICES & PRIMARY OBJECTS
----------------------------------
local StarterGui = game:GetService("StarterGui")
local Player = game:GetService("Players").LocalPlayer
local PlayerGui = Player.PlayerGui
----------------------------------
-- CONFIG VARIABLES
----------------------------------
----------------------------------
-- MISC VARIABLES
----------------------------------
----------------------------------
-- PRIVATE FUNCTIONS
----------------------------------
----------------------------------
-- PUBLIC FUNCTIONS
----------------------------------
----------------------------------
-- MAIN CODE
----------------------------------
StarterGui:SetCoreGuiEnabled(Enum.CoreGuiType.PlayerList, false) -- Disables Playerlist
PlayerGui:SetTopbarTransparency(1)
return public |
-----------------------------------
-- Area: Misareaux Coast
-- NPC: Dilapidated Gate
-- Entrance to Riverne Site #B01
-- !pos -259 -30 276 178
-----------------------------------
require("scripts/globals/missions")
local ID = require("scripts/zones/Misareaux_Coast/IDs")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if (player:getCurrentMission(COP) == tpz.mission.id.cop.THE_SAVAGE and player:getCharVar("PromathiaStatus") == 0) then
player:startEvent(8)
elseif (player:getCurrentMission(COP) == tpz.mission.id.cop.ANCIENT_VOWS and player:getCharVar("PromathiaStatus") == 0) then
player:startEvent(6)
elseif (player:getCurrentMission(COP) == tpz.mission.id.cop.FLAMES_IN_THE_DARKNESS and player:getCharVar("PromathiaStatus") == 0) then
player:startEvent(12)
elseif (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.STORMS_OF_FATE) == QUEST_ACCEPTED and player:getCharVar('StormsOfFate') == 0) then
player:startEvent(559)
elseif (player:getCurrentMission(COP) > tpz.mission.id.cop.AN_ETERNAL_MELODY or player:hasCompletedMission(COP, tpz.mission.id.cop.THE_LAST_VERSE)) then
player:startEvent(552)
else
player:messageSpecial(ID.text.DOOR_CLOSED)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 6 or csid == 12) then
player:setCharVar("PromathiaStatus", 1)
elseif (csid == 559) then
player:setCharVar('StormsOfFate', 1)
elseif (csid == 8 and option == 1) then
player:setCharVar("PromathiaStatus", 1)
player:setPos(729, -20, 410, 88, 29) -- Go to Riverne #B01
end
end
|
AddCSLuaFile()
LIB_MATH_TA = {}
LIB_MATH_TA.EPSILON = 0.00001
LIB_MATH_TA.HUGE = 100000
-- Converting coordinate to grid ignoring z on normal
function LIB_MATH_TA:SnapToGridOnSurface(pos, angle, radius, zRound)
local localpos = WorldToLocal(pos, Angle(), Vector(), angle)
local lx = math.Round(localpos.x / radius) * radius
local ly = math.Round(localpos.y / radius) * radius
local lz = (not zRound or zRound == 0) and localpos.z or math.Round(localpos.z / zRound) * zRound
localpos = Vector(lx, ly, lz)
return LocalToWorld(localpos, Angle(), Vector(), angle)
end
-- Fixing Mins and Maxs
function LIB_MATH_TA:FixMinMax(min, max)
local smin = Vector(min)
local smax = Vector(max)
if min.x > max.x then min.x = smax.x max.x = smin.x end
if min.y > max.y then min.y = smax.y max.y = smin.y end
if min.z > max.z then min.z = smax.z max.z = smin.z end
end
-- Converting vector to a grid
function LIB_MATH_TA:ConvertToGrid(pos, size)
local gridPos = Vector(
math.Round(pos.x / size) * size,
math.Round(pos.y / size) * size,
math.Round(pos.z / size) * size)
return gridPos
end
-- if angles angle less then EPSILON equal that angle to zero
function LIB_MATH_TA:AnglesToZeroz(angle)
if math.abs(angle.p) < LIB_MATH_TA.EPSILON then angle.p = 0 end
if math.abs(angle.y) < LIB_MATH_TA.EPSILON then angle.y = 0 end
if math.abs(angle.r) < LIB_MATH_TA.EPSILON then angle.r = 0 end
end
-- if normal coordinate less then EPSILON equal that coordinate to zero
function LIB_MATH_TA:NormalFlipZeros(normal)
if math.abs(normal.x) < LIB_MATH_TA.EPSILON then normal.x = 0 end
if math.abs(normal.y) < LIB_MATH_TA.EPSILON then normal.y = 0 end
if math.abs(normal.z) < LIB_MATH_TA.EPSILON then normal.z = 0 end
end
-- return degreese between two vectors
function LIB_MATH_TA:DegreeseBetween(vector1, vector2)
LIB_MATH_TA:NormalFlipZeros(vector1)
LIB_MATH_TA:NormalFlipZeros(vector2)
if vector1 == vector2 then return 0 end
local dot = vector1:Dot(vector2)
return math.deg(math.acos(dot))
end |
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
silencer_glaives_of_wisdom_lua = class({})
LinkLuaModifier( "modifier_generic_orb_effect_lua", "lua_abilities/generic/modifier_generic_orb_effect_lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( "modifier_silencer_glaives_of_wisdom_lua", "lua_abilities/silencer_glaives_of_wisdom_lua/modifier_silencer_glaives_of_wisdom_lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
-- Passive Modifier
function silencer_glaives_of_wisdom_lua:GetIntrinsicModifierName()
return "modifier_silencer_glaives_of_wisdom_lua"
end
--------------------------------------------------------------------------------
-- Ability Cast Filter
function silencer_glaives_of_wisdom_lua:CastFilterResultTarget( hTarget )
local flag = 0
if self:GetCaster():HasScepter() then
flag = DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES
end
local nResult = UnitFilter(
hTarget,
DOTA_UNIT_TARGET_TEAM_BOTH,
DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_CREEP,
flag,
self:GetCaster():GetTeamNumber()
)
if nResult ~= UF_SUCCESS then
return nResult
end
return UF_SUCCESS
end
--------------------------------------------------------------------------------
-- Ability Start
function silencer_glaives_of_wisdom_lua:OnSpellStart()
end
--------------------------------------------------------------------------------
-- Orb Effects
function silencer_glaives_of_wisdom_lua:GetProjectileName()
return "particles/units/heroes/hero_silencer/silencer_glaives_of_wisdom.vpcf"
end
function silencer_glaives_of_wisdom_lua:OnOrbFire( params )
-- play effects
local sound_cast = "Hero_Silencer.GlaivesOfWisdom"
EmitSoundOn( sound_cast, self:GetCaster() )
end
function silencer_glaives_of_wisdom_lua:OnOrbImpact( params )
local caster = self:GetCaster()
-- get damage
local int_mult = self:GetSpecialValueFor( "intellect_damage_pct" )
local damage = caster:GetIntellect() * int_mult/100
if caster:HasScepter() then
damage = damage*2
end
-- apply damage
local damageTable = {
victim = params.target,
attacker = caster,
damage = damage,
damage_type = self:GetAbilityDamageType(),
ability = self, --Optional.
}
ApplyDamage(damageTable)
-- overhead message
SendOverheadEventMessage(
nil,
OVERHEAD_ALERT_BONUS_SPELL_DAMAGE,
params.target,
damage,
nil
)
-- play effects
local sound_cast = "Hero_Silencer.GlaivesOfWisdom.Damage"
EmitSoundOn( sound_cast, params.target )
end
--------------------------------------------------------------------------------
-- Hero Events
-- function silencer_glaives_of_wisdom_lua:OnHeroCalculateStatBonus()
-- end
--------------------------------------------------------------------------------
-- Other Events
-- function silencer_glaives_of_wisdom_lua:OnHeroDiedNearby(handle unit, handle attacker, handle table)
-- end |