content
stringlengths
5
1.05M
local walk = {} walk._NAME = ... local Body = require'Body' local vector = require'vector' local util = require'util' local moveleg = require'moveleg' local libReactiveZMP = require'libReactiveZMPAdaptive' local libStep = require'libStep' local zmp_solver local step_planner require'mcm' require'wcm' -- Keep track of important times local t_entry, t_update, t_last_step --Gait parameters local tStep = Config.walk.tStep local stepHeight = Config.walk.stepHeight -- Save gyro stabilization variables between update cycles -- They are filtered. TODO: Use dt in the filters local angleShift = vector.new{0,0,0,0} local iStep,ph_last,roll_max local zmp_param_set = false local emergency_stop = false -- What foot trajectory are we using? local foot_traj_name = "foot_trajectory_base2" if Config.walk.traj and Config.walk.traj.hybridwalk then foot_traj_name = Config.walk.traj.hybridwalk end local foot_traj_func = moveleg[foot_traj_name] local init_odometry = function(uTorso) wcm.set_robot_utorso0(uTorso) wcm.set_robot_utorso1(uTorso) end local update_odometry = function(uTorso_in) local uTorso1 = wcm.get_robot_utorso1() --update odometry pose local odometry_step = util.pose_relative(uTorso_in,uTorso1) local pose_odom0 = wcm.get_robot_odometry() local pose_odom = util.pose_global(odometry_step, pose_odom0) wcm.set_robot_odometry(pose_odom) wcm.set_robot_utorso1(uTorso_in)--updae odometry variable end --------------------------- -- State machine methods -- --------------------------- function walk.entry() emergency_stop = false print(walk._NAME..' Entry' ) mcm.set_status_stabilization_mode(0) --We're in single support if Config.use_heeltoe_walk then mcm.set_walk_heeltoewalk(1) else mcm.set_walk_heeltoewalk(0) end -- Update the time of entry local t_entry_prev = t_entry -- When entry was previously called t_entry = Body.get_time() t_update = t_entry mcm.set_walk_vel({0,0,0})--reset target speed -- Initiate the ZMP solver zmp_solver = libReactiveZMP.new_solver({ ['tStep'] = Config.walk.tStep, ['tZMP'] = Config.walk.tZMP, ['start_phase'] = Config.walk.phSingle[1], ['finish_phase'] = Config.walk.phSingle[2], }) step_planner = libStep.new_planner() uLeft_now, uRight_now, uTorso_now, uLeft_next, uRight_next, uTorso_next= step_planner:init_stance() --Reset odometry varialbe init_odometry(uTorso_now) --Now we advance a step at next update t_last_step = Body.get_time() - tStep iStep = 1 -- Initialize the step index ph_last = 0 mcm.set_walk_bipedal(1) mcm.set_walk_stoprequest(0) --cancel stop request flag mcm.set_walk_steprequest(0) --cancel walkkick request flag mcm.set_walk_ismoving(1) --We started moving --Check the initial torso velocity local uTorsoVel = util.pose_relative(mcm.get_status_uTorsoVel(), {0,0,uTorso_now[3]}) local velTorso = math.sqrt(uTorsoVel[1]*uTorsoVel[1]+uTorsoVel[2]*uTorsoVel[2]) if velTorso>0.01 then if uTorsoVel[2]>0 then iStep = 3; --Torso moving to left, skip initial step else iStep = 4; --Torso moving to the right, skip the initial step handling end end mcm.set_motion_state(4) zmp_param_set = false roll_max = 0 end function walk.update() -- Get the time of update local t = Body.get_time() local t_diff = t - t_update t_update = t -- Save this at the last update time -- Grab the phase of the current step local ph,is_next_step = zmp_solver:get_ph(t,t_last_step,ph_last) if ph_last<0.5 and ph>=0.5 then local rpy = Body.get_rpy() local roll = rpy[1] local delay_threshold_angle = Config.walk.delay_threshold_angle or math.huge local stop_threshold_angle = Config.walk.stop_threshold_angle or math.huge local delay_factor = Config.walk.delay_factor or {0.8,1.7} ------------------------------------------------------- -- Adaptive timing support if roll>stop_threshold_angle or roll<-stop_threshold_angle and iStep>5 then emergency_stop = true print"EMERGENCY STOP!!!!" print"EMERGENCY STOP!!!!" print"EMERGENCY STOP!!!!" print"EMERGENCY STOP!!!!" end if supportLeg==0 then -- print("Right landing, roll angle",roll*RAD_TO_DEG) if roll>delay_threshold_angle then print("LANDING DELAYED!" ,roll*RAD_TO_DEG) zmp_solver:set_landing_delay_factor(delay_factor[2]) elseif roll<-delay_threshold_angle then print("LANDING FASTENED" ,roll*RAD_TO_DEG) zmp_solver:set_landing_delay_factor(delay_factor[1]) else zmp_solver:set_landing_delay_factor(1) end elseif supportLeg==1 then -- print("Left landing, roll angle",roll*RAD_TO_DEG) if roll<-delay_threshold_angle then print("LANDING DELAYED!",roll*RAD_TO_DEG ) zmp_solver:set_landing_delay_factor(delay_factor[2]) elseif roll>delay_threshold_angle then print("LANDING FASTENED" ,roll*RAD_TO_DEG) zmp_solver:set_landing_delay_factor(delay_factor[1]) else zmp_solver:set_landing_delay_factor(1) end else zmp_solver:set_landing_delay_factor(1) end end --------------------------------------------------- ph_last = ph if is_next_step then if emergency_stop then mcm.set_walk_ismoving(0) --no more moving (body FSM can check this) return "emergency" end --Should we stop now? local stoprequest = mcm.get_walk_stoprequest() local steprequest = mcm.get_walk_steprequest() if stoprequest>0 then return"done" end if steprequest>0 then return "done_step" end iStep = iStep + 1 -- Increment the step index supportLeg = iStep % 2 -- supportLeg: 0 for left support, 1 for right support local initial_step = false if iStep<=3 then initial_step = true end --step_planner:update_velocity(hcm.get_motion_velocity()) velCurrent = step_planner:update_velocity(mcm.get_walk_vel()) --Calculate next step and torso positions based on velocity uLeft_now, uRight_now, uTorso_now, uLeft_next, uRight_next, uTorso_next, uSupport = step_planner:get_next_step_velocity(uLeft_next,uRight_next,uTorso_next,supportLeg,initial_step) local uTorsoVelCurrent = mcm.get_status_uTorsoVel() if Config.variable_support then local torsoVelYMin = 0.20 local torsoVelYFactor = 0.5 local torsoVelYFactor = 0 local torsoVelXMin = 0.07 local torsoVelXFactor = 0.1 local torsoXExt = math.max(0,(math.abs(uTorsoVelCurrent[1])-torsoVelXMin))*torsoVelXFactor torsoXExt = -math.min(torsoXExt, 0.02)* util.sign(uTorsoVelCurrent[2]) local torsoYExt = math.max(0, (math.abs(uTorsoVelCurrent[2])-torsoVelYMin )) *torsoVelYFactor torsoYExt = -math.min(torsoYExt, 0.02)*util.sign(uTorsoVelCurrent[2]) local uSupportModY = torsoXExt + torsoYExt if Config.debug.walk then print("TorsoVel:",unpack(uTorsoVelCurrent)) print("torsoXExt:",torsoXExt) print("torsoYExt:",torsoYExt) print("supportModY:",uSupportModY) end if velCurrent[2]>0 and supportLeg ==0 then uSupportModY = uSupportModY - 0.01 end if velCurrent[2]>0 and supportLeg ~=0 then uSupportModY = uSupportModY + 0.01 end --quick hack for front walking if velCurrent[1]>0.04 then if supportLeg==0 then uSupportModY = uSupportModY - 0.01 else uSupportModY = uSupportModY + 0.01 end end print("supportModY:",uSupportModY) uSupport = util.pose_global({0,uSupportModY,0},uSupport) end local uTorsoVel = mcm.get_status_uTorsoVel() local uSupportDist1 = util.pose_relative(uSupport,uTorso_now) local uSupportDist2 = util.pose_relative(uSupport, uTorso_next) local y_dist = math.abs(uSupportDist1[2]+uSupportDist2[2]) local y_dist_mag = y_dist/(Config.walk.footY+Config.walk.supportY)/2 local tStepNew = Config.walk.tStep if Config.variable_tstep then -- print("DIST:",y_dist, y_dist_mag) tStepNew = Config.walk.tStep*y_dist_mag tStepNew = Config.walk.tStep* y_dist_mag end --Update walk coefficients zmp_solver:set_param(tStepNew) zmp_param_set = true -- Compute the ZMP coefficients for the next step zmp_solver:compute( uSupport, uTorso_now, uTorso_next ) t_last_step = Body.get_time() -- Update t_last_step end local uTorso = zmp_solver:get_com(ph) uTorso[3] = ph*(uLeft_next[3]+uRight_next[3])/2 + (1-ph)*(uLeft_now[3]+uRight_now[3])/2 --update the current COM velocity local uTorsoVel = zmp_solver:get_com_vel(ph) mcm.set_status_uTorsoVel(uTorsoVel) local phSingle = moveleg.get_ph_single(ph,Config.walk.phSingle[1],Config.walk.phSingle[2]) if iStep<=2 then phSingle = 0 end --This kills compensation and holds the foot on the ground local uLeft, uRight, zLeft, zRight, aLeft,aRight = uLeft_now, uRight_now, 0,0, 0,0 if supportLeg == 0 then uRight,zRight,aRight = foot_traj_func(phSingle,uRight_now,uRight_next,stepHeight) --LS else uLeft,zLeft,aLeft = foot_traj_func(phSingle,uLeft_now,uLeft_next,stepHeight) -- RS end --Heel lift first, heel land first --positive aLeft: toe lift --negative aLeft: heel lift local heeltoe_angle = Config.heeltoe_angle or 5*DEG_TO_RAD if Config.use_heeltoe_walk then mcm.set_walk_footlift({aLeft*heeltoe_angle, aRight*heeltoe_angle}) else mcm.set_walk_footlift({0,0}) end local uZMP = zmp_solver:get_zmp(ph) moveleg.store_stance(t,ph,uLeft,uTorso,uRight,supportLeg,uZMP, zLeft,zRight) -- Grab gyro feedback for these joint angles local gyro_rpy = moveleg.update_sensory_feedback() -- local gyro_rpy = moveleg.get_gyro_feedback( uLeft, uRight, uTorso, supportLeg ) moveleg.ft_compensate(t_diff) delta_legs, angleShift = moveleg.get_leg_compensation_new( supportLeg, ph, gyro_rpy, angleShift, 0, t_diff) moveleg.set_leg_positions() update_odometry(uTorso)--Update the odometry variable end -- walk.update function walk.exit() print(walk._NAME..' Exit') -- print("Total time: ",Body.get_time()-t_entry) if zmp_param_set then local uTorsoVel = zmp_solver:get_com_vel(1) --Get the final COM velocity mcm.set_status_uTorsoVel(uTorsoVel) else print("ZMP PARMAM NOT SET YET") end step_planner:save_stance(uLeft_next,uRight_next,uTorso_next) end return walk
local function reql_error_formatter(err) if type(err) ~= 'table' then return end if err.ReQLError then return err.message() end end describe('current handshake', function() local r, socket, current_handshake setup(function() assert:add_formatter(reql_error_formatter) r = require('rethinkdb') socket = require('rethinkdb.internal.socket') current_handshake = require('rethinkdb.internal.current_handshake') end) teardown(function() current_handshake = nil socket = nil r = nil assert:remove_formatter(reql_error_formatter) end) it('no password', function() local client = assert.is_table(socket(r, 'localhost', 28015, nil, 20)) finally(client.close) assert.is_true(current_handshake(r, client, '', 'admin')) end) end)
neb_service_check_proto = Proto("neb_service_check", "NEB SVC CHECK") local f_active_checks = ProtoField.bool("neb_service_check.active_checks_enabled", "active checks", 8, nil, 0x1) local f_check_type = ProtoField.uint16("neb_service_check.check_type", "check type", base.HEX, nil, nil, "") local f_host_id = ProtoField.uint32("neb_service_check.host_id", "Host id", base.HEX, nil, nil, "") local f_next_check = ProtoField.uint64("neb_service_check.next_check", "next check", base.HEX, nil, nil, "") local f_service_id = ProtoField.uint32("neb_service_check.service_id", "service id", base.HEX, nil, nil, "") local f_cmd_line = ProtoField.stringz("neb_service_check.command_line", "Command Line") neb_service_check_proto.fields = { f_active_checks, f_check_type, f_host_id, f_next_check, f_service_id, f_cmd_line } function neb_service_check_proto.dissector(buffer, pinfo, tree) pinfo.cols.protocol = "NEB Svc Check" local subtree = tree:add(neb_service_check_proto, buffer(), "NEB Svc check") subtree:add(f_active_checks, buffer(0,1)) subtree:add(f_check_type, buffer(1,2)) subtree:add(f_host_id, buffer(3,4)) subtree:add(f_next_check, buffer(7,8)) subtree:add(f_service_id, buffer(15,4)) subtree:add(f_cmd_line, buffer(19)) end
--[[ This file is part of 'Masque', an add-on for World of Warcraft. For license information, please see the included License.txt file or visit https://github.com/StormFX/Masque. * File...: Core\Regions\Texture.lua * Author.: StormFX Texture Regions * See Skins\Default.lua for region defaults. ]] local _, Core = ... ---------------------------------------- -- Internal --- -- @ Skins\Regions local Settings = Core.RegTypes.Legacy -- @ Skins\Default local Defaults = Core.Skins.Default -- @ Core\Utility local GetSize, SetPoints = Core.GetSize, Core.SetPoints local GetColor, GetTexCoords = Core.GetColor, Core.GetTexCoords -- @ Core\Regions\Mask local SkinMask = Core.SkinMask ---------------------------------------- -- Core --- -- Skins a texture region of a button. function Core.SkinTexture(Region, Button, Layer, Skin, Color, xScale, yScale) if Skin.Hide then Region:SetTexture() Region:Hide() return end local bType = Button.__MSQ_bType local Config = Settings[Layer] local Default = Defaults[Layer] if bType then Skin = Skin[bType] or Skin Config = Config[bType] or Config Default = Default[bType] or Default end if not Config.NoTexture then local Texture = Skin.Texture Color = Color or Skin.Color local SetColor = not Config.NoColor local UseColor = Config.UseColor if Skin.UseColor and UseColor then Region:SetTexture() Region:SetVertexColor(1, 1, 1, 1) Region:SetColorTexture(GetColor(Color)) elseif Texture then Region:SetTexture(Texture) Region:SetTexCoord(GetTexCoords(Skin.TexCoords)) if SetColor then Region:SetVertexColor(GetColor(Color)) end else local Atlas = Default.Atlas Texture = Default.Texture if Atlas then Region:SetAtlas(Atlas) if SetColor then Region:SetVertexColor(GetColor(Default.Color)) end elseif Texture then Region:SetTexture(Default.Texture) Region:SetTexCoord(GetTexCoords(Default.TexCoords)) if SetColor then Region:SetVertexColor(GetColor(Default.Color)) end elseif UseColor then Region:SetTexture() Region:SetVertexColor(1, 1, 1, 1) Region:SetColorTexture(GetColor(Default.Color)) end end end Region:SetBlendMode(Skin.BlendMode or Default.BlendMode or "BLEND") Region:SetDrawLayer(Skin.DrawLayer or Default.DrawLayer, Skin.DrawLevel or Default.DrawLevel or 0) Region:SetSize(GetSize(Skin.Width, Skin.Height, xScale, yScale)) local SetAllPoints = Skin.SetAllPoints or (not Skin.Point and Default.SetAllPoints) SetPoints(Region, Button, Skin, Default, SetAllPoints) -- Mask if Config.CanMask then SkinMask(Button, Region, Skin, xScale, yScale) end end
-- switch.lua - Main switch component local cqueues = require('cqueues') local socket = require('cqueues.socket') local console = require('console') local conf = require('configurator') local vpath = require('vpath') local vchan = require('vchan') local _SW = {} function _SW.new() local self = {} local console_clients = {} -- list local _async = cqueues.new() -- We store our VPI (and hence our VCI handlers) here: local VPI = {} -- Main loop: function self.run() local config = conf.new 'config/system.lua' { console = 'scalar', switch = 'scalar', } _async:wrap(function() for client in console_listener:clients() do console_obj = console.new { handle = client, async = _async, config = config, } table.insert(console_clients, console_obj) -- Add client to roster end end) print("The management console will be accessible via " .. config['data']['console']['bind'] .. ':' .. config['data']['console']['port']) end assert(_async:loop()) end return self end return _SW
#!/usr/bin/lua local states = { "alabama", "alaska", "arizona", "arkansas", "california", "colorado", "connecticut", "delaware", "florida", "georgia", "hawaii", "idaho", "illinois", "indiana", "iowa", "kansas", "kentucky", "louisiana", "maine", "maryland", "massachusetts", "michigan", "minnesota", "mississippi", "missouri", "montana", "nebraska", "nevada", "new hampshire", "new jersey", "new mexico", "new york", "north carolina", "north dakota", "ohio", "oklahoa", "oregon", "pennsylvania", "rhode island", "south carolina", "south dakota", "tennessee", "texas", "utah", "vermont", "virginia", "washington", "west virginia", "wisconsin", "wyoming", } function use_or() local x = 0 for _, v in pairs(states) do if "alabama" == v or "california" == v or "missouri" == v or "virginia" == v or "wisconsin" == v then x = x + 1 end end return x end function use_table() local x, vals = 0, {"alabama", "california", "missouri", "virginia", "wisconsin"} for _, v in pairs(states) do for _, s in pairs(vals) do if s == v then x = x + 1 end end end return x end return { name = "multi-conditions", desc = "judge with table and inline code", cases = { { name = "Use OR ", entry = use_or }, { name = "Use table", entry = use_table }, } }
return { image = "images/moveindicator.png", width = 16, height = 16, frametime = 0.04, animations = { click = { from = 1, to = 8 } } }
function Crone_Summon_Cyclone(Unit, event, miscUnit, misc) Unit:FullCastSpellOnTarget(38337, Unit:GetRandomPlayer()) end function Crone_Chain_Lightning(Unit, event, miscUnit, misc) Unit:FullCastSpellOnTarget(32337, Unit:GetClosestPlayer()) end function Crone(Unit, event, miscUnit, misc) Unit:RegisterEvent("Crone_Summon_Cyclone", 10000, 0) Unit:RegisterEvent("Crone_Chain_Lightning", 17000, 0) end RegisterUnitEvent(18168, 1, "Crone") --[[The Crone yells: How could you? What a cruel, cruel world... The Crone yells: It will all be over soon! The Crone yells: Woe to each and every one of you, my pretties!]]
local filesystem = require("Filesystem") local image = require("Image") local screen = require("Screen") local GUI = require("GUI") local paths = require("Paths") local system = require("System") if not component.isAvailable("stargate") then GUI.alert("This program requires stargate from mod \"SGCraft\"") return end local stargate = component.get("stargate") --------------------------------------------------------------------------------------------- local resources = filesystem.path(system.getCurrentScript()) local pathToContacts = paths.user.applicationData .. "Stargate/Contacts.cfg" local contacts = {} local Ch1Image = image.load(resources .. "Ch1.pic") local Ch2Image = image.load(resources .. "Ch2.pic") local workspace = GUI.workspace() --------------------------------------------------------------------------------------------- local function loadContacts() if filesystem.exists(pathToContacts) then contacts = filesystem.readTable(pathToContacts) end end local function saveContacts() filesystem.writeTable(pathToContacts, contacts) end local function chevronDraw(object) local inactiveColor, activeColor, fadeColor = 0x332400, 0xFFDB00, 0xCC6D00 -- screen.drawRectangle(object.x, object.y, object.width, object.height, object.isActivated and fadeColor or inactiveColor) -- screen.drawRectangle(object.x + 1, object.y, 3, object.height, object.isActivated and activeColor or inactiveColor) -- screen.drawText(object.x + 2, object.y + 1, object.isActivated and 0x0 or 0xFFFFFF, object.text) screen.drawImage(object.x, object.y, object.isActivated and Ch1Image or Ch2Image) return object end local function newChevronObject(x, y) local object = GUI.object(x, y, 5, 3) object.draw = chevronDraw object.isActivated = false object.text = " " return object end local function addChevron(x, y) table.insert(workspace.chevrons, workspace.chevronsContainer:addChild(newChevronObject(x, y))) end local function updateChevrons(state) for i = 1, #workspace.chevrons do workspace.chevrons[i].isActivated = state if not state then workspace.chevrons[i].text = " " end end end local function updateButtons() workspace.removeContactButton.disabled = #contacts == 0 workspace.connectContactButton.disabled = #contacts == 0 end local function update() local stargateState, irisState, imagePath = stargate.stargateState(), stargate.irisState() workspace.irisButton.text = irisState == "Closed" and "Open Iris" or "Close Iris" workspace.connectionButton.text = stargateState == "Connected" and "Disconnect" or "Connect" workspace.connectedToLabel.text = stargateState == "Connected" and "(Connected to " .. stargate.remoteAddress() .. ")" or "(Not connected)" if stargateState == "Connected" then workspace.connectContactButton.disabled = true workspace.messageContactButton.disabled = false if irisState == "Closed" then imagePath = "OnOn.pic" else imagePath = "OnOff.pic" end else workspace.connectContactButton.disabled = false workspace.messageContactButton.disabled = true if irisState == "Closed" then imagePath = "OffOn.pic" else imagePath = "OffOff.pic" end end updateButtons() workspace.SGImage.image = image.load(resources .. imagePath) end local function updateContacts() workspace.contactsComboBox:clear() if #contacts == 0 then workspace.contactsComboBox:addItem("No contacts found") else for i = 1, #contacts do workspace.contactsComboBox:addItem(contacts[i].name) end end end local function newThing(x, y, width, height) local object = GUI.object(x, y, width, height) object.draw = function(object) local x, y = object.x + object.width - 1, math.floor(object.y + object.height / 2) for i = object.y, object.y + object.height - 1 do screen.drawText(x, i, 0xEEEEEE, "│") end for i = object.x, object.x + width - 1 do screen.drawText(i, y, 0xEEEEEE, "─") end screen.drawText(x, y, 0xEEEEEE, "┤") end return object end local function dial(address) local success, reason = stargate.dial(address) if success then workspace.fuelProgressBar.value = math.ceil(stargate.energyToDial(address) / stargate.energyAvailable() * 100) workspace:draw() else GUI.alert("Failed to dial: " .. tostring(reason)) end end --------------------------------------------------------------------------------------------- local width, height = 32, 37 local x, y = workspace.width - width - 3, math.floor(workspace.height / 2 - height / 2) workspace:addChild(GUI.panel(1, 1, workspace.width, workspace.height, 0x1E1E1E)) workspace.SGImage = workspace:addChild(GUI.image(1, 1, image.load(resources .. "OffOff.pic"))) workspace.SGImage.localX, workspace.SGImage.localY = math.floor((x - 2) / 2 - image.getWidth(workspace.SGImage.image) / 2), workspace.height - image.getHeight(workspace.SGImage.image) + 1 workspace.chevronsContainer = workspace:addChild(GUI.container(workspace.SGImage.localX, workspace.SGImage.localY, workspace.SGImage.width, workspace.SGImage.height)) workspace.chevrons = {} addChevron(13, 30) addChevron(8, 17) addChevron(21, 6) addChevron(45, 1) addChevron(72, 6) addChevron(83, 17) addChevron(79, 30) workspace:addChild(newThing(workspace.SGImage.localX + workspace.SGImage.width, y, workspace.width - workspace.SGImage.localX - workspace.SGImage.width - width - 7, height)) workspace:addChild(GUI.label(x, y, width, 1, 0xEEEEEE, "Stargate " .. stargate.localAddress())):setAlignment(GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP); y = y + 1 workspace.connectedToLabel = workspace:addChild(GUI.label(x, y, width, 1, 0x555555, "(Not connected)")):setAlignment(GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP); y = y + 2 workspace.connectionButton = workspace:addChild(GUI.framedButton(x, y, width, 3, 0xEEEEEE, 0xEEEEEE, 0xBBBBBB, 0xBBBBBB, "Connect")); y = y + 3 -- workspace.connectionButton.animated = false workspace.connectionButton.onTouch = function() if stargate.stargateState() == "Idle" then local container = GUI.addBackgroundContainer(workspace, true, true, "Connect") local input = container.layout:addChild(GUI.input(1, 1, 36, 3, 0xEEEEEE, 0x666666, 0x666666, 0xEEEEEE, 0x262626, contacts.last, "Type address here")) input.onInputFinished = function() if input.text then dial(input.text) contacts.last = input.text saveContacts() container:remove() workspace:draw() end end container.panel.eventHandler = function(workspace, object, e1) if e1 == "touch" then input.onInputFinished() end end workspace:draw() else stargate.disconnect() end end workspace.irisButton = workspace:addChild(GUI.framedButton(x, y, width, 3, 0xEEEEEE, 0xEEEEEE, 0xBBBBBB, 0xBBBBBB, "Open Iris")); y = y + 3 workspace.irisButton.onTouch = function() if stargate.irisState() == "Open" then stargate.closeIris() else stargate.openIris() end end workspace.messageContactButton = workspace:addChild(GUI.framedButton(x, y, width, 3, 0xEEEEEE, 0xEEEEEE, 0xBBBBBB, 0xBBBBBB, "Message")); y = y + 4 workspace.messageContactButton.onTouch = function() local container = GUI.addBackgroundContainer(workspace, true, true, "Message") local input = container.layout:addChild(GUI.input(1, 1, 36, 3, 0xEEEEEE, 0x666666, 0x666666, 0xEEEEEE, 0x262626, nil, "Type message text here")) input.onInputFinished = function() if input.text then container:remove() stargate.sendMessage(input.text) workspace:draw() end end container.panel.eventHandler = function(workspace, object, e1) if e1 == "touch" then input.onInputFinished() end end workspace:draw() end workspace:addChild(GUI.label(x, y, width, 1, 0xEEEEEE, "Contacts")):setAlignment(GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP); y = y + 2 workspace.contactsComboBox = workspace:addChild(GUI.comboBox(x, y, width, 3, 0x3C3C3C, 0xBBBBBB, 0x555555, 0x888888)); y = y + 4 workspace.connectContactButton = workspace:addChild(GUI.framedButton(x, y, width, 3, 0xEEEEEE, 0xEEEEEE, 0xBBBBBB, 0xBBBBBB, "Connect")); y = y + 3 workspace.connectContactButton.onTouch = function() dial(contacts[workspace.contactsComboBox.selectedItem].address) end workspace.addContactButton = workspace:addChild(GUI.framedButton(x, y, width, 3, 0xEEEEEE, 0xEEEEEE, 0xBBBBBB, 0xBBBBBB, "Add contact")); y = y + 3 workspace.addContactButton.onTouch = function() local container = GUI.addBackgroundContainer(workspace, true, true, "Add contact") local input1 = container.layout:addChild(GUI.input(1, 1, 36, 3, 0xEEEEEE, 0x666666, 0x666666, 0xEEEEEE, 0x262626, nil, "Name")) local input2 = container.layout:addChild(GUI.input(1, 1, 36, 3, 0xEEEEEE, 0x666666, 0x666666, 0xEEEEEE, 0x262626, contacts.last, "Address")) container.panel.eventHandler = function(workspace, object, e1) if e1 == "touch" then if input1.text and input2.text then local exists = false for i = 1, #contacts do if contacts[i].address == input2.text then exists = true break end end if not exists then table.insert(contacts, {name = input1.text, address = input2.text}) updateContacts() saveContacts() updateButtons() end container:remove() workspace:draw() end end end workspace:draw() end workspace.removeContactButton = workspace:addChild(GUI.framedButton(x, y, width, 3, 0xEEEEEE, 0xEEEEEE, 0xBBBBBB, 0xBBBBBB, "Remove contact")); y = y + 4 workspace.removeContactButton.onTouch = function() if #contacts > 0 then table.remove(contacts, workspace.contactsComboBox.selectedItem) updateContacts() saveContacts() updateButtons() workspace:draw() end end workspace:addChild(GUI.label(x, y, width, 1, 0xEEEEEE, "Energy to dial")):setAlignment(GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP); y = y + 2 workspace.fuelProgressBar = workspace:addChild(GUI.progressBar(x, y, width, 0xBBBBBB, 0x0, 0xEEEEEE, 100, true, true, "", "%")); y = y + 3 workspace.exitButton = workspace:addChild(GUI.framedButton(x, y, width, 3, 0xEEEEEE, 0xEEEEEE, 0xBBBBBB, 0xBBBBBB, "Exit")); y = y + 4 workspace.exitButton.onTouch = function() workspace:stop() end workspace.eventHandler = function(workspace, object, e1, e2, e3, e4) if e1 == "sgIrisStateChange" then update() workspace:draw() elseif e1 == "sgStargateStateChange" then if e3 == "Idle" or e3 == "Connected" then update() updateChevrons(e3 == "Connected") workspace:draw() end elseif e1 == "sgChevronEngaged" then if workspace.chevrons[e3] then workspace.chevrons[e3].isActivated = true workspace.chevrons[e3].text = e4 workspace:draw() end elseif e1 == "sgMessageReceived" then GUI.alert(e3) end end loadContacts() updateContacts() update() updateChevrons(stargate.stargateState() == "Connected") workspace:draw() workspace:start()
-- clear.lua -- Implements the /clear command. function HandleClearCommand(Split, Player) if (Split[2] == nil) then Player:GetInventory():Clear() LOGINFO(Player:GetName() .. " cleared their inventory.") SendMessageSuccess(Player, cChatColor.LightGray .. "Cleared your own inventory.") return true end -- If they have the permission to clear other people's inventories, let them. if Player:HasPermission("basics.clear.others") then local InventoryCleared = false local ClearInventory = function(OtherPlayer) if (OtherPlayer:GetName() == Split[2]) then OtherPlayer:GetInventory():Clear() InventoryCleared = true end end cRoot:Get():FindAndDoWithPlayer(Split[2], ClearInventory) if (InventoryCleared) then LOGINFO(Player:GetName() .. " cleared the inventory of " .. Split[2] .. ".") SendMessageSuccess(Player, cChatColor.LightGray .. "Cleared the inventory of " .. Split[2] .. ".") else SendMessageFailure(Player, cChatColor.LightGray .. "Couldn't find that player.") end return true end return false end
--[[ 8:3 Extensions by Callum John (@ItsSeaJay) ]] path = "extensions.txt" file = io.open(path, "w") letters = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" } extensions = 1 io.output(file) for first in pairs(letters) do for second in pairs(letters) do for third in pairs(letters) do extension = "." .. letters[first] .. letters[second] .. letters[third] io.write(extension) -- Enforce 80 column rule if (extensions * 4) % 64 == 0 then io.write("\n") else io.write(" ") end extensions = extensions + 1 end end end io.close(file) print("Output", extensions, "extensions to", path)
local utils = require('vgit.core.utils') local Object = require('vgit.core.Object') local Blame = Object:extend() local function split_by_whitespace(str) return vim.split(str, ' ') end function Blame:new(info) if not info then return setmetatable({}, Blame) end -- TODO this is badly done crashes randomly please fix this parsing. local commit_hash_info = split_by_whitespace(info[1]) local author_mail_info = split_by_whitespace(info[3]) local author_time_info = split_by_whitespace(info[4]) local author_tz_info = split_by_whitespace(info[5]) local committer_mail_info = split_by_whitespace(info[7]) local committer_time_info = split_by_whitespace(info[8]) local committer_tz_info = split_by_whitespace(info[9]) local parent_hash_info = split_by_whitespace(info[11]) local author = info[2]:sub(8, #info[2]) local author_mail = author_mail_info[2] local committer = info[6]:sub(11, #info[6]) local committer_mail = committer_mail_info[2] local lnum = tonumber(commit_hash_info[3] or '1') local committed = true if author == 'Not Committed Yet' and committer == 'Not Committed Yet' and author_mail == '<not.committed.yet>' and committer_mail == '<not.committed.yet>' then committed = false end return setmetatable({ lnum = lnum, commit_hash = commit_hash_info[1], parent_hash = parent_hash_info[2], author = author, author_mail = (function() local mail = author_mail if mail:sub(1, 1) == '<' and mail:sub(#mail, #mail) then mail = mail:sub(2, #mail - 1) end return mail end)(), author_time = tonumber(author_time_info[2]), author_tz = author_tz_info[2], committer = committer, committer_mail = (function() local mail = committer_mail if mail:sub(1, 1) == '<' and mail:sub(#mail, #mail) then mail = mail:sub(2, #mail - 1) end return mail end)(), committer_time = tonumber(committer_time_info[2]), committer_tz = committer_tz_info[2], commit_message = info[10]:sub(9, #info[10]), committed = committed, }, Blame) end function Blame:age() return utils.age(self.author_time) end return Blame
{ data={name="Icechocola", author="Icechocola"},blocks={ {0x132e28, {2.118, 0}, command={faction=1257}}, {0x132e76, {-9.429, 50}, -1.047, bindingId=5, features=TURRET|LASER|AUTOFIRE|PALETTE}, {0x132e2b, {2.118, 50}}, {0x132e2b, {5.004, 55}, 1.047}, {0x132e5d, {-20.254, 28.75}, 2.094}, {0x132e2b, {-12.316, 25}, -1.047}, {0x132e34, {-12.315, 15}, -1.047}, {0x132e34, {-15.202, 20}, -2.094}, {0x132e34, {-6.542, 15.001}, -2.094}, {0x132e34, {-20.976, 20}, -1.047}, {0x132e34, {13.665, 50}, -1.047}, {0x132e2b, {-20.976, 50}, -1.047}, {0x132e2b, {-23.863, 45}}, {0x132e2b, {-20.976, 40}, -1.047}, {0x132e2b, {-15.203, 40}, -2.094}, {0x132e2b, {-29.637, 45}, -1.047}, {0x132e2b, {-32.523, 40}, 4.189}, {0x132e34, {-38.297, 40}, 3.142}, {0x132e2b, {-41.183, 35}, 4.189}, {0x132e2b, {-46.957, 34.999}, -1.047}, {0x132e2b, {-49.844, 39.999}}, {0x132e2b, {-46.957, 44.999}, -1.047}, {0x132e34, {-41.184, 45}, 2.094}, {0x132e34, {-38.297, 50}, 3.142}, {0x132eed, {-39.74, 60}, 3.142}, {0x132e34, {-46.957, 55}, 1.047}, {0x132e2e, {-52.731, 65}, 4.189}, {0x132e2b, {-58.504, 55}, 4.189}, {0x132e34, {-55.617, 50}, 1.047}, {0x132e34, {-49.844, 50}, 2.094}, {0x132e34, {-58.504, 45}, 2.094}, {0x132e34, {-64.278, 45}, 1.047}, {0x132e2b, {-67.164, 50}, 2.094}, {0x132e2b, {-64.278, 55}, 3.142}, {0x132e2b, {-67.164, 60}, 2.094}, {0x132e2b, {-64.278, 65}, 3.142}, {0x132e34, {-67.164, 40}, 2.094}, {0x132e34, {-72.938, 40}, 1.047}, {0x132e34, {-75.825, 35}, 2.094}, {0x132e34, {-81.598, 35}, 1.047}, {0x132e34, {-84.485, 30}, 2.094}, {0x132e34, {-90.258, 30}, 1.047}, {0x132e34, {-93.145, 25}, 2.094}, {0x132e34, {-98.919, 25}, 1.047}, {0x132e34, {-101.805, 20}, 2.094}, {0x132e34, {-107.579, 20}, 1.047}, {0x132e34, {-110.466, 15}, 2.094}, {0x132e34, {-116.239, 15}, 1.047}, {0x132e34, {-119.126, 10}, 2.094}, {0x132e34, {-116.239, 5}, 3.142}, {0x132e34, {-119.126, 0}, 2.094}, {0x132e34, {-116.239, -5}, 1.047}, {0x132e34, {-119.126, -10}, 4.189}, {0x132e34, {-116.239, -15}, -1.047}, {0x132e34, {-110.466, -15}, 4.189}, {0x132e34, {-107.579, -20}, -1.047}, {0x132e34, {-101.805, -20}, 4.189}, {0x132e34, {-98.919, -25}, -1.047}, {0x132e34, {-93.145, -25}, 4.189}, {0x132e34, {-90.258, -30}, -1.047}, {0x132e34, {-84.485, -30}, 4.189}, {0x132e34, {-81.598, -35}, -1.047}, {0x132e34, {-75.825, -35}, 4.189}, {0x132e34, {-72.938, -40}, -1.047}, {0x132e34, {-67.164, -40}, 4.189}, {0x132e34, {-64.278, -45}, -1.047}, {0x132e34, {-58.504, -45}, 4.189}, {0x132e34, {-55.617, -50}, -1.047}, {0x132e34, {-49.844, -50}, 4.189}, {0x132e34, {-46.957, -55}, -1.047}, {0x132eed, {-39.74, -60}, 3.142}, {0x132e2e, {-52.731, -65}, 2.094}, {0x132e2b, {-58.504, -55}, 2.094}, {0x132e2b, {-64.278, -55}, 3.142}, {0x132e2b, {-67.164, -60}, 4.189}, {0x132e2b, {-64.278, -65}, 3.142}, {0x132e2b, {-67.164, -50}, 4.189}, {0x132e34, {-46.957, -75}, -1.047}, {0x132e34, {-49.844, -80}, 4.189}, {0x132e34, {-46.957, -85}, 3.142}, {0x132e34, {-38.297, -50}, 3.142}, {0x132e34, {-41.184, -45}, 4.189}, {0x132e2b, {-46.957, -45}, 1.047}, {0x132e2b, {-49.844, -40}}, {0x132e2b, {-46.957, -35}, 1.047}, {0x132e2b, {-41.183, -35}, 2.094}, {0x132e34, {-38.297, -40}, 3.142}, {0x132e2b, {-32.523, -40}, 2.094}, {0x132e2b, {-29.637, -45}, 1.047}, {0x132e2b, {-23.863, -45.001}}, {0x132e2b, {-20.976, -40.001}, -1.047}, {0x132e2b, {-15.203, -40.001}, 4.189}, {0x132e76, {-9.429, -50.001}, 1.047, bindingId=5, features=TURRET|LASER|AUTOFIRE|PALETTE}, {0x132e2b, {-3.656, -40.001}, -1.047}, {0x132e2b, {-20.976, -50.001}, -1.047}, {0x132e34, {-32.523, -50}, 2.094}, {0x132e2b, {-55.617, -40}, 1.047}, {0x132e2b, {-55.617, 40}, -1.047}, {0x132e34, {-46.957, 75}, 1.047}, {0x132e34, {-49.844, 80}, 2.094}, {0x132e34, {-46.957, 85}, 1.047}, {0x132e34, {-32.523, 50}, -2.094}, {0x132e2b, {10.778, 55}, 2.094}, {0x132e2b, {13.665, 60}, 3.142}, {0x132e2b, {19.438, 60}, -2.094}, {0x132e37, {25.212, 50}}, {0x132e34, {19.438, 40}, -2.094}, {0x132eee, {12.222, 40}}, {0x132eed, {3.562, 40}}, {0x132e40, {2.118, 30}, 2.094}, {0x132e40, {-3.655, 30}, 1.047}, {0x132e2b, {-6.542, 25}}, {0x132e2b, {-3.655, 20}, -1.047}, {0x132e2b, {2.118, 20}}, {0x132e53, {5.005, 15}, 1.047}, {0x132e53, {10.779, 15}}, {0x132e2b, {13.665, 10}, 1.047}, {0x132e2b, {19.439, 10}}, {0x132e2b, {22.326, 15}, 1.047}, {0x132e2b, {28.099, 15}}, {0x132e2b, {30.986, 20}, 1.047}, {0x132e2b, {36.759, 20}}, {0x132e34, {39.646, 15}, 3.142}, {0x132e2b, {36.759, 10}, 2.094}, {0x132e2b, {30.986, 10}, 1.047}, {0x132e76, {25.212, 0}, -1.047, bindingId=5, features=TURRET|LASER|AUTOFIRE|PALETTE}, {0x132e2b, {30.986, -10}, 3.142}, {0x132e2b, {28.099, -15}}, {0x132e2b, {30.986, -20}, 1.047}, {0x132e2b, {36.759, -20}}, {0x132e34, {39.646, -15}, 3.142}, {0x132e2b, {36.759, -10}, 4.189}, {0x132eee, {44.698, -6.25}, 1.047}, {0x132e34, {45.42, -15}}, {0x132eee, {57.688, -6.25}, 2.094}, {0x132e34, {65.627, -10}, 3.142}, {0x132e34, {71.4, -9.999}}, {0x132e2e, {77.173, 0.001}}, {0x132e2e, {94.494, 0.001}, -2.094}, {0x132e2b, {88.721, -9.999}, 2.094}, {0x132e2b, {82.947, -9.999}, 1.047}, {0x132e2b, {88.72, 10.001}, 2.094}, {0x132e2b, {82.947, 10.001}, 1.047}, {0x132e37, {111.814, 0.002}}, {0x132e34, {123.361, 0.002}, -2.094}, {0x132e34, {65.626, 0}, 3.142}, {0x132eee, {57.688, 6.25}, -2.094}, {0x132e34, {65.626, 10}, 3.142}, {0x132e34, {71.399, 10.001}}, {0x132eee, {44.697, 6.25}, -1.047}, {0x132e34, {45.419, 14.999}}, {0x132e34, {36.759, -0.001}, -2.094}, {0x132e2b, {48.306, 0}, 1.047}, {0x132e2b, {54.08, 0}, 2.094}, {0x132e2b, {22.326, -15}, 1.047}, {0x132e2b, {19.439, -10}}, {0x132e2b, {13.665, -10}, -1.047}, {0x132e53, {10.778, -15}, 2.094}, {0x132e53, {5.005, -15}, 1.047}, {0x132e34, {2.118, -10}}, {0x132e34, {5.005, -5}, 1.047}, {0x132e2b, {-3.656, 40}, 1.047}, {0x132e34, {5.005, 5}, -1.047}, {0x132e34, {10.779, 5}}, {0x132e34, {13.665, 0}, -1.047}, {0x132e34, {10.778, -5}, 4.189}, {0x132e34, {2.118, 10}, 4.189}, {0x132e34, {-3.655, 10}, -1.047}, {0x132e2b, {-6.542, 5}, 4.189}, {0x132e2b, {-3.655, 0}, 3.142}, {0x132e2b, {-6.542, -5}, 4.189}, {0x132e34, {-3.655, -10}, 1.047}, {0x132e34, {-6.542, -15}}, {0x132e2b, {-3.655, -20}, 1.047}, {0x132e2b, {2.118, -20}}, {0x132e2b, {-6.542, -25}}, {0x132e40, {-3.655, -30}, -1.047}, {0x132e40, {2.118, -30}, 4.189}, {0x132eed, {3.562, -40}}, {0x132eee, {12.222, -40}}, {0x132e34, {13.665, -50}, 1.047}, {0x132e37, {25.212, -50}, -1.047}, {0x132e2b, {19.438, -60}, 2.094}, {0x132e2b, {13.665, -60}, 3.142}, {0x132e2b, {10.778, -55}, 4.189}, {0x132e2b, {5.005, -55}, -1.047}, {0x132e34, {19.438, -40}}, {0x132e2b, {-12.316, -25}, 1.047}, {0x132e34, {-15.202, -20}, 2.094}, {0x132e34, {-20.976, -20}, 1.047}, {0x132e2b, {-23.863, -15}, 4.189}, {0x132eee, {-31.079, -20}, 3.142}, {0x132e5d, {-20.254, -28.75}, 4.189}, {0x132e2b, {-20.976, -10}, 3.142}, {0x132e2b, {-15.202, -10}, 4.189}, {0x132e34, {-12.316, -15}, 1.047}, {0x132e2b, {-12.316, -5}, 3.142}, {0x132e2b, {-15.202, 0}, 4.189}, {0x132e2b, {-12.316, 5}, -1.047}, {0x132e2b, {-15.202, 10}, 4.189}, {0x132e2b, {-20.976, 10}, 3.142}, {0x132e2b, {-23.863, 15}, 4.189}, {0x132eee, {-31.079, 20}, 3.142}, {0x132e2b, {2.118, -50.001}, -2.094}}}
local Com = include("com", ...) ---------------------------------------------- --ComFinish ---------------------------------------------- local ComFinish = class("ComFinish", Com) function ComFinish:ctor() end function ComFinish:match(req, res) end return ComFinish
--[[ TheNexusAvenger Implementation of a command. --]] local BaseCommand = require(script.Parent.Parent:WaitForChild("BaseCommand")) local Command = BaseCommand:Extend() --[[ Creates the command. --]] function Command:__new() self:InitializeSuper("fly","UsefulFunCommands","Gives a set of players the ability to fly. Use E to toggle on/off.") self.Arguments = { { Type = "nexusAdminPlayers", Name = "Players", Description = "Players to fly.", }, } --Create the remote event. local FlyPlayerEvent = Instance.new("RemoteEvent") FlyPlayerEvent.Name = "FlyPlayer" FlyPlayerEvent.Parent = self.API.EventContainer self.FlyPlayerEvent = FlyPlayerEvent end --[[ Runs the command. --]] function Command:Run(CommandContext,Players) self.super:Run(CommandContext) --Fling the players. for _,Player in pairs(Players) do self.FlyPlayerEvent:FireClient(Player) end end return Command
-- Copyright 2022 Erick Israel Vazquez Neri -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local OnOff = require "st.zigbee.zcl.clusters".OnOff local build_cluster_attribute = require "st.zigbee.cluster_base".build_cluster_attribute local Enum8 = require "st.zigbee.data_types".Enum8 local OnOffButtonAttr = 0x8004 local OnOffButtonAttrLabel = "OnOffButton" -- returns prebuilt attribute -- on top of OnOff (0x0006) cluster -- which is used by device to emit -- button-specific events. return assert( build_cluster_attribute( OnOff, -- cluster OnOffButtonAttr, -- attr_id OnOffButtonAttrLabel, -- attr_name Enum8, -- data_type true)) -- is_writable
class "TimerManager" function TimerManager:TimerManager(...) local arg = {...} for k,v in pairs(arg) do if type(v) == "table" then if v.__ptr ~= nil then arg[k] = v.__ptr end end end if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then self.__ptr = Polycode.TimerManager(unpack(arg)) end end function TimerManager:removeTimer(timer) local retVal = Polycode.TimerManager_removeTimer(self.__ptr, timer.__ptr) end function TimerManager:addTimer(timer) local retVal = Polycode.TimerManager_addTimer(self.__ptr, timer.__ptr) end function TimerManager:Update() local retVal = Polycode.TimerManager_Update(self.__ptr) end function TimerManager:__delete() if self then Polycode.delete_TimerManager(self.__ptr) end end
Citizen.CreateThread(function() Config.CurrentLab = math.random(1, #Config.Locations["laboratories"]) --print('Lab entry has been set to location: '..Config.CurrentLab) end) QBCore.Functions.CreateCallback('qb-methlab:server:GetData', function(source, cb) local LabData = { CurrentLab = Config.CurrentLab } cb(LabData) end) QBCore.Functions.CreateUseableItem("labkey", function(source, item) local Player = QBCore.Functions.GetPlayer(source) local LabKey = item.info.lab ~= nil and item.info.lab or 1 TriggerClientEvent('qb-methlab:client:UseLabKey', source, LabKey) end) function GenerateRandomLab() local Lab = math.random(1, #Config.Locations["laboratories"]) return Lab end RegisterServerEvent('qb-methlab:server:loadIngredients') AddEventHandler('qb-methlab:server:loadIngredients', function() local Player = QBCore.Functions.GetPlayer(tonumber(source)) local hydrochloricacid = Player.Functions.GetItemByName('hydrochloricacid') local ephedrine = Player.Functions.GetItemByName('ephedrine') local acetone = Player.Functions.GetItemByName('acetone') if Player.PlayerData.items ~= nil then if (hydrochloricacid ~= nil and ephedrine ~= nil and acetone ~= nil) then if hydrochloricacid.amount >= 0 and ephedrine.amount >= 0 and acetone.amount >= 0 then Player.Functions.RemoveItem("hydrochloricacid", 3, false) TriggerClientEvent('inventory:client:ItemBox', source, QBCore.Shared.Items['hydrochloricacid'], "remove") Player.Functions.RemoveItem("ephedrine", 3, false) TriggerClientEvent('inventory:client:ItemBox', source, QBCore.Shared.Items['ephedrine'], "remove") Player.Functions.RemoveItem("acetone", 3, false) TriggerClientEvent('inventory:client:ItemBox', source, QBCore.Shared.Items['acetone'], "remove") end end end end) RegisterServerEvent('qb-methlab:server:CheckIngredients') AddEventHandler('qb-methlab:server:CheckIngredients', function() local Player = QBCore.Functions.GetPlayer(tonumber(source)) local hydrochloricacid = Player.Functions.GetItemByName('hydrochloricacid') local ephedrine = Player.Functions.GetItemByName('ephedrine') local acetone = Player.Functions.GetItemByName('acetone') if Player.PlayerData.items ~= nil then if (hydrochloricacid ~= nil and ephedrine ~= nil and acetone ~= nil) then if hydrochloricacid.amount >= 0 and ephedrine.amount >= 0 and acetone.amount >= 0 then TriggerClientEvent("qb-methlab:client:loadIngredients", source) else TriggerClientEvent('QBCore:Notify', source, "You do not have the correct items", 'error') end else TriggerClientEvent('QBCore:Notify', source, "You do not have the correct items", 'error') end else TriggerClientEvent('QBCore:Notify', source, "You Have Nothing...", "error") end end) RegisterServerEvent('qb-methlab:server:breakMeth') AddEventHandler('qb-methlab:server:breakMeth', function() local Player = QBCore.Functions.GetPlayer(tonumber(source)) local meth = Player.Functions.GetItemByName('methtray') local puremethtray = Player.Functions.GetItemByName('puremethtray') if Player.PlayerData.items ~= nil then if (meth ~= nil or puremethtray ~= nil) then TriggerClientEvent("qb-methlab:client:breakMeth", source) else TriggerClientEvent('QBCore:Notify', source, "You do not have the correct items", 'error') end else TriggerClientEvent('QBCore:Notify', source, "You Have Nothing...", "error") end end) RegisterServerEvent('qb-methlab:server:getmethtray') AddEventHandler('qb-methlab:server:getmethtray', function(amount) local Player = QBCore.Functions.GetPlayer(tonumber(source)) local methtray = Player.Functions.GetItemByName('methtray') local puremethtray = Player.Functions.GetItemByName('puremethtray') if puremethtray ~= nil then if puremethtray.amount >= 1 then Player.Functions.AddItem("puremeth", amount, false) TriggerClientEvent('inventory:client:ItemBox', source, QBCore.Shared.Items['puremeth'], "add") Player.Functions.RemoveItem("puremethtray", 1, false) TriggerClientEvent('inventory:client:ItemBox', source, QBCore.Shared.Items['puremethtray'], "remove") end elseif methtray ~= nil then if methtray.amount >= 1 then Player.Functions.AddItem("meth", amount, false) TriggerClientEvent('inventory:client:ItemBox', source, QBCore.Shared.Items['meth'], "add") Player.Functions.RemoveItem("methtray", 1, false) TriggerClientEvent('inventory:client:ItemBox', source, QBCore.Shared.Items['methtray'], "remove") end else TriggerClientEvent('QBCore:Notify', source, "You do not have the correct items", 'error') end end) RegisterServerEvent('qb-methlab:server:receivemethtray') AddEventHandler('qb-methlab:server:receivemethtray', function() local chance = math.random(1, 100) print(chance) if chance >= 90 then local Player = QBCore.Functions.GetPlayer(tonumber(source)) Player.Functions.AddItem("puremethtray", 3, false) TriggerClientEvent('inventory:client:ItemBox', source, QBCore.Shared.Items['puremethtray'], "add") else local Player = QBCore.Functions.GetPlayer(tonumber(source)) Player.Functions.AddItem("methtray", 3, false) TriggerClientEvent('inventory:client:ItemBox', source, QBCore.Shared.Items['methtray'], "add") end end)
--This is an example that uses the MLX90614 Infrared Temperature Sensor. --The sensor should be connected with SCL on EIO7 and SDA on EIO6. print("-------") print("/*Connect a MLX90614 with SCL on EIO7 and SDA on EIO6*/") print("") fwver = MB.R(60004, 3) devType = MB.R(60000, 3) if (fwver < 1.0224 and devType == 7) or (fwver < 0.2037 and devType == 4) then print("This lua script requires a higher firmware version (T7 Requires 1.0224 or higher, T4 requires 0.2037 or higher). Program Stopping") MB.W(6000, 1, 0) end function calc_I2C_options(resetAtStart, noStopAtStarting, disableStretching)--Returns a number 0-7 local optionsVal = 0 optionsVal = resetAtStart*1+noStopAtStarting*2+disableStretching*4 return optionsVal end --Configure the I2C Utility local sdaPin = 14 -- EIO6 local sclPin = 15 -- EIO7 local throttleVal = 65500--65523 local i2cOptions = calc_I2C_options(0,1,0)--Calculate the I2C Options value local myAddr = 0x5a--I2C address of the slave device I2C.config(sdaPin, sclPin, throttleVal, i2cOptions, myAddr) ------------ START SCAN FOR I2C SLAVE DEVICES --------------------- local addrs = I2C.search(0, 127)--find all I2C slaves and publish results local addrsLen = table.getn(addrs) local found = 0 if addrsLen == 0 then print("No I2C Slaves detected, program stopping") MB.W(6000, 1, 0)--end script end -- verify that the target device was found found = 0 for i=1, addrsLen do if addrs[i] == myAddr then print("I2C Slave Detected") found = 1 break end end if found == 0 then print("No I2C Slave detected, program stopping") MB.W(6000, 1, 0) end print(string.format('Num Found Addresses %d', table.getn(addrs))) for key,val in pairs(addrs) do print(string.format('%d: 0x%x, %d (dec)',key,val,val)) end ------------ END SCAN FOR I2C SLAVE DEVICES --------------------- print("") print("-------") print("/*Starting...*/") print("") function convTemp(rawTemp) -- Convert values to temperature C. local convTemp = (rawTemp[2]*256+rawTemp[1]) convTemp = convTemp * 0.02 convTemp = convTemp - 273.15 -- Convert temp to °C -- convTemp = (convTemp *9/5) + 32 -- Convert temp to °F return convTemp end local rawTemp = 0 local ambientTemp = 0 local objTemp = 0 LJ.IntervalConfig(0, 250) while true do if LJ.CheckInterval(0) then -- Read the ambient temperature of the MLX rawTemp = I2C.writeRead({0x06}, 3) ambientTemp = convTemp(rawTemp) -- Read the IR temperature of the MLX rawTemp = I2C.writeRead({0x07}, 3) objTemp = convTemp(rawTemp) -- Save results to USER_RAM0_F32 USER_RAM1_F32 MB.W(46000, 3, ambientTemp) MB.W(46002, 3, objTemp) print(string.format('Ambient Temperature: %.2f °C', ambientTemp)) print(string.format('IR Temperature: %.2f °C', objTemp)) end end --Stop the Lua Script MB.W(6000, 1, 0)
local Iterable = require('iterables/Iterable') local SecondaryCache = require('class')('SecondaryCache', Iterable) function SecondaryCache:__init(array, primary) local objects = {} for _, data in ipairs(array) do local obj = primary:_insert(data) objects[obj:__hash()] = obj end self._count = #array self._objects = objects self._primary = primary end function SecondaryCache:__pairs() return next, self._objects end function SecondaryCache:__len() return self._count end function SecondaryCache:_insert(data) local obj = self._primary:_insert(data) local k = obj:__hash() if not self._objects[k] then self._objects[k] = obj self._count = self._count + 1 end return obj end function SecondaryCache:_remove(data) local obj = self._primary:_insert(data) -- yes, this is correct local k = obj:__hash() if self._objects[k] then self._objects[k] = nil self._count = self._count - 1 end return obj end function SecondaryCache:get(k) return self._objects[k] end function SecondaryCache:iter() local objects, k, obj = self._objects return function() k, obj = next(objects, k) return obj end end return SecondaryCache
local function abluka_izle() local izle = vgui.Create( "DFrame" ) izle:SetSize( ScrW() * 1,ScrH() * 1 ) izle:SetTitle( " " ) izle:SetDraggable( false ) izle:MakePopup() izle:ShowCloseButton(false) izle:Center(true) function izle:Paint( w, h ) local x, y = self:GetPos() if ( !IsValid( LocalPlayer() ) ) then return end local WPos = LocalPlayer():LocalToWorld(Vector( -826.193787, 4785.672852, 666.715454 )) render.RenderView( { origin = abluka.izlemevector, angles = abluka.izlemeangle, x = x, y = y, w = w, h = h } ) end local kapat = vgui.Create( "DButton", izle ) kapat:SetPos( x * 0.95, y * 0.01 ) kapat:SetSize( x * 0.05, y * 0.05) kapat.DoClick = function() izle:Close() end kapat:TDLib() kapat:ClearPaint() :Circle(Color(40, 40, 40, 0)) :CircleFadeHover(Color(40,40,40,200), 15) :Text("×", "Trebuchet48") izle:TDLib() :FadeIn() :LinedCorners(Color(255,255,255,255)) end hook.Add("OnPlayerChat", "gui_abluka_izle", function(ply, strText) if (ply ~= LocalPlayer()) then return end strText = string.lower(strText) if (strText == "!ablukaizle") then abluka_izle() end end)
require("prototypes/scripts/util.lua") require("prototypes.categories.groups") require("prototypes.heat.data") require("prototypes.colonists.data") require("prototypes.engineering.data") require("prototypes.housing.data") require("prototypes.ambulance.data") require("prototypes.food.data") require("prototypes.manned.data") require("prototypes.research.data") require("prototypes.waste.data") require("prototypes.jobs.jobs") -- require("prototypes.gui.gui_data") -- require("prototypes.foodIndustry.foodIndustry") -- require("prototypes.robotArmy.robotarmy") -- require("prototypes.training.training") require("prototypes.fluid.fluid") require("prototypes.void.void") require("prototypes/informatron/informatron_data") require("data_raw_edits")
local Hooks = require(script.Components.Hooks) return { Menu = require(script.Components.Menu), MenuAction = require(script.Components.MenuAction), Plugin = require(script.Components.Plugin), PluginAction = require(script.Components.PluginAction), Toolbar = require(script.Components.Toolbar), ToolbarButton = require(script.Components.ToolbarButton), Widget = require(script.Components.Widget), -- Hooks -- Hooks = Hooks, usePlugin = Hooks.usePlugin, useToolbar = Hooks.useToolbar, useWidget = Hooks.useWidget, -- Not neccessary to expose, but maybe useful -- Context = require(script.Components.Context), MergeUtil = require(script.Util.MergeUtil), }
local z = ... return function(c,p,u) package.loaded[z] = nil z = nil if u > 1 then require("rs")(c, 401) return end require("rs")(c, 200, "") tmr.create():alarm(1000, 0, function() node.restart() end) end
hs.hotkey.alertDuration = 0 hs.hints.showTitleThresh = 0 hs.window.animationDuration = 0 -- Use the standardized config location, if present custom_config = hs.fs.pathToAbsolute(os.getenv("HOME") .. '/.config/hammerspoon/private/config.lua') if custom_config then print("Loading custom config") dofile( os.getenv("HOME") .. "/.config/hammerspoon/private/config.lua") privatepath = hs.fs.pathToAbsolute(hs.configdir .. '/private/config.lua') if privatepath then hs.alert("You have config in both .config/hammerspoon and .hammerspoon/private.\nThe .config/hammerspoon one will be used.") end else -- otherwise fallback to 'classic' location. if not privatepath then privatepath = hs.fs.pathToAbsolute(hs.configdir .. '/private') -- Create `~/.hammerspoon/private` directory if not exists. hs.fs.mkdir(hs.configdir .. '/private') end privateconf = hs.fs.pathToAbsolute(hs.configdir .. '/private/config.lua') if privateconf then -- Load awesomeconfig file if exists require('private/config') end end hsreload_keys = hsreload_keys or {{"cmd", "shift", "ctrl"}, "R"} if string.len(hsreload_keys[2]) > 0 then hs.hotkey.bind(hsreload_keys[1], hsreload_keys[2], "Reload Configuration", function() hs.reload() end) end -- ModalMgr Spoon must be loaded explicitly, because this repository heavily relies upon it. hs.loadSpoon("ModalMgr") -- Define default Spoons which will be loaded later if not hspoon_list then hspoon_list = { "HCalendar", } end -- Load those Spoons for _, v in pairs(hspoon_list) do hs.loadSpoon(v) end ---------------------------------------------------------------------------------------------------- -- Then we create/register all kinds of modal keybindings environments. ---------------------------------------------------------------------------------------------------- -- Register windowHints (Register a keybinding which is NOT modal environment with modal supervisor) -- hswhints_keys = hswhints_keys or {"alt", "tab"} -- if string.len(hswhints_keys[2]) > 0 then -- spoon.ModalMgr.supervisor:bind(hswhints_keys[1], hswhints_keys[2], 'Show Window Hints', function() -- spoon.ModalMgr:deactivateAll() -- hs.hints.windowHints() -- end) -- end ---------------------------------------------------------------------------------------------------- -- appM modal environment spoon.ModalMgr:new("appM") local cmodal = spoon.ModalMgr.modal_list["appM"] cmodal:bind('', 'escape', 'Deactivate appM', function() spoon.ModalMgr:deactivate({"appM"}) end) cmodal:bind('', 'Q', 'Deactivate appM', function() spoon.ModalMgr:deactivate({"appM"}) end) cmodal:bind('', 'tab', 'Toggle Cheatsheet', function() spoon.ModalMgr:toggleCheatsheet() end) if not hsapp_list then hsapp_list = { {key = 'f', name = 'Finder'}, {key = 's', name = 'Safari'}, {key = 't', name = 'Terminal'}, {key = 'v', id = 'com.apple.ActivityMonitor'}, {key = 'y', id = 'com.apple.systempreferences'}, } end for _, v in ipairs(hsapp_list) do if v.id then local located_name = hs.application.nameForBundleID(v.id) if located_name then cmodal:bind('', v.key, located_name, function() hs.application.launchOrFocusByBundleID(v.id) spoon.ModalMgr:deactivate({"appM"}) end) end elseif v.name then cmodal:bind('', v.key, v.name, function() hs.application.launchOrFocus(v.name) spoon.ModalMgr:deactivate({"appM"}) end) end end -- Then we register some keybindings with modal supervisor hsappM_keys = hsappM_keys or {"alt", "A"} if string.len(hsappM_keys[2]) > 0 then spoon.ModalMgr.supervisor:bind(hsappM_keys[1], hsappM_keys[2], "Enter AppM Environment", function() spoon.ModalMgr:deactivateAll() -- Show the keybindings cheatsheet once appM is activated spoon.ModalMgr:activate({"appM"}, "#FFBD2E", true) end) end ---------------------------------------------------------------------------------------------------- -- Finally we initialize ModalMgr supervisor spoon.ModalMgr.supervisor:enter()
local Game = require "game" local Player = require "player" local Enemy = require "enemy" local Background = require "background" local game function addKeypressHandler(handler) local previous = love.keyreleased love.keyreleased = function (key) handler(key) if previous then previous(key) end end end love.load = function() local player = Player.create() game = Game.create(player) local background = Background.create("Backgrounds/darkPurple.png") game:insertEntity(background) -- handle the space key addKeypressHandler(function(key) if key == 'space' then player:fireMissile(game) end end) Enemy.populate(game, 1) end love.update = function(dt) require("lib.lurker").update() require("lib.lovebird").update() game:update(dt) end love.draw = function() game:draw(dt) end
local TOCNAME,GBB=... local L = setmetatable({}, {__index = function (t, k) if GBB.L and GBB.L[k] then return GBB.L[k] elseif GBB.locales.enGB and GBB.locales.enGB[k] then return GBB.locales.enGB[k] else return "["..k.."]" end end}) function GBB.CreateChatFrame(name, ...) local Frame = name and FCF_OpenNewWindow(name, true) or ChatFrame1 if(...) then for index = 1, select('#', ...) do ChatFrame_AddMessageGroup(Frame, select(index, ...)) end end return Frame end function GetChannels() local channelList = {GetChannelList()} local channels = {} for i = 1, #channelList, 3 do table.insert(channels, { id = channelList[i], name = channelList[i+1], isDisabled = channelList[i+2] }) end return channels end function SetChannels(ChanNames, Frame, ShouldRemove) ShouldRemove = ShouldRemove or false for k, _ in pairs(ChanNames) do if ShouldRemove == true and k ~= "" then ChatFrame_RemoveChannel(Frame, k) elseif k ~= "" then ChatFrame_AddChannel(Frame, k) end end end function MissingChannels(ChanNames, ChannelsToAdd) local missingChannels = {} for k, _ in pairs (ChannelsToAdd) do if ChanNames[k] == nil and ChanNames[k] ~= "" then missingChannels[k] = 1 end end return missingChannels end function GBB.InsertChat() local chatFrameInit = false local tabName = "LFG" -- Don't create a new tab if it already exists for i = 1, NUM_CHAT_WINDOWS do local tab = _G["ChatFrame"..i.."Tab"] local name = tab:GetText() local shown =tab:IsShown() if name == tabName and shown == true then chatFrameInit = true end end if chatFrameInit == true then return end local ChannelsToAdd = { [L["lfg_channel"]] = 1, [L["world_channel"]] = 1, } -- Create new chat frame and new tab with no default message groups local Frame = GBB.CreateChatFrame(tabName, "SAY", "EMOTE", "YELL", "GUILD", "OFFICER", "PARTY", "PARTY_LEADER", "RAID", "RAID_LEADER", "RAID_WARNING", "BATTLEGROUND", "BATTLEGROUND_LEADER", "SYSTEM", "MONSTER_WHISPER", "MONSTER_BOSS_WHISPER", "INSTANCE_CHAT", "INSTANCE_CHAT_LEADER") -- Get all channels the player has joined local channels = GetChannels() local channelNames = {} for _, v in pairs(channels) do channelNames[v["name"]] = v["isDisabled"] end -- Figures out what spammy LFG channels ie LookingForGroup the user hasn't joined -- if they are missing any channels then join them in the new chat tab local missingChannels = MissingChannels(channelNames, ChannelsToAdd) for k, _ in pairs(missingChannels) do JoinChannelByName(k, nil, Frame:GetID()) -- since if missingChannels contains any channels that means they would be absent from channelNames channelNames[k] = 0 end -- Join every single possible channel including any channels that user was missing before SetChannels(channelNames, Frame, false) -- Remove all LFG Spammy channels from default chat tab SetChannels(ChannelsToAdd, ChatFrame1, true) -- Set focus back to default tab and enable chat notifications FCF_SelectDockFrame(ChatFrame1) GBB.DB["NotifyChat"]=true GBB.OptionsUpdate() end
-- buildrect <length> <width> -- -- Builds a rectangle of the given length and width -- ---------------------------- -- USAGE ---------------------------- -- Fuel goes in the first slot (very top left in the Turtle's inventory) -- First position the turtle directly ABOVE where the first block will go, facing OUTWARD -- o o o -- o o o -- o o o -- o o [] --> turtle faces this direction (outwards) -- buildrect 3 4 local tArgs = {...} local bDebug = false local selectedSlot=1 local abort = false local length = 0 local width = 0 local version = "1.0" ------------------------------------------------------------------------------- -- ARGUMENTS ------------------------------------------------------------------------------- if (#tArgs == 2) then length = tonumber(tArgs[1]) width = tonumber(tArgs[2]) else print("Usage: buildrect <length> <width>") return end ------------------------------------------------------------------------------- -- FUNCTIONS ------------------------------------------------------------------------------- function setSelectedSlot(slot) if turtle.select(slot) then selectedSlot = slot end end function getSelectedSlot() return selectedSlot end -- If fuel level is less than 10, refuel function fuel() if turtle.getFuelLevel() < 10 then local slot = getSelectedSlot() setSelectedSlot(1) if turtle.refuel(1) then print("Refueled!") else print("Refuelling failed.") abort = true end setSelectedSlot(slot) end end function placeSlab() -- is there a block in front of us? if turtle.detect() then abort = true else -- try to place a block if not turtle.place() then local slot = getSelectedSlot() -- try to find another suitable slot for i=slot,16,1 do setSelectedSlot(i) if turtle.place() then break end if i == 16 then abort = true end end end end end ------------------------------------------------------------------------------- -- MAIN PROGRAM START ------------------------------------------------------------------------------- print("buildrect version " .. version .. " starting...") -- fuel should be placed in slot 1 -- everything else in slots 2-16 setSelectedSlot(2) -- turtle should be started above an empty space, the first block to place turtle.down() turtle.back() placeSlab() for w = 1, width, 1 do print("Width: " .. w .. " of " .. width) -- don't need to place start and end blocks for l = 1, length - 2, 1 do turtle.back() placeSlab() fuel() if abort == true then break end end if abort == true then break end -- place start and end blocks if (w%2) == 0 then turtle.turnLeft() turtle.back() placeSlab() turtle.turnLeft() if w ~= width then turtle.back() placeSlab() end else turtle.turnRight() turtle.back() placeSlab() turtle.turnRight() if w ~= width then turtle.back() placeSlab() end end end turtle.up() print("Done!")
-- usage example: DATA_ROOT=/path/to/data/ which_direction=BtoA name=expt1 th train.lua -- -- code derived from https://github.com/soumith/dcgan.torch -- require 'torch' require 'nn' require 'optim' util = paths.dofile('util/util.lua') --require 'lib-new/MaxCoord' require 'image' require 'models' require 'math' require 'lib/NonparametricPatchAutoencoderFactory' require 'lib/MaxCoord' require 'lib/InstanceNormalization' require 'lib/innerSwap' require 'lib/myUtils' opt = { name = 'feature_visual', -- name of the experiment, should generally be passed on the command line --DATA_ROOT = './datasets/fix-3-mask-s-label', -- path to images (should have subfolders 'train', 'val', etc) DATA_ROOT = './datasets/test-feature-visual', -- path to images (should have subfolders 'train', 'val', etc) batchSize = 1, -- # images in batch loadSize = 256, -- scale images to this size fineSize = 256, -- then crop to this size ngf = 64, -- # of gen filters in first conv layer ndf = 64, -- # of discrim filters in first conv layer input_nc = 6, -- # of input image channels input_nc_net = 3, -- # of input image channels output_nc = 3, -- # of output image channels niter = 10000, --200 -- # of iter at starting learning rate lr = 0.2, -- initial learning rate for adam beta1 = 0.5, -- momentum term of adam ntrain = math.huge, -- # of examples per epoch. math.huge for full dataset flip = 0, -- if flip the images for data argumentation display = 1, -- display samples while training. 0 = false display_id = 10, -- display window id. display_plot = 'errD', -- which loss values to plot over time. Accepted values include a comma seperated list of: errL1, errG, and errD gpu = 1, -- gpu = 0 is CPU mode. gpu=X is GPU mode on GPU X which_direction = 'AtoB', -- AtoB or BtoA phase = 'train', -- train, val, test, etc preprocess = 'regular', -- for special purpose preprocessing, e.g., for colorization, change this (selects preprocessing functions in util.lua) nThreads = 10, -- # threads for loading data save_epoch_freq = 10, --20 -- save a model every save_epoch_freq epochs (does not overwrite previously saved models) save_latest_freq = 5000, --5000 -- save the latest model every latest_freq sgd iterations (overwrites the previous latest model) print_freq = 100, --20 -- print the debug information every print_freq iterations display_freq = 5, --100 -- display the current results every display_freq iterations save_display_freq = 100,--1000 -- save the current display of results every save_display_freq_iterations continue_train=0, -- if continue training, load the latest model: 1: true, 0: false serial_batches = 0, -- if 1, takes images in order to make batches, otherwise takes them randomly serial_batch_iter = 1, -- iter into serial image list checkpoints_dir = './checkpoints_visual', -- models are saved here cudnn = 1, -- set to 0 to not use cudnn condition_GAN = 0, -- set to 0 to use unconditional discriminator use_GAN = 1, -- set to 0 to turn off GAN term use_L1 = 1, -- set to 0 to turn off L1 term which_model_netD = 'basic', -- selects model to use for netD which_model_netG = 'unet', -- selects model to use for netG n_layers_D = 0, -- only used if which_model_netD=='n_layers' lambda = 1, -- weight on L1 term in objective SwapKernelSize = 3, -- kernel size of swap swap_layer = '20000000', -- swap the layer 1,2,3,4,5,6,7,8 AreaThreshold = 0.5, --Theshold for computing feature mask swap_stride = 1, -- swap stride end_layer = 4, content_weight = 13, } -- one-line argument parser. parses enviroment variables to override the defaults for k,v in pairs(opt) do opt[k] = tonumber(os.getenv(k)) or os.getenv(k) or opt[k] end print(opt) ------------------------------------init param----------------------------------------- local input_nc = opt.input_nc_net local output_nc = opt.output_nc local ngf = opt.ngf if opt.display then disp = require 'display' end -- translation direction local idx_A = nil local idx_B = nil idx_A = {1, input_nc} -- 123通道为input图 content图 idx_B = {input_nc+1, input_nc*2} -- 456通道为style图 idx_C= {input_nc+output_nc+1,input_nc*2+output_nc} -- 789通道为groundtruth if opt.display == 0 then opt.display = false end opt.manualSeed = torch.random(1, 10000) -- fix seed print("Random Seed: " .. opt.manualSeed) torch.manualSeed(opt.manualSeed) torch.setdefaulttensortype('torch.FloatTensor') local errD = 0; -------------------------------------- create data loader--------------------------------- local data_loader = paths.dofile('data/dataC.lua') print('#threads...' .. opt.nThreads) local data = data_loader.new(opt.nThreads, opt) print("Dataset Size: ", data:size()) tmp_d, tmp_paths = data:getBatch() ---------------------------------------define network-------------------------------------------------- local netG = nil netG = util.load('./checkpoints/tec_swap64_6-16/30_net_G.t7', opt) local function weights_init(netD,end_layer) local j=1 for i = 1, end_layer do local layer = netG:get(i) local tn = torch.typename(layer) if tn == 'cudnn.SpatialConvolution' or tn=='cudnn.SpatialFullConvolution' or tn == 'cudnn.SpatialBatchNormalization' then print(netD.modules[j]) print(netG.modules[i]) print(i,j) netD.modules[j].weight = netG.modules[i].weight:clone() netD.modules[j].bias = netG.modules[i].bias:clone() end j=j+1 end assert(1==2) return netD end function defineFV(input_nc, output_nc, ngf,end_layer) -- input is (nc) x 256 x 256 local e1 = - nn.SpatialConvolution(input_nc, ngf, 4, 4, 2, 2, 1, 1) -- 1 if end_layer == 1 then local e=e1 - nn.LeakyReLU(0.2, true) return nn.gModule({e1},{e}) end -- input is (ngf) x 128 x 128 local e2 = e1 - nn.LeakyReLU(0.2, true) - nn.SpatialConvolution(ngf, ngf * 2, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 2) --2 3 4 if end_layer == 4 then return nn.gModule({e1},{e2}) end -- input is (ngf * 2) x 64 x 64 local e3 = e2 - nn.LeakyReLU(0.2, true) - nn.SpatialConvolution(ngf * 2, ngf * 4, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 4) -- nn.LeakyReLU(0.2, true)--5 6 7 if end_layer == 7 then return nn.gModule({e1},{e3}) end -- input is (ngf * 4) x 32 x 32 local e4 = e3 - nn.LeakyReLU(0.2, true) - nn.SpatialConvolution(ngf * 4, ngf * 8, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 8) -- 8 9 10 if end_layer == 10 then return nn.gModule({e1},{e4})-- nn.LeakyReLU(0.2, true) end -- input is (ngf * 8) x 16 x 16 local e5 = e4 - nn.LeakyReLU(0.2, true) - nn.SpatialConvolution(ngf * 8, ngf * 8, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 8) -- 11 12 13 if end_layer == 13 then return nn.gModule({e1},{e5 - nn.LeakyReLU(0.2, true)}) end -- input is (ngf * 8) x 8 x 8 local e6 = e5 - nn.LeakyReLU(0.2, true) - nn.SpatialConvolution(ngf * 8, ngf * 8, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 8) --14 15 16 if end_layer == 16 then return nn.gModule({e1},{e6- nn.LeakyReLU(0.2, true)}) end -- input is (ngf * 8) x 4 x 4 local e7 = e6 - nn.LeakyReLU(0.2, true) - nn.SpatialConvolution(ngf * 8, ngf * 8, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 8) --17 18 19 if end_layer == 19 then return nn.gModule({e1},{e7}) end -- input is (ngf * 8) x 2 x 2 local e8 = e7 - nn.LeakyReLU(0.2, true) - nn.SpatialConvolution(ngf * 8, ngf * 8, 4, 4, 2, 2, 1, 1) -- nn.SpatialBatchNormalization(ngf * 8) -- 20 21 -- input is (ngf * 8) x 1 x 1 if end_layer == 21 then return nn.gModule({e1},{e8}) end local d1_ = e8 - nn.ReLU(true) - nn.SpatialFullConvolution(ngf * 8, ngf * 8, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 8) - nn.Dropout(0.5) -- 22 23 24 25 if end_layer == 25 then return nn.gModule({e1},{d1_}) end -- input is (ngf * 8) x 2 x 2 local d1 = {d1_,e7} - nn.JoinTable(2) --26 local d2_ = d1 - nn.ReLU(true) - nn.SpatialFullConvolution(ngf * 8 * 2, ngf * 8, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 8) - nn.Dropout(0.5) -- 27 28 29 30 if end_layer == 30 then return nn.gModule({e1},{d2_}) end -- input is (ngf * 8) x 4 x 4 local d2 = {d2_,e6} - nn.JoinTable(2) --31 local d3_ = d2 - nn.ReLU(true) - nn.SpatialFullConvolution(ngf * 8 * 2, ngf * 8, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 8) - nn.Dropout(0.5) -- 32 33 34 35 if end_layer == 35 then return nn.gModule({e1},{d3_}) end -- input is (ngf * 8) x 8 x 8 local d3 = {d3_,e5} - nn.JoinTable(2) --36 local d4_ = d3 - nn.ReLU(true) - nn.SpatialFullConvolution(ngf * 8 * 2, ngf * 8, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 8) -- 37 38 39 if end_layer == 39 then return nn.gModule({e1},{d4_- nn.LeakyReLU(0.2, true)}) end -- input is (ngf * 8) x 16 x 16 local d4 = {d4_,e4} - nn.JoinTable(2) --40 local d5_ = d4 - nn.ReLU(true) - nn.SpatialFullConvolution(ngf * 8 * 2, ngf * 4, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 4) -- 41 42 43 if end_layer == 43 then return nn.gModule({e1},{d5_}) end -- input is (ngf * 4) x 32 x 32 local d5 = {d5_,e3} - nn.JoinTable(2) -- 44 local d6_ = d5 - nn.ReLU(true) - nn.SpatialFullConvolution(ngf * 4 * 2, ngf * 2, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf * 2) -- 45 46 47 if end_layer == 47 then return nn.gModule({e1},{d6_}) end -- input is (ngf * 2) x 64 x 64 local d6 = {d6_,e2} - nn.JoinTable(2) -- 48 local d7_ = d6 - nn.ReLU(true) - nn.SpatialFullConvolution(ngf * 2 * 2, ngf, 4, 4, 2, 2, 1, 1) - nn.SpatialBatchNormalization(ngf) -- 49 50 51 if end_layer == 51 then return nn.gModule({e1},{d7_}) end error('not valid end layer') end local netFV = nil netFV = defineFV(opt.input_nc_net,opt.output_nc,opt.ngf,opt.end_layer) netFV = util.cudnn(netFV); netFV = weights_init(netFV,opt.end_layer) for i=1,#netG.modules do local layer = netG:get(i) local tn = torch.typename(layer) print(i,tn) end for i=1,#netFV.modules do local layer = netFV:get(i) local tn = torch.typename(layer) print(i,tn) end ---------------------------------------------------------------------------- local real_A = torch.Tensor(opt.batchSize, input_nc, opt.fineSize, opt.fineSize) local real_B = torch.Tensor(opt.batchSize, input_nc, opt.fineSize, opt.fineSize) local real_C = torch.Tensor(opt.batchSize, input_nc, opt.fineSize, opt.fineSize) local FeatureGroundtruth = nil; local errD= 0 local epoch_tm = torch.Timer() local tm = torch.Timer() local data_tm = torch.Timer() ---------------------------------------------------------------------------------------- -- local criterion = nn.AbsCriterion(); --abs 损失函数 local criterion = nn.MSECriterion() --mse 损失函数 optimStateD = { learningRate = opt.lr, beta1 = opt.beta1, } -- ---------------------------------------------------------------------------- if opt.gpu > 0 then print('transferring to gpu...') require 'cunn' cutorch.setDevice(opt.gpu) real_A = real_A:cuda(); real_B = real_B:cuda(); real_C = real_C:cuda(); if opt.cudnn==1 then netG = util.cudnn(netG); netFV = util.cudnn(netFV); end netG:cuda();criterion:cuda(); netFV:cuda(); print('done') else print('running model on CPU') end -- local parametersFV, gradParametersFV = netFV:getParameters() local imageB_ = image.load('./datasets/test-feature-visual/train/3.png') local imageB = imageB_[{{},{},{1,256}}] -- -------------------------------generate data image------------------------------------------------- function createRealFake() data_tm:reset(); data_tm:resume() local real_data, data_path = data:getBatch() data_tm:stop() real_A:copy(real_data[{ {}, idx_A, {}, {} }]) --1*3*256*256 -1 到 1 之间 real_B:copy(real_data[{ {}, idx_B, {}, {} }]) -- 为mask 范围为 -1 和 1 4D real_C:copy(real_data[{ {}, idx_C, {}, {} }]) --image_B = real_A:clone() netG:forward(real_A) FeatureGroundtruth_tmp=netG.modules[48].output:clone()-- print(FeatureGroundtruth_tmp:size()) print(netG.modules[48])--this is swaped feature --assert(1==2) --print() FeatureGroundtruth = FeatureGroundtruth_tmp[{{},{1,128},{},{}}] print(FeatureGroundtruth:size()) end createRealFake() local img = nil; img = torch.randn(real_A:size()):float():mul(0.001):cuda() -- img=real_B:clone(); -- -- create closure to evaluate f(X) and df/dX of discriminator local function feval(x) --netD_8:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) -- gradParametersD8:zero(); ----------------------------start foward 1-7 ---------------------------------------------------- local Output = netFV:forward(x) errD = criterion:forward(Output, FeatureGroundtruth) local df = criterion:backward(Output, FeatureGroundtruth) local grad = netFV:updateGradInput(x,df) --print(netD_8:updateGradInput(i8,df_d8):size()) --image.save('test.png',netD_8:forward(i8)[1]) --image.save('testG.png',G_output[1]) return errD, grad -- 1*3*256*256 end local function test(x) --netD_8:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) -- gradParametersD8:zero(); ----------------------------start foward 1-7 ---------------------------------------------------- local Output = netFV:forward(x) errD = criterion:forward(Output, FeatureGroundtruth) local df = criterion:backward(Output, FeatureGroundtruth) local grad = netFV:updateGradInput(x,df) --print(netD_8:updateGradInput(i8,df_d8):size()) --image.save('test.png',netD_8:forward(i8)[1]) --image.save('testG.png',G_output[1]) return errD, grad:mul(opt.content_weight) end -- ----------------------------------------------- train------------------------------------------- local best_err = nil paths.mkdir(opt.checkpoints_dir) paths.mkdir(opt.checkpoints_dir .. '/' .. opt.name ..'_'..opt.end_layer) image.save(paths.concat(opt.checkpoints_dir, opt.name..'_'..opt.end_layer , '0_train_res.png'), util.deprocess(img[1]:float())) -- save opt file = torch.DiskFile(paths.concat(opt.checkpoints_dir, opt.name..'_'..opt.end_layer, 'opt.txt'), 'w') file:writeObject(opt) file:close() -- parse diplay_plot string into table opt.display_plot = string.split(string.gsub(opt.display_plot, "%s+", ""), ",") for k, v in ipairs(opt.display_plot) do if not util.containsValue({"errG", "errD", "errL1"}, v) then error(string.format('bad display_plot value "%s"', v)) end end -- display plot config local plot_config = { title = "Loss over time", labels = {"epoch", unpack(opt.display_plot)}, ylabel = "loss", } -- display plot vars local plot_data = {} local plot_win local counter = 0 local destination_position local psnr local psnr_max=0 local crit = nn.MSECriterion() for epoch = 1, opt.niter do epoch_tm:reset() for i = 1, math.min(data:size(), opt.ntrain), opt.batchSize do tm:reset() optim.adam(feval, img, optimStateD) --test(img) -- display --print((a:float()-b:float()):sum()..'**************************************') counter = counter + 1 if counter % opt.display_freq == 0 and opt.display then disp.image(util.deprocess_batch(util.scaleBatch(img:float(),256,256)), {win=opt.display_id, title=opt.name .. ' input'}) end -- write display visualization to disk -- runs on the first batchSize images in the opt.phase set if counter % opt.save_display_freq == 0 and opt.display then local image_out = util.deprocess(img[1]:float()) --print(psnr) image.save(paths.concat(opt.checkpoints_dir, opt.name..'_'..opt.end_layer , counter .. '_train_res.png'), image_out) imageA = image.load(paths.concat(opt.checkpoints_dir, opt.name..'_'..opt.end_layer , counter .. '_train_res.png')) mse = crit:forward(imageA:float(), imageB:float())--计算PSNR指标用 psnr = 10*math.log10(1/mse) if psnr > psnr_max and counter > 500 then psnr_max = psnr destination_position = counter end end -- logging and display plot if counter % opt.print_freq == 0 then local loss = {errD=errD and errD or -1} local curItInBatch = ((i-1) / opt.batchSize) local totalItInBatch = math.floor(math.min(data:size(), opt.ntrain) / opt.batchSize) print(('Epoch: [%d][%8d / %8d]\t Time: %.3f DataTime: %.3f ' .. ' Err_D: %.4f '):format( epoch, curItInBatch, totalItInBatch, tm:time().real / opt.batchSize, data_tm:time().real / opt.batchSize, errD)) print(psnr) local plot_vals = { epoch + curItInBatch / totalItInBatch } for k, v in ipairs(opt.display_plot) do if loss[v] ~= nil then plot_vals[#plot_vals + 1] = loss[v] end end -- update display plot if opt.display then table.insert(plot_data, plot_vals) plot_config.win = plot_win plot_win = disp.plot(plot_data, plot_config) end end end -- print(('End of epoch %d / %d \t Time Taken: %.3f'):format( -- epoch, opt.niter, epoch_tm:time().real)) end print("psnr:", psnr_max, "destination_position:",destination_position)
local TOCNAME, _ = ... local BOM = BuffomatAddon ---@type BuffomatAddon ---@class BomOptionsPopupModule ---@field behaviourSettings table<number, table> A list of {Key name, Default} for 'Profile' settings local optionsPopupModule = BuffomatModule.DeclareModule("OptionsPopup") ---@type BomOptionsPopupModule local constModule = BuffomatModule.Import("Const") ---@type BomConstModule optionsPopupModule.behaviourSettings = { { "AutoOpen", true }, { "ScanInRestArea", false }, { "ScanInStealth", false }, { "ScanWhileMounted", true }, { "InWorld", true }, { "InPVP", true }, { "InInstance", true }, { "PreventPVPTag", true }, { "DeathBlock", true }, { "NoGroupBuff", false }, { "SameZone", false }, { "ResGhost", false }, { "ReplaceSingle", true }, { "ArgentumDawn", false }, { "Carrot", false }, { "MainHand", false }, { "SecondaryHand", false }, { "UseRank", true }, { "AutoCrusaderAura", true }, { "AutoDismount", true }, { "AutoDismountFlying", false }, { "AutoStand", true }, { "AutoDisTravel", true }, { "BuffTarget", false }, { "OpenLootable", true }, { "SelfFirst", false }, { "DontUseConsumables", false }, { "SlowerHardware", false }, { "HideSomeoneIsDrinking", false }, } local _t = BuffomatModule.Import("Languages") ---@type BomLanguagesModule local L = setmetatable( {}, { __index = function(_t, k) if BOM.L and BOM.L[k] then return BOM.L[k] else return "[" .. k .. "]" end end }) ---Makes a tuple to pass to the menubuilder to display a settings checkbox in popup menu ---@param db table - BomSharedState reference to read settings from it ---@param var string Variable name from optionsPopupModule.BehaviourSettings function optionsPopupModule:MakeSettingsRow(db, var) return L["options.short." .. var], false, db, var end local function bomOpenOptions() LibStub("AceConfigDialog-3.0"):Open(constModule.SHORT_TITLE) end ---Populate the [⚙] popup menu function optionsPopupModule:Setup(control, minimap) local name = (control:GetName() or "nil") .. (minimap and "Minimap" or "Normal") if not BOM.PopupDynamic:Wipe(name) then return end if minimap then BOM.PopupDynamic:AddItem(L.BtnOpen, false, BOM.ShowWindow) BOM.PopupDynamic:AddItem() BOM.PopupDynamic:AddItem(_t("options.short.ShowMinimapButton"), false, BOM.SharedState.Minimap, "visible") BOM.PopupDynamic:AddItem(_t("options.short.LockMinimapButton"), false, BOM.SharedState.Minimap, "lock") BOM.PopupDynamic:AddItem(_t("options.short.LockMinimapButtonDistance"), false, BOM.SharedState.Minimap, "lockDistance") BOM.PopupDynamic:AddItem() end -- -------------------------------------------- -- Use Profiles checkbox and submenu -- -------------------------------------------- BOM.PopupDynamic:AddItem(L["options.short.UseProfiles"], false, BOM.CharacterState, "UseProfiles") if BOM.CharacterState.UseProfiles then BOM.PopupDynamic:SubMenu(L["HeaderProfiles"], "subProfiles") BOM.PopupDynamic:AddItem(L["profile_auto"], false, BOM.ChooseProfile, "auto") for _i, profile in pairs(BOM.ALL_PROFILES) do BOM.PopupDynamic:AddItem(L["profile_" .. profile], false, BOM.ChooseProfile, profile) end BOM.PopupDynamic:SubMenu() end BOM.PopupDynamic:AddItem() -- -------------------------------------------- -- Selected spells check on/off -- -------------------------------------------- for i, spell in ipairs(BOM.SelectedSpells) do if not spell.isConsumable then BOM.PopupDynamic:AddItem(spell.singleLink or spell.single, "keep", BOM.GetProfileSpell(spell.ConfigID), "Enable") end end local inBuffGroup -- unused? nil? if inBuffGroup then BOM.PopupDynamic:SubMenu() end BOM.PopupDynamic:AddItem() BOM.PopupDynamic:SubMenu(L["popup.QuickSettings"], "subSettings") for i, set in ipairs(self.behaviourSettings) do BOM.PopupDynamic:AddItem(self:MakeSettingsRow(BOM.SharedState, set[1])) end -- ------------------------------------------- -- Watch in Raid group -> 1 2 3 4 5 6 7 8 -- ------------------------------------------- BOM.PopupDynamic:AddItem() BOM.PopupDynamic:SubMenu(L["HeaderWatchGroup"], "subGroup") for i = 1, 8 do BOM.PopupDynamic:AddItem(i, "keep", BomCharacterState.WatchGroup, i) end BOM.PopupDynamic:SubMenu() BOM.PopupDynamic:AddItem(L.BtnSettings, false, bomOpenOptions, 1) --BOM.PopupDynamic:AddItem(L["BtnCancel"], false) BOM.PopupDynamic:Show(control or "cursor", 0, 0) end
-- removing the directory banner vim.g.netrw_banner = 0 -- set width of the directory explorer to 25% of the page vim.g.netrw_winsize = 25 -- set tree view type vim.g.netrw_liststyle = 3 -- hide gitignore -- g.netrw_list_hide=netrw_gitignore#Hide() -- g.netrw_list_hide.=',\(^\|\s\s\)\zs\.\S\+'
D3View=Core.class(Sprite) function D3View:init(sw,sh,fov,near,far) self.view=Viewport.new() self.projection=Matrix.new() self.fov=fov or 45 self.near=near or 0.1 self.far=far or 1000 self:setSize(sw or 1,sh or 1) self.scene=Sprite.new() self.view:setContent(self.scene) self:addChild(self.view) end function D3View:setSize(w,h) self.sw=w self.sh=h self.projection:perspectiveProjection(self.fov,-self.sw/self.sh,self.near,self.far) self.view:setProjection(self.projection) self.view:setPosition(self.sw/2,self.sh/2) self.view:setScale(self.sw/2,self.sh/2,1) end function D3View:lookAt(eyex,eyey,eyez,targetx,targety,targetz,upx,upy,upz) self.view:lookAt(eyex,eyey,eyez,targetx,targety,targetz,upx or 0,upy or 1,upz or 0) Lighting.setCamera(eyex,eyey,eyez) end function D3View:lookAngles(eyex,eyey,eyez,pitch,yaw,roll) self.view:lookAngles(eyex,eyey,eyez,pitch,yaw,roll) Lighting.setCamera(eyex,eyey,eyez) end function D3View:getScene() return self.scene end D3=D3 or {} D3.View=D3View
local nk = require("nakama") local function echo(context, payload) nk.logger_info(string.format("Payload: %q", payload)) local content = { data = payload, } nk.notification_send(context.user_id, "Echo", content, 1, context.user_id, true) end nk.register_rpc(echo, "echo")
--[[ Description: Scythe library v3 (developer tools) Version: 3.0.0 Author: Lokasenna Links: Forum Thread https://forum.cockos.com/showthread.php?t=177772 Scythe Website http://jalovatt.github.io/scythe Donation: https://paypal.me/Lokasenna About: Examples and utilities for developing scripts with Scythe v3. This package requires "Scythe library v3" to be installed as well. Changelog: Minor updates to documentation and boilerplate Metapackage: true Provides: [main] /Development/Scythe library v3/development/examples/Scythe_Example - Default parameters.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Scythe_Example - Default parameters.lua [main] /Development/Scythe library v3/development/examples/Scythe_Example - General demonstration.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Scythe_Example - General demonstration.lua [main] /Development/Scythe library v3/development/examples/Scythe_Example - Menubar, Listbox, and TextEditor.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Scythe_Example - Menubar, Listbox, and TextEditor.lua [main] /Development/Scythe library v3/development/examples/Scythe_Example - Typical script options.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Scythe_Example - Typical script options.lua [main] /Development/Scythe library v3/development/examples/Scythe_Example - Working with Images.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Scythe_Example - Working with Images.lua [main] /Development/Scythe library v3/development/testing/Scythe_Test Runner.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/Scythe_Test Runner.lua [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_1.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_1.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_10.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_10.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_100.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_100.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_108.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_108.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_112.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_112.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_116.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_116.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_12.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_12.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_14.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_14.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_18.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_18.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_2.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_2.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_20.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_20.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_22.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_22.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_28.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_28.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_3.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_3.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_32.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_32.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_36.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_36.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_44.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_44.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_48.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_48.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_5.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_5.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_52.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_52.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_6.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_6.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_60.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_60.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_64.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_64.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_68.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_68.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_7.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_7.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_76.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_76.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_80.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_80.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_84.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_84.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_92.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_92.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/grid_96.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/grid_96.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/left_10.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/left_10.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/left_20.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/left_20.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/left_30.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/left_30.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/left_40.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/left_40.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/left_50.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/left_50.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/grid/left_60.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/grid/left_60.png [nomain] /Development/Scythe library v3/development/examples/Working with Images/guybrush small.png https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/examples/Working with Images/guybrush small.png [nomain] /Development/Scythe library v3/development/gui-testing/preventDefault1.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/gui-testing/preventDefault1.lua [nomain] /Development/Scythe library v3/development/gui-testing/preventDefault2.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/gui-testing/preventDefault2.lua [nomain] /Development/Scythe library v3/development/gui-testing/textbox-validation.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/gui-testing/textbox-validation.lua [nomain] /Development/Scythe library v3/development/gui-testing/user-event-hooks.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/gui-testing/user-event-hooks.lua [nomain] /Development/Scythe library v3/development/testing/lib/core.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/lib/core.lua [nomain] /Development/Scythe library v3/development/testing/tests/example.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/tests/example.lua [nomain] /Development/Scythe library v3/development/testing/tests/getContext.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/tests/getContext.lua [nomain] /Development/Scythe library v3/development/testing/tests/public/color.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/tests/public/color.lua [nomain] /Development/Scythe library v3/development/testing/tests/public/file.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/tests/public/file.lua [nomain] /Development/Scythe library v3/development/testing/tests/public/math.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/tests/public/math.lua [nomain] /Development/Scythe library v3/development/testing/tests/public/menu.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/tests/public/menu.lua [nomain] /Development/Scythe library v3/development/testing/tests/public/message.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/tests/public/message.lua [nomain] /Development/Scythe library v3/development/testing/tests/public/string.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/tests/public/string.lua [nomain] /Development/Scythe library v3/development/testing/tests/public/table.lua https://github.com/jalovatt/scythe/raw/11cee4e1cea8aefd2cde2bb322181e49075479f6/development/testing/tests/public/table.lua ]]--
utf8 = require"utf8" reflowprint = require"init" scalex,scaley = 1,1 alignment = "center" function badprint(progress,text,x,y,w,a,sx,sy) local t = text:sub(1, #text*progress) love.graphics.printf(t,x,y,w,a,0,sx,sy) end local letters_per_second = 25 function love.load() defaultFont = love.graphics.newFont() newFont = love.graphics.newFont(48) dt = 0 t = 1 text="The quick brown fox jumped over the lazy dog." end function love.update(dt) dt = math.min(t,dt + 1) end function love.draw() dt = dt + love.timer.getDelta() love.window.setTitle("ScaleX: "..scalex.." ScaleY: "..scaley.." Alignment: "..alignment.." Text: "..text) local rpx,rpy,rpw,rph = 32,32,love.graphics.getWidth()/2-64,9000 local bpx,bpy,bpw,bph = love.graphics.getWidth()/2+32,32,love.graphics.getWidth()/2-64,9000 love.graphics.print("ReflowPrint",rpx,rpy-16) love.graphics.print("BadPrint",bpx,bpy-16) love.graphics.setFont(newFont) love.graphics.rectangle("line",rpx,rpy,rpw,rph) reflowprint(dt/t,text,rpx,rpy,rpw,alignment,scalex,scaley) love.graphics.rectangle("line",bpx,bpy,bpw,bph) badprint(dt/t,text,bpx,bpy,bpw,alignment,scalex,scaley) love.graphics.setFont(defaultFont) love.graphics.line(0,0,love.graphics.getWidth()*dt/t,0) end function love.textinput(t) text = text .. t end function love.keypressed(key) dt = 0 if key == "backspace" then local byteoffset = utf8.offset(text, -1) if byteoffset then text = string.sub(text, 1, byteoffset - 1) end end if key == "left" then scalex = scalex/2 elseif key == "right" then scalex = scalex*2 elseif key == "up" then scaley = scaley/2 elseif key == "down" then scaley = scaley*2 elseif key == "space" then if alignment == "left" then alignment = "center" elseif alignment == "center" then alignment = "right" else--if alignment == "right" then alignment = "left" end end end
#include "assets/scripts/util.lua" local data local options local draws = 0 local fallbackOptions local window function InitWindow(dataReference, optionsReference) data = dataReference fallbackOptions = optionsReference[1] options = optionsReference[2] window = { enabled = false, interact = false, navbar = true, page = 1, pages = { -- INFO COUNTER { name = "counter", title = "INFO COUNTER", draw = function(x0, y0, x1, y1) -- Account for navbar size and draw background UiAlign("left") UiTranslate(x0, 0) UiColor(0, 0, 0, .8) UiRect(x1, y1) -- Draw counter full-size preview background UiPush() UiTranslate(1110, 0) local backColor = visual.hslrgb(options.counter.backColor[1][1], options.counter.backColor[1][2], options.counter.backColor[1][3]) UiColor(backColor[1], backColor[2], backColor[3], options.counter.backColor[2]) UiRect(600, y1) local textColor = visual.hslrgb(options.counter.textColor[1][1], options.counter.textColor[1][2], options.counter.textColor[1][3]) UiColor(textColor[1], textColor[2], textColor[3], options.counter.textColor[2]) local counts = {{options.counter.frameCount, CalculateFrameAccuracy(data[4], options), "FPS"}, {options.counter.bodyCount, GetBodyCount(VecSub(GetPlayerPos(), Vec(100, 100, 100)), VecAdd(GetPlayerPos(), Vec(100, 100, 100))), "BOD"}, {options.counter.shapeCount, GetShapeCount(VecSub(GetPlayerPos(), Vec(100, 100, 100)), VecAdd(GetPlayerPos(), Vec(100, 100, 100))), "SHA"}, {options.counter.fireCount, GetFireCount(), "FIR"}} UiTranslate(25, 75) for countIteration = 1, 4 do if counts[countIteration][1] then UiPush() UiAlign("left middle") UiFont("bold.ttf", 100) UiText(counts[countIteration][2]) UiAlign("right") UiTranslate(520, 0) UiFont("bold.ttf", 60) UiText(counts[countIteration][3]) UiPop() UiTranslate(0, 100) end end UiPop() -- Draw settings elements UiWindow(1320 - x0, y1, false) UiPush() UiTranslate(30, 30) UiFont("bold.ttf", 18) -- Left side elements UiPush() -- Enable and reset buttons UiPush() UiColor(1, 1, 1, 1) UiAlign("center middle") if UiTextedButton(options.counter.enabled and "ENABLED" or "DISABLED", "center middle", 240, 60, options.counter.enabled and {0, 1, 0, .5} or {1, 0, 0, .5}, {1, 1, 1, 1}) then options.counter.enabled = not options.counter.enabled end UiTranslate(240, 0) if UiTextedButton("RESET", "center middle", 240, 60, {1, 0, 0, .5}, {1, 1, 1, 1}) then options.counter = Clone(fallbackOptions.counter) end UiPop() UiTranslate(0, 90) -- Alignment window title UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("POSITION") UiPop() UiTranslate(0, 30) -- Alignment buttons UiPush() local buttonPositions = {{"TL", {0, 0}}, {"TM", {x1 / 2, 0}}, {"TR", {x1, 0}}, {"ML", {0, y1 / 2}}, {"MR", {x1, y1 / 2}}, {"BL", {0, y1}}, {"BM", {x1 / 2, y1}}, {"BR", {x1, y1}}} UiFont("bold.ttf", 16) for buttonIteration = 1, #buttonPositions do if UiTextedButton(buttonPositions[buttonIteration][1], "center middle", 60, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.counter.position = buttonPositions[buttonIteration][2] end UiTranslate(60, 0) end UiPop() UiTranslate(0, 90) -- Background color picker UiPush() UiPush() UiColor(0, 0, 0, .7) UiRect(240, 30) UiAlign("center middle") UiTranslate(120, 15) UiColor(1, 1, 1, 1) UiText("BACKGROUND COLOR") UiPop() UiTranslate(0, 30) options.counter.backColor[1] = UiColorPicker(options.counter.backColor[1], .5) UiPop() UiTranslate(240, 0) -- Text color picker UiPush() UiPush() UiColor(0, 0, 0, .7) UiRect(240, 30) UiAlign("center middle") UiTranslate(120, 15) UiColor(1, 1, 1, 1) UiText("TEXT COLOR") UiPop() UiTranslate(0, 30) options.counter.textColor[1] = UiColorPicker(options.counter.textColor[1], .5) UiPop() UiPop() -- Right side elements UiPush() UiTranslate(540, 0) -- FPS update delay title UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("FPS UPDATE DELAY") UiPop() UiTranslate(0, 30) -- FPS update delay slider UiPush() options.counter.delay = Round(UiColoredSlider(options.counter.delay, 0, 60, 480, 60, {0, 0, 0, .5}, {0, 0, 0, .2})) UiPop() UiTranslate(0, 90) -- Extra modification buttons if UiTextedButton(options.counter.backColor[2] == 0.5 and "BACKGROUND SHOWN" or "BACKGROUND HIDDEN", "center middle", 480, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.counter.backColor[2] = options.counter.backColor[2] == .5 and 0 or 0.5 end UiTranslate(0, 90) if UiTextedButton(options.counter.frameCount and "FRAME COUNT SHOWN" or "FRAME COUNT HIDDEN", "center middle", 480, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.counter.frameCount = not options.counter.frameCount end UiTranslate(0, 90) if UiTextedButton(options.counter.bodyCount and "BODY COUNT SHOWN" or "BODY COUNT HIDDEN", "center middle", 480, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.counter.bodyCount = not options.counter.bodyCount end UiTranslate(0, 90) if UiTextedButton(options.counter.shapeCount and "SHAPE COUNT SHOWN" or "SHAPE COUNT", "center middle", 480, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.counter.shapeCount = not options.counter.shapeCount end UiTranslate(0, 90) if UiTextedButton(options.counter.fireCount and "FIRE COUNT SHOWN" or "SHOW FIRE COUNT", "center middle", 480, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.counter.fireCount = not options.counter.fireCount end UiTranslate(0, 90) if UiTextedButton(options.counter.accuracy == 0 and "LOW ACCURACY" or "HIGH ACCURACY", "center middle", 480, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.counter.accuracy = options.counter.accuracy == 2 and 0 or 2 end UiPop() UiPop() end }, -- DEBRIS CLEANER { name = "cleaner", title = "DEBRIS CLEANER", draw = function(x0, y0, x1, y1) -- Account for navbar size and draw background UiAlign("left") UiTranslate(x0, 0) UiColor(0, 0, 0, .8) UiRect(x1, y1) -- Draw module description UiPush() UiTranslate(1110, 0) UiColor(0, 0, 0, .5) UiRect(600, y1) UiTranslate(300, 30) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("DESCRIPTION") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The debris cleaner works by removing small voxels that cause lots of physics calculations and are barely visible, this makes destruction of large objects much faster.") UiTranslate(0, 120) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("USAGE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The debris size multiplier defines how large objects you want to remove, the larger the objects the faster destructions will be. The optional buttons if set to ignore visible/active will make debris only be removed while seen/moved.") UiTranslate(0, 150) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("PERFORMANCE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("HIGH performance module with MEDIUM artifacts, good for LOW CPU usage. If used correctly a very powerful module to make sure you can get maximal framerates during destruction.") UiTranslate(0, 120) UiPop() -- Draw setting elements UiWindow(1320 - x0, y1, false) UiPush() UiTranslate(30, 30) UiFont("bold.ttf", 18) -- Left side elements UiPush() UiPush() -- Enable and reset buttons UiPush() UiColor(1, 1, 1, 1) UiAlign("center middle") if UiTextedButton(options.cleaner.enabled and "ENABLED" or "DISABLED", "center middle", 240, 60, options.cleaner.enabled and {0, 1, 0, .5} or {1, 0, 0, .5}, {1, 1, 1, 1}) then options.cleaner.enabled = not options.cleaner.enabled end UiTranslate(240, 0) if UiTextedButton("RESET", "center middle", 240, 60, {1, 0, 0, .5}, {1, 1, 1, 1}) then options.cleaner = Clone(fallbackOptions.cleaner) end UiPop() UiPop() UiTranslate(0, 90) -- Debris size title UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("DEBRIS SIZE (HIGHER = FASTER)") UiPop() UiTranslate(0, 30) -- Debris size slider UiPush() options.cleaner.multiplier = Round(UiColoredSlider(options.cleaner.multiplier, 0, 1, 480, 60, {0, 0, 0, .5}, {0, 0, 0, .2}), 2, .005) UiPop() UiTranslate(0, 90) UiPop() -- Right side elements UiPush() UiTranslate(540, 0) -- Extra modification buttons if UiTextedButton(options.cleaner.removeVisibleDebris and "REMOVING VISIBLE" or "IGNORING VISIBLE", "center middle", 480, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.cleaner.removeVisibleDebris = not options.cleaner.removeVisibleDebris end UiTranslate(0, 90) if UiTextedButton(options.cleaner.removeActiveDebris and "REMOVING ACTIVE" or "IGNORING ACTIVE", "center middle", 480, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.cleaner.removeActiveDebris = not options.cleaner.removeActiveDebris end UiPop() UiPop() end }, -- OBJECT STABILIZER { name = "stabilizer", title = "OBJECT STABILIZER", draw = function(x0, y0, x1, y1) -- Account for navbar size and draw background UiAlign("left") UiTranslate(x0, 0) UiColor(0, 0, 0, .8) UiRect(x1, y1) -- Draw module description UiPush() UiTranslate(1110, 0) UiColor(0, 0, 0, .5) UiRect(600, y1) UiTranslate(300, 30) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("DESCRIPTION") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The object stabilizer works by making all objects far away from the player static, this makes destruction of large objects much faster.") UiTranslate(0, 120) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("USAGE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The object size multiplier defines how large objects you want to freeze, the larger the objects the faster destructions will be. The optional buttons if set to ignore visible make objects only be frozen while not seen.") UiTranslate(0, 150) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("PERFORMANCE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("MEDIUM performance module with HIGH artifacts, good for LOW CPU usage. A game changer in specific cases, overall average.") UiTranslate(0, 120) UiPop() -- Draw setting elements UiWindow(1320 - x0, y1, false) UiPush() UiTranslate(30, 30) UiFont("bold.ttf", 18) -- Left side elements UiPush() UiPush() -- Enable and reset buttons UiPush() UiColor(1, 1, 1, 1) UiAlign("center middle") if UiTextedButton(options.stabilizer.enabled and "ENABLED" or "DISABLED", "center middle", 240, 60, options.stabilizer.enabled and {0, 1, 0, .5} or {1, 0, 0, .5}, {1, 1, 1, 1}) then options.stabilizer.enabled = not options.stabilizer.enabled end UiTranslate(240, 0) if UiTextedButton("RESET", "center middle", 240, 60, {1, 0, 0, .5}, {1, 1, 1, 1}) then options.stabilizer = Clone(fallbackOptions.stabilizer) end UiPop() UiPop() UiTranslate(0, 90) -- Size slider UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("SIZE MULTIPLIER (HIGHER = FASTER)") UiPop() UiTranslate(0, 30) UiPush() options.stabilizer.multiplier = Round(UiColoredSlider(options.stabilizer.multiplier, 0, 1, 480, 60, {0, 0, 0, .5}, {0, 0, 0, .2}), 2, .005) UiPop() UiTranslate(0, 90) UiPop() -- Right side elements UiPush() UiTranslate(540, 0) -- Extra modification buttons if UiTextedButton(options.stabilizer.stabilizeVisibleObjects and "STABILIZING VISIBLE" or "IGNORING VISIBLE", "center middle", 480, 60, {0, 0, 0, .5}, {1, 1, 1, 1}) then options.stabilizer.stabilizeVisibleObjects = not options.stabilizer.stabilizeVisibleObjects end UiPop() UiPop() end }, -- FIRE { name = "fire", title = "FIRE CONTROLLER", draw = function(x0, y0, x1, y1) -- Account for navbar size and draw background UiAlign("left") UiTranslate(x0, 0) UiColor(0, 0, 0, .8) UiRect(x1, y1) -- Draw module description UiPush() UiTranslate(1110, 0) UiColor(0, 0, 0, .5) UiRect(600, y1) UiTranslate(300, 30) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("DESCRIPTION") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The fire controller works by limiting fire to a specific amount so that you can be destructive without massive frame drops.") UiTranslate(0, 120) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("USAGE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The fire amount defines how much fire that should be allowed, not fully accurate but works overall. The spread will decide how fast the fire can spread, keep this to a minimum in most cases.") UiTranslate(0, 150) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("PERFORMANCE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("HIGH performance module with LOW artifacts, good for LOW CPU and gpu usage. Really useful in most scenarios where fires are in the way of higher framerates or the other way around.") UiTranslate(0, 120) UiPop() -- Draw setting elements UiWindow(1320 - x0, y1, false) UiPush() UiTranslate(30, 30) UiFont("bold.ttf", 18) -- Left side elements UiPush() UiPush() -- Enable and reset buttons UiPush() UiColor(1, 1, 1, 1) UiAlign("center middle") if UiTextedButton(options.fire.enabled and "ENABLED" or "DISABLED", "center middle", 240, 60, options.fire.enabled and {0, 1, 0, .5} or {1, 0, 0, .5}, {1, 1, 1, 1}) then options.fire.enabled = not options.fire.enabled end UiTranslate(240, 0) if UiTextedButton("RESET", "center middle", 240, 60, {1, 0, 0, .5}, {1, 1, 1, 1}) then options.fire = Clone(fallbackOptions.fire) end UiPop() UiPop() UiTranslate(0, 90) -- Amount title UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("AMOUNT (LOWER = FASTER)") UiPop() UiTranslate(0, 30) -- Amount slider UiPush() options.fire.amount = Round(UiColoredSlider(options.fire.amount, 0, 10000, 480, 60, {0, 0, 0, .5}, {0, 0, 0, .2}), -2, 50) UiPop() UiTranslate(0, 90) UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("SPREAD (LOWER = FASTER)") UiPop() UiTranslate(0, 30) UiPush() options.fire.spread = Round(UiColoredSlider(options.fire.spread, 0, 100, 480, 60, {0, 0, 0, .5}, {0, 0, 0, .2}), 0, 0.5) UiPop() UiTranslate(0, 90) UiPop() -- Right side elements UiPush() UiTranslate(540, 0) UiPop() UiPop() end }, -- SUN { name = "sun", title = "SUN CONTROLLER", draw = function(x0, y0, x1, y1) -- Account for navbar size and draw background UiAlign("left") UiTranslate(x0, 0) UiColor(0, 0, 0, .8) UiRect(x1, y1) -- Draw module description UiPush() UiTranslate(1110, 0) UiColor(0, 0, 0, .5) UiRect(600, y1) UiTranslate(300, 30) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("DESCRIPTION") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The sun controller works by limiting sunrays in the scene, this makes general gameplay more enjoyable but sadly less visibly pleasing.") UiTranslate(0, 120) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("USAGE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The brightness will limit the amount of sun in the scene so that rays fade faster, the shadow length works the same but only for shadows.") UiTranslate(0, 150) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("PERFORMANCE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("MEDIUM performance module with HIGH artifacts, good for LOW GPU usage. Will make the scene look very dull for a small increase in FPS, great for larger maps.") UiTranslate(0, 120) UiPop() -- Draw setting elements UiWindow(1320 - x0, y1, false) UiPush() UiTranslate(30, 30) UiFont("bold.ttf", 18) -- Left side elements UiPush() UiPush() -- Enable and reset buttons UiPush() UiColor(1, 1, 1, 1) UiAlign("center middle") if UiTextedButton(options.sun.enabled and "ENABLED" or "DISABLED", "center middle", 240, 60, options.sun.enabled and {0, 1, 0, .5} or {1, 0, 0, .5}, {1, 1, 1, 1}) then options.sun.enabled = not options.sun.enabled end UiTranslate(240, 0) if UiTextedButton("RESET", "center middle", 240, 60, {1, 0, 0, .5}, {1, 1, 1, 1}) then options.sun = Clone(fallbackOptions.sun) end UiPop() UiPop() UiTranslate(0, 90) -- Brightness slider UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("BRIGHTNESS (LOWER = FASTER)") UiPop() UiTranslate(0, 30) UiPush() options.sun.brightness = Round(UiColoredSlider(options.sun.brightness, 0, 1, 480, 60, {0, 0, 0, .5}, {0, 0, 0, .2}), 2, .005) UiPop() UiTranslate(0, 90) -- Shadow length slider UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("SHADOW LENGTH (LOWER = FASTER)") UiPop() UiTranslate(0, 30) UiPush() options.sun.length = Round(UiColoredSlider(options.sun.length, 0, 256, 480, 60, {0, 0, 0, .5}, {0, 0, 0, .2}), 0, 0) UiPop() UiPop() -- Right side elements UiPush() UiTranslate(540, 0) UiPop() UiPop() end }, -- LIGHT { name = "light", title = "LIGHT CONTROLLER", draw = function(x0, y0, x1, y1) -- Account for navbar size and draw background UiAlign("left") UiTranslate(x0, 0) UiColor(0, 0, 0, .8) UiRect(x1, y1) -- Draw module description UiPush() UiTranslate(1110, 0) UiColor(0, 0, 0, .5) UiRect(600, y1) UiTranslate(300, 30) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("DESCRIPTION") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The light controller works by having light sources dimmed (except the sun, see sun controller module).") UiTranslate(0, 120) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("USAGE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The light intensity will change the lights intensity so that less or more rays are bounced in the scene.") UiTranslate(0, 150) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("PERFORMANCE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("Low performance module with LOW artifacts, good for LOW CPU and GPU usage. Not very powerful and should not be enabled unless you want to squeeze out every frame possible.") UiTranslate(0, 120) UiPop() -- Draw setting elements UiWindow(1320 - x0, y1, false) UiPush() UiTranslate(30, 30) UiFont("bold.ttf", 18) -- Left side elements UiPush() -- Enable and reset buttons UiPush() UiColor(1, 1, 1, 1) UiAlign("center middle") if UiTextedButton(options.light.enabled and "ENABLED" or "DISABLED", "center middle", 240, 60, options.light.enabled and {0, 1, 0, .5} or {1, 0, 0, .5}, {1, 1, 1, 1}) then options.light.enabled = not options.light.enabled end UiTranslate(240, 0) if UiTextedButton("RESET", "center middle", 240, 60, {1, 0, 0, .5}, {1, 1, 1, 1}) then options.light = Clone(fallbackOptions.light) end UiPop() UiTranslate(0, 90) -- Intensity title UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("LIGHT INTENSITY (LOWER = FASTER)") UiPop() UiTranslate(0, 30) -- Intensity slider UiPush() options.light.intensity = Round(UiColoredSlider(options.light.intensity, 0, 10, 480, 60, {0, 0, 0, .5}, {0, 0, 0, .2})) UiPop() UiTranslate(0, 90) UiPop() -- Right side elements UiPush() UiTranslate(540, 0) UiPop() UiPop() end }, -- FOG { name = "fog", title = "FOG CONTROLLER", draw = function(x0, y0, x1, y1) -- Account for navbar size and draw background UiAlign("left") UiTranslate(x0, 0) UiColor(0, 0, 0, .8) UiRect(x1, y1) -- Draw module description UiPush() UiTranslate(1110, 0) UiColor(0, 0, 0, .5) UiRect(600, y1) UiTranslate(300, 30) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("DESCRIPTION") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The fog controller works by removing fog in the distance as it does not seem to have an impact on the framerate.") UiTranslate(0, 120) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("USAGE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("The fog amount will change how thick the fog is (if fog is used in the scene).") UiTranslate(0, 150) UiFont("bold.ttf", 36) UiColor(1, 1, 1, 1) UiAlign("center top") UiText("PERFORMANCE") UiTranslate(0, 45) UiFont("regular.ttf", 18) UiWordWrap(300) UiText("Very LOW performance module with very LOW artifacts, not very useful but added to remove extra effects.") UiTranslate(0, 120) UiPop() -- Draw setting elements UiWindow(1320 - x0, y1, false) UiPush() UiTranslate(30, 30) UiFont("bold.ttf", 18) -- Left side elements UiPush() UiPush() -- Enable and reset buttons UiPush() UiColor(1, 1, 1, 1) UiAlign("center middle") if UiTextedButton(options.fog.enabled and "ENABLED" or "DISABLED", "center middle", 240, 60, options.fog.enabled and {0, 1, 0, .5} or {1, 0, 0, .5}, {1, 1, 1, 1}) then options.fog.enabled = not options.fog.enabled end UiTranslate(240, 0) if UiTextedButton("RESET", "center middle", 240, 60, {1, 0, 0, .5}, {1, 1, 1, 1}) then options.fog = Clone(fallbackOptions.fog) end UiPop() UiPop() UiTranslate(0, 90) -- Amount title UiPush() UiColor(0, 0, 0, .7) UiRect(480, 30) UiAlign("center middle") UiTranslate(240, 15) UiColor(1, 1, 1, 1) UiText("AMOUNT (LOWER = FASTER)") UiPop() UiTranslate(0, 30) -- Amount slider UiPush() options.fog.amount = Round(UiColoredSlider(options.fog.amount, 0, 1, 480, 60, {0, 0, 0, .5}, {0, 0, 0, .2}), 2, .005) UiPop() UiTranslate(0, 90) UiPop() -- Right side elements UiPush() UiTranslate(540, 0) UiPop() UiPop() end } } } end function TickWindow(dt) -- If the ALT button was pressed, toggle the performance window and save the options. -- This is used to make sure the settings were fully saved as no changes can be made without the window shown. if (InputDown("alt") and InputPressed(GetString("savegame.mod.keybind"))) or PauseMenuButton("Performance Mod") then window.enabled = not window.enabled window.interact = not window.interact SetString("savegame.mod.options", util.serialize(options)) end end function DrawWindow() local x0, y0, x1, y1 = UiSafeMargins() -- Draw the performance window if window.enabled then if window.interact then UiMakeInteractive() if InputPressed("lmb") then SetString("savegame.mod.options", util.serialize(options)) end end UiPush() SetBool("hud.aimdot", false) UiWindow(x1 - x0, y1 - y0, true) UiAlign("center middle") UiColor(1, 1, 1, 1) -- The left side navigation bar. if window.navbar then UiPush() UiPush() UiAlign("left") UiColor(0, 0, 0, .9) UiRect(240, y1) x0 = x0 + 240 UiPop() for pageIteration = 1, #window.pages do local pageName = window.pages[pageIteration].name local pageOptions = options[pageName] local textColor = pageOptions.enabled and {.9, 1, .9} or {1, .9, .9} if HasVersion(pageOptions.version) then UiFont("bold.ttf", 18) if UiTextedButton(window.pages[pageIteration].title, "center middle", 240, 60, {0, 0, 0, 0}, pageOptions.enabled and {0, 1, 0} or {1, 0, 0}) then window.page = pageIteration end if window.page == pageIteration then UiPush() UiAlign("left") UiColor(1, 1, 1, .1) UiRect(240, 60) UiPop() end UiTranslate(0, 60) end end UiPop() end UiPush() window.pages[window.page].draw(x0, y0, x1, y1) UiPop() UiPop() else -- Draw the information counter if options.counter.enabled then UiInformationCounter(0, 0, 1, data, options) end end draws = draws + 1 end
vim.g.mapleader = " " local utils = require('utils') local nnoremap = utils.nnoremap local vnoremap = utils.vnoremap nnoremap('<TAB>', ':bnext<CR>') nnoremap('<S-TAB>', ':bprevious<CR>') nnoremap('<C-h>', '<C-w>h') nnoremap('<C-j>', '<C-w>j') nnoremap('<C-k>', '<C-w>k') nnoremap('<C-l>', '<C-w>l') vnoremap('<', '<gv') vnoremap('>', '>gv') nnoremap('<C-s>', ':w<CR>') nnoremap('<C-Q>', ':wq!<CR>') nnoremap('C-c', ':bdelete<CR>')
local Event = require "xgame.event.Event" local TouchEvent = require "xgame.event.TouchEvent" local FLMovieClip = require "xgame.swf.FLMovieClip" local swf = require "xgame.swf.swf" local FLRadioButton = swf.class("FLRadioButton", FLMovieClip) function FLRadioButton:ctor() self.touchable = true self.touchChildren = false self:addListener(TouchEvent.CLICK, self._onclick, self) self.selected = false end function FLRadioButton:_onclick() self.selected = not self.selected self:dispatch(Event.CHANGE) end function FLRadioButton.Get:selected() return self._selected end function FLRadioButton.Set:selected(value) self._selected = value self:gotoAndStop(value and "true" or "false") end return FLRadioButton
format_version = "1.0" texts = { ["propertyname_LearningRate"] = "Learning Rate", ["propertyname_Threshold"] = "Threshold", ["ui_type template Threshold"] = "^0 V", ["propertyname_HalfWave"] = "Half Wave", ["propertyname_FullWave"] = "Full Wave", ["propertyname_Squared"] = "Squared", ["propertyname_Rectification"] = "Rectification", ["propertyname_RectificationDisplay"] = "Rectification mode", ["on"] = "On", ["off"] = "Off", ["n/a"] = "N/A", ["halfwave"] = "Half Wave", ["fullwave"] = "Full Wave", ["squared"] = "Squared", ["audioInput"] = "Audio Input", ["envelopeOutput"] = "Audio envelope out", ["envOutput"] = "Envelope CV out", ["gateOutput"] = "Gate CV out", ["propertyname_GateDisplay"] = "Gate", ["short_learningRate"] = "lRate", ["shortest_learningRate"] = "LrnR", ["short_threshold"] = "Thresh", ["shortest_threshold"] = "Thr", }
local utils = require("flutter-tools.utils") local M = {} local fmt = string.format --- @param prefs table user preferences local function validate_prefs(prefs) vim.validate { outline = {prefs.outline, "table", true}, dev_log = {prefs.dev_log, "table", true}, closing_tags = {prefs.closing_tags, "table", true} } end ---Create a proportional split using a percentage specified as a float ---@param percentage number ---@param fallback number ---@return string local function get_split_cmd(percentage, fallback) return string.format("botright %dvnew", math.max(vim.o.columns * percentage, fallback)) end local defaults = { flutter_path = nil, flutter_lookup_cmd = utils.is_linux and "flutter sdk-path" or nil, widget_guides = { enabled = false, debug = false }, debugger = { enabled = false }, closing_tags = { highlight = "Comment", prefix = "// " }, outline = setmetatable( {}, { __index = function(_, k) return k == "open_cmd" and get_split_cmd(0.3, 40) or nil end } ), dev_log = setmetatable( {}, { __index = function(_, k) return k == "open_cmd" and get_split_cmd(0.4, 50) or nil end } ), experimental = { lsp_derive_paths = false } } local deprecations = { flutter_outline = { fallback = "widget_guides", message = "please use 'widget_guides' instead" } } local function handle_deprecation(key, value, config) local deprecation = deprecations[key] if not deprecation then return end vim.defer_fn( function() utils.echomsg(fmt("%s is deprecated: %s", key, deprecation.message), "WarningMsg") end, 1000 ) if deprecation.fallback then config[deprecation.fallback] = value end end local config = setmetatable({}, {__index = defaults}) function M.get() return config end function M.set(user_config) if not user_config or type(user_config) ~= "table" then return config end for key, value in pairs(user_config) do handle_deprecation(key, value, user_config) end validate_prefs(user_config) config = setmetatable(user_config, {__index = defaults}) return config end return M
--[[ DO NOT EDIT THIS FILE! This file is a critical module for this application and editing it could result in undesirable behavior, including but not limited to unintended changes to your file system. ]] function split(str, delim) local t = {} for substr in string.gmatch(str, "[^" .. delim .. "]+") do table.insert(t, substr) end return t end function read_config_file(file_contents) local obj = {}; for i, l in ipairs(split(file_contents, "\n")) do local key, value = string.match(l, "(%w+): ([%-.%w]+)"); if key and value then value = tonumber(value); obj[key] = value; end end return obj; end function serialize(t) local str = ""; for k,v in pairs(t) do str = str .. k .. ": " .. v; str = str .. "\n"; end return str; end function table_to_str(t) if t==nil or type(t) ~= "table" then return "{}" end local out = "" out = out .. "{" for k,v in pairs(t) do out = out .. "[" .. k .. "]=" if type(v) == "table" then out = out .. table_to_str(v) else out = out .. v end out = out .. "," end out = out .. "}" return out end
--[[ © 2020 TERRANOVA do not share, re-distribute or modify without permission of its author. --]] ITEM.name = "Cadburry Milk Chocolate"; ITEM.model = "models/cadbury1/cadbury1.mdl"; ITEM.width = 1; ITEM.height = 1; ITEM.description = "Classic Australian chocolate eaten by only the most god-like people."; ITEM.permit = "consumables"; ITEM.category = "Australian" ITEM.price = 20; ITEM.restoreHealth = 5; ITEM.flag = "z"
local Visualizer = {} Visualizer.__index = Visualizer function Visualizer.new() local self = setmetatable({}, Visualizer) self.overlayEntities = {} return self end function Visualizer:DrawOverlay(entity, inputOutput) inputOutput = inputOutput or "" local overlayEntity = Entity.new(game.surfaces[1].create_entity{ name = "TA-Arrow" .. self:GetDirectionStr(entity.direction) .. inputOutput, position = entity.position, force = game.forces.player }) table.insert(self.overlayEntities, overlayEntity) return overlayEntity end function Visualizer:DrawTextOverlay(entity, txt) local overlayEntity = Entity.new(game.surfaces[1].create_entity{ name = "flying-text", position = entity.position, force = game.forces.player, text = txt }) overlayEntity.obj.active = false table.insert(self.overlayEntities, overlayEntity) return overlayEntity end function Visualizer:Clear() for _,entity in ipairs(self.overlayEntities) do entity.obj.destroy() end end function Visualizer:GetDirectionStr(direction) if direction == CONST.DIRECTIONS.EAST then return "East" elseif direction == CONST.DIRECTIONS.SOUTH then return "South" elseif direction == CONST.DIRECTIONS.WEST then return "West" end return "North" end return Visualizer
require 'nvim_utils' vim.o.completeopt = 'menu,menuone,noselect' vim.g.delimitMate_expand_cr = 2 vim.g.delimitMate_expand_space = 1 vim.g.delimitMate_jump_expansion = 1 vim.g.delimitMate_balance_matchpairs = 1 local completion_maps = { ['i<C-space>'] = { [[compe#complete()]], noremap = true, expr = true; }; ['i<CR>'] = { [[compe#confirm({ 'keys': "<Plug>delimitMateCR", 'mode': '' })]], noremap = true, expr = true; }; ["i<C-e>"] = { [[compe#close('<C-e>')]], noremap = true, expr = true; }; ["i<C-u>"] = { [[compe#scroll({ 'delta': +4 })]], noremap = true, expr = true; }; ["i<C-d>"] = { [[compe#scroll({ 'delta': -4 })]], noremap = true, expr = true; }; ["i<Tab>"] = { [[v:lua.tab_complete()]], noremap = true, expr = true; }; ["s<Tab>"] = { [[v:lua.tab_complete()]], noremap = true, expr = true; }; ["i<S-Tab>"] = { [[v:lua.s_tab_complete()]], noremap = true, expr = true; }; ["s<S-Tab>"] = { [[v:lua.s_tab_complete()]], noremap = true, expr = true; } } nvim_apply_mappings(completion_maps, { silent = true }) local check_back_space = function() local col = vim.fn.col('.') - 1 if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then return true else return false end end _G.tab_complete = function() if vim.fn.pumvisible() == 1 then return utils.t '<C-n>' elseif check_back_space() then return utils.t '<Tab>' else return vim.fn['compe#complete']() end end _G.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return utils.t '<C-p>' else return utils.t '<S-Tab>' end end require 'compe'.setup { enabled = true; autocomplete = true; debug = false; preselect = 'enable'; source = { path = true; buffer = true; nvim_lsp = true; nvim_lua = true; } }
local variableClass = {} local defaultClass = "misc" -- Save all function saveAll() for class, data in pairs(variableClass) do local path = "settings_"..class if fileExists(path) then fileDelete(path) end local file = fileCreate(path) if file then fileWrite(file, toJSON(data)) fileClose(file) end end --print("Saved all client variables") end addEventHandler("onClientResourceStop", resourceRoot, saveAll) -- Set variable function setClientVariable(variable, value, class) if variable and value then variable = tostring(variable) value = tostring(value) class = tostring(class or defaultClass) if not variableClass[class] then loadVariableClass(class) end variableClass[class][variable] = value local data = {} data[variable] = value local path = "settings_"..class if fileExists(path) then fileDelete(path) end local file = fileCreate(path) if file then fileWrite(file, toJSON(data)) fileClose(file) end triggerEvent("settings:onSettingChange", localPlayer, variable, value, class) triggerServerEvent("settings:syncPlayerSettings", localPlayer, data) --print("Updated client variable '"..variable.."' as '"..value.."' from '"..class.."' class") end end -- Get variable function getClientVariable(variable, class) if variable then variable = tostring(variable) class = tostring(class or defaultClass) if not variableClass[class] then loadVariableClass(class) end return variableClass[class][variable] or nil end end function loadVariableClass(class) if class then local path = "settings_"..class if fileExists(path) then local file = fileOpen(path) if file then local content = fileRead(file, fileGetSize(file)) if content then content = fromJSON(content) variableClass[class] = type(content) == "table" and content or {} local data = {} for i, v in pairs(content) do data[i] = v end triggerServerEvent("settings:syncPlayerSettings", localPlayer, data) end fileClose(file) else variableClass[class] = {} end else variableClass[class] = {} end --print("Loaded client variable class '"..class.."' into memory") end end
require("config") require("framework.init") -- define global module game = {} function game.startup() cc.FileUtils:getInstance():addSearchPath("res/") display.addSpriteFrames(GAME_TEXTURE_DATA_FILENAME, GAME_TEXTURE_IMAGE_FILENAME) game.mainScene() end function game.exit() os.exit() end function game.mainScene() local BenchmarkScene = require("scenes.Sprite3DScene") display.replaceScene(BenchmarkScene.new()) end
local original_rocket_silo = data.raw["rocket-silo"]["rocket-silo"] local beaconed_data = { machine_energy_usage = original_rocket_silo.active_energy_usage, machine_emissions = original_rocket_silo.energy_source.emissions_per_minute, machine_crafting_speed = original_rocket_silo.crafting_speed, machine_module_slots = original_rocket_silo.module_specification.module_slots, beacon_count = global_rocket_silo_beacon_count, average_beacon_count = global_rocket_silo_average_beacon_count, beacon_effect = global_beacon_transmission_effect, beacon_module_slots = global_beacon_module_slots, beacon_module_speed_bonus = global_speed_module_1_speed_bonus, beacon_module_energy_usage_bonus = global_speed_module_1_energy_usage_bonus, machine_module_speed_bonus = global_productivity_module_1_speed_bonus, machine_module_energy_usage_bonus = global_productivity_module_1_energy_usage_bonus, machine_module_productivity_bonus = global_productivity_module_1_productivity_bonus, machine_module_pollution_bonus = global_productivity_module_1_pollution_bonus, emission_hack = 1 } beaconed_rocket_silo = util.table.deepcopy(data.raw["rocket-silo"]["rocket-silo"]) beaconed_rocket_silo.name = "beaconed-rocket-silo" beaconed_rocket_silo.icon = "__Built-in-Beacons__/graphics/icons/beaconed-rocket-silo.png" beaconed_rocket_silo.minable.result = "beaconed-rocket-silo" beaconed_rocket_silo.next_upgrade = "beaconed-rocket-silo-2" beaconed_rocket_silo.crafting_speed = beaconed_stats(beaconed_data).beaconed_crafting_speed beaconed_rocket_silo.active_energy_usage = beaconed_stats(beaconed_data).beaconed_energy_usage_string beaconed_rocket_silo.energy_source.drain = beaconed_stats(beaconed_data).beaconed_drain_string --beaconed_rocket_silo.crafting_speed = 4.4 --beaconed_rocket_silo.energy_usage = "3150kW" --beaconed_rocket_silo.energy_source.drain = "9608kW" --beaconed_rocket_silo.lamp_energy_usage = "10kW" --beaconed_rocket_silo.active_energy_usage = "50400kW" beaconed_rocket_silo.allowed_effects = {"productivity", "pollution"} beaconed_rocket_silo.fast_replaceable_group = "rocket-silo" beaconed_rocket_silo.rocket_entity = "beaconed-rocket" if settings.startup["productivity-mode"].value == 'Modded Modules' then beaconed_rocket_silo.module_specification.module_slots = data.raw["rocket-silo"]["rocket-silo"].module_specification.module_slots * 2 if settings.startup["show-module-slot-row-length"].value > 0 then beaconed_rocket_silo.module_specification.module_info_max_icons_per_row = settings.startup["show-module-slot-row-length"].value end if settings.startup["show-module-slot-rows"].value > 0 then beaconed_rocket_silo.module_specification.module_info_max_icon_rows = settings.startup["show-module-slot-rows"].value end else beaconed_rocket_silo.module_specification.module_slots = 0 beaconed_rocket_silo.base_productivity = beaconed_stats(beaconed_data).beaconed_base_productivity end beaconed_rocket = util.table.deepcopy(data.raw['rocket-silo-rocket']['rocket-silo-rocket']) beaconed_rocket.name = "beaconed-rocket" if settings.startup["modded-entity-graphics"].value == "ON" then beaconed_rocket_silo.base_day_sprite = { layers = { { filename = "__base__/graphics/entity/rocket-silo/06-rocket-silo.png", width = 300, height = 300, shift = util.by_pixel(2, -2), hr_version = { filename = "__base__/graphics/entity/rocket-silo/hr-06-rocket-silo.png", width = 608, height = 596, shift = util.by_pixel(3, -1), scale = 0.5 } },--layer from base game { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/beaconed-06-rocket-silo-overlay.png", width = 292, height = 293, frame_count = 1, shift = util.by_pixel(1, -2.5), tint = beaconed_rocket_silo_1_tint, hr_version = { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/hr-beaconed-06-rocket-silo-overlay.png", width = 583, height = 586, frame_count = 1, shift = util.by_pixel(0.75, -2.5), tint = beaconed_rocket_silo_1_tint, scale = 0.5 } } } } beaconed_rocket_silo.satellite_animation = { layers = { { filename = "__base__/graphics/entity/rocket-silo/15-rocket-silo-turbine.png", priority = "medium", width = 28, height = 46, frame_count = 32, line_length = 8, animation_speed = 0.4, shift = util.by_pixel(-100, 110), hr_version = { filename = "__base__/graphics/entity/rocket-silo/hr-15-rocket-silo-turbine.png", priority = "medium", width = 54, height = 88, frame_count = 32, line_length = 8, animation_speed = 0.4, shift = util.by_pixel(-100, 111), scale = 0.5 } },--layer from base game { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/beaconed-15-rocket-silo-turbine-overlay.png", priority = "medium", width = 28, height = 45, frame_count = 32, line_length = 8, animation_speed = 0.4, shift = util.by_pixel(-100, 111.5), tint = beaconed_rocket_silo_1_tint, hr_version = { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/hr-beaconed-15-rocket-silo-turbine-overlay.png", priority = "medium", width = 55, height = 89, frame_count = 32, line_length = 8, animation_speed = 0.4, shift = util.by_pixel(-99.75, 111.25), tint = beaconed_rocket_silo_1_tint, scale = 0.5 } }, } } beaconed_rocket_silo.base_front_sprite = { layers = { { filename = "__base__/graphics/entity/rocket-silo/14-rocket-silo-front.png", width = 292, height = 132, shift = util.by_pixel(-2, 78), hr_version = { filename = "__base__/graphics/entity/rocket-silo/hr-14-rocket-silo-front.png", width = 580, height = 262, shift = util.by_pixel(-1, 78), scale = 0.5 } }, { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/beaconed-14-rocket-silo-front-overlay.png", width = 289, height = 132, shift = util.by_pixel(-0.5, 78), tint = beaconed_rocket_silo_1_tint, hr_version = { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/hr-beaconed-14-rocket-silo-front-overlay.png", width = 578, height = 263, shift = util.by_pixel(-0.5, 78.25), tint = beaconed_rocket_silo_1_tint, scale = 0.5 } }, } } beaconed_rocket_silo.arm_01_back_animation = { layers = { { filename = "__base__/graphics/entity/rocket-silo/08-rocket-silo-arms-back.png", priority = "medium", width = 66, height = 76, frame_count = 32, line_length = 32, animation_speed = 0.3, shift = util.by_pixel(-54, -84), hr_version = { filename = "__base__/graphics/entity/rocket-silo/hr-08-rocket-silo-arms-back.png", priority = "medium", width = 128, height = 150, frame_count = 32, line_length = 32, animation_speed = 0.3, shift = util.by_pixel(-53, -84), scale = 0.5 } }, { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/beaconed-08-rocket-silo-arms-back-overlay.png", priority = "medium", width = 64, height = 75, frame_count = 32, line_length = 8, animation_speed = 0.3, shift = util.by_pixel(-53, -83.5), tint = beaconed_rocket_silo_1_tint, hr_version = { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/hr-beaconed-08-rocket-silo-arms-back-overlay.png", priority = "medium", width = 127, height = 149, frame_count = 32, line_length = 8, animation_speed = 0.3, shift = util.by_pixel(-52.75, -83.25), tint = beaconed_rocket_silo_1_tint, scale = 0.5 } }, } } beaconed_rocket_silo.arm_02_right_animation = { layers = { { filename = "__base__/graphics/entity/rocket-silo/08-rocket-silo-arms-right.png", priority = "medium", width = 94, height = 94, frame_count = 32, line_length = 32, animation_speed = 0.3, shift = util.by_pixel(100, -38), hr_version = { filename = "__base__/graphics/entity/rocket-silo/hr-08-rocket-silo-arms-right.png", priority = "medium", width = 182, height = 188, frame_count = 32, line_length = 32, animation_speed = 0.3, shift = util.by_pixel(101, -38), scale = 0.5 } }, { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/beaconed-08-rocket-silo-arms-right-overlay.png", priority = "medium", width = 91, height = 95, frame_count = 32, line_length = 8, animation_speed = 0.3, shift = util.by_pixel(101.5, -37.5), tint = beaconed_rocket_silo_1_tint, hr_version = { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/hr-beaconed-08-rocket-silo-arms-right-overlay.png", priority = "medium", width = 182, height = 188, frame_count = 32, line_length = 8, animation_speed = 0.3, shift = util.by_pixel(101.5, -37.5), tint = beaconed_rocket_silo_1_tint, scale = 0.5 } }, } } beaconed_rocket_silo.arm_03_front_animation = { layers = { { filename = "__base__/graphics/entity/rocket-silo/13-rocket-silo-arms-front.png", priority = "medium", width = 66, height = 114, frame_count = 32, line_length = 32, animation_speed = 0.3, shift = util.by_pixel(-52, 16), hr_version = { filename = "__base__/graphics/entity/rocket-silo/hr-13-rocket-silo-arms-front.png", priority = "medium", width = 126, height = 228, frame_count = 32, line_length = 32, animation_speed = 0.3, shift = util.by_pixel(-51, 16), scale = 0.5 } }, { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/hr-beaconed-13-rocket-silo-arms-front-overlay.png", priority = "medium", width = 64, height = 115, frame_count = 32, line_length = 8, animation_speed = 0.3, shift = util.by_pixel(-51, 16.5), tint = beaconed_rocket_silo_1_tint, hr_version = { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/hr-beaconed-13-rocket-silo-arms-front-overlay.png", priority = "medium", width = 126, height = 228, frame_count = 32, line_length = 8, animation_speed = 0.3, shift = util.by_pixel(-51, 16.5), tint = beaconed_rocket_silo_1_tint, scale = 0.5 } }, } } beaconed_rocket.rocket_sprite = { layers = { { filename = "__base__/graphics/entity/rocket-silo/02-rocket.png", width = 154, height = 300, shift = util.by_pixel(-4, -28+112), hr_version = { filename = "__base__/graphics/entity/rocket-silo/hr-02-rocket.png", width = 310, height = 596, shift = util.by_pixel(-5, -27+112), scale = 0.5 } }, { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/beaconed-02-rocket-overlay.png", width = 155, height = 298, shift = util.by_pixel(-4.5, -26+112), tint = beaconed_rocket_1_tint, hr_version = { filename = "__Built-in-Beacons__/graphics/entity/beaconed-rocket-silo/hr-beaconed-02-rocket-overlay.png", width = 308, height = 594, shift = util.by_pixel(-4.5, -26+112), tint = beaconed_rocket_1_tint, scale = 0.5 } } } } end data:extend({ beaconed_rocket, beaconed_rocket_silo }) data:extend({ { type = "item", name = "beaconed-rocket-silo", icon = "__Built-in-Beacons__/graphics/icons/beaconed-rocket-silo.png", icon_size = 64, icon_mipmaps = 4, subgroup = "defensive-structure", order = "e[rocket-silo]", place_result = "beaconed-rocket-silo", stack_size = 1, localised_description = {'item-description.beaconed-rocket-silo', global_rocket_silo_beacon_count} }, }) data:extend({ { type = "recipe", name = "beaconed-rocket-silo", enabled = false, icon = "__Built-in-Beacons__/graphics/icons/beaconed-rocket-silo.png", icon_size = 64, icon_mipmaps = 4, subgroup = "built-in-beacons", order = "i", ingredients = { {"rocket-silo", 1}, {"beacon", global_rocket_silo_average_beacon_count}, {"speed-module", global_rocket_silo_average_beacon_count * global_beacon_module_slots} }, results = { {type = "item", name = "beaconed-rocket-silo", amount = 1} }, allow_as_intermediate = false, localised_description = {'item-description.beaconed-rocket-silo', global_rocket_silo_beacon_count} } }) if global_logging == true then log(serpent.block( beaconed_data )) log(serpent.block( beaconed_stats(beaconed_data) )) end
--[[ Pixel Vision 8 - New Template Script Copyright (C) 2017, Pixel Vision 8 (http://pixelvision8.com) Created by Jesse Freeman (@jessefreeman) This project was designed to display some basic instructions when you create a new tool. Simply delete the following code and implement your own Init(), Update() and Draw() logic. Learn more about making Pixel Vision 8 games at https://www.gitbook.com/@pixelvision8 ]]-- -- Load in the editor framework script to access tool components LoadScript("sb-sprites") LoadScript("pixel-vision-os-v2") LoadScript("code-icon-button") LoadScript("code-rename-modal") LoadScript("code-new-file-modal") local toolName = "Workspace Explorer" local pixelVisionOS = nil local editorUI = nil local lastStartID = nil local PlayVersion, DrawVersion, TuneVersion, MakeVersion = "Pixel Vision 8 Play", "Pixel Vision 8 Draw", "Pixel Vision 8 Tune", "Pixel Vision 8 Make" local runnerName = SystemName() local totalPerWindow = 12 local currentDirectory = "none" local shuttingDown = false local files = nil local windowIconButtons = nil local trashPath = "/Tmp/Trash/" local workspacePath = "/Workspace/" local refreshTime = 0 local refreshDelay = 5 local fileCount = 0 local fileTypeMap = { folder = "filefolder", updirectory = "fileparentfolder", lua = "filecode", json = "filejson", png = "filepng", pv8 = "filerun", txt = "filetext", -- TODO these are not core file types unknown = "fileunknown", colors = "filecolor", system = "filesettings", font = "filefont", music = "filemusic", sounds = "filesound", sprites = "filesprites", tilemap = "filetilemap", pvt = "filerun", new = "filenewfile" } local extToTypeMap = { colors = "png", system = "json", font = "font.png", music = "json", sounds = "json", sprites = "png", tilemap = "json" } local renameModal = nil local rootPath = ReadMetaData("RootPath", "/") local windowScrollHistory = {} local newFileModal = nil -- local editors = { -- colors = {name = "ColorEditor", path = rootPath .."ColorTool/"}, -- sprites = {name = "SpriteEditor", path = rootPath .."SpriteTool/"}, -- font = {name = "FontEditor", path = rootPath .."FontTool/"}, -- tilemap = {name = "TilemapEditor", path = rootPath .."TilemapTool/"}, -- lua = {name = "TextEditor", path = rootPath .."TextEditorTool/"}, -- json = {name = "TextEditor", path = rootPath .."TextEditorTool/"}, -- system = {name = "ChipEditor", path = rootPath .."ChipEditor/"}, -- sounds = {name = "SoundEditor", path = rootPath .."SFXTool/"}, -- music = {name = "MusicEditor", path = rootPath .."MusicTool/"}, -- txt = {name = "TextEditor", path = rootPath .."TextEditorTool/"}, -- png = {name = "ImagePreview", path = rootPath .."ImagePreviewTool/"} -- } -- This this is an empty game, we will the following text. We combined two sets of fonts into -- the default.font.png. Use uppercase for larger characters and lowercase for a smaller one. local title = "EMPTY TOOL" local messageTxt = "This is an empty tool template. Press Ctrl + 1 to open the editor or modify the files found in your workspace game folder." -- Container for horizontal slider data local desktopIcons = nil local vSliderData = nil local currentSelectedFile = nil -- Flags for managing focus local WindowFocus, DesktopIconFocus, WindowIconFocus, NoFocus = 1, 2, 3, 4 local desktopIcons = { -- { -- name = "ReaperBoy", -- sprite = "diskempty", -- tooltip = "The current project", -- path = "/Workspace/Games/ReaperBoyLD42Disk1/" -- } } NewFolderShortcut, RunShortcut, EditShortcut, RenameShortcut, CopyShortcut, PasteShortcut, DeleteShortcut, EmptyTrashShortcut, EjectDiskShortcut = 5, 9, 10, 11, 12, 13, 14, 16, 17 -- Get all of the available editors local editorMapping = FindEditors() -- local messageModal = nil -- TODO need menu constants to make updating them easier if things change later on -- The Init() method is part of the game's lifecycle and called a game starts. We are going to -- use this method to configure background color, ScreenBufferChip and draw a text box. function Init() DrawWallpaper() -- Disable the back key in this tool EnableBackKey(false) EnableAutoRun(false) -- Create an instance of the Pixel Vision OS pixelVisionOS = PixelVisionOS:Init() -- Get a reference to the Editor UI editorUI = pixelVisionOS.editorUI newFileModal = NewFileModal:Init(editorUI) newFileModal.editorUI = editorUI -- Create modals -- messageModal = MessageModal:Init("Warning Modal", "This is a warning message which should show a lot of text in a small window on top of the main UI.", 100) -- TODO need to see if the log file actually exists local logExits = true local menuOptions = { -- About ID 1 {name = "About", action = function() pixelVisionOS:ShowAboutModal(toolName) end, toolTip = "Learn about PV8."}, -- Settings ID 2 {name = "Settings", action = OnLaunchSettings, toolTip = "Learn about PV8."}, {name = "View Log", enabled = logExits, action = OnLaunchLog, toolTip = "Open up the log file."}, {divider = true}, -- New Folder ID 5 {name = "New Folder", action = OnNewFolder, enabled = false, toolTip = "Create a new file."}, {divider = true}, -- Run ID 8 {name = "Run", key = Keys.R, action = OnRun, enabled = false, toolTip = "Run the current game."}, -- Edit ID 9 {name = "Edit", key = Keys.E, action = OnEdit, enabled = false, toolTip = "Edit the selected file."}, {name = "Rename", action = OnTriggerRename, enabled = false, toolTip = "Rename the currently selected file."}, -- Copy ID 10 {name = "Copy", key = Keys.C, action = OnCopy, enabled = false, toolTip = "Copy the selected file."}, -- Paste ID 11 {name = "Paste", key = Keys.V, action = OnPaste, enabled = false, toolTip = "Paste the selected file."}, -- Delete ID 12 {name = "Delete", key = Keys.D, action = OnDeleteFile, enabled = false, toolTip = "Delete the current file."}, {divider = true}, -- Empty Trash ID 14 {name = "Empty Trash", action = OnEmptyTrash, enabled = false, toolTip = "Delete everything in the trash."}, -- Eject ID 15 {name = "Eject Disk", action = OnEjectDisk, enabled = false, toolTip = "Eject the currently selected disk."}, -- Shutdown ID 16 {name = "Shutdown", action = OnShutdown, toolTip = "Shutdown PV8."} -- Quit the current game } local menuOffset = -2 local addAt = 6 if(runnerName ~= PlayVersion) then table.insert(menuOptions, addAt, {name = "New Project", action = OnNewGame, enabled = false, toolTip = "Create a new file."}) menuOffset = menuOffset + 1 -- NewCodeShortcut = addAt NewGameShortcut = addAt -- table.insert(newFileOptions, addAt) addAt = addAt + 1 end newFileOptions = {} -- -- Add new project option -- if(runnerName ~= PlayVersion) then -- -- table.insert(menuOptions, addAt, {name = "New Project", action = OnNewGame, enabled = false, toolTip = "Create a new file."}) -- menuOffset = menuOffset + 1 -- NewCodeShortcut = addAt -- table.insert(newFileOptions, addAt) -- addAt = addAt + 1 -- -- end -- Add text options to the menu if(runnerName ~= PlayVersion and runnerName ~= DrawVersion and runnerName ~= TuneVersion) then table.insert(menuOptions, addAt, {name = "New Code", action = function() OnNewFile("code", "lua") end, enabled = false, toolTip = "Run the current game."}) menuOffset = menuOffset + 1 NewCodeShortcut = addAt table.insert(newFileOptions, addAt) addAt = addAt + 1 table.insert(menuOptions, addAt, {name = "New JSON", action = function() OnNewFile("untitled", "json") end, enabled = false, toolTip = "Run the current game."}) menuOffset = menuOffset + 1 NewJSONShortcut = addAt table.insert(newFileOptions, addAt) addAt = addAt + 1 end -- Add draw options if(runnerName ~= PlayVersion and runnerName ~= TuneVersion) then table.insert(menuOptions, addAt, {name = "New Colors", action = function() OnNewFile("colors", "png", "colors") end, enabled = false, toolTip = "Run the current game.", file = "colors.png"}) menuOffset = menuOffset + 1 NewColorsShortcut = addAt table.insert(newFileOptions, addAt) addAt = addAt + 1 table.insert(menuOptions, addAt, {name = "New Sprites", action = function() OnNewFile("sprites", "png", "sprites") end, enabled = false, toolTip = "Run the current game.", file = "sprites.png"}) menuOffset = menuOffset + 1 NewSpritesShortcut = addAt table.insert(newFileOptions, addAt) addAt = addAt + 1 table.insert(menuOptions, addAt, {name = "New Font", action = function() OnNewFile("untitled", "font.png", "font") end, enabled = false, toolTip = "Run the current game."}) menuOffset = menuOffset + 1 NewFontShortcut = addAt table.insert(newFileOptions, addAt) addAt = addAt + 1 table.insert(menuOptions, addAt, {name = "New Tilemap", action = function() OnNewFile("tilemap", "json", "tilemap") end, enabled = false, toolTip = "Run the current game.", file = "tilemap.json"}) menuOffset = menuOffset + 1 NewTilemapShortcut = addAt table.insert(newFileOptions, addAt) addAt = addAt + 1 end -- Add music options if(runnerName ~= PlayVersion and runnerName ~= DrawVersion) then table.insert(menuOptions, addAt, {name = "New Sounds", action = function() OnNewFile("sounds", "json", "sounds") end, enabled = false, toolTip = "Run the current game.", file = "sounds.json"}) menuOffset = menuOffset + 1 NewSoundsShortcut = addAt table.insert(newFileOptions, addAt) addAt = addAt + 1 table.insert(menuOptions, addAt, {name = "New Music", action = function() OnNewFile("music", "json", "music") end, enabled = false, toolTip = "Run the current game.", file = "music.json"}) menuOffset = menuOffset + 1 NewMusicShortcut = addAt table.insert(newFileOptions, addAt) addAt = addAt + 1 end -- Update the shortcuts based on what new file options were added RunShortcut = RunShortcut + menuOffset EditShortcut = EditShortcut + menuOffset RenameShortcut = RenameShortcut + menuOffset CopyShortcut = CopyShortcut + menuOffset PasteShortcut = PasteShortcut + menuOffset DeleteShortcut = DeleteShortcut + menuOffset EmptyTrashShortcut = EmptyTrashShortcut + menuOffset EjectDiskShortcut = EjectDiskShortcut + menuOffset pixelVisionOS:CreateTitleBarMenu(menuOptions, "See menu options for this tool.") -- Change the title pixelVisionOS:ChangeTitle(toolName, "toolbaricontool") -- local bgColor = BackgroundColor() RebuildDesktopIcons() -- TODO need to read bios to see if this was changed? trashPath = "/Tmp/Trash/" -- trashButton.redrawBackground = true -- table.insert(desktopItems, trashButton) -- trashButton.onAction = function() -- OpenWindow("/Workspace/Trash/") -- end -- totalDesktopItems = #desktopItems local newPath = ReadSaveData("lastPath", "none") -- print("!New Path", newPath, "lastScrollPos", lastScrollPos, ReadSaveData("sessionID", "")) if(SessionID() == ReadSaveData("sessionID", "") and newPath ~= "none") then OpenWindow(newPath, tonumber(ReadSaveData("scrollPos", "0")), tonumber(ReadSaveData("selection", "0"))) -- print("restore editors") end -- TODO if no editors are registered -- print("Load editors") end function DrawWallpaper() -- Check version -- Set up logo values local logoSpriteData = _G["logoplay"] local colorOffset = 0 local backgroundColor = 5 -- Set logo if(runnerName == MakeVersion) then logoSpriteData = _G["logomake"] -- colorOffset = 0 -- backgroundColor = 5 elseif(runnerName == DrawVersion) then logoSpriteData = _G["logodraw"] colorOffset = 5 backgroundColor = 1 elseif(runnerName == TuneVersion) then logoSpriteData = _G["logotune"] -- colorOffset = 0 backgroundColor = 8 end -- Update background BackgroundColor(backgroundColor) -- Draw logo if(logoSpriteData ~= nil) then UpdateTiles(13, 13, logoSpriteData.width, logoSpriteData.spriteIDs, colorOffset) end end function OnNewFile(fileName, ext, type) if(type == nil) then type = ext end -- -- if(newFileModal == nil) then -- -- end newFileModal:SetText("New ".. type, fileName, "Name " .. type .. " file") pixelVisionOS:OpenModal(newFileModal, function() if(newFileModal.selectionValue == false) then return end local filePath = currentDirectory .. newFileModal.inputField.text .. "." .. ext NewFile(filePath) RefreshWindow() end ) end function OnTriggerRename(callback) -- TODO need to get the currently selected file -- print("Rename file") if(renameModal == nil) then renameModal = RenameModal:Init(editorUI) renameModal.editorUI = editorUI end -- TODO need to get the filename for the currently selected file -- local text = "Untitled" pixelVisionOS:OpenModal(renameModal, OnRenameFile) renameModal:SetText(CurrentlySelectedFile().name) end function OnRenameFile() -- Need to read the last text input from the modal and rename the file local text = renameModal:GetText() local file = CurrentlySelectedFile() -- Make sure the new name is not the same as the old name if(text ~= file.name) then -- Check to see if the file is an extension if(file.isDirectory == true) then -- Add a trailing slash to the extension text = text .. "/" else -- Remap the extension by looking for it in the extToTypeMap local tmpExt = extToTypeMap[file.type] -- If the type doesn't exist, use the default ext if(tmpExt == nil) then tmpExt = file.ext end -- Add the new ext to the file text = text .. "." .. tmpExt end -- Rename the file by moving it and giving it a new name if(MoveFile(file.path, file.parentPath .. text)) then RefreshWindow() end end end function RefreshWindow() OpenWindow(currentDirectory, scrollTo, selection) end function OnCloseModal() -- Clear the background? -- Redraw the desktop? -- Redraw the window on top of the screen -- OpenWindow(currentDirectory) end function OnEmptyTrash() -- Get all the files in the trash local files = GetDirectoryContents(trashPath) -- Loop through all the files in the root of the trash and delete them for i = 1, #files do DeleteFile(files[i].path, true) end -- Need to rebuild the desktop to change the trash icon RebuildDesktopIcons() -- If we are in the trash, redraw the window at the root of the trash if(TrashOpen()) then OpenWindow(trashPath) end end function OnRun() -- Only try to run if the directory is a game if(currentDirectory == nil or currentDirectory == "none" or pixelVisionOS:ValidateGameInDir(currentDirectory) == false) then return end LoadGame(currentDirectory) end -- -- function CurrentlySelectedFile() -- -- local path = nil -- -- if(windowIconButtons ~= nil) then -- -- -- -- end -- -- return path -- -- end local filesToCopy = nil function OnCopy() if(windowIconButtons ~= nil) then -- Remove previous files to be copied filesToCopy = {} -- TODO this needs to eventually support multiple selections local file = CurrentlySelectedFile() if(CanCopy(file)) then -- Copy the file to the list table.insert(filesToCopy, file) -- Enable the paste shortcut pixelVisionOS:EnableMenuItem(PasteShortcut, true) else -- Display a message that the file can not be copied pixelVisionOS:ShowMessageModal(toolName .. "Error", "'".. file.name .. "' can not be copied.", 160, false) -- Make sure we can't activate paste pixelVisionOS:EnableMenuItem(PasteShortcut, false) end -- -- -- TODO Need to go through all of the items in the group and see which ones are selected -- -- local selections = editorUI:ToggleGroupSelections(windowIconButtons) -- local total = #selections -- -- local errorFiles = {} -- -- for i = 1, total do -- -- local id = selections[i] -- local file = files[id] -- -- if(CanCopy(file)) then -- table.insert(filesToCopy, file) -- -- -- print("Copy path", file.name, file.path, file.type) -- -- else -- -- table.insert(errorFiles, file.name) -- end -- -- end -- Create message on what can be copied -- local validTotal = total - #errorFiles -- -- pixelVisionOS:DisplayMessage(tostring(validTotal) .. " of " .. tostring(total) .. " selected items were copied.", 5) -- MoveFile("/PixelVisionOS/bios.json", "/CanvasDemo/") end end function OnPaste(dest) dest = dest or currentDirectory if(filesToCopy == nil) then return end local total = #filesToCopy -- Loop through all of the files to make sure there aren't any conflicts local conflicts = {} for i = 1, total do local file = filesToCopy[i] local tmpPath = dest .. file.fullName -- Make sure file doesn't exist and the src path doesn't match the dest path if(PathExists(tmpPath) and tmpPath ~= file.path) then table.insert(conflicts, tmpPath) end end if(#conflicts > 0) then pixelVisionOS:ShowMessageModal( "Paste Files", "Looks like there is an existing file with the same name in '".. dest .. "'. Do you want to overwrite that file?", 128 + 16, true, function() -- Only perform the copy if the user selects OK from the modal if(pixelVisionOS.messageModal.selectionValue) then for i = 1, #conflicts do DeleteFile(conflicts[i], false) end TriggerFileCopy(dest) end end ) else TriggerFileCopy(dest) end -- pixelVisionOS:EnableMenuItem(PasteShortcut, false) end function TriggerFileCopy(dest) -- This function assumes all the copy action has been checked and can be performed for i = 1, #filesToCopy do CopyFile(filesToCopy[i].path, dest) end filesToCopy = nil -- TODO Clear window selection? RefreshWindow() end function CanCopy(file) return (file.name ~= "Run" and file.type ~= "updirectory") end function CanDelete(file) end function OnEjectDisk() -- print("Selected", desktopIconButtons.currentSelection) local id = desktopIconButtons.currentSelection local iconButton = desktopIconButtons.buttons[id] if(currentDirectory ~= "none") then CloseWindow() end EjectDisk("/" .. desktopIcons[id].name .. "/") RebuildDesktopIcons() end function OnShutdown() local systemName = SystemName() pixelVisionOS:ShowMessageModal("Shutdown " .. systemName, "Are you sure you want to shutdown "..systemName.."?", 160, true, function() if(pixelVisionOS.messageModal.selectionValue == true) then -- Save changes shuttingDown = true BackgroundColor(0) DrawRect(0, 0, 256, 480, 0, DrawMode.TilemapCache) local startX = math.floor((32 - #systemName) * .5) DrawText(systemName:upper(), startX, 10, DrawMode.Tile, "large", 15) DrawText("IS READY FOR SHUTDOWN.", 5, 11, DrawMode.Tile, "large", 15) ShutdownSystem() end end ) end function RebuildDesktopIcons() -- TODO clear desktop with background color DrawRect(216, 16, 39, 216, BackgroundColor(), DrawMode.TilemapCache) -- Build Desktop Icons desktopIcons = {} if(PathExists("/Workspace/")) then table.insert(desktopIcons, { name = "Workspace", sprite = "filedrive", tooltip = "This is the main drive", path = "/Workspace/" }) end local disks = DisksPaths() for k, v in pairs(disks) do -- print(k, v) table.insert(desktopIcons, { name = k, sprite = "diskempty", tooltip = "This is a disk.", path = v }) end -- -- print("Total disks", #disks) -- Draw desktop icons local startY = 16 desktopIconButtons = editorUI:CreateIconGroup() desktopIconButtons.onTrigger = OnDesktopIconClick desktopIconButtons.onAction = OnDesktopIconSelected -- local selectedItem = desktopIcons[value] -- -- print("Can eject " .. selectedItem.name) -- -- -- pixelVisionOS:EnableMenuItem(NewGameShortcut, false) -- -- pixelVisionOS:EnableMenuItem(NewFolderShortcut, false) -- -- pixelVisionOS:EnableMenuItem(CopyShortcut, false) -- -- pixelVisionOS:EnableMenuItem(PasteShortcut, false) -- -- pixelVisionOS:EnableMenuItem(NewFileShortcut, false) -- -- -- -- pixelVisionOS:EnableMenuItem(EjectDiskShortcut, selectedItem.name ~= "Trash") -- -- editorUI:ClearIconGroupSelections(windowIconButtons) -- -- end for i = 1, #desktopIcons do local item = desktopIcons[i] local button = editorUI:NewIconGroupButton(desktopIconButtons, {x = 216 - 8, y = startY}, item.sprite, item.name, item.tooltip, bgColor) startY = startY + 32 + 8 -- button.redrawBackground = true -- table.insert(desktopItems, button) -- button.onAction = function(doubleClick) -- -- if(doubleClick == true) then -- OpenWindow(item.path) -- button.selected = true -- editorUI:Invalidate(button) -- -- activeButton = button -- end -- -- end end local trashFiles = GetDirectoryContents(trashPath) table.insert(desktopIcons, { name = "Trash", sprite = #trashFiles > 0 and "filetrashfull" or "filetrashempty", tooltip = "The trash folder", path = "/Tmp/Trash/" }) pixelVisionOS:EnableMenuItem(EmptyTrashShortcut, #trashFiles > 0) local item = desktopIcons[#desktopIcons] local trashButton = editorUI:NewIconGroupButton(desktopIconButtons, {x = 216 - 8, y = 200 - 2}, item.sprite, item.name, item.tooltip, bgColor) -- end end function OnDesktopIconSelected(value) -- TODO need to check if the disk can be ejected? UpdateContextMenu(DesktopIconFocus) -- Clear any window selections editorUI:ClearIconGroupSelections(windowIconButtons) end local currentOpenIconButton = nil function OnDesktopIconClick(value, doubleClick) -- print("Desktop Icon Click", value, doubleClick) -- Close the currently open button if(currentOpenIconButton ~= nil) then editorUI:CloseIconButton(currentOpenIconButton) end currentOpenIconButton = desktopIconButtons.buttons[value] editorUI:OpenIconButton(currentOpenIconButton) OpenWindow(desktopIcons[value].path) -- Force a single selection if shift key is not down -- if(#editorUI:ToggleGroupSelections(desktopIconButtons) > 0) then -- -- editorUI:ClearGroupSelections(desktopIconButtons) -- -- editorUI:SelectToggleButton(desktopIconButtons, value, true) -- -- end end function OnNewGame() -- TODO should see if this is defined in the bios local defaultTemplate = ReadBiosData("DefaultTemplate") or "/Disks/PixelVisionOS/Templates/PV8System/" -- print("defaultTemplate", defaultTemplate) if(currentDirectory == "none" or PathExists(defaultTemplate) == false) then pixelVisionOS:ShowMessageModal(toolName .. " Error", "There is no default template.", 160, false) return end newFileModal:SetText("New Project", "NewProject", "Folder Name") pixelVisionOS:OpenModal(newFileModal, function() if(newFileModal.selectionValue == false) then return end local newPath = UniqueFilePath(currentDirectory .. newFileModal.inputField.text .. "/") -- local success = NewFolder(newPath) if(success == true) then local files = GetDirectoryContents(defaultTemplate) for i = 1, #files do CopyFile(files[i].path, newPath) end -- TODO need a way to select the new game and find its scroll option OpenWindow(currentDirectory, scrollTo, selection) else pixelVisionOS:DisplayMessage("Failed to create a new game", 5) end end ) end function OnNewFolder(name) if(currentDirectory == "none") then return end if(name == nil) then name = "Untitled" end -- if(newFileModal == nil) then -- newFileModal = NewFileModal:Init(editorUI) -- newFileModal.editorUI = editorUI -- end newFileModal:SetText("New Folder", name, "Folder Name") pixelVisionOS:OpenModal(newFileModal, function() if(newFileModal.selectionValue == false) then return end local filePath = currentDirectory .. newFileModal.inputField.text NewFolder(filePath.."/") RefreshWindow() end ) end function OnDeleteFile() -- Ask the user if they want to delete the file first pixelVisionOS:ShowMessageModal("Delete File", "Are you sure you want to move this file to the trash?", 160, true, function() -- If the user selects ok, we attempt to delete the file if(pixelVisionOS.messageModal.selectionValue) then -- Look to see if the current file exists and if it's not in the trash if(currentSelectedFile ~= nil and currentDirectory:sub(1, #trashPath) ~= trashPath) then -- Delete the file DeleteFile(currentSelectedFile.path) -- TODO should only do this if the trash is empty -- Rebuild the desktop if we need to change the trash icon RebuildDesktopIcons() -- Clear the selection selection = nil -- Refresh the currently open window RefreshWindow() else -- Let the user know the file can not be deleted pixelVisionOS:ShowMessageModal(toolName .. " Error", "'".. currentSelectedFile.name .. "' could not be deleted.", 160, false) end end end ) end function OpenWindow(path, scrollTo, selection) if(scrollTo == nil and windowScrollHistory[path] ~= nil) then scrollTo = windowScrollHistory[path] end refreshTime = 0 -- print("OpenWindow", path, scrollTo) -- Clear the previous file list files = {} -- save the current directory currentDirectory = path -- Set a default scrollTo value if none is provided scrollTo = scrollTo or 0 selection = selection or 0 -- Draw the window chrome DrawSprites(windowchrome.spriteIDs, 8, 16, windowchrome.width, false, false, DrawMode.TilemapCache) -- Create the slider for the window vSliderData = editorUI:CreateSlider({x = 192, y = 26, w = 16, h = 195}, "vsliderhandle", "This is a vertical slider") vSliderData.value = scrollTo vSliderData.onAction = OnValueChange -- Create the close button closeButton = editorUI:CreateButton({x = 192, y = 16}, "closewindow", "Close the window.") closeButton.hitRect = {x = closeButton.rect.x + 2, y = closeButton.rect.y + 2, w = 10, h = 10} closeButton.onAction = CloseWindow -- Create a icon button group for all of the files windowIconButtons = editorUI:CreateIconGroup() windowIconButtons.onTrigger = OnWindowIconClick -- Make sure we disable any selection on the desktop when clicking inside of the window icon group windowIconButtons.onAction = OnWindowIconSelect -- Reset the last start id lastStartID = -1 -- Parse files -- Get the list of files from the Lua Service files = GetDirectoryContents(path) -- Save a count of the files before we add the special files to the list fileCount = #files -- TODO need to see if the game can be run only if there is a code file if(runnerName ~= DrawVersion and runnerName ~= TuneVersion) then -- Check to see if this is a game directory if(pixelVisionOS:ValidateGameInDir(path) and TrashOpen() == false) then table.insert( files, 1, { name = "Run", type = "pv8", ext = "pv8", path = path, isDirectory = false } ) end end local parentDirectory = ParentDirectory(path) -- Check to see if this is a root directory if(parentDirectory ~= "/Disks/" and parentDirectory ~= "/Tmp/" and parentDirectory ~= "/") then -- local results = {} -- for match in string.gmatch(parentDirectory, "[^/]+") do -- table.insert(results, match) -- end table.insert( files, 1, { name = "..", type = "updirectory", path = parentDirectory, isDirectory = true } ) end -- Enable the scroll bar if needed editorUI:Enable(vSliderData, #files > totalPerWindow) -- Redraw the window for the first time -- DrawWindow(files, 0, totalPerWindow) OnValueChange(scrollTo) -- Select file editorUI:SelectIconButton(windowIconButtons, selection, false) -- We need to use a global file system API so append disk to it -- Enable creating a new game only when not inside of another game -- pixelVisionOS:EnableMenuItem(NewGameShortcut, not pixelVisionOS:ValidateGameInDir(currentDirectory)) -- Enable the new folder option when the window is open -- pixelVisionOS:EnableMenuItem(NewFolderShortcut, true) -- -- pixelVisionOS:EnableMenuItem(CopyShortcut, false) -- Enable all the editor functions UpdateContextMenu(WindowFocus) -- Update the window's title ChangeWindowTitle(path, "toolbaricontool") end function UpdateContextMenu(inFocus) if(inFocus == WindowFocus) then local canRun = pixelVisionOS:ValidateGameInDir(currentDirectory) and not TrashOpen() if(runnerName == DrawVersion or runnerName == TuneVersion) then canRun = false end -- New File options if(runnerName ~= PlayVersion) then pixelVisionOS:EnableMenuItem(NewGameShortcut, not canRun and not TrashOpen()) end pixelVisionOS:EnableMenuItem(NewFolderShortcut, not TrashOpen()) -- pixelVisionOS:EnableMenuItem(NewFileShortcut, not TrashOpen()) for i = 1, #newFileOptions do local id = newFileOptions[i] local enable = not TrashOpen() if(enable == true) then local menuData = pixelVisionOS.titleBar.menu.options[id] if(menuData.file ~= nil) then -- print("Test Path", currentDirectory .. menuData.file) enable = not PathExists(currentDirectory .. menuData.file) end end pixelVisionOS:EnableMenuItem(id, enable) end -- File options pixelVisionOS:EnableMenuItem(EditShortcut, false) pixelVisionOS:EnableMenuItem(RunShortcut, canRun) pixelVisionOS:EnableMenuItem(RenameShortcut, false) -- pixelVisionOS:EnableMenuItem(RunShortcut, not TrashOpen()) pixelVisionOS:EnableMenuItem(CopyShortcut, not TrashOpen()) pixelVisionOS:EnableMenuItem(DeleteShortcut, false) -- Disk options -- local canEject = not TrashOpen() and currentDirectory:sub(1, #workspacePath) == workspacePath pixelVisionOS:EnableMenuItem(EjectDiskShortcut, CanEject()) -- Special cases -- Only active paste if there is something to paste pixelVisionOS:EnableMenuItem(PasteShortcut, filesToCopy ~= nil and #filesToCopy > 0) elseif(inFocus == DesktopIconFocus) then -- New File options if(runnerName ~= PlayVersion) then pixelVisionOS:EnableMenuItem(NewGameShortcut, false) end pixelVisionOS:EnableMenuItem(NewFolderShortcut, false) -- pixelVisionOS:EnableMenuItem(NewFileShortcut, false) for i = 1, #newFileOptions do pixelVisionOS:EnableMenuItem(newFileOptions[i], false) end -- File options pixelVisionOS:EnableMenuItem(EditShortcut, false) pixelVisionOS:EnableMenuItem(RunShortcut, false) pixelVisionOS:EnableMenuItem(RenameShortcut, false) pixelVisionOS:EnableMenuItem(CopyShortcut, false) pixelVisionOS:EnableMenuItem(PasteShortcut, false) pixelVisionOS:EnableMenuItem(DeleteShortcut, false) -- Disk options pixelVisionOS:EnableMenuItem(EjectDiskShortcut, CanEject()) elseif(inFocus == WindowIconFocus) then local currentSelection = CurrentlySelectedFile() local specialFile = currentSelection.name == ".." or currentSelection.name == "Run" -- Check to see if currentDirectory is a game local canRun = pixelVisionOS:ValidateGameInDir(currentDirectory) and not TrashOpen() if(runnerName == DrawVersion or runnerName == TuneVersion) then canRun = false end -- New File options if(runnerName ~= PlayVersion) then pixelVisionOS:EnableMenuItem(NewGameShortcut, not canRun and not TrashOpen()) end pixelVisionOS:EnableMenuItem(NewFolderShortcut, not TrashOpen()) -- pixelVisionOS:EnableMenuItem(NewFileShortcut, not TrashOpen()) for i = 1, #newFileOptions do local id = newFileOptions[i] local enable = not TrashOpen() if(enable == true) then local menuData = pixelVisionOS.titleBar.menu.options[id] if(menuData.file ~= nil) then -- print("Test Path", currentDirectory .. menuData.file) enable = not PathExists(currentDirectory .. menuData.file) end end pixelVisionOS:EnableMenuItem(id, enable) end -- File options pixelVisionOS:EnableMenuItem(EditShortcut, not TrashOpen() and not specialFile) -- TODO Can't rename up directory? pixelVisionOS:EnableMenuItem(RenameShortcut, not TrashOpen() and not specialFile) pixelVisionOS:EnableMenuItem(RunShortcut, canRun) -- pixelVisionOS:EnableMenuItem(RunShortcut, canRun) pixelVisionOS:EnableMenuItem(CopyShortcut, not TrashOpen() and not specialFile) -- TODO need to makes sure the file can be deleted pixelVisionOS:EnableMenuItem(DeleteShortcut, not TrashOpen() and not specialFile) -- Disk options pixelVisionOS:EnableMenuItem(EjectDiskShortcut, false) else -- New File options if(runnerName ~= PlayVersion) then pixelVisionOS:EnableMenuItem(NewGameShortcut, false) end pixelVisionOS:EnableMenuItem(NewFolderShortcut, false) -- pixelVisionOS:EnableMenuItem(NewFileShortcut, false) for i = 1, #newFileOptions do pixelVisionOS:EnableMenuItem(newFileOptions[i], false) end -- File options pixelVisionOS:EnableMenuItem(EditShortcut, false) pixelVisionOS:EnableMenuItem(RunShortcut, false) pixelVisionOS:EnableMenuItem(RenameShortcut, false) pixelVisionOS:EnableMenuItem(CopyShortcut, false) pixelVisionOS:EnableMenuItem(PasteShortcut, false) pixelVisionOS:EnableMenuItem(DeleteShortcut, false) -- Disk options pixelVisionOS:EnableMenuItem(EjectDiskShortcut, false) end end function OnLaunchSettings() local editorPath = ReadBiosData("SettingsEditor") if(editorPath == nil) then editorPath = rootPath .."SettingsTool/" end local success = LoadGame(editorPath) end function OnLaunchLog() local editorPath = ReadBiosData("LogEditor") if(editorPath == nil) then editorPath = rootPath .."LogPreviewTool/" end local success = LoadGame(editorPath) end -- This is a helper for changing the text on the title bar function ChangeWindowTitle(pathTitle, titleIconName) -- Clean up the path if(pathTitle:sub(1, 7) == "/Disks/") then pathTitle = pathTitle:sub(7, #pathTitle) elseif(pathTitle:sub(1, 5) == "/Tmp/") then pathTitle = pathTitle:sub(5, #pathTitle) end DrawRect(24, 16, 168, 8, 0, DrawMode.TilemapCache) local maxChars = 43 if(#pathTitle > maxChars) then pathTitle = pathTitle:sub(0, maxChars - 3) .. "..." else pathTitle = string.rpad(pathTitle, maxChars, "") end DrawText(pathTitle:upper(), 19, 17, DrawMode.TilemapCache, "medium", 15, - 4) -- Look for desktop icon -- TODO make sure the correct desktop item is highlighted local pathSplit = string.split(pathTitle, "/") local desktopIconName = pathSplit[1] local iconID = -1 for i = 1, #desktopIcons do if(desktopIcons[i].name == desktopIconName) then iconID = i break end end -- Try to find the icon button if we open a window and its not selected beforehand if(currentOpenIconButton == nil and iconID > 0) then currentOpenIconButton = desktopIconButtons.buttons[iconID] editorUI:OpenIconButton(currentOpenIconButton) end end function CloseWindow() -- Clear the previous scroll history windowScrollHistory = {} closeButton = nil vSliderData = nil windowIconButtons = nil currentSelectedFile = nil currentDirectory = "none" DrawRect(8, 16, windowchrome.width * 8, math.floor(#windowchrome.spriteIDs / windowchrome.width) * 8, BackgroundColor(), DrawMode.TilemapCache) DrawWallpaper() if(activeButton ~= nil) then activeButton.selected = false editorUI:Invalidate(activeButton) activeButton = nil end editorUI:ClearGroupSelections(desktopIconButtons) if(currentOpenIconButton ~= nil) then editorUI:CloseIconButton(currentOpenIconButton) end editorUI:ClearFocus() UpdateContextMenu(NoFocus) -- pixelVisionOS:EnableMenuItem(NewGameShortcut, false) -- pixelVisionOS:EnableMenuItem(NewFolderShortcut, false) -- pixelVisionOS:EnableMenuItem(CopyShortcut, false) -- pixelVisionOS:EnableMenuItem(PasteShortcut, false) -- pixelVisionOS:EnableMenuItem(NewFileShortcut, false) end function OnWindowIconSelect(id) local index = id + (lastStartID)-- TODO need to add the scrolling offset local tmpItem = files[index] local type = tmpItem.type local path = tmpItem.path -- pixelVisionOS:EnableMenuItem(PasteShortcut, type ~= "updirectory" and tmpItem.name ~= "Run") currentSelectedFile = tmpItem editorUI:ClearIconGroupSelections(desktopIconButtons) UpdateContextMenu(WindowIconFocus) end function TrashOpen() return currentDirectory:sub(1, #trashPath) == trashPath end function CanEject() local value = false local id = desktopIconButtons.currentSelection if(id > 0) then local selection = desktopIcons[id] value = selection.name ~= "Workspace" and selection.name ~= "Trash" end return value end function CurrentlySelectedFile() local index = windowIconButtons.currentSelection + lastStartID local tmpItem = files[index] return tmpItem end function OnWindowIconClick(id) -- Make sure desktop icons are not selected editorUI:ClearGroupSelections(desktopIconButtons) -- local index = id + (lastStartID)-- TODO need to add the scrolling offset local tmpItem = CurrentlySelectedFile()-- files[index] local type = tmpItem.type local path = tmpItem.path -- TODO need a list of things we can't delete -- Enable delete option -- print("Window Icon Click", tmpItem.name) local type = tmpItem.type -- If the type is a folder, open it if(type == "folder" or type == "updirectory") then windowScrollHistory[currentDirectory] = vSliderData.value OpenWindow(tmpItem.path) -- Check to see if the file is in the trash elseif(TrashOpen()) then -- Show warning message about trying to edit files in the trash pixelVisionOS:ShowMessageModal(toolName .. " Error", "You are not able to edit files inside of the trash.", 160, false ) -- Check to see if the file is an executable elseif(type == "pv8") then LoadGame(path) -- Check to see if there is an editor for the type or if the type is unknown elseif(editorMapping[type] == nil or type == "unknown") then pixelVisionOS:ShowMessageModal(toolName .. " Error", "There is no tool installed to edit this file.", 160, false ) -- Now we are ready to try to edit a file else -- Find the correct editor from the list local editorPath = editorMapping[type] -- Make sure there is an editor for the file -- if(editorPath ~= nil) then -- -- -- Get the path to the editor from the bios -- local bioPath = ReadBiosData(editors[type].name) -- -- if(newPath ~= nil) then -- editorPath = bioPath -- end -- Set up the meta data for the editor local metaData = { directory = currentDirectory, file = tmpItem.path, filePath = tmpItem.path, -- TODO this should be the root path fileName = tmpItem.fullName, -- introMessage = "Editing '" .. tmpItem.fullName .."'." } -- Check to see if the path to the editor exists if(PathExists(editorPath)) then -- Load the tool LoadGame(editorPath, metaData) -- else -- -- -- Display message if the editor isn't found -- pixelVisionOS:DisplayMessage("The editor for this file is not installed.", 3) -- else -- -- pixelVisionOS:ShowMessageModal(toolName .. " Error", "There is no tool installed to edit this file." .. editorPath, 160, false) -- -- end end -- TODO find an editor for the file's extension end end function OnMenuQuit() QuitCurrentTool() end function OnValueChange(value) local totalPerRow = 3 local totalPerPage = 12 local totalFiles = #files local totalRows = math.ceil(totalFiles / totalPerRow) + 1 local hiddenRows = totalRows - math.ceil(totalPerPage / totalPerRow) local offset = Clamp(hiddenRows * value, 0, hiddenRows - 1) DrawWindow(files, offset * totalPerRow, totalPerPage) end function DrawWindow(files, startID, total) if(startID < 0) then startID = 0 end -- print("DrawWindow", startID) if(lastStartID == startID) then return end -- TODO the icon buttons should have their own clear graphic -- DrawRect(10, 28, 180, 192, 11, DrawMode.TilemapCache) editorUI:ClearIconGroup(windowIconButtons) lastStartID = startID local startX = 13 local startY = 32 local row = 0 local maxColumns = 3 local padding = 16 local width = 48 local height = 40 local bgColor = 11 local isGameDir = pixelVisionOS:ValidateGameInDir(currentDirectory) for i = 1, total do -- Calculate the real index local fileID = i + startID local index = i - 1 -- Update column value local column = index % maxColumns local newX = index % maxColumns * (width + padding) + startX local newY = row * (height + padding / 2) + startY if(fileID <= #files) then local item = files[fileID] -- Find the right type for the file UpdateFileType(item, isGameDir) local spriteName = GetIconSpriteName(item) local toolTip = "Double click to " if(item.name == "Run") then toolTip = toolTip .. "run this game." elseif(item.name == "..") then toolTip = toolTip .. "go to the parent folder." elseif(item.isDirectory == true) then toolTip = toolTip .. "open the " .. item.name .. " folder." else toolTip = toolTip .. "edit " .. item.fullName .. "." end local button = editorUI:NewIconGroupButton(windowIconButtons, {x = newX, y = newY}, spriteName, item.name, toolTip, bgColor) -- -- if(item.type ~= "updirectory" and item.type ~= "folder" and item.type ~= "run") then -- editorUI:Enable(button, not TrashOpen()) -- end -- button.cachedSpriteData.empty = windowemptyicon if (column == (maxColumns - 1)) then row = row + 1 end else DrawRect(newX, newY, 48, 48 - 8, bgColor, DrawMode.TilemapCache) -- DrawSprites(windowemptyicon.spriteIDs, newX, newY, windowemptyicon.width, false, false, DrawMode.TilemapCache) end end end function UpdateFileType(item, isGameFile) local key = item.type--item.isDirectory and item.type or item.ext -- Only convert file types when we are in a game directory if(isGameFile == true) then key = item.type -- TODO support legacy files if(key == "png") then if(item.name == "sprites") then key = "sprites" -- elseif(item.name == "tilemap") then -- key = "tilemap" elseif(item.name == "colors") then key = "colors" end elseif(key == "json") then if(item.name == "sounds")then key = "sounds" elseif(item.name == "tilemap") then key = "tilemap" elseif(item.name == "music") then key = "music" elseif(item.name == "data") then key = "system" end end -- Specific mapping if(key == "font.png") then key = "font" --print("Found font") elseif(key == "sprite.png" or key == "sprites.json") then key = "sprite" elseif(key == "tilemap.png" or key == "tilemap.json") then key = "tilemap" end end if(item.isDirectory == false and item.name ~= "Run") then -- TODO need to look this up based on if an editor is registered with the system if(editorMapping[key] == nil) then key = fileTypeMap[item.ext] and item.ext or "unknown" end end item.type = key end function GetIconSpriteName(item) local iconName = fileTypeMap[item.type] return iconName == nil and "unknown" or fileTypeMap[item.type] end -- The Update() method is part of the game's life cycle. The engine calls Update() on every frame -- before the Draw() method. It accepts one argument, timeDelta, which is the difference in -- milliseconds since the last frame. function Update(timeDelta) if(shuttingDown == true) then return end -- This needs to be the first call to make sure all of the OS and editor UI is updated first pixelVisionOS:Update(timeDelta) -- Only update the tool's UI when the modal isn't active if(pixelVisionOS:IsModalActive() == false) then if(currentDirectory ~= "none") then -- Check for file system changes refreshTime = refreshTime + timeDelta if(refreshTime > refreshDelay) then tmpFiles = GetDirectoryContents(currentDirectory) if(#tmpFiles > fileCount) then RefreshWindow() end refreshTime = 0 end end editorUI:UpdateIconGroup(desktopIconButtons) editorUI:UpdateIconGroup(windowIconButtons) editorUI:UpdateButton(closeButton) editorUI:UpdateSlider(vSliderData) end end -- The Draw() method is part of the game's life cycle. It is called after Update() and is where -- all of our draw calls should go. We'll be using this to render sprites to the display. function Draw() -- We can use the RedrawDisplay() method to clear the screen and redraw the tilemap in a -- single call. RedrawDisplay() if(shuttingDown == true) then return end -- The UI should be the last thing to draw after your own custom draw calls pixelVisionOS:Draw() end function Shutdown() -- print("File Tool Shutdown", SessionID(), currentDirectory) -- Save the current session ID WriteSaveData("sessionID", SessionID()) -- Make sure we don't save paths in the tmp directory WriteSaveData("lastPath", currentDirectory) -- Save the current session ID WriteSaveData("scrollPos", (vSliderData ~= nil and vSliderData.value or 0)) -- Save the current selection WriteSaveData("selection", (windowIconButtons ~= nil and editorUI:ToggleGroupSelections(windowIconButtons)[1] or 0)) end
local base = require('imgui.Widget') ---@class im.Selectable:im.Widget local M = class('im.Selectable', base) function M:ctor(...) base.ctor(self, ...) end function M:setLabel(label) self:setParam(1, label) return self end function M:getLabel() return self:getParam(1) end function M:setSelected(label) self:setParam(2, label) return self end function M:getSelected() return self:getParam(2) end function M:setFlags(flag, ...) self:setParam(3, bit.bor(flag, ...)) return self end function M:getFlags() return self:getParam(3) end function M:setContentSize(size) base.setContentSize(self, size) self:setParam(4, imgui.size(size)) return self end function M:getContentSize() return imgui.toccsize(self:getParam(4)) end function M:setOnSelect(f) self._onsel = f return self end function M:_handler() local ret imgui.pushID(tostring(self)) ret = { imgui.selectable(unpack(self._param)) } imgui.popID() self._ret = ret if ret[1] and self._onsel then self:_onsel() end base._handler(self) end return M
--[[ Globals ]]-- local args = {...} local computer = args[1] local env = setmetatable( {}, {__index = computer.env} ) -- FILE / INPUT READING function env.load( fn, name, mode, e ) return load( fn, name, mode or "bt", e or computer.env ) end function env.loadfile(path) return setfenv( love.filesystem.load(env.disk.absolute(path)), computer.env ) end function env.loadstring( str, name, mode, e ) return load( str, name, mode or "bt", e or computer.env ) end function env.require(path) expect( path, "string" ) local before = {"/", "/disk1/", "/disk1/lib/", "/rom/lib"} local after = {"", ".lua"} -- Add source path of file to search path local source = debug.getinfo(2).source if source and string.sub(source,1,1) == "@" then table.insert( before, 1, env.disk.getPath( string.sub(source,2) ) ) end for i = 1, #before do for j = 1, #after do local p = env.disk.absolute( before[i]..env.disk.absolute(path)..after[j] ) if env.disk.exists(p) then local file = env.disk.read(p) local fn, err = load( file, "="..env.disk.getFilename(p), "bt", computer.env ) if not fn then error( err, 2 ) end return fn() end end end error( "Couldn't find "..path, 2 ) end -- LUA EXTENSIONS / MODIFICATIONS function env.getfenv(level) expect( level, {"number", "nil"} ) level = level or 1 if level == 0 then return env._G elseif level >= 1 then local e = getfenv(level+1) if e == _G then return env._G else return e end else error( "bad agrument #1 to 'getfenv' (invalid level)", 2 ) -- Mimic standard lua error end end env.expect = expect -- RETURN return env
--- View is a clipped rectangular area where the scene is rendered. -- Views can be transformed, drawn and easily shaded. -- @module view -- @alias view -- @inherit layer local view = {} local viewMT = { __index = view } local reg = debug.getregistry() reg.View = view setmetatable(view, { __index = reg.Layer }) local lg = love.graphics local lg_origin = lg.origin local lg_setBlendMode = lg.setBlendMode local lg_setCanvas = lg.setCanvas local lg_newCanvas = lg.newCanvas local lg_clear = lg.clear local lg_setScissor = lg.setScissor local lg_setColor = lg.setColor local lg_rectangle = lg.rectangle local lg_push = lg.push local lg_translate = lg.translate local lg_scale = lg.scale local lg_rotate = lg.rotate local lg_pop = lg.pop local lg_reset = lg.reset local lg_setShader = lg.setShader local lg_getDimensions = lg.getDimensions local lg_draw = lg.draw --- This is an internal function. -- Please use @{scene.newView} instead. -- @tparam[opt] number x X-position in pixels -- @tparam[opt] number y Y-position in pixels -- @tparam[opt] number width Width in pixels -- @tparam[opt] number height Height in pixels -- @tparam[opt] table mt Metatable of base object -- @treturn view New view object -- @see scene.newView function view.new(vx, vy, vw, vh, mt) if vx == nil then vx, vy = 0, 0 vw, vh = lg_getDimensions() end local t = reg.Layer.new(0, 0, mt or viewMT) t.vx, t.vy = vx, vy t.vw, t.vh = vw, vh t.cx, t.cy = vw/2, vh/2 t.background = { 0, 0, 0, 1 } return t end --- Destroys the view and all of its children. function view:destroy() self.background = nil reg.Layer.destroy(self) end --- Sets the position and dimensions of the view inside the game window. -- @tparam number x X-position in pixels -- @tparam number y Y-position in pixels -- @tparam number width Width in pixels -- @tparam number height Height in pixels -- @see view:getBounds function view:setBounds(vx, vy, vw, vh) self.vx, self.vy = vx, vy vw = math.ceil(vw) vh = math.ceil(vh) if self.vw == vw and self.vh == vh then return end self.vw, self.vh = vw, vh self.cx, self.cy = vw/2, vh/2 if self.canvas then local ok, canvas = pcall(lg_newCanvas, vw, vh) self.canvas = ok and canvas end end --- Gets the position and dimensions of the view inside the game window. -- @treturn number X-position in pixels -- @treturn number Y-position in pixels -- @treturn number Width in pixels -- @treturn number Height in pixels -- @see view:setBounds function view:getBounds() return self.vx, self.vy, self.vw, self.vh end --- Gets the dimensions of the view inside the game window. -- @treturn number Width in pixels -- @treturn number Height in pixels -- @see view:setDimensions function view:getDimensions() return self.vw, self.vh end --- Sets the dimensions of the view inside the game window. -- @tparam number width Width in pixels -- @tparam number height Height in pixels -- @see view:getDimensions function view:setDimensions(vw, vh) self:setBounds(self.vx, self.vy, vw, vh) end --- Sets the visible range in scene coordinates. -- The specified position will be drawn in the center of the view. -- @tparam number x Scene X-coordinate -- @tparam number y Scene Y-coordinate -- @tparam[opt] number width Range width -- @tparam[opt] number height Range height -- @see view:getScene function view:setScene(x, y, w, h) self.x = x self.y = y if w and h then self.sx = self.vw/w self.sy = self.vh/h end end --- Gets the visible range in scene coordinates. -- The returned position is drawn in the center of the view. -- @treturn number Scene X-coordinate -- @treturn number Scene Y-coordinate -- @treturn[opt] number Range width -- @treturn[opt] number Range height -- @see view:setScene function view:getScene() local w, h = self.vw/self.sx, self.vh/self.sy return self.x, self.y, w, h end --- Sets the background color. -- @tparam number red Red value (0-1) -- @tparam number green Green value (0-1) -- @tparam number blue Blue value (0-1) -- @tparam[opt] number alpha Alpha value (0-1) -- @see view:getBackground function view:setBackground(r, g, b, a) if type(r) == "table" then r, g, b, a = unpack(r) end a = a or 1 local bg = self.background bg[1], bg[2], bg[3], bg[4] = r, g, b, a end --- Gets the background color. -- @treturn number Red value (0-1) -- @treturn number Green value (0-1) -- @treturn number Blue value (0-1) -- @treturn number Alpha value (0-1) -- @see view:setBackground function view:getBackground() local bg = self.background return bg[1], bg[2], bg[3], bg[4] end --- Sets the pixel shader. -- @tparam[opt] userdata shader Pixel shader object -- @see view:getShader function view:setShader(shader) if self.shader == shader then return end self.shader = shader if shader and not self.canvas then local ok, canvas = pcall(lg_newCanvas, self.vw, self.vh) self.canvas = ok and canvas end end --- Gets the pixel shader. -- @treturn userdata Pixel shader object -- @see view:setShader function view:getShader() return self.shader end --- Draws the view and all of its visible child nodes. function view:draw() if not self.visible then return end local vx, vy, vw, vh = self:getBounds() local canvas = self.canvas local shader = self.shader lg_origin() lg_setBlendMode("alpha", "alphamultiply") if canvas and shader then lg_setCanvas(canvas) lg_clear(self.background) else lg_setScissor(vx, vy, vw, vh) lg_setColor(self.background) lg_rectangle("fill", vx, vy, vw, vh) end lg_push("transform") if not canvas then lg_translate(vx, vy) end lg_translate(self.cx, self.cy) lg_scale(self.sx, self.sy) lg_rotate(self.r) lg_translate(-self.x, self.y) for _, v in ipairs(self.list) do v:draw() end lg_pop() if canvas and shader then lg_setCanvas() lg_reset() lg_setShader(shader) lg_draw(canvas, vx, vy) lg_setShader() else lg_setScissor() end end --- Converts a position from local to scene coordinates. -- The origin of the scene is the center of the root @{layer}. -- @tparam number x Local X-coordinate -- @tparam number y Local Y-coordinate -- @treturn number Scene X-coordinate -- @treturn number Scene Y-coordinate -- @see view:sceneToLocal function view:localToScene(x, y) return x, y end --- Converts a position from scene to local coordinates. -- The origin of the scene is the center of the root @{layer}. -- @tparam number x Scene X-coordinate -- @tparam number y Scene Y-coordinate -- @treturn number Local X-coordinate -- @treturn number Local Y-coordinate -- @see view:localToScene function view:sceneToLocal(x, y) return x, y end --- Converts a position from window to scene coordinates. -- The origin of the scene is the center of the root @{layer}. -- @tparam number x X window coordinate -- @tparam number y Y window coordinate -- @treturn number X scene coordinate -- @treturn number Y scene coordinate -- @see view:sceneToWindow function view:windowToScene(x, y) -- origin (center of the viewport) x = x - self.cx y = y - self.cy -- flip (y-axis increases up) y = -y -- transform x, y = self:localToParent(x, y) return x, y end --- Converts a position from scene to window coordinates. -- The origin of the scene is the center of the root @{layer}. -- @tparam number x X scene coordinate -- @tparam number y Y scene coordinate -- @treturn number X window coordinate -- @treturn number Y window coordinate -- @see view:windowToScene function view:sceneToWindow(x, y) -- transform x, y = self:parentToLocal(x, y) -- flip (y-axis increases down) y = -y -- origin (top left of the window) x = self.cx + x y = self.cy + y return x, y end return view.new
Mining = {} Mining.Core = {} Mining.Database = {} Mining.Users = {} Mining.Config = {} print("Loading XYZ Mining System") local path = "xyz_mining/" if SERVER then local files, folders = file.Find(path .. "*", "LUA") for _, folder in SortedPairs(folders, true) do print("Loading folder:", folder) for b, File in SortedPairs(file.Find(path .. folder .. "/sh_*.lua", "LUA"), true) do print("Loading file:", File) AddCSLuaFile(path .. folder .. "/" .. File) include(path .. folder .. "/" .. File) end for b, File in SortedPairs(file.Find(path .. folder .. "/sv_*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end for b, File in SortedPairs(file.Find(path .. folder .. "/cl_*.lua", "LUA"), true) do print("Loading file:", File) AddCSLuaFile(path .. folder .. "/" .. File) end end end if CLIENT then local files, folders = file.Find(path .. "*", "LUA") for _, folder in SortedPairs(folders, true) do print("Loading folder:", folder) for b, File in SortedPairs(file.Find(path .. folder .. "/sh_*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end for b, File in SortedPairs(file.Find(path .. folder .. "/cl_*.lua", "LUA"), true) do print("Loading file:", File) include(path .. folder .. "/" .. File) end end end print("Loaded XYZ Mining System")
local model = remodel.readModelFile("test-models/folder-and-value.rbxmx")[1] assert(model.Name == "Root") model.Name = "Foo" assert(model.Name == "Foo")
--- GENERATED CODE - DO NOT MODIFY -- Amazon Kinesis Video Streams Media (kinesis-video-media-2017-09-30) local M = {} M.metadata = { api_version = "2017-09-30", json_version = "", protocol = "rest-json", checksum_format = "", endpoint_prefix = "kinesisvideo", service_abbreviation = "Kinesis Video Media", service_full_name = "Amazon Kinesis Video Streams Media", signature_version = "v4", target_prefix = "", timestamp_format = "", global_endpoint = "", uid = "kinesis-video-media-2017-09-30", } local keys = {} local asserts = {} keys.InvalidEndpointException = { ["Message"] = true, nil } function asserts.AssertInvalidEndpointException(struct) assert(struct) assert(type(struct) == "table", "Expected InvalidEndpointException to be of type 'table'") if struct["Message"] then asserts.AssertErrorMessage(struct["Message"]) end for k,_ in pairs(struct) do assert(keys.InvalidEndpointException[k], "InvalidEndpointException contains unknown key " .. tostring(k)) end end --- Create a structure of type InvalidEndpointException -- <p> Status Code: 400, Caller used wrong endpoint to write data to a stream. On receiving such an exception, the user must call <code>GetDataEndpoint</code> with <code>AccessMode</code> set to "READ" and use the endpoint Kinesis Video returns in the next <code>GetMedia</code> call. </p> -- @param args Table with arguments in key-value form. -- Valid keys: -- * Message [ErrorMessage] -- @return InvalidEndpointException structure as a key-value pair table function M.InvalidEndpointException(args) assert(args, "You must provide an argument table when creating InvalidEndpointException") local query_args = { } local uri_args = { } local header_args = { } local all_args = { ["Message"] = args["Message"], } asserts.AssertInvalidEndpointException(all_args) return { all = all_args, query = query_args, uri = uri_args, headers = header_args, } end keys.GetMediaOutput = { ["ContentType"] = true, ["Payload"] = true, nil } function asserts.AssertGetMediaOutput(struct) assert(struct) assert(type(struct) == "table", "Expected GetMediaOutput to be of type 'table'") if struct["ContentType"] then asserts.AssertContentType(struct["ContentType"]) end if struct["Payload"] then asserts.AssertPayload(struct["Payload"]) end for k,_ in pairs(struct) do assert(keys.GetMediaOutput[k], "GetMediaOutput contains unknown key " .. tostring(k)) end end --- Create a structure of type GetMediaOutput -- -- @param args Table with arguments in key-value form. -- Valid keys: -- * ContentType [ContentType] <p>The content type of the requested media.</p> -- * Payload [Payload] <p> The payload Kinesis Video Streams returns is a sequence of chunks from the specified stream. For information about the chunks, see . The chunks that Kinesis Video Streams returns in the <code>GetMedia</code> call also include the following additional Matroska (MKV) tags: </p> <ul> <li> <p>AWS_KINESISVIDEO_CONTINUATION_TOKEN (UTF-8 string) - In the event your <code>GetMedia</code> call terminates, you can use this continuation token in your next request to get the next chunk where the last request terminated.</p> </li> <li> <p>AWS_KINESISVIDEO_MILLIS_BEHIND_NOW (UTF-8 string) - Client applications can use this tag value to determine how far behind the chunk returned in the response is from the latest chunk on the stream. </p> </li> <li> <p>AWS_KINESISVIDEO_FRAGMENT_NUMBER - Fragment number returned in the chunk.</p> </li> <li> <p>AWS_KINESISVIDEO_SERVER_TIMESTAMP - Server time stamp of the fragment.</p> </li> <li> <p>AWS_KINESISVIDEO_PRODUCER_TIMESTAMP - Producer time stamp of the fragment.</p> </li> </ul> <p>The following tags will be present if an error occurs:</p> <ul> <li> <p>AWS_KINESISVIDEO_ERROR_CODE - String description of an error that caused GetMedia to stop.</p> </li> <li> <p>AWS_KINESISVIDEO_ERROR_ID: Integer code of the error.</p> </li> </ul> <p>The error codes are as follows:</p> <ul> <li> <p>3002 - Error writing to the stream</p> </li> <li> <p>4000 - Requested fragment is not found</p> </li> <li> <p>4500 - Access denied for the stream's KMS key</p> </li> <li> <p>4501 - Stream's KMS key is disabled</p> </li> <li> <p>4502 - Validation error on the Stream's KMS key</p> </li> <li> <p>4503 - KMS key specified in the stream is unavailable</p> </li> <li> <p>4504 - Invalid usage of the KMS key specified in the stream</p> </li> <li> <p>4505 - Invalid state of the KMS key specified in the stream</p> </li> <li> <p>4506 - Unable to find the KMS key specified in the stream</p> </li> <li> <p>5000 - Internal error</p> </li> </ul> -- @return GetMediaOutput structure as a key-value pair table function M.GetMediaOutput(args) assert(args, "You must provide an argument table when creating GetMediaOutput") local query_args = { } local uri_args = { } local header_args = { ["Content-Type"] = args["ContentType"], } local all_args = { ["ContentType"] = args["ContentType"], ["Payload"] = args["Payload"], } asserts.AssertGetMediaOutput(all_args) return { all = all_args, query = query_args, uri = uri_args, headers = header_args, } end keys.ClientLimitExceededException = { ["Message"] = true, nil } function asserts.AssertClientLimitExceededException(struct) assert(struct) assert(type(struct) == "table", "Expected ClientLimitExceededException to be of type 'table'") if struct["Message"] then asserts.AssertErrorMessage(struct["Message"]) end for k,_ in pairs(struct) do assert(keys.ClientLimitExceededException[k], "ClientLimitExceededException contains unknown key " .. tostring(k)) end end --- Create a structure of type ClientLimitExceededException -- <p>Kinesis Video Streams has throttled the request because you have exceeded the limit of allowed client calls. Try making the call later.</p> -- @param args Table with arguments in key-value form. -- Valid keys: -- * Message [ErrorMessage] -- @return ClientLimitExceededException structure as a key-value pair table function M.ClientLimitExceededException(args) assert(args, "You must provide an argument table when creating ClientLimitExceededException") local query_args = { } local uri_args = { } local header_args = { } local all_args = { ["Message"] = args["Message"], } asserts.AssertClientLimitExceededException(all_args) return { all = all_args, query = query_args, uri = uri_args, headers = header_args, } end keys.GetMediaInput = { ["StreamName"] = true, ["StreamARN"] = true, ["StartSelector"] = true, nil } function asserts.AssertGetMediaInput(struct) assert(struct) assert(type(struct) == "table", "Expected GetMediaInput to be of type 'table'") assert(struct["StartSelector"], "Expected key StartSelector to exist in table") if struct["StreamName"] then asserts.AssertStreamName(struct["StreamName"]) end if struct["StreamARN"] then asserts.AssertResourceARN(struct["StreamARN"]) end if struct["StartSelector"] then asserts.AssertStartSelector(struct["StartSelector"]) end for k,_ in pairs(struct) do assert(keys.GetMediaInput[k], "GetMediaInput contains unknown key " .. tostring(k)) end end --- Create a structure of type GetMediaInput -- -- @param args Table with arguments in key-value form. -- Valid keys: -- * StreamName [StreamName] <p>The Kinesis video stream name from where you want to get the media content. If you don't specify the <code>streamName</code>, you must specify the <code>streamARN</code>.</p> -- * StreamARN [ResourceARN] <p>The ARN of the stream from where you want to get the media content. If you don't specify the <code>streamARN</code>, you must specify the <code>streamName</code>.</p> -- * StartSelector [StartSelector] <p>Identifies the starting chunk to get from the specified stream. </p> -- Required key: StartSelector -- @return GetMediaInput structure as a key-value pair table function M.GetMediaInput(args) assert(args, "You must provide an argument table when creating GetMediaInput") local query_args = { } local uri_args = { } local header_args = { } local all_args = { ["StreamName"] = args["StreamName"], ["StreamARN"] = args["StreamARN"], ["StartSelector"] = args["StartSelector"], } asserts.AssertGetMediaInput(all_args) return { all = all_args, query = query_args, uri = uri_args, headers = header_args, } end keys.NotAuthorizedException = { ["Message"] = true, nil } function asserts.AssertNotAuthorizedException(struct) assert(struct) assert(type(struct) == "table", "Expected NotAuthorizedException to be of type 'table'") if struct["Message"] then asserts.AssertErrorMessage(struct["Message"]) end for k,_ in pairs(struct) do assert(keys.NotAuthorizedException[k], "NotAuthorizedException contains unknown key " .. tostring(k)) end end --- Create a structure of type NotAuthorizedException -- <p>Status Code: 403, The caller is not authorized to perform an operation on the given stream, or the token has expired.</p> -- @param args Table with arguments in key-value form. -- Valid keys: -- * Message [ErrorMessage] -- @return NotAuthorizedException structure as a key-value pair table function M.NotAuthorizedException(args) assert(args, "You must provide an argument table when creating NotAuthorizedException") local query_args = { } local uri_args = { } local header_args = { } local all_args = { ["Message"] = args["Message"], } asserts.AssertNotAuthorizedException(all_args) return { all = all_args, query = query_args, uri = uri_args, headers = header_args, } end keys.InvalidArgumentException = { ["Message"] = true, nil } function asserts.AssertInvalidArgumentException(struct) assert(struct) assert(type(struct) == "table", "Expected InvalidArgumentException to be of type 'table'") if struct["Message"] then asserts.AssertErrorMessage(struct["Message"]) end for k,_ in pairs(struct) do assert(keys.InvalidArgumentException[k], "InvalidArgumentException contains unknown key " .. tostring(k)) end end --- Create a structure of type InvalidArgumentException -- <p>The value for this input parameter is invalid.</p> -- @param args Table with arguments in key-value form. -- Valid keys: -- * Message [ErrorMessage] -- @return InvalidArgumentException structure as a key-value pair table function M.InvalidArgumentException(args) assert(args, "You must provide an argument table when creating InvalidArgumentException") local query_args = { } local uri_args = { } local header_args = { } local all_args = { ["Message"] = args["Message"], } asserts.AssertInvalidArgumentException(all_args) return { all = all_args, query = query_args, uri = uri_args, headers = header_args, } end keys.ConnectionLimitExceededException = { ["Message"] = true, nil } function asserts.AssertConnectionLimitExceededException(struct) assert(struct) assert(type(struct) == "table", "Expected ConnectionLimitExceededException to be of type 'table'") if struct["Message"] then asserts.AssertErrorMessage(struct["Message"]) end for k,_ in pairs(struct) do assert(keys.ConnectionLimitExceededException[k], "ConnectionLimitExceededException contains unknown key " .. tostring(k)) end end --- Create a structure of type ConnectionLimitExceededException -- <p>Kinesis Video Streams has throttled the request because you have exceeded the limit of allowed client connections.</p> -- @param args Table with arguments in key-value form. -- Valid keys: -- * Message [ErrorMessage] -- @return ConnectionLimitExceededException structure as a key-value pair table function M.ConnectionLimitExceededException(args) assert(args, "You must provide an argument table when creating ConnectionLimitExceededException") local query_args = { } local uri_args = { } local header_args = { } local all_args = { ["Message"] = args["Message"], } asserts.AssertConnectionLimitExceededException(all_args) return { all = all_args, query = query_args, uri = uri_args, headers = header_args, } end keys.StartSelector = { ["StartSelectorType"] = true, ["StartTimestamp"] = true, ["AfterFragmentNumber"] = true, ["ContinuationToken"] = true, nil } function asserts.AssertStartSelector(struct) assert(struct) assert(type(struct) == "table", "Expected StartSelector to be of type 'table'") assert(struct["StartSelectorType"], "Expected key StartSelectorType to exist in table") if struct["StartSelectorType"] then asserts.AssertStartSelectorType(struct["StartSelectorType"]) end if struct["StartTimestamp"] then asserts.AssertTimestamp(struct["StartTimestamp"]) end if struct["AfterFragmentNumber"] then asserts.AssertFragmentNumberString(struct["AfterFragmentNumber"]) end if struct["ContinuationToken"] then asserts.AssertContinuationToken(struct["ContinuationToken"]) end for k,_ in pairs(struct) do assert(keys.StartSelector[k], "StartSelector contains unknown key " .. tostring(k)) end end --- Create a structure of type StartSelector -- <p>Identifies the chunk on the Kinesis video stream where you want the <code>GetMedia</code> API to start returning media data. You have the following options to identify the starting chunk: </p> <ul> <li> <p>Choose the latest (or oldest) chunk.</p> </li> <li> <p>Identify a specific chunk. You can identify a specific chunk either by providing a fragment number or time stamp (server or producer). </p> </li> <li> <p>Each chunk's metadata includes a continuation token as a Matroska (MKV) tag (<code>AWS_KINESISVIDEO_CONTINUATION_TOKEN</code>). If your previous <code>GetMedia</code> request terminated, you can use this tag value in your next <code>GetMedia</code> request. The API then starts returning chunks starting where the last API ended.</p> </li> </ul> -- @param args Table with arguments in key-value form. -- Valid keys: -- * StartSelectorType [StartSelectorType] <p>Identifies the fragment on the Kinesis video stream where you want to start getting the data from.</p> <ul> <li> <p>NOW - Start with the latest chunk on the stream.</p> </li> <li> <p>EARLIEST - Start with earliest available chunk on the stream.</p> </li> <li> <p>FRAGMENT_NUMBER - Start with the chunk containing the specific fragment. You must also specify the <code>StartFragmentNumber</code>.</p> </li> <li> <p>PRODUCER_TIMESTAMP or SERVER_TIMESTAMP - Start with the chunk containing a fragment with the specified producer or server time stamp. You specify the time stamp by adding <code>StartTimestamp</code>.</p> </li> <li> <p> CONTINUATION_TOKEN - Read using the specified continuation token. </p> </li> </ul> <note> <p>If you choose the NOW, EARLIEST, or CONTINUATION_TOKEN as the <code>startSelectorType</code>, you don't provide any additional information in the <code>startSelector</code>.</p> </note> -- * StartTimestamp [Timestamp] <p>A time stamp value. This value is required if you choose the PRODUCER_TIMESTAMP or the SERVER_TIMESTAMP as the <code>startSelectorType</code>. The <code>GetMedia</code> API then starts with the chunk containing the fragment that has the specified time stamp.</p> -- * AfterFragmentNumber [FragmentNumberString] <p>Specifies the fragment number from where you want the <code>GetMedia</code> API to start returning the fragments. </p> -- * ContinuationToken [ContinuationToken] <p>Continuation token that Kinesis Video Streams returned in the previous <code>GetMedia</code> response. The <code>GetMedia</code> API then starts with the chunk identified by the continuation token.</p> -- Required key: StartSelectorType -- @return StartSelector structure as a key-value pair table function M.StartSelector(args) assert(args, "You must provide an argument table when creating StartSelector") local query_args = { } local uri_args = { } local header_args = { } local all_args = { ["StartSelectorType"] = args["StartSelectorType"], ["StartTimestamp"] = args["StartTimestamp"], ["AfterFragmentNumber"] = args["AfterFragmentNumber"], ["ContinuationToken"] = args["ContinuationToken"], } asserts.AssertStartSelector(all_args) return { all = all_args, query = query_args, uri = uri_args, headers = header_args, } end keys.ResourceNotFoundException = { ["Message"] = true, nil } function asserts.AssertResourceNotFoundException(struct) assert(struct) assert(type(struct) == "table", "Expected ResourceNotFoundException to be of type 'table'") if struct["Message"] then asserts.AssertErrorMessage(struct["Message"]) end for k,_ in pairs(struct) do assert(keys.ResourceNotFoundException[k], "ResourceNotFoundException contains unknown key " .. tostring(k)) end end --- Create a structure of type ResourceNotFoundException -- <p>Status Code: 404, The stream with the given name does not exist.</p> -- @param args Table with arguments in key-value form. -- Valid keys: -- * Message [ErrorMessage] -- @return ResourceNotFoundException structure as a key-value pair table function M.ResourceNotFoundException(args) assert(args, "You must provide an argument table when creating ResourceNotFoundException") local query_args = { } local uri_args = { } local header_args = { } local all_args = { ["Message"] = args["Message"], } asserts.AssertResourceNotFoundException(all_args) return { all = all_args, query = query_args, uri = uri_args, headers = header_args, } end function asserts.AssertFragmentNumberString(str) assert(str) assert(type(str) == "string", "Expected FragmentNumberString to be of type 'string'") assert(#str <= 128, "Expected string to be max 128 characters") assert(#str >= 1, "Expected string to be min 1 characters") end -- function M.FragmentNumberString(str) asserts.AssertFragmentNumberString(str) return str end function asserts.AssertStreamName(str) assert(str) assert(type(str) == "string", "Expected StreamName to be of type 'string'") assert(#str <= 256, "Expected string to be max 256 characters") assert(#str >= 1, "Expected string to be min 1 characters") end -- function M.StreamName(str) asserts.AssertStreamName(str) return str end function asserts.AssertContentType(str) assert(str) assert(type(str) == "string", "Expected ContentType to be of type 'string'") assert(#str <= 128, "Expected string to be max 128 characters") assert(#str >= 1, "Expected string to be min 1 characters") end -- function M.ContentType(str) asserts.AssertContentType(str) return str end function asserts.AssertStartSelectorType(str) assert(str) assert(type(str) == "string", "Expected StartSelectorType to be of type 'string'") end -- function M.StartSelectorType(str) asserts.AssertStartSelectorType(str) return str end function asserts.AssertErrorMessage(str) assert(str) assert(type(str) == "string", "Expected ErrorMessage to be of type 'string'") end -- function M.ErrorMessage(str) asserts.AssertErrorMessage(str) return str end function asserts.AssertContinuationToken(str) assert(str) assert(type(str) == "string", "Expected ContinuationToken to be of type 'string'") assert(#str <= 128, "Expected string to be max 128 characters") assert(#str >= 1, "Expected string to be min 1 characters") end -- function M.ContinuationToken(str) asserts.AssertContinuationToken(str) return str end function asserts.AssertResourceARN(str) assert(str) assert(type(str) == "string", "Expected ResourceARN to be of type 'string'") assert(#str <= 1024, "Expected string to be max 1024 characters") assert(#str >= 1, "Expected string to be min 1 characters") end -- function M.ResourceARN(str) asserts.AssertResourceARN(str) return str end function asserts.AssertTimestamp(timestamp) assert(timestamp) assert(type(timestamp) == "string", "Expected Timestamp to be of type 'string'") end function M.Timestamp(timestamp) asserts.AssertTimestamp(timestamp) return timestamp end function asserts.AssertPayload(blob) assert(blob) assert(type(string) == "string", "Expected Payload to be of type 'string'") end function M.Payload(blob) asserts.AssertPayload(blob) return blob end local content_type = require "aws-sdk.core.content_type" local request_headers = require "aws-sdk.core.request_headers" local request_handlers = require "aws-sdk.core.request_handlers" local settings = {} local function endpoint_for_region(region, use_dualstack) if not use_dualstack then if region == "us-east-1" then return "kinesisvideo.amazonaws.com" end end local ss = { "kinesisvideo" } if use_dualstack then ss[#ss + 1] = "dualstack" end ss[#ss + 1] = region ss[#ss + 1] = "amazonaws.com" if region == "cn-north-1" then ss[#ss + 1] = "cn" end return table.concat(ss, ".") end function M.init(config) assert(config, "You must provide a config table") assert(config.region, "You must provide a region in the config table") settings.service = M.metadata.endpoint_prefix settings.protocol = M.metadata.protocol settings.region = config.region settings.endpoint = config.endpoint_override or endpoint_for_region(config.region, config.use_dualstack) settings.signature_version = M.metadata.signature_version settings.uri = (config.scheme or "https") .. "://" .. settings.endpoint end -- -- OPERATIONS -- --- Call GetMedia asynchronously, invoking a callback when done -- @param GetMediaInput -- @param cb Callback function accepting three args: response, error_type, error_message function M.GetMediaAsync(GetMediaInput, cb) assert(GetMediaInput, "You must provide a GetMediaInput") local headers = { [request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version), [request_headers.AMZ_TARGET_HEADER] = ".GetMedia", } for header,value in pairs(GetMediaInput.headers) do headers[header] = value end local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "POST") if request_handler then request_handler(settings.uri, "/getMedia", GetMediaInput, headers, settings, cb) else cb(false, err) end end --- Call GetMedia synchronously, returning when done -- This assumes that the function is called from within a coroutine -- @param GetMediaInput -- @return response -- @return error_type -- @return error_message function M.GetMediaSync(GetMediaInput, ...) local co = coroutine.running() assert(co, "You must call this function from within a coroutine") M.GetMediaAsync(GetMediaInput, function(response, error_type, error_message) assert(coroutine.resume(co, response, error_type, error_message)) end) return coroutine.yield() end return M
-- Copyright (c) 2011 by Robert G. Jakabosky <bobby@sharedrealm.com> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local type = type local pairs = pairs module(...) -- -- Simple table dup function -- local function copy_recur(seen, tab) if type(tab) ~= 'table' then return tab end local new = seen[tab] -- if this table has been copied. if new then return new end -- create new table. new = {} seen[tab] = new -- copy values from table to new table. for k,v in pairs(tab) do k = copy_recur(seen, k) v = copy_recur(seen, v) new[k] = v end return new end function copy(tab) if tab then local seen = {} return copy_recur(seen, tab) end return tab end
local talk_count = 1 local shout_count = 1 local done = false local shout_again = false local stop_walk = false mother_gone = false father_animation_count = 1 father_x = 12 father_speed = 15 mother_animation_count = 1 mother_x = 20 mother_speed = 15 function animation_set() --splash local splash = anim8.newGrid(64,32,images.splash:getDimensions()) splash_anim = anim8.newAnimation(splash('1-5',1),0.25, function() splash_anim:pauseAtEnd() --states = "title" splash_finished = true end) --player local g = anim8.newGrid(8,16, images.player_sheet:getWidth(), images.player_sheet:getHeight()) idle = anim8.newAnimation(g('1-2',1),1) walk_right = anim8.newAnimation(g('3-6',1), 0.25) walk_left = anim8.newAnimation(g('3-6',1), 0.25):flipH() local _fs = anim8.newGrid(11,18,images.f_shot_sheet:getWidth(),images.f_shot_sheet:getHeight()) f_shot_anim = anim8.newAnimation(_fs('1-5',1),0.2,function() f_shot_anim:pauseAtEnd() f_shot_anim2_flag = true sounds.gunshot:play() sounds.gunshot:setLooping(false) end) f_shot_anim2 = anim8.newAnimation(_fs('6-15',1),0.1, function() f_shot_anim2:pauseAtEnd() lr_event = 5 end) --leave sequence local _fleave = anim8.newGrid(11,18,images.f_leave:getWidth(),images.f_leave:getHeight()) f_leave = anim8.newAnimation(_fleave('1-45',1),0.5,function() f_leave:pauseAtEnd() end) f_headbang = anim8.newAnimation(_fleave('39-45',1),0.5,function() sounds.smash_head:play() sounds.smash_head:setLooping(false) end) local _pk = anim8.newGrid(8,16,images.player_killed_sheet:getWidth(),images.player_killed_sheet:getHeight()) player_killed = anim8.newAnimation(_pk('1-14',1),0.2, function() player_killed:pauseAtEnd() en_anim = "mys" fade_to_black = true end) local _pp = anim8.newGrid(8,16,images.player_panic_sheet:getWidth(),images.player_panic_sheet:getHeight()) player_panic = anim8.newAnimation(_pp('1-8',1),1,function() player_panic:pauseAtEnd() player_ending_shot = true end) local _shoot_pose = anim8.newGrid(8,16, images.shoot_pose_sheet:getWidth(), images.shoot_pose_sheet:getHeight()) shoot_pose_anim = anim8.newAnimation(_shoot_pose('1-3',1),0.3, "pauseAtEnd") local _reload = anim8.newGrid(8,16, images.reload_sheet:getWidth(),images.reload_sheet:getHeight()) reload_anim = anim8.newAnimation(_reload('1-4',1),0.3,function() reload_anim:pauseAtStart() reload_animate = false ending_animate = false end) local _leave = anim8.newGrid(8,16,images.leave_sheet:getWidth(),images.leave_sheet:getHeight()) leave_anim = anim8.newAnimation(_leave('1-4',1),0.3, function() leave_anim:pauseAtEnd() end) wait_anim = anim8.newAnimation(_shoot_pose('3-1',1),0.3,function() wait_anim:pauseAtEnd() end) --father local _f = anim8.newGrid(11,18,images.father_sheet:getWidth(),images.father_sheet:getHeight()) father_anim = { --talk anim8.newAnimation(_f('1-2',1),0.5, function() if done == true then father_anim[1]:pauseAtStart() end if talk_count < 4 then talk_count = talk_count + 1 else father_anim[1]:pauseAtStart() father_animation_count = father_animation_count + 1 end end), -- shout anim8.newAnimation(_f('3-4',1),0.5, function() if father_move == true then father_anim[2]:pauseAtStart() father_animation_count = father_animation_count + 1 end if shout == true then father_anim[2]:pauseAtEnd() father_animation_count = 4 mother_animation_count = 4 end end), --walk anim8.newAnimation(_f('5-8',1),0.15, function() if father_x >= 55 then father_x = 60 shout_again = false father_move = false father_anim[3]:pauseAtStart() father_animation_count = 2 father_anim[2]:resume() shout = true end end), --push anim8.newAnimation(_f('9-14',1),0.25, function() sounds.mother_scream:play() sounds.mother_scream:setLooping(false) done = true father_animation_count = 1 end) } --mother local _m = anim8.newGrid(11,17,images.mother_sheet:getWidth(),images.mother_sheet:getHeight()) mother_anim = { --talk anim8.newAnimation(_m('1-2',1),0.5, function() if talk_count < 2 then talk_count = talk_count + 1 else mother_anim[1]:pauseAtStart() mother_animation_count = mother_animation_count + 1 end end), --shout anim8.newAnimation(_m('3-4',1),0.5, function() if shout_again == false then if stop_walk == false then if shout_count < 2 then shout_count = shout_count + 1 else mother_anim[2]:pauseAtStart() mother_animation_count = father_animation_count + 1 mother_move = true end end end end), --walk anim8.newAnimation(_m('5-8',1),0.15, function() if mother_x >= 65 then mother_move = false mother_animation_count = 2 mother_anim[2]:resume() stop_walk = true shout_again = true mother_anim[3]:pauseAtStart() elseif mother_x >= 50 then father_move = true end end), --fall anim8.newAnimation(_m('9-14',1),0.25, function() mother_gone = true end), } --child local _child = anim8.newGrid(8,16,images.player_child_sheet:getWidth(),images.player_child_sheet:getHeight()) child = anim8.newAnimation(_child('1-4',1),0.05) --player child pushing chair local _push = anim8.newGrid(8,16,images.player_child_push:getWidth(),images.player_child_push:getHeight()) player_push = anim8.newAnimation(_push('1-4',1),0.25) --window left local wl = anim8.newGrid(128,32,images.window_left:getWidth(),images.window_left:getHeight()) win_left_anim = anim8.newAnimation(wl('1-6',1),0.1, function() win_left_anim:gotoFrame(4) Timer.after(3, function() win_left_anim:pauseAtStart() win_move_l = false end) end) --window right local wr = anim8.newGrid(128,32,images.window_right:getWidth(),images.window_right:getHeight()) win_right_anim = anim8.newAnimation(wr('1-5',1),0.1, function() win_right_anim:gotoFrame(3) Timer.after(2,function() win_right_anim:pauseAtStart() win_move_r = false end) end) --enemy local en = anim8.newGrid(12,14,images.enemy_sheet:getWidth(),images.enemy_sheet:getHeight()) enemy_idle = anim8.newAnimation(en('4-5',1),1) enemy_mys = anim8.newAnimation(en('1-3',1),1) enemy_move = anim8.newAnimation(en('6-7',1),0.5) local _ed = anim8.newGrid(12,14,images.enemy_dead_sheet:getWidth(),images.enemy_dead_sheet:getHeight()) enemy_dead = anim8.newAnimation(_ed('1-8',1),0.1,function() enemy_dead:pauseAtEnd() fade_to_black = true end) --moving car local _car = anim8.newGrid(32,48,images.car_moving:getWidth(),images.car_moving:getHeight()) car_anim = anim8.newAnimation(_car('1-17',1),0.1,"pauseAtEnd") --player door local _pd = anim8.newGrid(16,24,images.player_door:getWidth(),images.player_door:getHeight()) pd_anim = anim8.newAnimation(_pd('1-14',1),0.1,function() pd_anim:pauseAtEnd() end) --in house local _ih = anim8.newGrid(128,32,images.in_house:getWidth(),images.in_house:getHeight()) ih_anim = anim8.newAnimation(_ih('1-10',1),0.1,"pauseAtEnd") --tv local _tv = anim8.newGrid(8,17,images.tv_anim:getWidth(),images.tv_anim:getHeight()) tv_anim = anim8.newAnimation(_tv('1-5',1),0.1,false) --corpse local _corpse = anim8.newGrid(17,24,images.corpse_anim:getWidth(),images.corpse_anim:getHeight()) corpse_fall_anim = anim8.newAnimation(_corpse('1-13',1),0.075, function() sounds.body_fall:play() sounds.body_fall:setLooping(false) corpse_fall_anim:pauseAtEnd() corpse_trigger = false local corpse = Items(images.corpse,images["secretRoom"],90,40,"corpse") table.insert(obj,corpse) local corpse_dial = Interact(false,{"A corpse!?","What?!...","Why is there a corpse here!?...","Touch it?"},{"Yes","No"},"It's not responding","corpse") table.insert(dialogue,corpse_dial) end) --clock local _clock = anim8.newGrid(12,22,images.clock_anim:getWidth(),images.clock_anim:getHeight()) attic_clock_anim = anim8.newAnimation(_clock('1-9',1),1) --skip button local _skip = anim8.newGrid(8,8,images.skip:getWidth(),images.skip:getHeight()) skip_button = anim8.newAnimation(_skip('1-9',1),0.1) --sit to stand local _f1 = anim8.newGrid(11,18,images.f1:getWidth(),images.f1:getHeight()) f1_anim = anim8.newAnimation(_f1('1-12',1),0.5,"pauseAtEnd") end function epic_scene_update(dt) mother_anim[mother_animation_count]:update(dt) father_anim[father_animation_count]:update(dt) if father_move == true then father_x = father_x + father_speed * dt end if mother_move == true then mother_x = mother_x + mother_speed * dt end end function epic_scene_draw() love.graphics.setColor(1, 1, 1, 1) if mother_gone == false then if love.system.getOS() == "Android" then android.lightChange(true) end mother_anim[mother_animation_count]:draw(images.mother_sheet,mother_x,27) else if love.system.getOS() == "Android" then android.lightChange(false) end player.visible = true player.x = 14 player.y = 27 parent_found = true fade.state = true currentRoom = images["secretRoom"] end father_anim[father_animation_count]:draw(images.father_sheet,father_x,26) end
return {'avondland','avondster','avocado','avocadopeer','avond','avondappel','avondbede','avondbezoek','avondbijeenkomst','avondblad','avondbulletin','avondcollege','avondcourant','avondcursus','avonddienst','avondduister','avondeditie','avondenlang','avondeten','avondfeest','avondgebed','avondgymnasium','avondhandel','avondhemel','avondhoofd','avondjapon','avondjournaal','avondjurk','avondkerk','avondkledij','avondkleding','avondklok','avondkrant','avondles','avondlicht','avondlied','avondlijk','avondlucht','avondmaal','avondmaalsbeker','avondmaalsdienst','avondmaalsstellen','avondmaalstafel','avondmaalsviering','avondmaaltijd','avondmalen','avondmis','avondnieuws','avondonderwijs','avondopening','avondopenstelling','avondopleiding','avondpartij','avondpermissie','avondploeg','avondpost','avondprogramma','avondprogrammering','avondretour','avondrood','avondschemer','avondschemering','avondschool','avondsluiting','avondspits','avondspitsuur','avondspreekuur','avondstond','avondstudent','avondstudie','avondsymposium','avondtarief','avondtoilet','avonduur','avondvergadering','avondvierdaagse','avondvlinder','avondvlucht','avondvoorstelling','avondvullend','avondwake','avondwandeling','avondwedstrijd','avondwerk','avondwijding','avondwinkel','avondzitting','avondzon','avonturen','avonturenboek','avonturenfilm','avonturenkomedie','avonturenpark','avonturenroman','avonturenverhaal','avonturier','avonturierster','avonturisme','avontuur','avontuurlijk','avontuurtje','avontuurlijkheid','avondmens','avonddis','avondboterham','avonturistisch','avondmist','avondnevel','avondmarkt','avondactiviteit','avondconcert','avondrit','avondritueel','avondsessie','avondspel','avondtraining','avonduitzending','avonturentocht','avondbrood','avondrust','avondwind','avondvoeding','avondstilte','avondkaart','avondshow','avondbries','avondmenu','avondgodsdienstoefening','avondpauwoog','avondappels','avondbezoeken','avondbladen','avondbulletins','avondcolleges','avondconcerten','avonddiensten','avondedities','avonden','avondfeesten','avondgebeden','avondjaponnen','avondje','avondjes','avondjournaals','avondklokken','avondliederen','avondmaalde','avondmaalsbekers','avondmaalstafels','avondmaalsvieringen','avondmaalt','avondmaaltijden','avondopeningen','avondopenstellingen','avondopleidingen','avondprogrammas','avondscholen','avondspelletje','avondspelletjes','avondspreekuren','avondstonden','avondtasje','avondtoiletten','avonduren','avondvergaderingen','avondvlinders','avondvullende','avondzittingen','avonturenromans','avonturiers','avonturiersters','avontuurde','avontuurden','avontuurlijke','avontuurlijker','avontuurlijkere','avontuurlijkst','avontuurlijkste','avontuurt','avontuurtjes','avocados','avondcursussen','avondjurken','avondkranten','avondlessen','avondlijke','avondpermissies','avondploegen','avondstudenten','avondvluchten','avondvoorstellingen','avondwandelingen','avondwandelingetje','avondwijdingen','avondwinkels','avonturenfilms','avonturenverhalen','avondwedstrijden','avondmensen','avondpartijen','avonturenboeken','avonturistische','avondvierdaagsen','avondactiviteiten','avondmarkten','avonduitzendingen','avonduurtjes','avondzonnetje','avondjurkje','avondspelen','avondtrainingen','avondritje','avondschemeringen','avondsessies','avondsluitingen','avondritten','avondfeestje','avonduurtje','avondstudies','avondgebeuren','avondbriesje','avondrituelen'}
local eval = require "eval" local util = require "util" local function multiplyString (str, n) local s = "" for i=1,n do s = s .. str end return s end local function transform (text, data, delimiter, nestedCycles, nestedConditions) local substrings = {} -- array with substrings local iteratorIndex = 0 repeat local startDelimiterIndex = text:indexOf(delimiter.open, iteratorIndex) if startDelimiterIndex then substrings[#substrings + 1] = text:sub(iteratorIndex, startDelimiterIndex - 1) if text:charAt(startDelimiterIndex + delimiter.open:len() + nestedCycles - 1) == "#" then -- cycle local startExpressionIndex = startDelimiterIndex + delimiter.open:len() + nestedCycles + 1 -- one more because # -- find array name local arrayExpressionEndIndex = text:indexOf("\n", startExpressionIndex) local arrayExpression = text:sub(startExpressionIndex, arrayExpressionEndIndex - 1) local array = eval.code(arrayExpression, data, true) -- find element that will be repeated local endDelimiter = delimiter.close .. multiplyString("#", nestedCycles) .. "\n" local endDelimiterIndex = text:indexOf(endDelimiter, arrayExpressionEndIndex + 1) local element = text:sub(arrayExpressionEndIndex + 1, endDelimiterIndex - 1) -- iterate the array over the element if array then -- do not iterate over non-existing arrays local iterator = multiplyString("i", nestedCycles) if util.isArray(array) then for i=1,#array do data[iterator] = i substrings[#substrings + 1] = transform(element, data, delimiter, nestedCycles + 1, nestedConditions) end else -- array is object for i,_ in pairs(array) do data[iterator] = i substrings[#substrings + 1] = transform(element, data, delimiter, nestedCycles + 1, nestedConditions) end end data[iterator] = nil -- reset iterator end iteratorIndex = endDelimiterIndex + delimiter.close:len() + nestedCycles + 1 -- one more because # elseif text:charAt(startDelimiterIndex + delimiter.open:len() + nestedConditions - 1) == "?" then -- condition local startExpressionIndex = startDelimiterIndex + delimiter.open:len() + nestedConditions + 1 -- one more because ? -- find condition name local conditionExpressionEndIndex = text:indexOf("\n", startExpressionIndex) local conditionExpression = text:sub(startExpressionIndex, conditionExpressionEndIndex - 1) local condition = eval.code(conditionExpression, data, true) -- find element that will be conditioned local endDelimiter = delimiter.close .. multiplyString("?", nestedConditions) .. "\n" local endDelimiterIndex = text:indexOf(endDelimiter, conditionExpressionEndIndex + 1) local element = text:sub(conditionExpressionEndIndex + 1, endDelimiterIndex - 1) -- condition over the element if condition then substrings[#substrings + 1] = transform(element, data, delimiter, nestedCycles, nestedConditions + 1) end iteratorIndex = endDelimiterIndex + delimiter.close:len() + nestedConditions + 1 -- one more because ? elseif text:charAt(startDelimiterIndex + delimiter.open:len()) == "=" then -- set local startExpressionIndex = startDelimiterIndex + delimiter.open:len() + 1 -- one more because = local endDelimiterIndex = text:indexOf(delimiter.close .. "=", startExpressionIndex) -- find property name and value local propertyNameEndIndex = text:indexOf("=", startExpressionIndex) local propertyName = text:sub(startExpressionIndex, propertyNameEndIndex - 1) local propertyExpression = text:sub(propertyNameEndIndex + 1, endDelimiterIndex - 1) data[propertyName:trim()] = eval.code(propertyExpression, data, true) iteratorIndex = endDelimiterIndex + delimiter.close:len() + 1 -- one more because = elseif text:charAt(startDelimiterIndex + delimiter.open:len()) == "@" then -- require local startExpressionIndex = startDelimiterIndex + delimiter.open:len() + 1 -- one more because @ local endDelimiterIndex = text:indexOf(delimiter.close .. "@", startExpressionIndex) -- find required module local moduleName = text:sub(startExpressionIndex, endDelimiterIndex - 1) local names = util.split(moduleName:trim(), ".") data[names[#names]] = require(moduleName:trim()) -- set propertyName to be the last name after "." iteratorIndex = endDelimiterIndex + delimiter.close:len() + 1 -- one more because @ else -- replace local startExpressionIndex = startDelimiterIndex + delimiter.open:len() local endDelimiterIndex = text:indexOf(delimiter.close, startExpressionIndex) -- find property value local propertyExpression = text:sub(startExpressionIndex, endDelimiterIndex - 1) substrings[#substrings + 1] = eval.code(propertyExpression, data, true) iteratorIndex = endDelimiterIndex + delimiter.close:len() end else substrings[#substrings + 1] = text:sub(iteratorIndex, text:len()) end until startDelimiterIndex == nil return table.concat(substrings) -- concatenate all substrings end return function (text, data, parameters) local datapool = parameters or {} if data then setmetatable(datapool, {__index = data}) end return transform(text, datapool, {open = "{{", close = "}}"}, 1, 1) end
local T, C, L = Tukui:unpack() local UnitFrames = T.UnitFrames local Class = select(2, UnitClass("player")) local STAGGER_RED_TRANSITION = STAGGER_RED_TRANSITION local STAGGER_RED_INDEX = STAGGER_RED_INDEX or 3 local STAGGER_YELLOW_TRANSITION = STAGGER_YELLOW_TRANSITION local STAGGER_YELLOW_INDEX = STAGGER_YELLOW_INDEX or 2 local STAGGER_GREEN_TRANSITION = STAGGER_GREEN_TRANSITION local STAGGER_GREEN_INDEX = STAGGER_GREEN_INDEX or 1 ---------------------------------------------------------------- -- Monk Class Resources ---------------------------------------------------------------- if (Class ~= "MONK") then return end -- post update stagger bar local PostUpdateStagger = function(self, cur, max) local perc = cur / max local colors = T.Colors.power["STAGGER"] local r, g, b if (perc >= STAGGER_RED_TRANSITION) then r, g, b = unpack(colors[STAGGER_RED_INDEX or 3]) -- red elseif (perc > STAGGER_YELLOW_TRANSITION) then r, g, b = unpack(colors[STAGGER_YELLOW_INDEX or 2]) -- yellow else r, g, b = unpack(colors[STAGGER_GREEN_INDEX or 1]) -- green end self:SetStatusBarColor(r, g, b) self.Value:SetFormattedText("%s / %s - %.1f%%", T.ShortValue(cur), T.ShortValue(max), 100 * (cur / max)) if (cur ~= 0) then self:Show() else self:Hide() end end local basePlayer = UnitFrames.Player function UnitFrames:Player() -- first, we call the base function basePlayer(self) -- second, we edit it local Harmony = self.HarmonyBar local PlayerWidth, _ = unpack(C.Units.Player) local PowerTexture = T.GetTexture(C.Textures.UFPowerTexture) local Font, FontSize, FontStyle = C.Medias.PixelFont, 12, "MONOCHROMEOUTLINE" -- Harmony Bar Harmony:ClearAllPoints() Harmony:SetPoint("BOTTOMLEFT", self, "TOPLEFT", 0, 3) Harmony:SetWidth(PlayerWidth) Harmony:SetHeight(5) local Spacing = 1 local SizeAscension, DeltaAscension = T.EqualSizes(Harmony:GetWidth(), 6, Spacing) local SizeNoTalent, DeltaNoTalent = T.EqualSizes(Harmony:GetWidth(), 5, Spacing) for i = 1, 6 do Harmony[i]:ClearAllPoints() Harmony[i]:SetHeight(Harmony:GetHeight()) Harmony[i]:SetWidth(SizeAscension) Harmony[i]:CreateBackdrop() if ((DeltaNoTalent > 0) and (i <= DeltaNoTalent)) then Harmony[i].NoTalent = SizeNoTalent + 1 else Harmony[i].NoTalent = SizeNoTalent end if ((DeltaAscension > 0) and (i <= DeltaAscension)) then Harmony[i].Ascension = SizeAscension + 1 else Harmony[i].Ascension = SizeAscension end if (i == 1) then Harmony[i]:SetPoint("TOPLEFT", Harmony, "TOPLEFT", 0, 0) else Harmony[i]:SetPoint("LEFT", Harmony[i-1], "RIGHT", Spacing, 0) end end -- Stagger Bar local Stagger = CreateFrame("StatusBar", self:GetName() .. "StaggerBar", self) Stagger:SetPoint("CENTER", UIParent, "BOTTOM", 0, 288) Stagger:SetWidth(225) Stagger:SetHeight(14) Stagger:SetStatusBarTexture(PowerTexture) Stagger:CreateBackdrop() Stagger.Backdrop:SetOutside() Stagger.Background = Stagger:CreateTexture(nil, "BORDER") Stagger.Background:SetAllPoints() Stagger.Background:SetColorTexture(unpack(C.General.BackgroundColor)) Stagger.Value = Stagger:CreateFontString(nil, "OVERLAY") Stagger.Value:SetPoint("CENTER", Stagger, "CENTER", 0, 0) Stagger.Value:SetFont(C.Medias.Font, 12) Stagger.Value:SetJustifyH("CENTER") Stagger.Value:SetTextColor(.84,.75,.65) Stagger.PostUpdate = PostUpdateStagger -- Register with oUF self.Stagger = Stagger end
local _={} _[16]={1} _[15]={} _[14]={1} _[13]={} _[12]={text=" to move.",tags=_[15]} _[11]={text="joystick",tags=_[15]} _[10]={text="left ",tags=_[16]} _[9]={text="Use ",tags=_[15]} _[8]={text="to jump.",tags=_[13]} _[7]={text="A ",tags=_[14]} _[6]={text="Press ",tags=_[13]} _[5]={_[9],_[10],_[11],_[12]} _[4]={_[6],_[7],_[8]} _[3]={"return"} _[2]={"text",_[5]} _[1]={"text",_[4]} return {_[1],_[2],_[3]} --[[ { "text", { { tags = <1>{}, text = "Press " }, { tags = { 1 }, text = "A " }, { tags = <table 1>, text = "to jump." } } } { "text", { { tags = <1>{}, text = "Use " }, { tags = { 1 }, text = "left " }, { tags = <table 1>, text = "joystick" }, { tags = <table 1>, text = " to move." } } } { "return" } ]]--
config = { inputs = { controls = { left = {'key:left', 'axis:leftx-', 'button:dpleft'}, right = {'key:right', 'axis:leftx+', 'button:dpright'}, up = {'key:up', 'axis:lefty-', 'button:dpup'}, down = {'key:down', 'axis:lefty+', 'button:dpdown'}, action = {'key:x', 'button:a', 'mouse:1'}, }, pairs = { move = {'left', 'right', 'up', 'down'} }, joystick = love.joystick.getJoysticks()[1], deadzone = .33, } }
require "app.ui.base.init" require "app.ui.EditBoxUI" _ENV=namespace "ui" using_namespace "luaClass" using_namespace "container" using_namespace "game" class "SettingUI" { super(cc.Layer); super(LUIObject); public{ FUNCTION.SettingUI(function(self) self=self:__super() self:LUIObject() self:setContentSize(display.cx*2,display.cy*2) self.onTouch=true self:setBackGround() local back= createLabel("返回",25) :setAnchorPoint(0,0) :setPosition(0,0) :addTo(self) onNodeTouch(back,function() self:remove() end) if mod.Limit.openConsole then local editUI= EditBoxUI( cc.size(display.cx,display.cy/4), Path:getInstance().ui.edit ) :setAnchorPoint(0,0.5) :setPosition(display.cx/4,display.cy*2-50) :addTo(self,100) :setPlaceHolder("输入控制台命令") local editLb=createLabel("控制台",20) :addTo(self,100) :setAnchorPoint(0,0.5) :setPosition(0,display.cy*2-50) local ok=createLabel("执行",20) :addTo(self,100) :setAnchorPoint(1,0.5) :setPosition(display.cx*1.5,display.cy*2-50) onNodeTouch(ok,function ( ) local text=editUI:getText() if text=="" then return end self:doConsole(text) self:remove() end) end local musicClose=createLabel("关闭音乐",20) :addTo(self,100) :setAnchorPoint(0,0.5) :setPosition(0,display.cy*2-150) onNodeTouch(musicClose,function() Audio:getInstance():stop() end) local musicOpen=createLabel("开启音乐",20) :addTo(self,100) :setAnchorPoint(0,0.5) :setPosition(0,display.cy*2-250) onNodeTouch(musicOpen,function() Audio:getInstance():resume() end) end); FUNCTION.doConsole(function(self,text) EventManager:getInstance():console(unpack(text:split(" "))) end); }; }
return { client = require( "ruled.client" ), notification = require( "ruled.notification" ), }
local Explosion = class "Explosion" function Explosion:init(x, y) self.pos = {x = x, y = y} self.bg = true self.lifetime = 9 * 0.05 end return Explosion
package("glew") set_homepage("http://glew.sourceforge.net/") set_description("A cross-platform open-source C/C++ extension loading library.") set_urls("https://github.com/nigels-com/glew/releases/download/glew-$(version)/glew-$(version).zip") add_versions("2.1.0", "2700383d4de2455f06114fbaf872684f15529d4bdc5cdea69b5fb0e9aa7763f1") add_versions("2.2.0", "a9046a913774395a095edcc0b0ac2d81c3aacca61787b39839b941e9be14e0d4") if is_plat("windows") or is_plat("mingw") then add_syslinks("opengl32") elseif is_plat("linux") then add_syslinks("GL") add_deps("libx11", "xorgproto") end add_defines("GLEW_NO_GLU") on_load("windows", "mingw", function (package) if not package:config("shared") then package:add("defines", "GLEW_STATIC") end end) on_install("linux", "macosx", "mingw", "windows", function (package) local configs = {} configs.mode = package:debug() and "debug" or "release" if package:config("shared") then configs.kind = "shared" elseif package:is_plat("linux") and package:config("pic") ~= false then configs.cxflags = "-fPIC" end os.cp(path.join(package:scriptdir(), "port", "xmake.lua"), "xmake.lua") import("package.tools.xmake").install(package, configs) end) on_test(function (package) assert(package:has_cfuncs("glewInit", {includes = "GL/glew.h"})) end)
--- Render component base class. -- This is base class for all types of render components. -- @classmod RenderComponent --- Should this render component render graphics. -- @tfield bool visible
-- -- Created by IntelliJ IDEA. -- User: Kunkka -- Date: 17/3/1 -- Time: 下午9:26 -- To change this template use File | Settings | File Templates. -- local NodeTest = class("NodeTest", gk.Layer) function NodeTest:ctor() NodeTest.super.ctor(self) gk.util:drawNodeBounds(self.layer1, nil, -3) gk.util:drawNodeBounds(self.scrollView1, nil, -3) end return NodeTest
--Global variables PortalTimer = {} Warps = {} Jails = {} BackCoords = {} BackWorld = {} TpRequestTimeLimit = 0 TeleportRequests = {} Jailed = {} Muted = {} SocialSpyList = {} GodModeList = {} --Initialize the plugin function Initialize(Plugin) Plugin:SetName(g_PluginInfo.Name) Plugin:SetVersion(g_PluginInfo.Version) --Register hooks cPluginManager:AddHook(cPluginManager.HOOK_TAKE_DAMAGE, OnTakeDamage) cPluginManager.AddHook(cPluginManager.HOOK_PLAYER_RIGHT_CLICK, OnPlayerRightClick) cPluginManager.AddHook(cPluginManager.HOOK_UPDATING_SIGN, OnUpdatingSign) cPluginManager:AddHook(cPluginManager.HOOK_CHAT, OnChat) cPluginManager:AddHook(cPluginManager.HOOK_EXECUTE_COMMAND, OnExecuteCommand) cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_BREAKING_BLOCK, OnPlayerBreakingBlock) cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_PLACING_BLOCK, OnPlayerPlacingBlock) cPluginManager:AddHook(cPluginManager.HOOK_WORLD_TICK, OnWorldTick) cPluginManager:AddHook(cPluginManager.HOOK_ENTITY_TELEPORT, OnEntityTeleport) cPluginManager:AddHook(cPluginManager.HOOK_KILLED, OnKilled) cPluginManager:AddHook(cPluginManager.HOOK_PLAYER_JOINED, OnPlayerJoined) cPluginManager:AddHook(cPluginManager.HOOK_ENTITY_CHANGING_WORLD, OnEntityChangingWorld) dofile(cPluginManager:GetPluginsPath() .. "/InfoReg.lua") RegisterPluginInfoCommands() RegisterPluginInfoConsoleCommands() --Set folders which will be used later on HomesFolder = Plugin:GetLocalFolder().."/homes" --If there's no home folder, the plugin will create it if not cFile:IsFolder(HomesFolder) then cFile:CreateFolder(HomesFolder) end --Read warps from the warps.ini file WarpsINI = cIniFile() if WarpsINI:ReadFile("warps.ini") then local WarpNum = WarpsINI:GetNumKeys() - 1 for i=0, WarpNum do local Tag = WarpsINI:GetKeyName(i) Warps[Tag] = {} Warps[Tag]["w"] = WarpsINI:GetValue(Tag , "w") Warps[Tag]["x"] = WarpsINI:GetValueI(Tag , "x") Warps[Tag]["y"] = WarpsINI:GetValueI(Tag , "y") Warps[Tag]["z"] = WarpsINI:GetValueI(Tag , "z") end end --Read jails from the jails.ini file JailsINI = cIniFile() if JailsINI:ReadFile("jails.ini") then local JailNum = JailsINI:GetNumKeys() - 1 for i=0, JailNum do local Tag = JailsINI:GetKeyName(i) Jails[Tag] = {} Jails[Tag]["w"] = JailsINI:GetValue(Tag , "w") Jails[Tag]["x"] = JailsINI:GetValueI(Tag , "x") Jails[Tag]["y"] = JailsINI:GetValueI(Tag , "y") Jails[Tag]["z"] = JailsINI:GetValueI(Tag , "z") end end UsersINI = cIniFile() UsersINI:ReadFile("users.ini") --Read tpa timeout config local SettingsINI = cIniFile() SettingsINI:ReadFile("settings.ini") TpRequestTimeLimit = SettingsINI:GetValueSetI("Teleport", "RequestTimeLimit", 0) if SettingsINI:GetNumKeyComments("Teleport") == 0 then SettingsINI:AddKeyComment("Teleport", "RequestTimeLimit: Time in seconds after which tpa/tpahere will timeout, 0 - disabled") end SettingsINI:WriteFile("settings.ini") cRoot:Get():ForEachPlayer(CheckPlayer) LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion()) return true end function OnDisable() LOG("Disabled " .. cPluginManager:GetCurrentPlugin():GetName() .. "!") end
local class = require('../classes/new') local base = require('./base') local Invite = class(base) function Invite:__onUpdate () self.channel = self.parent self.server = self.parent.parent end function Invite:accept () self.parent.parent.rest:request( { method = 'POST', path = 'invites/'..self.code, } ) end function Invite:delete () local success = self.parent.parent.rest:request( { method = 'DELETE', path = 'invites/'..self.code, } ) if not success then return end self.server.invites:remove(self) self.channel.invites:remove(self) end return Invite
--Image to Lua converter by MrLenyn --It works by drawing lines instead of pixels, outputs a script ready to use in Stormworks monitors, with good performance. --Version: 0.10 transparency = false zoom_var = false pos_var = false size_limit = 300 function click(rx,ry,w,h, x, y) if x >= rx and y >= ry and x <= rx+w and y <= ry+h then return true else return false end end function draw_button(x,y,w,h,text,state) --83, 219, 165 love.graphics.setColor(45/255,110/255,110/255,1) love.graphics.rectangle("fill",x,y,w,h) --box love.graphics.setColor(25/255,90/255,90/255,1) -- checkbox color white love.graphics.rectangle("fill",x+7,y+8,10,10) if state then love.graphics.setColor(103/255,239/255,185/255,1) -- checkbox color love.graphics.rectangle("fill",x+7,y+8,10,10) end love.graphics.setColor(0,0,0,1) -- checkbox love.graphics.rectangle("line",x+7,y+8,10,10) love.graphics.setColor(1,1,1,1) love.graphics.print(text, x + 23, y,0,0.5,0.5) end function love.load() print("---------------------------------------") print("<<Image to Lua converter by Mr Lenyn>>") print("---------------------------------------") print("Please drag and drop your .png to the window") print("Keep your images small (64x64) and under") print("And your color count too") print("Stormworks character limit is 4096") print(" ") print(" ") font = love.graphics.newFont("OpenSans-Regular.ttf",32) function love.filedropped(file) file:open("r") data = file:read() file:close() filedata = love.filesystem.newFileData(data, 'img', 'file') imagedata = love.image.newImageData(filedata) width, height = imagedata:getDimensions() if width < size_limit and height < size_limit then -- limiting file size pixel_table = {} ---------------------- --awesome gama fix equation by XLjedi gama_fix = true g_factor = 1.21 ---------------------- color_count = 0 color_table = {} color_final = {} rect_table = {} temp_table = {} zoom = 5 ----------------------------------- for y = 0, height-1 do for x = 0, width-1 do r,g,b,a = imagedata:getPixel(x,y) index = (x+y*width) i = index table.insert(pixel_table, {r,g,b,a,x,y}) end end function dump(o) -- function to print table to console if type(o) == 'table' then local s = '{' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '},'..'{' .. dump(v) .. ',' end return s .. '}' else return tostring(o) end end startDraw = true --notes: --tables are being saved from 1 of course, so 0,0 is stored at pos 1 in table. --pixel_table [1] = r, [2] = g, [3] = b, [4] = a, [5] = x, [6] = y if startDraw then -- constructing color table and color count for i = 1, #pixel_table do current_color = tostring("\"" .. pixel_table[i][1] * 255 .. "," .. pixel_table[i][2] * 255 .. "," .. pixel_table[i][3] * 255 .. "," .. pixel_table[i][4] * 255 .. "\"") if i > 1 then last_color = tostring("\"" .. pixel_table[i-1][1] * 255 .. "," .. pixel_table[i-1][2] * 255 .. "," .. pixel_table[i-1][3] * 255 .. "," .. pixel_table[i-1][4] * 255 .. "\"") end if current_color ~= last_color and pixel_table[i][4] ~= 0 then color_found = false for c = 1, #color_table do if current_color == color_table[c] then color_found = true end end if not color_found then table.insert(color_table, current_color) table.insert(color_final, {pixel_table[i][1] * 255, pixel_table[i][2] * 255, pixel_table[i][3] * 255, pixel_table[i][4] * 255}) end end color_count = #color_final end color_count_finished = true end --constructing rectangle table --table should look like: rect_table = {[1] = "r,g,b,a", rectX1, rectY1, rectX2, rectY2, ... ) line_lenght = 1 for i = 1, #color_table do -- constructing final table temp_table = {} for b = 1, #pixel_table do px = pixel_table[b][5] py = pixel_table[b][6] current_color = tostring("\"" .. pixel_table[b][1] * 255 .. "," .. pixel_table[b][2] * 255 .. "," .. pixel_table[b][3] * 255 .. "," .. pixel_table[b][4] * 255 .. "\"") if b < #pixel_table then next_color = tostring("\"" .. pixel_table[b+1][1] * 255 .. "," .. pixel_table[b+1][2] * 255 .. "," .. pixel_table[b+1][3] * 255 .. "," .. pixel_table[b+1][4] * 255 .. "\"") end if current_color == color_table[i] then if current_color == next_color and px < width - 1 then line_lenght = line_lenght + 1 elseif line_lenght > 1 then table.insert(temp_table, px + 1 - line_lenght) table.insert(temp_table, py) table.insert(temp_table, line_lenght) line_lenght = 1 else table.insert(temp_table, px) table.insert(temp_table, py) table.insert(temp_table, line_lenght) line_lenght = 1 end end end if gama_fix then temp_table = math.floor(color_final[i][1]^g_factor/255^g_factor*color_final[i][1]) .. "," .. math.floor(color_final[i][2]^g_factor/255^g_factor*color_final[i][2]) .. "," .. math.floor(color_final[i][3]^g_factor/255^g_factor*color_final[i][3]) .. "," .. math.floor(color_final[i][4]^g_factor/255^g_factor*color_final[i][4]) .. "," .. table.concat(temp_table, ",") else temp_table = color_final[i][1] .. "," .. color_final[i][2] .. "," .. color_final[i][3] .. "," .. color_final[i][4] .. "," .. table.concat(temp_table, ",") end table.insert(rect_table, temp_table) end if not transparency then --setting background (color with the most pixels) longest_table = 0 longest_table_index = 0 for i = 1, #rect_table do if #rect_table[i] > longest_table then longest_table_index = i longest_table = #rect_table[i] back_color = color_final[i][1] .. "," .. color_final[i][2] .. "," .. color_final[i][3] .. "," .. color_final[i][4] end end table.remove(rect_table, longest_table_index) table.insert(rect_table, 1, back_color) end --final rect table looks like = {{backgroundrgb},{r,g,b,a,px,py,lenght,px2,py2,lenght2 ... }} final_rect_table = "{" .. string.sub(dump(rect_table),4) .. "}" --------------------------------------------------------- --Printing to console! print("--------------------") print("Copied to clipboard!") print("--------------------") --Result string! print("") print("") if zoom_var then print("zoom=1 ") z_text = "zoom=1 " else z_text = "" end if pos_var then print("x=0 ") print("y=0 ") p_text = "x=0 " .. "y=0 " else p_text = "" end print("s=screen ") print("p=" .. final_rect_table) print(" ") print("function onDraw() ") if not transparency then print("s.setColor(p[1][1],p[1][2],p[1][3],p[1][4]) ") -- background drawn print("s.drawClear() ") print("for i=2,#p do ") trans_text = "s.setColor(p[1][1],p[1][2],p[1][3],p[1][4]) " .. "s.drawClear() " .. "for i=2,#p do " else print("for i=1,#p do ") -- no background drawn trans_text = "for i=1,#p do " end print("s.setColor(p[i][1],p[i][2],p[i][3],p[i][4]) ") print("for w=5,#p[i],3 do ") --drawing code if zoom_var and not pos_var then -- zoom print("s.drawRectF(p[i][w]*zoom,p[i][w+1]*zoom,p[i][w+2]*zoom,1*zoom) ") drawn_text = "s.drawRectF(p[i][w]*zoom,p[i][w+1]*zoom,p[i][w+2]*zoom,1*zoom) " end if zoom_var and pos_var then --zoom and pos print("s.drawRectF(p[i][w]*zoom+x,p[i][w+1]*zoom+y,p[i][w+2]*zoom,1*zoom) ") drawn_text = "s.drawRectF(p[i][w]*zoom+x,p[i][w+1]*zoom+y,p[i][w+2]*zoom,1*zoom) " end if pos_var and not zoom_var then -- pos only print("s.drawRectF(p[i][w]*x,p[i][w+1]+y,p[i][w+2],1) ") drawn_text = "s.drawRectF(p[i][w]+x,p[i][w+1]+y,p[i][w+2],1) " end if not zoom_var and not pos_var then print("s.drawRectF(p[i][w],p[i][w+1],p[i][w+2],1) ") drawn_text = "s.drawRectF(p[i][w],p[i][w+1],p[i][w+2],1) " end print("end") print("end") print("end") -------------------------------------------------------- --final string to copy to clipboard and save final_text = z_text .. p_text .. "s=screen " .. "p=" .. final_rect_table .. "function onDraw() " .. trans_text .. "s.setColor(p[i][1],p[i][2],p[i][3],p[i][4]) " .. "for w=5,#p[i],3 do " .. drawn_text .. "end " .. "end " .. "end " --saving on appdata local success, message = love.filesystem.write('text.txt', final_text) if success then print ("") end --copying to clipboard love.system.setClipboardText(final_text) copy_alpha = 1 -- for "copied to clipboad" text sign else print(">>>Image too big!<<<") end end end function love.mousepressed(x,y,button, istouch, presses) if click(50,50,230,25,x,y) then transparency = not transparency elseif click(50,80,230,25,x,y) then zoom_var = not zoom_var elseif click(50,110,230,25,x,y) then pos_var = not pos_var end end function love.keypressed(key, scancode, isrepeat) if key == "escape" then love.event.quit() end if key == "a" then zoom = zoom + 2 end if key == "s" then zoom = zoom - 2 end end function love.draw() s_width, s_height = love.graphics.getDimensions() love.graphics.setFont(font, 64) love.graphics.setBackgroundColor(38/255,74/255,74/255,1) --buttons draw_button(50,50,230,25,"Transparency (More code!)", transparency) draw_button(50,80,230,25,"Zoom Variable", zoom_var) draw_button(50,110,230,25,"Position Variable", pos_var) if not startDraw then love.graphics.print("DRAG AND DROP", s_width/2-120, s_height/2) love.graphics.print(".png files only", s_width/2-50, s_height/2+45,0,0.5,0.5) end if imagedata then if width > size_limit and height > size_limit then -- limiting file size love.graphics.setColor(0.8,0.1,0.1,1) love.graphics.print("IMAGE IS TOO BIG!", s_width/2-125, s_height/2-100) end end if startDraw then for i = 1, #pixel_table do love.graphics.setColor(pixel_table[i][1], pixel_table[i][2], pixel_table[i][3], pixel_table[i][4]) love.graphics.rectangle("fill", pixel_table[i][5]*zoom+s_width/2-(width/2*zoom), pixel_table[i][6]*zoom+s_height/2-(height/2*zoom) + 40, zoom, zoom) end love.graphics.setColor(45/255,110/255,110/255,1) --info boxes if width > size_limit and height > size_limit then love.graphics.setColor(0.8,0.1,0.1,1) end love.graphics.rectangle("fill",300,50,230,25) love.graphics.setColor(45/255,110/255,110/255,1) love.graphics.rectangle("fill",300,80,230,25) if #final_text >= 4096 then love.graphics.setColor(0.8,0.1,0.1,1) end love.graphics.rectangle("fill",300,110,230,25) love.graphics.setColor(1,1,1,1) love.graphics.print("Size : " .. width .. "x" .. height, 310, 50,0,0.5,0.5) love.graphics.setColor(1,1,1,1) love.graphics.print("Color count : " .. color_count, 310, 80,0,0.5,0.5) love.graphics.print("Character count : " .. #final_text, 310, 110,0,0.5,0.5) copy_alpha = copy_alpha - 0.005 if copy_alpha > 0 then love.graphics.setColor(1,1,1,copy_alpha) love.graphics.print("Copied to Clipboard", s_width/2-155, s_height/2+200,0) end end end
do local _ = { market = { icon = '__base__/graphics/icons/market.png', picture = { filename = '__base__/graphics/entity/market/market.png', width = 156, shift = {0.95, 0.2}, height = 127 }, close_sound = 0, order = 'd-a-a', collision_box = {{-1.4, -1.4}, {1.4, 1.4}}, corpse = 'big-remnants', max_health = 150, icon_mipmaps = 4, type = 'market', subgroup = 'other', flags = {'placeable-neutral', 'player-creation', 'hidden'}, allow_access_to_all_forces = true, name = 'market', selection_box = {{-1.5, -1.5}, {1.5, 1.5}}, open_sound = 0, icon_size = 64, damaged_trigger_effect = { damage_type_filters = 'fire', entity_name = 'spark-explosion', type = 'create-entity', offsets = {{0, 1}}, offset_deviation = {{-0.5, -0.5}, {0.5, 0.5}} } } }; return _; end
-- -- Formspecs -- function extinct_bees.get_bee_hive_active_formspec(life_percent) return "size[8,8.5]" .. "no_prepend[]" .. -- bg appearance "image[2,1;1,2.2;extinct_bees_bee_hive_progress_bg.png^" .. "[lowpart:" .. life_percent .. ":extinct_bees_bee_hive_progress_fg.png]" .. "bgcolor[#343434;false]" .. "listcolors[#00000030;#F8F8FF30]" .. "background[0,0;8,4;extinct_bees_bee_hive_bg.png]" .. -- input lists "container[1,0.75]" .. "list[context;queen;0,0;1,1]" .. "list[context;drone;0,1.5;1,1]" .. "container_end[]" .. -- output lists [WIP] "container[4, 0.5]" .. -- top "list[context;dst1;0.5,0;1,1]" .. "list[context;dst2;1.5,0;1,1]" .. -- middle "list[context;dst3;0,1;1,1]" .. "list[context;dst4;1,1;1,1]" .. "list[context;dst5;2,1;1,1]" .. -- bottom "list[context;dst6;0.5,2;1,1]" .. "list[context;dst7;1.5,2;1,1]" .. "container_end[]" .. --player inventory "list[current_player;main;0,4.25;8,1;]" .. -- toolleiste "list[current_player;main;0,5.5;8,3;8]" .. -- player inventory "listring[current_player;main]" .. "listring[context;queen]" .. "listring[current_player;main]" .. "listring[context;drone]" .. "listring[current_player;main]" .. "listring[context;dst1]" .. "listring[current_player;main]" .. "listring[context;dst2]" .. "listring[current_player;main]" .. "listring[context;dst3]" .. "listring[current_player;main]" .. "listring[context;dst4]" .. "listring[current_player;main]" .. "listring[context;dst5]" .. "listring[current_player;main]" .. "listring[context;dst6]" .. "listring[current_player;main]" .. "listring[context;dst7]" .. "listring[current_player;main]" end function extinct_bees.get_bee_hive_inactive_formspec() return "size[8,8.5]" .. "no_prepend[]" .. -- bg appearance "image[2,1;1,2.2;extinct_bees_bee_hive_progress_bg.png]" .. "bgcolor[#343434;false]" .. "listcolors[#00000030;#F8F8FF30]" .. "background[0,0;8,4;extinct_bees_bee_hive_bg.png]" .. --player inventory "list[current_player;main;0,4.25;8,1;]" .. -- toolleiste "list[current_player;main;0,5.5;8,3;8]" .. -- player inventory -- input lists "container[1,0.75]" .. "list[context;queen;0,0;1,1]" .. "list[context;drone;0,1.5;1,1]" .. "container_end[]" .. --output lists "container[4, 0.5]" .. -- top "list[context;dst1;0.5,0;1,1]" .. "list[context;dst2;1.5,0;1,1]" .. -- middle "list[context;dst3;0,1;1,1]" .. "list[context;dst4;1,1;1,1]" .. "list[context;dst5;2,1;1,1]" .. -- bottom "list[context;dst6;0.5,2;1,1]" .. "list[context;dst7;1.5,2;1,1]" .. "container_end[]" .. "listring[current_player;main]" .. "listring[context;queen]" .. "listring[current_player;main]" .. "listring[context;drone]" .. "listring[current_player;main]" .. "listring[context;dst1]" .. "listring[current_player;main]" .. "listring[context;dst2]" .. "listring[current_player;main]" .. "listring[context;dst3]" .. "listring[current_player;main]" .. "listring[context;dst4]" .. "listring[current_player;main]" .. "listring[context;dst5]" .. "listring[current_player;main]" .. "listring[context;dst6]" .. "listring[current_player;main]" .. "listring[context;dst7]" .. "listring[current_player;main]" end local function add_mutation_to_drops(drops, properties, drone_species) -- get the possible mutation between queen and drone local mutation, mut_chance mutation, mut_chance = extinct_bees.get_mutation(properties.mutation, drone_species) -- provided no mutation is possible, the drones species has a 50% chance -- to recur if not mutation then mutation = drone_species mut_chance = 2 end if 0.5 < math.random() then mutation = "extinct_bees:" .. mutation .. "_queen" else mutation = "extinct_bees:" .. mutation .. "_drone" end drops[#drops + 1] = {item = mutation, chance = mut_chance, min_drop = 0, max_drop = 1} return drops end local function can_dig(pos, player) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() return inv:is_empty("queen") and inv:is_empty("drone") and inv:is_empty("dst1") and inv:is_empty("dst2") and inv:is_empty("dst3") and inv:is_empty("dst4") and inv:is_empty("dst5") and inv:is_empty("dst6") and inv:is_empty("dst7") end local function allow_metadata_inventory_put(pos, listname, index, stack, player) -- pos = position of the node -- listname = names of the list -- index = gibt immer 1 zurück? -- stack = the item stack des ausgewählten item -- player = ? if minetest.is_protected(pos, player:get_player_name()) then return 0 end local meta = minetest.get_meta(pos) local inv = meta:get_inventory() if listname == "drone" then if minetest.get_item_group(stack:get_name(), "drone") ~= 0 then if inv:is_empty("drone") then return 1 end end elseif listname == "queen" then if minetest.get_item_group(stack:get_name(), "queen") ~= 0 then if inv:is_empty("queen") then return 1 end end end return 0 end local function allow_metadata_inventory_move(pos, from_list, from_index, to_list, to_index, count, player) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local stack = inv:get_stack(from_list, from_index) return allow_metadata_inventory_put(pos, to_list, to_index, stack, player) end local function allow_metadata_inventory_take(pos, listname, index, stack, player) if minetest.is_protected(pos, player:get_player_name()) then return 0 end return stack:get_count() end local function hive_node_timer(pos, elapsed) -- -- [[ Inizialize metadata ]] -- local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local total_lifespan = meta:get_float("total_lifespan") or 0 local remaining_lifespan = meta:get_float("remaining_lifespan") or 0 local life_percent = meta:get_float("life_percent") or 0 local hive_state = meta:get_string("hive_state") local flower_radius = meta:get_int("flower_radius") or 0 local flower_count = meta:get_int("flower_count") or 0 -- timer abbruch bedingung local restart = false -- -- [[ Checking input lists ]] -- -- hive activates when both inputs have a bee if hive_state == "inactive" and not inv:is_empty("queen") and not inv:is_empty("drone") then utils.swap_node(pos, "extinct_bees:bee_hive_active") hive_state = "active" local queen = inv:get_stack("queen", 1) local species = extinct_bees.get_species_from_name(queen:get_name()) local properties = extinct_bees.get_species_properties(species) flower_radius = properties["flower"].radius flower_count = properties["flower"].count total_lifespan = properties.lifespan remaining_lifespan = total_lifespan elseif hive_state == "active" and inv:is_empty("queen") or inv:is_empty("drone") then remaining_lifespan = 0 end -- -- [[ Update formspecs and calculates the output ]] -- local formspec local infotext if remaining_lifespan > 0 then local flowers_in_area = utils.count_flowers_around_node(pos, flower_radius) if #flowers_in_area < flower_count then infotext = "Not enough flowers around Hive!" else remaining_lifespan = remaining_lifespan - 1 end life_percent = 100 - math.floor((remaining_lifespan / total_lifespan) * 100) formspec = extinct_bees.get_bee_hive_active_formspec(100 - life_percent) -- lifespan over if remaining_lifespan == 0 then math.randomseed(os.time() + tonumber(tostring({}):sub(8))) local queen = inv:get_stack("queen", 1) local drone = inv:get_stack("drone", 1) local queen_species = extinct_bees.get_species_from_name(queen:get_name()) local drone_species = extinct_bees.get_species_from_name(drone:get_name()) local queen_properties = extinct_bees.get_species_properties(queen_species) -- randomize the output local output_dst = {"dst1", "dst2", "dst3", "dst4", "dst5", "dst6", "dst7"} output_dst = utils.rand_permutation(output_dst) -- guaranteed drops local output = {ItemStack(queen:get_name()), ItemStack(drone:get_name())} local drops = utils.shallow_copy(queen_properties.drops) drops = add_mutation_to_drops(drops, queen_properties, drone_species) for _, drop in ipairs(drops) do local stack = ItemStack(drop.item) local count = drop.min_drop local n = drop.max_drop - drop.min_drop for _ = 1, n, 1 do local r = math.random() if r <= (1 / drop.chance) then count = count + 1 end end stack:set_count(count) table.insert(output, stack) end -- delete input inv:remove_item("queen", queen:get_name()) inv:remove_item("drone", drone:get_name()) -- fill output for i, dst in ipairs(output_dst) do if output[i] then inv:add_item(dst, output[i]) end end end restart = true else utils.swap_node(pos, "extinct_bees:bee_hive") hive_state = "inactive" life_percent = 0 formspec = extinct_bees.get_bee_hive_inactive_formspec() -- stop timer on the inhive_state furnace minetest.get_node_timer(pos):stop() end if not infotext then if hive_state == "active" then infotext = "Progress: " .. (life_percent) .. "%" else infotext = "Hive is inactive" end end -- -- [[ Set meta values ]] -- meta:set_float("total_lifespan", total_lifespan) meta:set_float("remaining_lifespan", remaining_lifespan) meta:set_float("life_percent", life_percent) meta:set_string("hive_state", hive_state) meta:set_int("flower_radius", flower_radius) meta:set_int("flower_count", flower_count) meta:set_string("formspec", formspec) meta:set_string("infotext", infotext) return restart end -- -- [[ Node definitions ]] -- minetest.register_node( "extinct_bees:bee_hive", { description = "Bee Hive", tiles = { "extinct_bees_bee_hive0_top.png", "extinct_bees_bee_hive0_top.png", "extinct_bees_bee_hive1_sides.png", "extinct_bees_bee_hive1_sides.png", "extinct_bees_bee_hive1_sides.png", "extinct_bees_bee_hive2_front.png" }, paramtype2 = "facedir", drop = "extinct_bees:bee_hive", groups = {oddly_breakable_by_hand = 1, hive = 1}, legacy_facedir_simple = true, is_ground_content = false, --sounds = default.node_sound_stone_defaults(), can_dig = can_dig, on_timer = hive_node_timer, on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", extinct_bees.get_bee_hive_inactive_formspec()) meta:set_string("infotext", "Empty Bee Hive") meta:set_string("hive_state", "inactive") local inv = meta:get_inventory() inv:set_size("queen", 1) inv:set_size("drone", 1) inv:set_size("dst1", 1) -- top inv:set_size("dst2", 1) -- top inv:set_size("dst3", 1) -- middle inv:set_size("dst4", 1) -- middle inv:set_size("dst5", 1) -- middle inv:set_size("dst6", 1) -- bottom inv:set_size("dst7", 1) -- bottom end, -- allow_metadata_inventory_put = allow_metadata_inventory_put, allow_metadata_inventory_move = allow_metadata_inventory_move, allow_metadata_inventory_take = allow_metadata_inventory_take, -- on_metadata_inventory_put = function(pos) minetest.get_node_timer(pos):start(1.0) end, on_blast = function(pos) local drops = {} default.get_inventory_drops(pos, "queen", drops) default.get_inventory_drops(pos, "drone", drops) for i = 1, 7, 1 do default.get_inventory_drops(pos, "dst" .. i, drops) end drops[#drops + 1] = "extinct_bees:bee_hive" minetest.remove_node(pos) return drops end } ) minetest.register_node( "extinct_bees:bee_hive_active", { description = "Bee Hive", tiles = { "extinct_bees_bee_hive0_top.png", "extinct_bees_bee_hive0_top.png", "extinct_bees_bee_hive1_sides.png", "extinct_bees_bee_hive1_sides.png", "extinct_bees_bee_hive1_sides.png", "extinct_bees_bee_hive2_front.png" }, paramtype2 = "facedir", light_source = 5, drop = "extinct_bees:bee_hive", groups = {oddly_breakable_by_hand = 1, not_in_creative_inventory = 1, hive = 1}, legacy_facedir_simple = true, is_ground_content = false, --sounds = default.node_sound_stone_defaults(), can_dig = can_dig, on_timer = hive_node_timer, -- allow_metadata_inventory_put = allow_metadata_inventory_put, allow_metadata_inventory_move = allow_metadata_inventory_move, allow_metadata_inventory_take = allow_metadata_inventory_take } )
package("git") set_kind("binary") set_homepage("https://git-scm.com/") set_description("A free and open source distributed version control system") if os.host() == "windows" then if os.arch() == "x64" then add_urls("https://github.com/tboox/xmake-win64env/archive/$(version).zip", {alias = "github"}) add_urls("https://gitlab.com/tboox/xmake-win64env/-/archive/$(version)/xmake-win64env-$(version).zip", {alias = "gitlab"}) add_versions("github:v1.0.3", "df43e419a358b136cfc0ae343560684321722a39713c205a7a894edd9d15b2b5") add_versions("gitlab:v1.0.3", "376807a3386f15e734f3b2f51ed5d151d434fb99b7349412a2fb9e83d5e29d5c") else add_urls("https://github.com/tboox/xmake-win32env/archive/$(version).zip", {alias = "github"}) add_urls("https://gitlab.com/tboox/xmake-win32env/-/archive/$(version)/xmake-win32env-$(version).zip", {alias = "gitlab"}) add_versions("github:v1.0.3", "2a3b71baae67f3ebb057748d1261970d18d80be52e88427a4719d2185594fc21") add_versions("gitlab:v1.0.3", "2a627f78349702a85b710399c14f5dc0acfdb5ad840765e3e2637d554a373807") end end on_install("macosx", "linux", function (package) import("package.manager.install")("git") end) on_install("windows", function (package) -- install winenv with git local winenv_dir = path.join(val("globaldir"), "winenv") os.mkdir(winenv_dir) os.cp("*", winenv_dir) -- load winenv import("winenv", {rootdir = winenv_dir})(winenv_dir) end) on_test(function (package) os.vrun("git --version") end)
--[[ TheNexusAvenger Displays information about the current round the player is selecting in the lobby. --]] local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local ReplicatedStorageProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ReplicatedStorage")) local NexusReplication = ReplicatedStorageProject:GetResource("External.NexusReplication") local LobbySelectionRounds = NexusReplication:GetGlobalContainer():WaitForChildBy("Name","LobbySelectionRounds") local SetReady = ReplicatedStorageProject:GetResource("Replication.Lobby.SetReady") local CurrentRoundState = ReplicatedStorageProject:GetResource("State.CurrentRound") local GreenTextButtonFactory = ReplicatedStorageProject:GetResource("UI.AudibleTextButtonFactory").CreateDefault(Color3.new(0,170/255,0)) --[[ Displays the information about the lobby selection. --]] local function ShowLobbyInformation(Round) --Create the round information container. local RoundInformation = Instance.new("ScreenGui") RoundInformation.ResetOnSpawn = false RoundInformation.Parent = Players.LocalPlayer:WaitForChild("PlayerGui") local RoundTypeNameText = Instance.new("TextLabel") RoundTypeNameText.BackgroundTransparency = 1 RoundTypeNameText.Size = UDim2.new(1,0,0.075,0) RoundTypeNameText.Position = UDim2.new(0,0,1,0) RoundTypeNameText.Font = "SourceSansBold" RoundTypeNameText.TextColor3 = Color3.new(0,0,0) RoundTypeNameText.TextStrokeColor3 = Color3.new(1,1,1) RoundTypeNameText.TextStrokeTransparency = 0 RoundTypeNameText.TextScaled = true RoundTypeNameText.Parent = RoundInformation local RequiredPlayersText = Instance.new("TextLabel") RequiredPlayersText.BackgroundTransparency = 1 RequiredPlayersText.Size = UDim2.new(1,0,0.05,0) RequiredPlayersText.Position = UDim2.new(0,0,1,0) RequiredPlayersText.Font = "SourceSansBold" RequiredPlayersText.TextColor3 = Color3.new(0,0,0) RequiredPlayersText.TextStrokeColor3 = Color3.new(1,1,1) RequiredPlayersText.TextStrokeTransparency = 0 RequiredPlayersText.TextScaled = true RequiredPlayersText.Parent = RoundInformation local ReadyPlayersText = Instance.new("TextLabel") ReadyPlayersText.BackgroundTransparency = 1 ReadyPlayersText.Size = UDim2.new(1,0,0.04,0) ReadyPlayersText.Position = UDim2.new(0,0,1,0) ReadyPlayersText.Font = "SourceSansBold" ReadyPlayersText.TextColor3 = Color3.new(0,0,0) ReadyPlayersText.TextStrokeColor3 = Color3.new(1,1,1) ReadyPlayersText.TextStrokeTransparency = 0 ReadyPlayersText.TextScaled = true ReadyPlayersText.Visible = false ReadyPlayersText.Parent = RoundInformation --Create the ready button. local ReadyButton,ReadyText = GreenTextButtonFactory:Create() ReadyButton.Size = UDim2.new(0.3,0,0.06,0) ReadyButton.Position = UDim2.new(0.5,0,1,0) ReadyButton.AnchorPoint = Vector2.new(0.5,0) ReadyButton.SizeConstraint = Enum.SizeConstraint.RelativeYY ReadyButton:SetControllerIcon(Enum.KeyCode.ButtonX) ReadyButton:MapKey(Enum.KeyCode.ButtonX,Enum.UserInputType.MouseButton1) ReadyButton.Parent = RoundInformation ReadyText.Text = "READY" --[[ Clears the events. --]] local Events = {} local function DisconnectEvents() for _,Connection in pairs(Events) do Connection:Disconnect() end Events = {} end --[[ Updates the text. --]] local RequiredPlayersMet = false local function UpdateText() local CurrentPlayers,RequiedPlayers,MaxPlayers = #Round.Players:GetAll(),Round.RequiredPlayers,Round.MaxPlayers RequiredPlayersMet = (CurrentPlayers >= RequiedPlayers) RoundTypeNameText.Text = string.upper(Round.RoundName) if CurrentPlayers >= RequiedPlayers then RequiredPlayersText.Text = tostring(CurrentPlayers).."/"..tostring(MaxPlayers).." Players" else RequiredPlayersText.Text = tostring(RequiedPlayers).." Players Required" end ReadyPlayersText.Text = tostring(#Round.ReadyPlayers:GetAll()).."/"..tostring(CurrentPlayers).." Ready" ReadyPlayersText.Visible = (Round.ReadyPlayers:Contains(Players.LocalPlayer)) end --Connect leaving the round. table.insert(Events,Round.Players.ItemRemoved:Connect(function(Player) if Player == Players.LocalPlayer then DisconnectEvents() if Player == Players.LocalPlayer then RoundTypeNameText:TweenPosition(UDim2.new(0,0,1,0),Enum.EasingDirection.In,Enum.EasingStyle.Back,0.7,true,function() RoundInformation:Destroy() end) RequiredPlayersText:TweenPosition(UDim2.new(0,0,1,0),Enum.EasingDirection.In,Enum.EasingStyle.Back,0.6,true,function() RequiredPlayersText:Destroy() end) ReadyPlayersText:TweenPosition(UDim2.new(0,0,1,0),Enum.EasingDirection.In,Enum.EasingStyle.Back,0.5,true,function() ReadyPlayersText:Destroy() end) if ReadyButton.AdornFrame.Parent then ReadyButton.AdornFrame:TweenPosition(UDim2.new(0.5,0,1,0),Enum.EasingDirection.In,Enum.EasingStyle.Back,0.5,true,function() ReadyButton:Destroy() end) end end end end)) --Connect the round starting. table.insert(Events,CurrentRoundState.CurrentRoundChanged:Connect(function() DisconnectEvents() RoundInformation:Destroy() ReadyButton:Destroy() end)) --Connect being ready. table.insert(Events,ReadyButton.MouseButton1Down:Connect(function() SetReady:FireServer() ReadyButton.AdornFrame:TweenPosition(UDim2.new(0.5,0,1,0),Enum.EasingDirection.In,Enum.EasingStyle.Back,0.5,true,function() ReadyButton:Destroy() end) end)) --Connect updating the text. table.insert(Events,Round.Players.ItemAdded:Connect(UpdateText)) table.insert(Events,Round.Players.ItemRemoved:Connect(UpdateText)) table.insert(Events,Round.ReadyPlayers.ItemAdded:Connect(UpdateText)) table.insert(Events,Round.ReadyPlayers.ItemRemoved:Connect(UpdateText)) table.insert(Events,RunService.RenderStepped:Connect(function() local WhiteFactor = (RequiredPlayersMet and 1 or (math.sin((tick() * 2) % (2 * math.pi))/2) + 0.5) RequiredPlayersText.TextStrokeColor3 = Color3.new(1,WhiteFactor,WhiteFactor) end)) UpdateText() --Show the text. RoundTypeNameText:TweenPosition(UDim2.new(0,0,0.6,0),Enum.EasingDirection.Out,Enum.EasingStyle.Back,0.5) RequiredPlayersText:TweenPosition(UDim2.new(0,0,0.66,0),Enum.EasingDirection.Out,Enum.EasingStyle.Back,0.55) ReadyPlayersText:TweenPosition(UDim2.new(0,0,0.72,0),Enum.EasingDirection.Out,Enum.EasingStyle.Back,0.6) ReadyButton.AdornFrame:TweenPosition(UDim2.new(0.5,0,0.71,0),Enum.EasingDirection.Out,Enum.EasingStyle.Back,0.6) end --[[ Connects a new lobby round. --]] local function ConnectLobbyRound(Round) Round.Players.ItemAdded:Connect(function(Player) if Player == Players.LocalPlayer then ShowLobbyInformation(Round) end end) end --Connect the lobby rounds. LobbySelectionRounds.ChildAdded:Connect(ConnectLobbyRound) for _,Round in pairs(LobbySelectionRounds:GetChildren()) do ConnectLobbyRound(Round) end
function Delrissas_Minions(pUnit, Misc) random=math.random(1, 25) if random==1 then pUnit:SpawnCreature(24557, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24558, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24656, 128.804245, 11.850257, -20.004900, 4.610291, 14, 12000000); -- Fizzle pUnit:SpawnCreature(24554, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24561, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==2 then pUnit:SpawnCreature(24557, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24558, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24656, 128.804245, 11.850257, -20.004900, 4.610291, 14, 12000000); -- Fizzle pUnit:SpawnCreature(24554, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24559, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==3 then pUnit:SpawnCreature(24557, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24558, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24656, 128.804245, 11.850257, -20.004900, 4.610291, 14, 12000000); -- Fizzle pUnit:SpawnCreature(24554, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24555, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); pUnit:SpawnCreature(24552, 119.496450, 9.265259, -20.004902, 5.552326, 14, 12000000); end if random==4 then pUnit:SpawnCreature(24557, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24558, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24656, 128.804245, 11.850257, -20.004900, 4.610291, 14, 12000000); -- Fizzle pUnit:SpawnCreature(24554, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24553, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==5 then pUnit:SpawnCreature(24557, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24558, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24656, 128.804245, 11.850257, -20.004900, 4.610291, 14, 12000000); -- Fizzle pUnit:SpawnCreature(24554, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24556, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==6 then pUnit:SpawnCreature(24558, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24656, 124.948463, 11.833995, -20.004911, 4.771299, 14, 12000000); -- Fizzle pUnit:SpawnCreature(24554, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24561, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24559, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==7 then pUnit:SpawnCreature(24558, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24656, 124.948463, 11.833995, -20.004911, 4.771299, 14, 12000000); -- Fizzle pUnit:SpawnCreature(24554, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24561, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24555, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); pUnit:SpawnCreature(24552, 119.496450, 9.265259, -20.004902, 5.552326, 14, 12000000); end if random==8 then pUnit:SpawnCreature(24558, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24656, 124.948463, 11.833995, -20.004911, 4.771299, 14, 12000000); -- Fizzle pUnit:SpawnCreature(24554, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24561, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24553, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==9 then pUnit:SpawnCreature(24554, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24561, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24559, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24555, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==10 then pUnit:SpawnCreature(24558, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24656, 124.948463, 11.833995, -20.004911, 4.771299, 14, 12000000); -- Fizzle pUnit:SpawnCreature(24554, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24561, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24556, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==11 then pUnit:SpawnCreature(24554, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24561, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24559, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24553, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==12 then pUnit:SpawnCreature(24554, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24561, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24559, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24556, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==13 then pUnit:SpawnCreature(24561, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24559, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24553, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24555, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); pUnit:SpawnCreature(24552, 119.496450, 9.265259, -20.004902, 5.552326, 14, 12000000); end if random==14 then pUnit:SpawnCreature(24561, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24559, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24556, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24555, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); pUnit:SpawnCreature(24552, 119.496450, 9.265259, -20.004902, 5.552326, 14, 12000000); end if random==15 then pUnit:SpawnCreature(24559, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24553, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24555, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24552, 134.965820, 9.356191, -20.004902, 4.259219, 14, 12000000); pUnit:SpawnCreature(24556, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==16 then pUnit:SpawnCreature(24555, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24553, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24556, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24557, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==17 then pUnit:SpawnCreature(24556, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24553, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24555, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24552, 134.965820, 9.356191, -20.004902, 4.259219, 14, 12000000); pUnit:SpawnCreature(24558, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); pUnit:SpawnCreature(24656, 122.813576, 11.031157, -20.004902, 4.912669, 14, 12000000); -- Fizzle end if random==18 then pUnit:SpawnCreature(24556, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24553, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24555, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24552, 134.965820, 9.356191, -20.004902, 4.259219, 14, 12000000); pUnit:SpawnCreature(24554, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==19 then pUnit:SpawnCreature(24556, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24553, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24555, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24552, 134.965820, 9.356191, -20.004902, 4.259219, 14, 12000000); pUnit:SpawnCreature(24561, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==20 then pUnit:SpawnCreature(24556, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24553, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24555, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24552, 134.965820, 9.356191, -20.004902, 4.259219, 14, 12000000); pUnit:SpawnCreature(24559, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==21 then pUnit:SpawnCreature(24553, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24556, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24557, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24558, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); pUnit:SpawnCreature(24656, 122.813576, 11.031157, -20.004902, 4.912669, 14, 12000000); -- Fizzle end if random==22 then pUnit:SpawnCreature(24553, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24556, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24557, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24554, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==23 then pUnit:SpawnCreature(24553, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24556, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24557, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24561, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==24 then pUnit:SpawnCreature(24553, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24556, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24557, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24559, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); end if random==25 then pUnit:SpawnCreature(24553, 123.870529, 12.468772, -20.004911, 4.856926, 14, 12000000); pUnit:SpawnCreature(24556, 130.000900, 11.941279, -20.004900, 4.399158, 14, 12000000); pUnit:SpawnCreature(24557, 132.254776, 10.996053, -20.004902, 4.230160, 14, 12000000); pUnit:SpawnCreature(24555, 121.413750, 11.002829, -20.004902, 5.005877, 14, 12000000); pUnit:SpawnCreature(24552, 119.496450, 9.265259, -20.004902, 5.552326, 14, 12000000); end end RegisterUnitEvent(24560, 6, "Delrissas_Minions")
local alert = require("hs.alert") local timer = require("hs.timer") local eventtap = require("hs.eventtap") local events = eventtap.event.types local module = {} -- You either override these here or after including this file from another, e.g. -- -- altHold = require("altHold") -- altHold.timeFrame = 2 -- altHold.action = function() -- do something special -- end -- how long must the alt key be held? module.timeFrame = 2 -- what to do when the alt key has been held that long module.action = function() alert("You held the Alt/Option key!") end -- Synopsis: -- what we're looking for is the alt key down event and no other -- key or flag change event before the specified time has passed -- verify that *only* the ctrl key flag is being pressed local onlyAlt = function(ev) local result = ev:getFlags().alt for k,v in pairs(ev:getFlags()) do if k ~= "alt" and v then result = false break end end return result end module.eventwatcher = eventtap.new({events.flagsChanged, events.keyDown}, function(ev) -- if we're called and a time is running, something changed -- unset the timer if module.countDownTimer then module.countDownTimer:stop() module.countDownTimer = nil end if ev:getType() == events.flagsChanged then if onlyAlt(ev) then module.countDownTimer = timer.doAfter(module.timeFrame, function() module.countDownTimer = nil if module.action then module.action() end end) end end return false ; end):start()
local utils = {}; utils.load_module = function(module) local success, err = pcall(require, module); if not success then error(string.format('Error loading module `%s`.\n\n%s.', module, err)); end; end; return utils;
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-- -- ─────────────────────────────────────────────────-- -- Plugin: lsp-status.nvim -- Github: github.com/nvim-lua/lsp-status.nvim -- ─────────────────────────────────────────────────-- -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-- -- ━━━━━━━━━━━━━━━━━━━❰ configs ❱━━━━━━━━━━━━━━━━━━━-- -- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━-- require('lsp-status').status() require('lsp-status').register_progress() require('lsp-status').config({ indicator_errors = '✗', indicator_warnings = '⚠', indicator_info = '', indicator_hint = '', indicator_ok = '✔', current_function = true, diagnostics = false, select_symbol = nil, update_interval = 100, status_symbol = ' 🇻' })
--[[ GameOverState Class ]] GameOverState = Class{__includes = BaseState} function GameOverState:update(dt) if love.keyboard.wasPressed('enter') or love.keyboard.wasPressed('return') then gStateMachine:change('play') end end function GameOverState:enter(params) self.gameGrid = params.gameGrid end function GameOverState:render() love.graphics.clear(0.4, 0, 0, 1) self.gameGrid:render() self.gameGrid:revealAll() love.graphics.printf('Game Over', 0, 16, VIRTUAL_WIDTH, 'center') love.graphics.printf('Press Enter to play', 0, VIRTUAL_HEIGHT - 32, VIRTUAL_WIDTH, 'center') end
local pcall = pcall local require = require local getmetatable = getmetatable --- Internal configuration of --- Aspect Template Engine. Be careful. --- @class aspect.config local config = {} --- JSON configuration config.json = { encode = nil, decode = nil, error = "JSON encode/decode no available. Please install `cjson` or `json` or configure `require('aspect.config').json` before using Aspect" } --- UTF8 configuration config.utf8 = { len = nil, lower = nil, upper = nil, sub = nil, match = nil, } config.env = { } --- escape filter settings (HTML strategy) config.escape = { pattern = "[}{\"><'&]", replaces = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["'"] = "&#39;" } } --- condition aliases (also see bellow) config.is_false = { [""] = true, [0] = true, } --- empty string variants (also see bellow) config.is_empty_string = { [""] = true, } config.is_n = { } --- dynamically configure config.is_false and config.is_empty_string do --- https://github.com/openresty/lua-nginx-module#core-constants local ngx = ngx or {} if ngx.null then config.is_false[ngx.null] = true config.is_empty_string[ngx.null] = true end --- https://luarocks.org/modules/openresty/lua-cjson local has_cjson, cjson = pcall(require, "cjson.safe") if has_cjson then config.is_false[cjson.null] = true config.is_empty_string[cjson.null] = true config.json.encode = cjson.encode config.json.decode = cjson.decode else local has_json, json = pcall(require, "json") if has_json then config.json.encode = json.encode config.json.decode = json.decode if json.null then config.is_false[json.null] = true config.is_empty_string[json.null] = true end if json.empty_array then config.is_false[json.empty_array] = true end end end --- https://github.com/isage/lua-cbson local has_cbson, cbson = pcall(require, "cbson") if has_cbson then config.is_false[getmetatable(cbson.null())] = true config.is_false[getmetatable(cbson.array())] = true config.is_empty_string[getmetatable(cbson.null())] = true end --- https://www.tarantool.io/ru/doc/1.10/reference/reference_lua/yaml/ local has_yaml, yaml = pcall(require, "yaml") if has_yaml and yaml.NULL then config.is_false[yaml.NULL] = true config.is_empty_string[yaml.NULL] = true end --- https://github.com/gvvaughan/lyaml local has_lyaml, lyaml = pcall(require, "lyaml") if has_lyaml then config.is_false[lyaml.null] = true config.is_empty_string[lyaml.null] = true end --- https://www.tarantool.io/ru/doc/2.4/reference/reference_lua/msgpack/ local has_msgpack, msgpack = pcall(require, "msgpack") if has_msgpack then config.is_false[msgpack.NULL] = true config.is_empty_string[msgpack.NULL] = true end --- https://www.tarantool.io/en/doc/2.4/reference/reference_lua/box_null/ if box and box.NULL then config.is_false[box.NULL] = true config.is_empty_string[box.NULL] = true end end --- Detect UTF8 module do local utf8 for _, name in ipairs({"lua-utf8", "utf8", "lutf8"}) do local ok, module = pcall(require, name) if ok then utf8 = module break end end if utf8 then config.utf8.len = utf8.len or utf8.length config.utf8.upper = utf8.upper config.utf8.lower = utf8.lower config.utf8.sub = utf8.sub config.utf8.match = utf8.match config.utf8.find = utf8.find end end --- Compiler configuration config.compiler = { is_boolean = { ["true"] = true, ["false"] = true }, special = { ["true"] = "true", ["false"] = "false", ["nil"] = "nil", ["null"] = "nil" }, --- danger variables names reserved_words = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true, ["while"] = true, }, --- correspondence table for math operators math_ops = { ["+"] = "+", ["-"] = "-", ["/"] = "/", ["*"] = "*", ["%"] = "%", ["**"] = "^", }, --- correspondence table for comparison operators comparison_ops = { ["=="] = "==", ["!="] = "~=", [">="] = ">=", ["<="] = "<=", ["<"] = "<", [">"] = ">", }, --- correspondence table for logic operators logic_ops = { ["and"] = "and", ["or"] = "or" }, other_ops = { ["~"] = true, ["|"] = true, ["."] = true, ["["] = true, ["]"] = true, [","] = true }, --- reserved variables names reserved_vars = { _self = true, _context = true, _charset = true, __ = true }, tag_type = { EXPRESSION = 1, CONTROL = 2, COMMENT = 3, }, strip = { ["-"] = "%s", ["~"] = "[ \t]" } } config.tokenizer = { patterns = { NUMBER1 = '^[%+%-]?%d+%.?%d*[eE][%+%-]?%d+', -- 123.45e-32 NUMBER2 = '^[%+%-]?%d+%.?%d*', -- 123 or 123.456 NUMBER3 = '^0x[%da-fA-F]+', -- 0xDeadBEEF NUMBER4 = '^%d+%.?%d*[eE][%+%-]?%d+', NUMBER5 = '^%d+%.?%d*', WORD = '^[%a_][%w_]*', WSPACE = '^%s+', STRING1 = "^(['\"])%1", -- empty string STRING2 = [[^(['"])(\*)%2%1]], STRING3 = [[^(['"]).-[^\](\*)%2%1]], CHAR1 = "^''", CHAR2 = [[^'(\*)%1']], CHAR3 = [[^'.-[^\](\*)%1']], PREPRO = '^#.-[^\\]\n', } } config.loop = { keys = { parent = true, iteration = true, index = true, index0 = true, revindex = true, revindex0 = true, first = true, last = true, length = true, prev_item = true, next_item = true, has_more = true, --- trees level = true, level0 = true, first_node = true, last_node = true, path = true } } config.macro = { import_type = { GROUP = 1, SINGLE = 2 } } config.escapers = {} config.date = { months = { ["jan"] = 1, ["january"] = 1, ["feb"] = 2, ["february"] = 2, ["mar"] = 3, ["march"] = 3, ["apr"] = 4, ["april"] = 4, ["may"] = 5, ["may"] = 5, ["jun"] = 6, ["june"] = 6, ["jul"] = 7, ["july"] = 7, ["aug"] = 8, ["august"] = 8, ["sep"] = 9, ["september"] = 9, ["oct"] = 10, ["october"] = 10, ["nov"] = 11, ["november"] = 11, ["dec"] = 12, ["december"] = 12, }, months_locale = { en = { [1] = {"Jan", "January"}, [2] = {"Feb", "February"}, [3] = {"Mar", "March"}, [4] = {"Apr", "April"}, [5] = {"May", "May"}, [6] = {"Jun", "June"}, [7] = {"Jul", "July"}, [8] = {"Aug", "August"}, [9] = {"Sep", "September"}, [10] = {"Oct", "October"}, [11] = {"Nov", "November"}, [12] = {"Dec", "December"}, } }, week = { ["mon"] = 1, ["monday"] = 1, ["tue"] = 2, ["tuesday"] = 2, ["wed"] = 3, ["wednesday"] = 3, ["thu"] = 4, ["thursday"] = 4, ["fri"] = 5, ["friday"] = 5, ["sat"] = 6, ["saturday"] = 6, ["sun"] = 7, ["sunday"] = 7, }, week_locale = { en = { [1] = {"Mon", "Monday"}, [2] = {"Tue", "Tuesday"}, [3] = {"Wed", "Wednesday"}, [4] = {"Thu", "Thursday"}, [5] = {"Fri", "Friday"}, [6] = {"Sat", "Saturday"}, [7] = {"Sun", "Sunday"}, }, }, aliases = { c = "%a %b %d %H:%m%s %Y", r = "%I:%M:%S %p", R = "%I:%M", T = "%H:%M:%S", D = "%m/%d/%y", F = "%Y-%m-%d" } } return config
-- Copyright (c) 2011-2014, Syhunt Informatica -- License: 3-clause BSD license -- See https://github.com/felipedaragon/sandcat/ for details. PageMenu = {} PageMenu.doc_url = 'http://www.syhunt.com/sandcat/?n=' PageMenu.livefilter = 'Sandcat Live Headers files (*.sclive)|*.sclive' PageMenu.htmlfilter = 'HTML files (*.html;*.htm)|*.html;*.htm' PageMenu.imagefilter = 'Image files|*.bmp;*.gif;*.jpg;*.jpe;*.jpeg;*.png;*.svg' PageMenu.allfiles = 'All files (*.*)|*.*' PageMenu.openfilter = PageMenu.htmlfilter..'|'..PageMenu.imagefilter..'|'..PageMenu.allfiles PageMenu.newtabscript = '' function PageMenu:NewTab() if PageMenu.newtabscript ~= '' then browser.dostring(PageMenu.newtabscript) else browser.newtab() end end function PageMenu:OpenPage() local f = app.openfile(self.openfilter,'html') if f ~= '' then tab:gotourl(f) end end function PageMenu:SaveCacheAs() local destfile = app.savefile('Sandcat Cache files (*.scc)|*.scc','scc') if destfile ~= '' then ctk.dir.packtotar(browser.info.cachedir,destfile) end end function PageMenu:OpenLiveHeaders() local lv = '' local f = app.openfile(self.livefilter,'sclive') if f ~= '' then tab:cache_import(f) lv = tab:cache_extractfile('\\Requests\\Headers') tab:loadheaders(lv) ctk.file.delete(lv) end end function PageMenu:SaveLiveHeadersAs() local destfile = app.savefile(self.livefilter,'sclive') if destfile ~= '' then tab:saveheaders(destfile) local lv = ctk.file.getcontents(destfile) if lv ~= '' then tab:cache_storestring('\\Requests\\Headers',lv) tab:cache_export(destfile) -- overwrites initial export else app.showmessage('Failed to export live headers.') end end end function PageMenu:CloseAllTabs() if app.ask_yn('Close all tabs?') then browser.closetabs() end end function PageMenu:CloseAllButActiveTab() if app.ask_yn('Close all but active tab?') then browser.closetabs(tab.name) end end function PageMenu:SaveCachedAs_Ask(filename) debug.print('Saving cached resource from: '..filename) if ctk.file.exists(filename) then local name = ctk.url.getfilename(self.saveurl) local ext = ctk.url.getfileext(self.saveurl,false) if name == '' then name = 'Untitled.html' ext = 'html' end local sug = app.dir..name local destfile = app.savefile('All files (*.*)|*.*',ext,sug) if destfile ~= '' then ctk.file.copy(filename,destfile) end ctk.file.delete(filename) else self:SavePageAs() -- try online version end end function PageMenu:SaveCachedAs(url) if url == nil then url = tab.url end self.saveurl = url if url ~= '' then if self.crm == nil then self.crm = osr:new() end local c = self.crm c.onsetsource = function(s,h) PageMenu:SaveCachedAs_Ask(PageMenu.crm:savetofile()) end c:loadcached(url) end end function PageMenu:SavePageAs() if tab:hasloadedurl(true) then debug.print('Saving Page from the cloud...') browser.navbar:eval('SandcatDownloader.SaveURL_As($(#url).value)') end end function PageMenu:TakeScreenshot() if tab:hasloadedurl(true) then local sf = tab.screenshot if sf ~= '' then local sug = app.dir..ctk.file.getname(sf) local destfile = app.savefile('PNG files (*.png)|*.png','png',sug) if destfile ~= '' then ctk.file.copy(sf,destfile) end end ctk.file.delete(sf) end end function PageMenu:ViewDevTools() if tab:hasloadedurl(true) then tab:viewdevtools() end end function PageMenu:DeleteURLLogItem(itemid,logname) local logfile = browser.info.configdir..logname..'.sclist' local slp = ctk.string.loop:new() local found = false if ctk.file.exists(logfile) then slp:loadfromfile(logfile) while slp:parsing() do if ctk.string.match(slp.current,'<item*id="'..itemid..'"*>') then slp:curdelete() found = true end end if found == true then slp:savetofile(logfile) end end slp:release() tab.engine:eval('$("#'..itemid..'").remove()') end function PageMenu:ViewURLLogFile(newtab,histname) local html = Sandcat:getfile('histview.html') local style = '' local histfile = browser.info.configdir..histname..'.sclist' local tabicon = '@ICON_BLANK' local menu = '' local sl = ctk.string.list:new() if newtab == nil then newtab = true end if histname == 'History' then style = [[ tr.item { context-menu: selector(#historymenu); } ]] menu = [[ <li onclick="PageMenu:DeleteURLLogItem('%i','History')">Delete</li> ]] end if histname == 'Bookmarks' then style = [[ th.visited { display: none; } td.visited { display: none; } ]] tabicon = 'url(Resources.pak#16/icon_bookmarks.png)' menu = [[ <li onclick="PageMenu:DeleteURLLogItem('%i','Bookmarks')">Delete</li> ]] end if ctk.file.exists(histfile) then local p = ctk.html.parser:new() p:load(ctk.file.getcontents(histfile)) while p:parsing() do if p.tagname == 'item' then local url = p:getattrib('url') local visited = p:getattrib('visited') local name = p:getattrib('name') local id = p:getattrib('id') sl:add('<tr.item url="'..url..'" role="option" style="context-menu: selector(#menu'..id..');" id="'..id..'">') sl:add('<td>'..name..'</td>') sl:add('<td>'..url..'</td>') sl:add('<td.visited>'..visited..'</td>') sl:add('<menu.context id="menu'..id..'">'..ctk.string.replace(menu,'%i',id)..'</menu>') sl:add('</tr>') end end p:release() end html = ctk.string.replace(html,'%style%',style) html = ctk.string.replace(html,'%history%',sl.text) sl:release() if newtab then local j = {} j.title = histname j.tag = string.lower(histname)..'view' j.toolbar = 'Resources.pak#histview_tb'..string.lower(histname)..'.html' j.icon = tabicon j.html = html browser.newtabx(j) else tab:loadx(html) end end function PageMenu:ViewHistory(newtab) self:ViewURLLogFile(newtab,'History') end function PageMenu:ViewBookmarks(newtab) self:ViewURLLogFile(newtab,'Bookmarks') end function PageMenu:ViewTasks() if browser.info.tasks ~= '' then browser.setactivepage('tasks') else app.showmessage('No tasks to display.') end --[[ TaskView = TaskView or Sandcat:require('taskview') TaskView:loadtasks() ]] end function PageMenu:ViewDownloads() TaskView = TaskView or Sandcat:require('taskview') TaskView:loaddownloads() end
local checkpoints = require("Checkpoints/checkpoints") local nocrap = require("Modules.Dregu.no_crap") local sunkencity1 = { identifier = "sunkencity 1", title = "Sunken City 1: Sticky Situation", theme = THEME.SUNKEN_CITY, width = 4, height = 6, file_name = "sunk-1.lvl", world = 7, level = 1, } local level_state = { loaded = false, callbacks = {}, } sunkencity1.load_level = function() if level_state.loaded then return end level_state.loaded = true define_tile_code("sunken_arrow_trap") level_state.callbacks[#level_state.callbacks+1] = set_pre_tile_code_callback(function(x, y, layer) local ent = spawn_entity(ENT_TYPE.FLOOR_POISONED_ARROW_TRAP, x, y, layer, 0, 0) ent = get_entity(ent) return true end, "sunken_arrow_trap") level_state.callbacks[#level_state.callbacks+1] = set_post_entity_spawn(function (ent) ent.color:set_rgba(108, 220, 235, 255) --light blue end, SPAWN_TYPE.ANY, 0, ENT_TYPE.FLOOR_THORN_VINE) checkpoints.activate() if not checkpoints.get_saved_checkpoint() then toast(sunkencity1.title) end end sunkencity1.unload_level = function() if not level_state.loaded then return end checkpoints.deactivate() local callbacks_to_clear = level_state.callbacks level_state.loaded = false level_state.callbacks = {} for _,callback in ipairs(callbacks_to_clear) do clear_callback(callback) end end return sunkencity1
ITEM.name = "Flattened plastic bag" ITEM.description= "A bag that has been stepped on multiple times. There is something inside." ITEM.model = "models/props_junk/garbage_bag001a.mdl" ITEM.width = 2 ITEM.height = 2 ITEM.flag = "A" ITEM.items[1] = { dropAmount = 2, dropRareChance = 15, dropVeryRareChance = 5, itemsCommon = { {"cig1", {["quantity"] = 2}}, {"cannedcorn", {["quantity"] = 2}}, {"cannedbeans", {["quantity"] = 2}}, {"cannedtomato", {["quantity"] = 2}}, {"cannedolives", {["quantity"] = 2}}, {"cannedchilibeans", {["quantity"] = 2}}, {"moonshine", {["quantity"] = 2}}, {"vodka2", {["quantity"] = 2},}, {"vodka2", {["quantity"] = 2}}, }, itemsRare = { {"brokenpda"}, {"brokenguitar"}, {"brokenradio"}, {"brokenradiohandheld"}, {"brokengeigercounter"}, {"brokenflashlight"}, {"brokenpda"}, {"izlomhand"}, }, itemsVeryRare = { {"gpsmappingdevice"}, {"anomalymap"}, }, }
-- Cjdns admin module for Lua -- Written by Philip Horger -- hacked up dumpTable, switchpinger, peerstats -- and other oddities by William Fleurant common = require 'cjdns/common' RouterFunctions = {} RouterFunctions.__index = RouterFunctions common.RouterFunctions = RouterFunctions function RouterFunctions.new(ai, config) properties = { ai = ai, config = config or ai.config } return setmetatable(properties, RouterFunctions) end function RouterFunctions:dumpTable(page) local response, err = self.ai:auth({ q = "NodeStore_dumpTable()", page = page, }) return response.routingTable end function RouterFunctions:lookup(address) local response, err = self.ai:auth({ q = "RouterModule_lookup", address = address }) if not response then return nil, err elseif response.error ~= "none" then return nil, response.error elseif response.result then return response.result else return nil, "bad response format" end end function RouterFunctions:availableFunctions(page) local response, err = self.ai:auth({q = "Admin_availableFunctions"}) print (err) print (response) end function RouterFunctions:switchpinger(path, data, timeout) local response, err = self.ai:auth({ q = "SwitchPinger_ping", path = path, data = 0, timeout = '' }) for k,v in pairs(response) do print(k,v) end return response end function RouterFunctions:peerStats(page) if page then page = page else page = 0 end while page do local response, err = self.ai:auth({ q = "InterfaceController_peerStats", page = page, }) for pubkey,switch in pairs(response.peers,response.peers) do print (response.peers[pubkey]['publicKey'], response.peers[pubkey]['switchLabel']) end if response.more then page = page + 1 else page = nil end end return response end function RouterFunctions:AuthorizedPasswords_list() local response, err = self.ai:auth({ q = "AuthorizedPasswords_list()" }) print("AuthorizedPasswords_list()") return reponse end function RouterFunctions:pingNode(path, timeout) local request = { q = "RouterModule_pingNode", path = path } if timeout then request.timeout = timeout end local response, err = self.ai:auth(request) if not response then return nil, err elseif response.error then return nil, response.error elseif response.result then if response.result == "timeout" then return nil, "timeout" else return response.ms end else return nil, "bad response format" end end function RouterFunctions:memory(page) local response, err = self.ai:call({q = "Admin_availableFunctions", page=page}) for key,value in pairs(response.availableFunctions) do print(key) end print(response) end
local awful = require("awful") local gears = require("gears") local wibox = require("wibox") local beautiful = require("beautiful") local lain = require("lain") local clickable_container = require("widgets.clickable-container") local markup = lain.util.markup return function(widget, buttons, data, response) widget:reset() widget:add( wibox.container.background( wibox.container.place( wibox.container.constraint( wibox.container.margin( wibox.widget.textbox(markup.font(beautiful.font_base .. " Bold 12", "Available Networks")), 20 ), "exact", 300, 50 ), "left", "center" ), "#050505" ) ) local more_menu, more_menu_container, more_menu_controller for i, network in ipairs(response.devices) do local cache = data[network] local signal, ssid, ssid_margin, connected, ssid_container, container if cache then signal = cache.signal ssid = cache.ssid ssid_container = cache.ssid_container connected = cache.connected container = cache.container else signal = wibox.widget.textbox() ssid = wibox.widget.textbox() connected = wibox.widget.textbox() ssid_container = clickable_container( wibox.container.place( wibox.container.constraint( wibox.widget { wibox.container.margin( { wibox.container.margin(signal, 0, 15), ssid, layout = wibox.layout.fixed.horizontal }, 20 ), nil, wibox.container.margin(connected, 0, 20), layout = wibox.layout.align.horizontal }, "exact", 300, 50 ), "left", "center" ) ) container = ssid_container data[network] = { signal, ssid = ssid, ssid_container = ssid_container, connected = connected, container = container } end local icon_string = "" if network.signal > 66 then icon_string = "" elseif network.signal > 33 then icon_string = "" end signal:set_markup(awful.util.theme_functions.icon_string({ icon = icon_string, font = "Font Awesome 5 Pro" })) ssid:set_markup(markup.font(beautiful.font_base .. " Bold 10", network.ssid)) if network.inUse then connected:set_markup("Connected") else connected:set_markup("") end container:buttons( { awful.button( {}, awful.button.names.LEFT, function() if network.inUse then awful.spawn("nmcli d wifi disconnect '" .. network.ssid .. "'") else awful.spawn("nmcli d wifi connect '" .. network.ssid .. "'") end widget.popup.visible = false end ) } ) if i < 7 then widget:add(container) -- elseif i < 15 then -- if more_menu == nil then -- more_menu = -- wibox.widget { -- layout = wibox.layout.fixed.vertical -- } -- more_menu_container = -- awful.popup { -- screen = awful.screen.focused(), -- visible = false, -- ontop = true, -- shape = gears.shape.rectangle, -- offset = {y = 5}, -- widget = wibox.container.background(more_menu, "#ff0000") -- } -- more_menu_container:move_next_to(widget.popup) -- more_menu_controller = -- wibox.container.background( -- wibox.container.constraint( -- wibox.container.margin( -- wibox.widget.textbox(markup.font(beautiful.font_base .. " Bold 10", "More")), -- 15, -- 15, -- 10, -- 10 -- ), -- "exact", -- 300 -- ), -- "#292929" -- ) -- more_menu_controller:buttons( -- { -- awful.button( -- {}, -- awful.button.names.LEFT, -- function() -- awful.placement.bottom_right( -- more_menu_container, -- { -- margins = { -- bottom = 50, -- right = 400 -- }, -- parent = awful.screen.focused() -- } -- ) -- more_menu_container.visible = not more_menu_container.visible -- end -- ) -- } -- ) -- widget:add(more_menu_controller) -- end -- more_menu:add(container) end if more_menu_container then more_menu_container.visible = false end end widget:add( wibox.container.background( wibox.container.place( wibox.container.constraint( wibox.container.margin(wibox.widget.textbox(markup.font(beautiful.font_base .. " Bold 12", "VPNs")), 20), "exact", 300, 50 ), "left", "center" ), "#050505" ) ) for i, network in ipairs(response.vpns) do local cache = data[network] local name, name_margin, connected, name_container, container if cache then signal = cache.signal name = cache.name name_container = cache.name_container connected = cache.connected container = cache.container else name = wibox.widget.textbox() connected = wibox.widget.textbox() name_container = clickable_container( wibox.container.place( wibox.container.constraint( wibox.widget { wibox.container.margin( { name, layout = wibox.layout.fixed.horizontal }, 20 ), nil, wibox.container.margin(connected, 0, 20), layout = wibox.layout.align.horizontal }, "exact", 300, 50 ), "left", "center" ) ) container = name_container data[network] = { name = name, name_container = name_container, connected = connected, container = container } end name:set_markup(markup.font(beautiful.font_base .. " Bold 10", network.name)) if network.connected then connected:set_markup("Connected") else connected:set_markup("") end container:buttons( { awful.button( {}, awful.button.names.LEFT, function() if network.connected then awful.spawn("nmcli con down '" .. network.name .. "'") else awful.spawn("nmcli con up '" .. network.name .. "'") end widget.popup.visible = false end ) } ) widget:add(container) end end
---引导系统-客户端表现 ---@script Guide effect ---@copyright Lilith Games, Avatar Team ---@author Sid Zhang local root = script.Parent local tweenerHand = Tween:TweenProperty(root.ImgDot.ImgHand, {Pivot = Vector2(0.35, 1)}, 0.5, Enum.EaseCurve.Linear) local tweenerCircle = Tween:TweenProperty(root.ImgDot.ImgCircle, {Size = Vector2(276, 276), Alpha = 0}, 0.5, Enum.EaseCurve.Linear) ::Repeat:: --重置UI位置与状态 root.ImgDot.ImgHand.Pivot = Vector2(0.35, 1.5) root.ImgDot.ImgCircle.Size = Vector2(48, 48) root.ImgDot.ImgCircle.Alpha = 1 tweenerHand:Play() tweenerHand:WaitForComplete() tweenerCircle:Play() tweenerCircle:WaitForComplete() goto Repeat
-- luacheck: max line length 180 -- local sys = require'sys' -- local nvim = require'nvim' local load_module = require'tools'.helpers.load_module -- local set_command = nvim.commands.set_command -- local set_autocmd = nvim.autocmds.set_autocmd -- local set_mapping = nvim.mappings.set_mapping local neogit = load_module'neogit' if neogit == nil then return false end neogit.setup { -- mappings = { -- -- modify status buffer mappings -- status = { -- -- Adds a mapping with "B" as key that does the "BranchPopup" command -- -- ["B"] = "BranchPopup", -- -- Removes the default mapping of "s" -- -- ["s"] = "", -- } -- } } return true
local timer = require 'timer' local _pubics, _subics, qn = {}, {} local RSP = { ok = 200, cre = 201, del = 202, chg = 204, ctn = 205, breq = 400, unauth = 401, nfnd = 404, nalw = 405, cnft = 409 } local CMD = { r = 0, w = 1, dcv = 2, wa = 3, e = 4, ob = 5, noti = 6 } local ERR = { sces = 0, nfnd = 1, unrd = 2, unwt = 3, une = 4, timeout = 5, nilclient = 6 } local TTYPE = { rt = 0, obj = 1, inst = 2, rsc = 3 } local TAG = { nfnd = '_notfound_', unrd = '_unreadable_', exec = '_exec_', unwt = '_unwritable_' } local core = { RSP = RSP, CMD = CMD, ERR = ERR, TTYPE = TTYPE, TAG = TAG } -- ok function core._rawHdlr(conn, topic, message) local strmsg, intf, jmsg, _evt, tid = qn:decrypt(message), core._path(topic) if (strmsg:sub(1, 1) == '{' and strmsg:sub(-1) == '}') then jmsg = cjson.decode(strmsg) tid = jmsg.transId end if (intf == _subics.register) then _evt = 'register:rsp:' .. tid if (jmsg.status == RSP.ok or jmsg.status == RSP.cre) then qn:_lfUp(true) else qn:_lfUp(false) end elseif (intf == _subics.deregister) then _evt = 'deregister:rsp:' .. tid elseif (intf == _subics.notify) then _evt = 'notify:rsp:' .. tid elseif (intf == _subics.update) then _evt = 'update:rsp:' .. tid elseif (intf == _subics.ping) then _evt = 'ping:rsp:' .. tid elseif (intf == _subics.request) then _evt = '_request' -- No callbacks elseif (intf == _subics.announce) then _evt = 'announce' jmsg = strmsg -- No callbacks end if (_evt ~= nil) then qn:emit(_evt, jmsg) if (qn._tobjs[_evt] ~= nil) then timer.clearTimeout(qn._tobjs[_evt]) end end qn:emit('message', topic, strmsg) -- emit raw message out end function core._reqHdlr(msg) local rsp, rtn = { transId = msg.transId, cmdId = msg.cmdId, status = RSP.ok, data = nil }, true local tgtype, target = qn:_target(msg.oid, msg.iid, msg.rid) if (tgtype == TTYPE.rt or msg.oid == nil) then rsp.status = RSP.breq -- Request Root is not allowed elseif (target == TAG.nfnd) then rsp.status = RSP.nfnd else rtn = false end if (rtn == true) then qn:pubResponse(rsp) return end if (msg.cmdId == CMD.r) then if (target == TAG.unrd) then rsp.status = RSP.nalw else rsp.status = RSP.ctn end rsp.data = target elseif (msg.cmdId == CMD.w) then -- [TODO] 1. allow object and instance 2. tackle access control in the near future if (tgtype == TTYPE.obj or tgtype == TTYPE.inst) then -- will support in the future rsp.status = RSP.nalw elseif (tgtype == TTYPE.rsc) then rsp.status = RSP.chg qn:writeResrc(msg.oid, msg.iid, msg.rid, msg.data, function (err, val) if (err == ERR.unwt) then rsp.status = RSP.nalw else rsp.data = val end end) end elseif (cmdId == CMD.dcv) then local export, attrs = {} if (tgtype == TTYPE.obj) then attrs = qn:getAttrs(msg.oid) or {} local obj, resrcList = qn.so[msg.oid], {} for iid, resrcs in pairs(obj) do resrcList[iid] = {} for rid, r in resrcs do table.insert(resrcList[iid], rid) end end attrs.resrcList = resrcList elseif (tgtype == TTYPE.inst) then attrs = qn:getAttrs(msg.oid, msg.iid) elseif (tgtype == TTYPE.rsc) then attrs = qn:getAttrs(msg.oid, msg.iid, msg.rid) end for k, v in pairs(attrs) do if (k ~= 'mute' and k ~= 'lastrp') then export[k] = v end end rsp.status = RSP.ctn rsp.data = export elseif (cmdId == CMD.wa) then local badAttr = false local allowedAttrsMock = { pmin = true, pmax = true, gt = true, lt = true, step = true, cancel = true, pintvl = true } if (msg.attrs ~= 'table') then rsp.status = RSP.breq else for k, v in pairs(msg.attrs) do if (allowedAttrsMock[k] ~= true) then badAttr = true end end if (badAttr == true) then rsp.status = RSP.breq else rsp.status = RSP.chg if (tgtype == TTYPE.obj) then if (msg.attrs.cancel ~= nil) then msg.attrs.cancel = true end -- [TODO] always avoid report, support in future qn:setAttrs(msg.oid, msg.attrs) elseif (tgtype == TTYPE.inst) then if (msg.attrs.cancel ~= nil) then msg.attrs.cancel = true end -- [TODO] always avoid report, support in future qn:setAttrs(msg.oid, msg.iid, msg.attrs) elseif (tgtype == TTYPE.rsc) then if (msg.attrs.cancel) then qn:disableReport(msg.oid, msg.iid, msg.rid) end qn:setAttrs(msg.oid, msg.iid, msg.rid, msg.attrs) else rsp.status = RSP.nfnd end end end elseif (cmdId == CMD.e) then if (tgtype ~= TTYPE.rsc) then rsp.status = RSP.nalw else rsp.status = RSP.chg qn:execResrc(msg.oid, msg.iid, msg.rid, msg.data, function (err, execRsp) for k, v in pairs(execRsp) do rsp[k] = v end end) end elseif (cmdId == CMD.ob) then rsp.status = RSP.chg if (tgtype == TTYPE.obj or tgtype == TTYPE.inst) then rsp.status = RSP.nalw -- [TODO] will support in the future elseif (tgtype == TTYPE.rsc) then qn:enableReport(msg.oid, msg.iid, msg.rid) end elseif (cmdId == CMD.noti) then return -- notify, this is not a request, do nothing else rsp.status = RSP.breq -- unknown request end qn:pubResponse(rsp) end function core.register(q) local intfs, cId = { 'register', 'deregister', 'notify', 'update', 'ping' } qn = q qn:on('raw', core._rawHdlr) qn:on('_request', core._reqHdlr) cId = qn.clientId for i, itf in ipairs(intfs) do _pubics[itf] = itf .. '/' .. cId _subics[itf] = itf .. '/response/' .. cId end _pubics.response = 'response/' .. cId _subics.request = 'request/' .. cId _subics.announce = 'announce' qn.so = qn.so or {} -- LWM2M Object: LWM2M Server Object -- 0 = short server id, 1 = lifetime, 2 = default pmin, 3 = default pmax, 8 = registration update trigger qn.so[1] = { [0] = nil, [1] = qn.lifetime, [2] = 1, [3] = 60, [8] = { exec = function (...) qn.pubRegister() end } } -- LWM2M Object: Device -- 0 = manuf, 1 = model, 4 = reboot, [X]5 = factory reset, 6 = available power sources, -- 7 = power source voltage, 17 = device type, 18 = hardware version, 19 = software version qn.so[3] = { [0] = 'lwmqn', [1] = 'MQ1', [4] = { exec = function () node.restart() end }, [6] = 0, [7] = 5000, [17] = 'generic', [18] = 'v1', [19] = 'v1' } -- LWM2M Object: Connectivity Monitoring -- 4 = ip, 5 = router ip qn.so[4] = { [4] = qn.ip, [5] = '' } -- load protected methods qn._lfUp = function (q, enable) q._lfsecs = 0 timer.clearInterval(q._upder) q._upder = nil if (enable == true) then q._upder = timer.setInterval(function () q._lfsecs = q._lfsecs + 1 if (q._lfsecs == q.lifetime) then q:pubUpdate({ lifetime = q.lifetime }) q._lfsecs = 0 end end, 1000) end end qn._chkResrc = function (q, oid, iid, rid, currVal) local attrs, rpt = q:getAttrs(oid, iid, rid), false if (attrs == nil) then return false end -- target not found if (attrs.cancel or attrs.mute) then return false end local lastrp, gt, lt, step = attrs.lastrp, attrs.gt, attrs.lt, attrs.step if (type(currVal) == 'table') then if (type(lastrp) == 'table') then for k, v in pairs(currVal) do rpt = rpt or v ~= lastrp[k] end else rpt = true end elseif (type(currVal) ~= 'number') then rpt = lastrp ~= currVal else if (type(gt) == 'number' and type(lt) == 'number' and lt > gt) then rpt = lastrp ~= currVal and currVal > gt and currVal < lt else rpt = type(gt) == 'number' and lastrp ~= currVal and currVal > gt rpt = rpt or type(lt) == 'number' and lastrp ~= currVal and currVal < lt end if (type(step) == 'number') then rpt = rpt or math.abs(currVal - lastrp) > step end end if (rpt) then attrs.lastrp = currVal q:pubNotify({ oid = oid, iid = iid, rid = rid, data = currVal }) end return rpt end qn.enableReport = function (q, oid, iid, rid, attrs) local tgtype, target = q:_target(oid, iid, rid) if (target == TAG.nfnd) then return false end local resrcAttrs = q:getAttrs(oid, iid, rid) local rpid = oid .. ':' .. iid .. ':' .. rid local pminMs, pmaxMs, rRpt = resrcAttrs.pmin * 1000, resrcAttrs.pmax * 1000 -- pmin and pmax are MUSTs resrcAttrs.cancel = false resrcAttrs.mute = true q._rpters[rpid] = { minRep = nil, maxRep = nil, poller = nil } -- reporter place holder rRpt = q._rpters[rpid] rRpt.minRep = timer.setTimeout(function () -- mute is use to control the poller if (pminMs == 0) then resrcAttrs.mute = false -- if no pmin, just report at pmax triggered else q:readResrc(oid, iid, rid, function (err, val) resrcAttrs.mute = false q:pubNotify({ oid = oid, iid = iid, rid = rid, data = val }) end) end end, pminMs) rRpt.maxRep = timer.setInterval(function () resrcAttrs.mute = true q:readResrc(oid, iid, rid, function (err, val) resrcAttrs.mute = false q:pubNotify({ oid = oid, iid = iid, rid = rid, data = val }) end) if (rRpt.minRep ~= nil) then timer.clearTimeout(rRpt.minRep) end rRpt.minRep = nil rRpt.minRep = timer.setTimeout(function () if (pminMs == 0) then resrcAttrs.mute = false -- if no pmin, just report at pmax triggered else q:readResrc(oid, iid, rid, function (err, val) resrcAttrs.mute = false q:pubNotify({ oid = oid, iid = iid, rid = rid, data = val }) end) end end, pminMs) end, pmaxMs) return true end qn.disableReport = function (q, oid, iid, rid) local rpid = oid .. ':' .. iid .. ':' .. rid local resrcAttrs, rRpt = q:getAttrs(oid, iid, rid), q._rpters[rpid] if (rRpt == nil) then return false end if (resrcAttrs == nil) then return false end resrcAttrs.cancel = true resrcAttrs.mute = true timer.clearTimeout(rRpt.minRep) timer.clearInterval(rRpt.maxRep) timer.clearInterval(rRpt.poller) rRpt.minRep = nil rRpt.maxRep = nil rRpt.poller = nil q._rpters[rpid] = nil return true end qn._tCtrl = function (q, key, delay) q._tobjs[key] = timer.setTimeout(function () qn:emit(key, { status = ERR.timeout }) if (q._tobjs[key] ~= nil) then q._tobjs[key] = nil end end, delay) end end function core._path(path) local head, tail = 1, #path path = path:gsub("%.", "/") if (path:sub(1, 1) == '/') then head = 2 end if (path:sub(#path, #path) == '/') then tail = tail - 1 end return path:sub(head, tail) end return core
data:extend( { { type = "item-subgroup", name = "fconsumer-food", group = "fconsumer", order = "a", }, -- Algae Patty { type = "item", name = "food-algae-patty", icon = "__fconsumer__/icons/algae-patty.png", icon_size = 32, subgroup = "fconsumer-food", order = "a[food-algae-patty]", stack_size = 200 }, { type = "recipe", name = "cook-algae-patty", enabled = true, ingredients = { {type = "item", name = "algae-green", amount = 5}, }, energy_required = 3, -- crafting time result = "food-algae-patty" }, -- Food { type = "item", name = "food", icon = "__fconsumer__/icons/food.png", icon_size = 32, subgroup = "fconsumer-food", order = "a[food]", stack_size = 200 }, -- Soylent Green { type = "item", name = "food-soylent-green", icon = "__fconsumer__/icons/algae-patty.png", icon_size = 32, subgroup = "fconsumer-food", order = "a[food-soylent-green]", stack_size = 200 }, { type = "recipe", name = "cook-soylent-green", enabled = true, category = "crafting-with-fluid", ingredients = { {type = "fluid", name = "liquid-nutrient-pulp", amount = 50} }, energy_required = 5, -- crafting time result = "food-soylent-green" }, { type = "recipe", name = "cook-soylent-green-food", enabled = true, category = "crafting-with-fluid", ingredients = { {type = "fluid", name = "liquid-nutrient-pulp", amount = 50} }, energy_required = 5, -- crafting time result = "food" }, })
--- -- This file contains all shared networking functions, to sync and manage the information between server and clients -- @author saibotk -- @module ttt2net ttt2net = {} -- Network message name constants ttt2net.NETMSG_META_UPDATE = "TTT2_NET_META_UPDATE" ttt2net.NETMSG_DATA_UPDATE = "TTT2_NET_DATA_UPDATE" ttt2net.NETMSG_REQUEST_FULL_STATE_UPDATE = "TTT2_NET_REQUEST_FULL_STATE_UPDATE" -- Network stream message name constants ttt2net.NET_STREAM_FULL_STATE_UPDATE = "TTT2_NET_STREAM_FULL_STATE_UPDATE" --- -- @class Player --- -- Player extensions -- Some simple functions on the player class, to simplify the use of this system. local plymeta = assert(FindMetaTable("Player"), "[TTT2NET] FAILED TO FIND PLAYER TABLE") --- -- Returns the current bool value for a given path on the player. -- -- @param any path The path to return the value for -- @param[opt] boolean fallback The fallback value to return instead of nil -- @return boolean The value at the path or fallback if the value is nil -- @realm shared function plymeta:TTT2NETGetBool(path, fallback) return tobool(ttt2net.GetOnPlayer(path, self) == true or fallback) end --- -- Returns the current number value for a given path on the player. -- -- @param any path The path to return the value for -- @param number fallback The fallback value to return instead of nil -- @return number The value at the path or fallback if the value is nil -- @realm shared function plymeta:TTT2NETGetInt(path, fallback) return tonumber(ttt2net.GetOnPlayer(path, self) or fallback) end --- -- Returns the current unsigned number value for a given path on the player. -- -- @param any path The path to return the value for -- @param number fallback The fallback value to return instead of nil -- @return number The value at the path or fallback if the value is nil -- @realm shared function plymeta:TTT2NETGetUInt(path, fallback) return tonumber(ttt2net.GetOnPlayer(path, self) or fallback) end --- -- Returns the current float value for a given path on the player. -- -- @param any path The path to return the value for -- @param number fallback The fallback value to return instead of nil -- @return number The value at the path or fallback if the value is nil -- @realm shared function plymeta:TTT2NETGetFloat(path, fallback) return tonumber(ttt2net.GetOnPlayer(path, self) or fallback) end --- -- Returns the current string value for a given path on the player. -- -- @param any path The path to return the value for -- @param string fallback The fallback value to return instead of nil -- @return string The value at the path or fallback if the value is nil -- @realm shared function plymeta:TTT2NETGetString(path, fallback) return tostring(ttt2net.GetOnPlayer(path, self) or fallback) end
local PLUGIN = PLUGIN PLUGIN.name = "Simple Nicknames" PLUGIN.author = "alexgrist" PLUGIN.description = "Allows players to nickname themselves." PLUGIN.license = [[ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> ]] ix.lang.AddTable("english", { cmdSetNickname = "Set your nickname.", nicknameTooLong = "The nickname you chose is too long!", nicknameNowKnown = "You are now known as %s." }) ix.command.Add("SetNickname", { description = "@cmdSetNickname", arguments = { bit.bor(ix.type.text, ix.type.optional) }, OnRun = function(self, client, nickname) local character = client:GetCharacter() local name = character:GetName() if (isstring(nickname) and nickname != "" and nickname != "none") then if (nickname:len() > 24) then return "@nicknameTooLong" end if (!string.find(name, "'")) then name = string.gsub(name, " ", " '" .. nickname .. "' ") else name = string.gsub(name, "'.*'", "'" .. nickname .. "'") end else name = string.gsub(name, "'.*' ", "") end character:SetName(name) return "@nicknameNowKnown", name end })
-- Combine tests require './lib' require './data' setup() local old_setup = setup local old_teardown = teardown local empty_function = function() end setup = empty_function teardown = empty_function local function shuffle(tbl) local size = #tbl for i = size, 1, -1 do local rand = math.random(size) tbl[i], tbl[rand] = tbl[rand], tbl[i] end return tbl end local files = {'mt1.lua','mt2.lua','mt3.lua','mt4.lua'} local num_files = #files for i = 1, num_files do table.insert(files, files[i]) end files = shuffle(files) for _, f in ipairs(files) do dofile(f) end old_teardown()
require 'luarocks.loader' local https = require 'ssl.https' local json = require 'lunajson' local options = require 'mp.options' local osd_ass_cc = mp.get_property_osd('osd-ass-cc/0') local chat local opt = { toggle_key = 'c', enable_position_binds = true, osd_position = 1, -- osd_position uses 'numpad values' message_duration = 10, -- in seconds message_limit = 10, update_interval = 0.3, redraw_interval = 0.5, -- text styling font = 'Helvetica', font_size = 8, font_colour = 'FFFFFF', border_size = 1.0, border_colour = '000000', alpha = '11', mod_font_colour = '00FF00', mod_border_colour = '111111', streamer_font_colour = '0000FF', streamer_border_colour = '111111', } options.read_options(opt) local Deque = {} Deque.__index = Deque function Deque.new() local self = setmetatable({}, Deque) self.head = 0 self.tail = -1 return self end function Deque:flush() while not self:empty() do self:lpop() end self.head = 0 self.tail = -1 end function Deque:lpush(value) local head = self.head - 1 self.head = head self[head] = value end function Deque:rpush(value) local tail = self.tail + 1 self.tail = tail self[tail] = value end function Deque:lpeek() if self:empty() then error('empty deque') end return self[self.head] end function Deque:lpop() if self:empty() then error('empty deque') end local head = self.head local value = self[head] self[head] = nil self.head = head + 1 return value end function Deque:rpeek() if self:empty() then error('empty deque') end return self[self.tail] end function Deque:rpop() if self:empty() then error('empty deque') end local tail = self.tail local value = self[tail] self[tail] = nil self.tail = tail - 1 return value end function Deque:length() if self.head > self.tail then return 0 else return self.tail - self.head + 1 end end function Deque:empty() return self:length() == 0 end local TwitchChat = {} TwitchChat.__index = TwitchChat function TwitchChat.new(video_id) local self = setmetatable({}, TwitchChat) self.video_id = video_id self.messages = Deque.new() self.display = Deque.new() local url = string.format('https://rechat.twitch.tv/rechat-messages?start=%s&video_id=v%s', 0, video_id) local resp_body, code, headers, status = https.request(url) if code ~= 400 then error(string.format('received http status %s for "%s"', code, url)) end local resp = json.decode(resp_body) local pat_range = '0 is not between (%d+) and (%d+)' self.ts_start, self.ts_end = string.match(resp.errors[1].detail, pat_range) if self.ts_start == nil or self.ts_end == nil then error('unable to parse start and end timestamps') end self.ts_current = self.ts_start return self end function TwitchChat:fetch_block(ts_absolute) local url = string.format('https://rechat.twitch.tv/rechat-messages?start=%s&video_id=v%s', math.floor(ts_absolute), self.video_id) local resp_body, code, headers, status = https.request(url) if code == 200 then local resp = json.decode(resp_body) for _, msg in ipairs(resp.data) do local message = {} message.ts = (msg.attributes.timestamp / 1000) - self.ts_start message.user = msg.attributes.tags['display-name'] message.text = msg.attributes.message message.is_streamer = msg.attributes.from:lower() == msg.attributes.room:lower() message.is_mod = msg.attributes.tags.mod self.messages:rpush(message) end else error(string.format('http error %s: %s', code, resp_body)) end self.ts_current = ts_absolute + 30 end function TwitchChat:fetch_next_block() self:fetch_block(self.ts_current) end function TwitchChat:fetch_block_at_ts(ts) self:fetch_block(self.ts_start + ts) end function TwitchChat:update_display(ts) while not self.display:empty() and self.display:lpeek().ts < ts - opt.message_duration do self.display:lpop() end if self.messages:empty() then self:fetch_next_block() end while not self.messages:empty() and self.messages:lpeek().ts < ts - opt.message_duration do self.messages:lpop() end while not self.messages:empty() and self.messages:lpeek().ts < ts do self.display:rpush(self.messages:lpop()) end end function has_vo() local vo_conf = mp.get_property("vo-configured") local video = mp.get_property("video") return vo_conf == "yes" and (video and video ~= "no" and video ~= "") end function txt_username(msg) local s = '' if msg.user == nil then return '' end if msg.is_streamer then s = string.format( '{\\1c&H%s&}{\\3c&H%s&}%s:{\\1c&H%s&}{\\3c&H%s&}', opt.streamer_font_colour, opt.streamer_border_colour, msg.user, opt.font_colour, opt.border_colour ) elseif msg.is_mod then s = string.format( '{\\1c&H%s&}{\\3c&H%s&}%s:{\\1c&H%s&}{\\3c&H%s&}', opt.mod_font_colour, opt.mod_border_colour, msg.user, opt.font_colour, opt.border_colour ) else s = msg.user .. ':' end return string.format('{\\b1}%s{\\b0}', s) end function ev_tick() if chat == nil then return end local video_ts = mp.get_property_number('time-pos', 0) chat:update_display(video_ts) end function ev_redraw() if chat == nil or chat.display:empty() then return end local message = '' if not has_vo() then return end message = string.format( '%s{\\an%d}{\\fs%d}{\\fn%s}{\\bord%f}{\\3c&H%s&}{\\1c&H%s&}{\\alpha&H%s&}', osd_ass_cc, opt.osd_position, opt.font_size, opt.font, opt.border_size, opt.border_colour, opt.font_colour, opt.alpha ) for idx=chat.display.head, chat.display.tail do if idx - chat.display.head == opt.message_limit then chat.display:lpop() break end local msg = chat.display[idx] message = message .. string.format( '%s %s\\N', txt_username(msg), msg.text ) end mp.osd_message(message, opt.redraw_interval + 0.1) end local tm_tick = mp.add_periodic_timer(opt.update_interval, ev_tick) tm_tick:kill() local tm_redraw = mp.add_periodic_timer(opt.redraw_interval, ev_redraw) tm_redraw:kill() local tm_redraw_enabled = false function ev_pause(name, paused) if paused == true then tm_tick:stop() else tm_tick:resume() end end function ev_toggle() if tm_redraw_enabled then tm_redraw:kill() tm_redraw_enabled = false mp.osd_message('', 0) else tm_redraw:resume() tm_redraw_enabled = true ev_redraw() end end function ev_set_pos(position) opt.osd_position = position end function ev_seek() tm_tick:kill() chat.messages:flush() local video_ts = mp.get_property_number('time-pos', 0) chat:fetch_block_at_ts(video_ts) tm_tick:resume() end function ev_start_file() local path = mp.get_property('path') if path == nil then return end local pat_twitch_vod = 'twitch.tv/videos/(%d+)' local video_id = string.match(path, pat_twitch_vod) if video_id ~= nil then chat = TwitchChat.new(video_id) tm_tick:resume() tm_redraw:resume() tm_redraw_enabled = true mp.register_event('playback-restart', ev_seek) mp.observe_property('pause', 'bool', ev_pause) mp.add_key_binding(opt.toggle_key, 'toggle', ev_toggle, {repeatable=false}) end end function ev_end_file() if tm_tick ~= nil then tm_tick:kill() end if tm_redraw ~= nil then tm_redraw:kill() end tm_redraw_enabled = false tm_tick = nil tm_redraw = nil mp.unregister_event(ev_seek) mp.unobserve_property(ev_pause) mp.remove_key_binding('toggle') end mp.register_event('start-file', ev_start_file) mp.register_event('end-file', ev_end_file) if opt.enable_position_binds then for key=1, 9 do mp.add_key_binding('KP' .. key, 'position-' .. key, function() ev_set_pos(key) end) end end
local Packages = script.Parent.Parent.Parent local Roact = require(Packages.Roact) local ClientContext = require(script.Parent.ClientContext) local Connector = Roact.Component:extend("Connector") function Connector:init() self:setState({ tripStatus = self.props.clientSession.tripStatus, }) end function Connector:render() return self.props.render(self.state.tripStatus) end function Connector:didMount() self.connection = self.props.clientSession:subscribe(function(tripStatus) self:setState({ tripStatus = tripStatus or Roact.None, }) end) end function Connector:willUnmount() self.connection:Disconnect() self.connection = nil end local function withTripStatus(callback) return ClientContext.with(function(clientSession) return Roact.createElement(Connector, { render = callback, clientSession = clientSession, }) end) end return withTripStatus
ar.dog = 'The dog goes woof!'; ar.cat = 'The cat says meow!'; ar['bird'] = "The bird is in the cat's stomache!";
-- -- ButtonFrameFactory -- -- ## External ------------------------------------------------- local _G = _G local type, ipairs, tinsert = type, ipairs, table.insert --[[----------------------------------------------------------------------------- Blizzard Vars -------------------------------------------------------------------------------]] local CreateFrame, BackdropTemplateMixin = CreateFrame, BackdropTemplateMixin --[[----------------------------------------------------------------------------- Local Vars -------------------------------------------------------------------------------]] local LibStub, M, Assert, P, LSM, _, _, G = ABP_WidgetConstants:LibPack() local _, Table, String, LogFactory = ABP_LibGlobals:LibPackUtils() local _, AceGUI = G:LibPack_AceLibrary() local toStringSorted = Table.toStringSorted ---@class ButtonFrameFactory local _L = LibStub:NewLibrary(M.ButtonFrameFactory) ---@type LogFactory local p = LogFactory:NewLogger('ButtonFrameFactory') ---@type Wait local Wait = ABP_Wait --[[----------------------------------------------------------------------------- Support Functions -------------------------------------------------------------------------------]] ---@param widget FrameWidget ---@param name string The widget name. local function RegisterWidget(widget, name) assert(widget ~= nil) assert(name ~= nil) local WidgetBase = AceGUI.WidgetBase widget.userdata = {} widget.events = {} widget.base = WidgetBase widget.frame.obj = widget local mt = { __tostring = function() return name end, __index = WidgetBase } setmetatable(widget, mt) end local function RegisterCallbacks(widget) ---@param fw FrameWidget widget:SetCallback('OnRefreshSpellCooldowns', function(fw, event, ...) local sourceEvent, spellID = ... --local params = { sourceEvent=sourceEvent, spellID=spellID, delay=delay } --p:log('%s: %s params=%s', fw:GetName(), event, toStringSorted(params)) for _, btnName in ipairs(fw:GetButtons()) do ---@type ButtonUIWidget _G[btnName].widget:Fire(sourceEvent) end end) ---@param fw FrameWidget widget:SetCallback('OnRefreshItemCooldowns', function(fw, event, ...) for _, btnName in ipairs(fw:GetButtons()) do ---@type ButtonUIWidget _G[btnName].widget:UpdateState() end end) end --[[----------------------------------------------------------------------------- Methods -------------------------------------------------------------------------------]] ---@param widget FrameWidget local function WidgetMethods(widget) local AssertThatMethodArgIsNotNil = Assert.AssertThatMethodArgIsNotNil widget.rendered = false widget.buttons = {} local frame = widget.frame function widget:GetName() return widget.frame:GetName() end function widget:GetFrameIndex() return self.frameIndex end ---@return BarData function widget:GetConfig() return P:GetBar(self.frameIndex) end function widget:Toggle() if self:IsShown() then self:Hide(); return end self:Show() end function widget:SetFrameState(frameIndex, isEnabled) AssertThatMethodArgIsNotNil(frameIndex, 'frameIndex', 'SetFrameState(frameIndex)') P:SetBarEnabledState(frameIndex, isEnabled) if isEnabled then if self.ShowGroup then self:ShowGroup() end return end if self.HideGroup then self:HideGroup() end end -- Synchronize UI and Profile data function widget:IsShownInConfig(frameIndex) AssertThatMethodArgIsNotNil(frameIndex, 'frameIndex', 'IsShownInConfig(frameIndex)') local actualFrameIsShown = frame:IsShown() P:SetBarEnabledState(frameIndex, actualFrameIsShown) return P:IsBarEnabled(frameIndex) end function widget:SetGroupState(isShown) if isShown == true then if self.ShowGroup then self:ShowGroup() end return end if self.HideGroup then self:HideGroup() end end function widget:ToggleGroup() if #self.buttons > 0 then local firstBtn = _G[self.buttons[1]] if firstBtn:IsShown() then self:HideGroup() else self:ShowButtons() end end end function widget:HideGroup() frame:Hide() self:HideButtons() end function widget:ShowGroup() frame:Show() self:ShowButtons() end function widget:ShowButtons() for _, btnName in ipairs(self.buttons) do _G[btnName]:Show() end end function widget:HideButtons() for _, btnName in ipairs(self.buttons) do _G[btnName]:Hide() end end function widget:AddButton(buttonName) if type(buttonName) ~= 'string' then return end tinsert(self.buttons, buttonName) end function widget:GetButtonCount() return #self.buttons end function widget:GetButtons() return self.buttons end function widget:IsRendered() return self.rendered end function widget:IsNotRendered() return not self:IsRendered() end function widget:MarkRendered() self.rendered = true end end --local function getProfileUtil() -- if not P then P = WidgetLibFactory:GetProfile() end -- return P --end function _L:GetFrameByIndex(frameIndex) local frameName = P:GetFrameNameByIndex(frameIndex) return _G[frameName] end function _L:IsFrameShownByIndex(frameIndex) return self:GetFrameByIndex(frameIndex):IsShown() end function _L:CreateFrame(frameIndex) local FrameBackdrop = { ---@see LibSharedMedia bgFile = LSM:Fetch(LSM.MediaType.BACKGROUND, "Blizzard Marble"), --bgFile = LSM:Fetch(LSM.MediaType.BACKGROUND, "Blizzard Parchment"), --bgFile = LSM:Fetch(LSM.MediaType.BACKGROUND, "Solid"), --edgeFile = LSM:Fetch(LSM.MediaType.BORDER, "Blizzard Chat Bubble"), --edgeFile = LSM:Fetch(LSM.MediaType.BORDER, "Blizzard Dialog"), tile = false, tileSize = 26, edgeSize = 0, insets = { left = 0, right = 0, top = 0, bottom = 0 } } local FrameHandleBackdrop = { ---@see LibSharedMedia bgFile = LSM:Fetch(LSM.MediaType.BACKGROUND, "Solid"), tile = false, tileSize = 26, edgeSize = 0, insets = { left = 0, right = 0, top = 0, bottom = 0 } } ---@class Frame local f = self:GetFrameByIndex(frameIndex) local barConfig = P:GetBar(frameIndex) local fh = CreateFrame("Frame", nil, f, BackdropTemplateMixin and "BackdropTemplate" or nil) --fh:SetToplevel(true) ---@class FrameWidget local widget = { p = p, profile = P, frameIndex = frameIndex, options = barConfig.widget, frameHandleHeight = 4, dragHandleHeight = 0, padding = 2, frameStrata = 'LOW', frame = f, frameHandle = fh } widget.frame = f f.widget, fh.widget = widget, widget --local halfPadding = widget.padding/2 local widthAdj = widget.padding local heightAdj = widget.padding + widget.dragHandleHeight local frameWidth = (widget.options.colSize * widget.options.buttonSize) + widthAdj f:SetWidth(frameWidth) f:SetHeight((widget.options.rowSize * widget.options.buttonSize) + heightAdj) f:SetFrameStrata(widget.frameStrata) f:SetBackdrop(FrameBackdrop) f:SetBackdropColor(0, 0, 0, 1) fh:SetBackdrop(FrameHandleBackdrop) --fh:SetBackdropColor(0.92, 0.96, 0.26, 0.2) -- yellow --fh:SetBackdropColor(0.92, 0.96, 0.26, 0.5) -- orange fh:SetBackdropColor(235/255, 152/255, 45/255, 1) fh:SetWidth(frameWidth) fh:EnableMouse(true) fh:SetMovable(true) fh:SetResizable(true) fh:SetHeight(widget.frameHandleHeight) fh:SetFrameStrata(widget.frameStrata) fh:SetPoint("BOTTOM", f, "TOP", 0, 1) fh:SetScript("OnLoad", function() self:RegisterForDrag("LeftButton"); end) -- TODO: Overridden in ButtonFactory, will migrate it here -- fh:SetScript("OnMouseDown", function() f:StartMoving(); end) fh:SetScript("OnMouseUp", function() f:StopMovingOrSizing(); end) fh:SetScript("OnDragStart", function() f:StartMoving(); end) fh:SetScript("OnDragStop", function() f:StopMovingOrSizing(); end) fh:Show() RegisterWidget(widget, f:GetName() .. '::Widget') WidgetMethods(widget) RegisterCallbacks(widget) return widget end _L.mt.__call = _L.CreateFrame
local mgn = mgn local start_time = 0 local end_time = 0 local alpha = 0 local sounds = { explosion = {Path = {"ambient/intro/explosion02.wav", "ambient/medieval_thunder4.wav", "ambient/explosions/explode_6.wav"}, Played = false}, citadelpan = {Path = {"ambient/intro/citadelpan.wav", "ambient/explosions/exp2.wav"}, Played = false}, debris = {Path = {"ambient/intro/debris02.wav", "ambient/explosions/exp3.wav"}, Played = false} } do for _, data in pairs(sounds) do local paths = data.Path data.Path = paths[1] for i = 1, #paths do local path = paths[i] if file.Exists(path, "GAME") then data.Path = path break end end end end local function PlaySoundOnce(snd) if sounds[snd] and not sounds[snd].Played then surface.PlaySound(sounds[snd].Path) sounds[snd].Played = true end end local function ExplosionEffect() local realtime = RealTime() if start_time == 0 then start_time = realtime + 6 end_time = realtime + 6 + 8 PlaySoundOnce("explosion") end if realtime < start_time then -- don't do anything until the explosion starts return end if realtime < end_time then alpha = math.Clamp(alpha + FrameTime() * 3, 0, 1) util.ScreenShake(LocalPlayer():GetPos(), 5, 3, 0.25, 512) if alpha == 1 then PlaySoundOnce("citadelpan") timer.Simple(6, function() PlaySoundOnce("debris") end) end else -- end explosion alpha = math.Clamp(alpha - FrameTime() * 0.175, 0, 1) end DrawColorModify({ ["$pp_colour_brightness"] = 0.5 * alpha, ["$pp_colour_contrast"] = 1, ["$pp_colour_colour"] = 1 - (0.66 * alpha), ["$pp_colour_mulr"] = 80 * alpha, ["$pp_colour_mulg"] = 112 * alpha, ["$pp_colour_mulb"] = 0, }) DrawBloom(0.65, 4 * alpha, 4, 4, 1, 1, 1, 1, 1) DrawMotionBlur(0.1, 0.79 * alpha, 0.033) surface.SetDrawColor(Color(255, 192, 0, 164 * alpha)) surface.DrawRect(0, 0, ScrW(), ScrH()) for i = 1, ScrW() * 1.5 do -- some kind of noise, wish I could do this better local randX = math.random(0, ScrW()) local randY = math.random(0, ScrH()) surface.SetDrawColor(Color(0, 0, 0, alpha * math.random(192, 255))) surface.DrawRect(randX, randY, math.random(1, 2), math.random(1, 2)) end surface.SetDrawColor(Color(0, 0, 0, 48 * alpha)) surface.DrawRect(0, 0, ScrW(), ScrH()) end mgn.Stage.Exploding = { Started = false, StartedAt = 0, StartTime = 266, Length = 22, EndTime = 288, Next = mgn.Stage.Idle, Start = function(self, time) start_time = 0 end_time = 0 alpha = 0 for _, data in pairs(sounds) do data.Played = false end mgn.VOX("alert. containment breached") hook.Add("RenderScreenspaceEffects", "mgn.ExplosionEffect", ExplosionEffect) end, Think = function(self, chrono) return chrono < self.Length end, End = function(self, time) start_time = 0 end_time = 0 alpha = 0 for _, data in pairs(sounds) do data.Played = false end hook.Remove("RenderScreenspaceEffects", "mgn.ExplosionEffect") mgn.OverloadStart = 0 end }
----------------------------------------------------------------------------------------------------------------------- -- cron.lua - v1.0 (2011-04) -- Enrique García Cota - enrique.garcia.cota [AT] gmail [DOT] com -- time-related functions for Lua. -- inspired by Javascript's setTimeout and setInterval ----------------------------------------------------------------------------------------------------------------------- local function isCallable(callback) local tc = type(callback) if tc == 'function' then return true end if tc == 'table' then local mt = getmetatable(callback) return type(mt) == 'table' and type(mt.__call) == 'function' end return false end local function checkTimeAndCallback(time, callback) assert(type(time) == "number" and time > 0, "time must be a positive number") assert(isCallable(callback), "callback must be a function") end local entries = setmetatable({}, {__mode = "k"}) local function newEntry(time, callback, update, ...) local entry = { time = time, callback = callback, args = {...}, running = 0, update = update } entries[entry] = entry return entry end local function updateTimedEntry(self, dt) -- returns true if expired self.running = self.running + dt if self.running >= self.time then self.callback(unpack(self.args)) return true end end local function updatePeriodicEntry(self, dt) self.running = self.running + dt while self.running >= self.time do self.callback(unpack(self.args)) self.running = self.running - self.time end end local cron = {} function cron.reset() entries = {} end function cron.cancel(id) entries[id] = nil end function cron.after(time, callback, ...) checkTimeAndCallback(time, callback) return newEntry(time, callback, updateTimedEntry, ...) end function cron.every(time, callback, ...) checkTimeAndCallback(time, callback) return newEntry(time, callback, updatePeriodicEntry, ...) end function cron.update(dt) assert(type(dt) == "number" and dt > 0, "dt must be a positive number") local expired = {} for _, entry in pairs(entries) do if entry:update(dt, runningTime) then table.insert(expired,entry) end end for i=1, #expired do entries[expired[i]] = nil end end return cron
local ADDON_NAME, ns = ... local L = ns.L ns.defaults = { macro = true, scale = 1, windowPosition = "CENTER", windowX = 0, windowY = 0, windowWidth = 420, windowHeight = 360, } ns.data = { achievements = { { -- Secret Fish of Mechagon id = 13489, pre = { L.Achievement1Pre }, criteria = { { -- Bolted Steelhead id = 44738, quest = 55305, item = 167655, zone = 1462, dropchance = 1, }, { -- Energized Lightning Cod id = 44744, quest = 55311, item = 167661, zone = 1462, dropchance = 1, }, { -- Solarsprocket Barbel id = 44745, quest = 55312, item = 167662, zone = 1462, dropchance = 1, }, { -- Bottom Feeding Stinkfish id = 44737, quest = 55299, item = 167654, zone = 1462, waypoint = 79004900, dropchance = 1, }, { -- Pong Hopping Springfish id = 44739, quest = 55306, item = 167656, zone = 1462, waypoint = 65893030, dropchance = 1, }, { -- Shadowy Cave Eel id = 44740, quest = 55307, item = 167657, zone = 1462, waypoint = 56822222, dropchance = 1, }, { -- Mechanical Blowfish id = 44741, quest = 55308, item = 167658, zone = 1462, waypoint = 25007700, dropchance = 1, }, { -- Spitting Clownfish id = 44742, quest = 55309, item = 167659, zone = 1462, waypoint = 83867258, dropchance = 1, }, { -- Sludge-fouled Carp id = 44743, quest = 55310, item = 167660, zone = 1462, waypoint = 65005100, dropchance = 1, }, { -- Tasty Steelfin id = 44746, quest = 55313, item = 167663, zone = 1462, waypoint = 47003700, dropchance = 1, }, }, post = { L.Achievement1Post }, }, { -- Secret Fish and Where to Find Them id = 13502, pre = { L.Achievement2Pre1, L.Achievement2Pre2, L.Achievement2Pre3, L.Achievement2Pre4 }, criteria = { { -- Camouflaged Snark id = 44805, item = 167717, }, { -- Deceptive Maw id = 44808, item = 167729, }, { -- Inconspicuous Catfish id = 44812, item = 167730, }, { -- Unseen Mimmic id = 44824, item = 167716, }, { -- Very Tiny Whale id = 44827, item = 167720, }, { -- Collectable Saltfin id = 44806, item = 167718, }, { -- Travelling Goby id = 44823, item = 167714, }, { -- Invisible Smelt id = 44813, item = 167721, }, { pre = { L.SpecificZoneTypePre }, -- Rotted Blood Cod id = 44820, item = 167712, zone = 863, waypoint = 55305780, }, { -- Jade Story Fish id = 44815, item = 167706, zone = 371, }, { -- Thunderous Flounder id = 44822, item = 167723, zone = 504, }, { -- Kirin Tor Clown id = 44816, item = 167707, zone = 501, post = { " |cffbbbbbb" .. L.KirinTorClownPost .. "|r" }, }, { -- Mechanized Mackerel id = 44817, item = 167705, zone = 1462, }, { -- Queen's Delight id = 44818, item = 167728, zone = 1355, }, { -- Ancient Mana Fin id = 44803, item = 167708, zone = 680, }, { -- Prisoner Fish id = 44814, item = 167722, zone = 244, post = { " |cffbbbbbb" .. L.PrisonFishPost .. "|r" }, }, { -- Barbed Fjord Fin id = 44804, item = 167710, zone = 117, }, { -- Dead Fel Bone id = 44807, item = 167711, zone = 830, waypoint = 34507648, }, { -- Tortollan Tank Dweller id = 44828, item = 167724, zone = 896, waypoint = 18934239, }, { -- Thin Air Flounder id = 45952, item = 169897, zone = 379, waypoint = 44555256, }, { -- Well Lurker id = 45953, item = 169898, zone = 198, waypoint = 60822586, }, { -- Drowned Goldfish id = 44809, item = 167709, zone = 942, waypoint = 45895335, }, { pre = { L.NightTypePre }, -- Elusive Moonfish id = 44810, item = 167715, }, { pre = { L.DayTypePre }, -- Golden Sunsoaker id = 44811, item = 167719, }, { pre = { L.GhostTypePre }, -- Veiled Ghost id = 44826, item = 167713, zone = 619, waypoint = 45866851, }, { -- Deadeye Wally id = 44821, item = 167727, zone = 619, waypoint = 45866851, }, { -- Quiet Floater id = 44819, item = 167726, zone = 619, waypoint = 45866851, }, { -- Spiritual Salmon id = 44825, item = 167725, zone = 619, waypoint = 45866851, }, { pre = { L.GreenRoughyPre }, -- Green Roughy id = 45754, item = 169884, zone = 1462, dropchance = 1, }, { pre = { L.DisplacedScrapfinPre }, -- Displaced Scrapfin id = 45755, item = 169870, zone = 1462, dropchance = 1, post = { L.DisplacedScrapfinPost }, }, }, post = { L.Achievement2Post }, }, }, -- TODO add all zones zones = { ["Generic"] = { color = "eeeeee", }, [1462] = { -- Mechagon Island color = "dbd9a9", icon = "2915728", }, [863] = { -- Nazmir color = "4d56b7", icon = "2032229", }, [371] = { -- The Jade Forest color = "c9e6a0", icon = "617824", }, [504] = { -- Isle of Thunder color = "98b6c9", icon = "136014", }, [501] = { -- Dalaran color = "e275e8", icon = "237433", }, [627] = { -- Dalaran color = "e275e8", icon = "237433", }, [619] = { -- Broken Isles color = "6ebcc4", icon = "1535374", }, [1355] = { -- Nazjatar color = "4db3ea", icon = "3012068", }, [680] = { -- Suramar color = "5466bb", icon = "1409002", }, [244] = { -- Tol Barad color = "87a1b2", icon = "409548", }, [117] = { -- Howling Fjord color = "778c7f", icon = "236783", }, [830] = { -- Krokuun color = "aacb96", icon = "1711341", }, [896] = { -- Drustvar color = "59afc9", icon = "2065567", }, [379] = { -- Kun-Lai Summit color = "dc9c3a", icon = "617832", }, [198] = { -- Mount Hyjal color = "f1d6e6", icon = "409547", }, [942] = { -- Stormsong Valley color = "d7d4be", icon = "2125382", }, }, }
--[[ Copyright (c) 2018, Vsevolod Stakhov <vsevolod@highsecure.ru> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- --[[ local lua_util = require "lua_util" local ucl = require "ucl" local logger = require "rspamd_logger" local rspamd_util = require "rspamd_util" local argparse = require "argparse" local rescore_utility = require "rescore_utility" local opts local ignore_symbols = { ['DATE_IN_PAST'] =true, ['DATE_IN_FUTURE'] = true, } local parser = argparse() :name "rspamadm rescore" :description "Estimate optimal symbol weights from log files" :help_description_margin(37) parser:option "-l --log" :description "Log file or files (from rescore)" :argname("<log>") :args "*" parser:option "-c --config" :description "Path to config file" :argname("<file>") :default(rspamd_paths["CONFDIR"] .. "/" .. "rspamd.conf") parser:option "-o --output" :description "Output file" :argname("<file>") :default("new.scores") parser:flag "-d --diff" :description "Show differences in scores" parser:flag "-v --verbose" :description "Verbose output" parser:flag "-z --freq" :description "Display hit frequencies" parser:option "-i --iters" :description "Learn iterations" :argname("<n>") :convert(tonumber) :default(10) parser:option "-b --batch" :description "Batch size" :argname("<n>") :convert(tonumber) :default(100) parser:option "-d --decay" :description "Decay rate" :argname("<n>") :convert(tonumber) :default(0.001) parser:option "-m --momentum" :description "Learn momentum" :argname("<n>") :convert(tonumber) :default(0.1) parser:option "-t --threads" :description "Number of threads to use" :argname("<n>") :convert(tonumber) :default(1) parser:option "-o --optim" :description "Optimisation algorithm" :argname("<alg>") :convert { LBFGS = "LBFGS", ADAM = "ADAM", ADAGRAD = "ADAGRAD", SGD = "SGD", NAG = "NAG" } :default "ADAM" parser:option "--ignore-symbol" :description "Ignore symbol from logs" :argname("<sym>") :args "*" parser:option "--penalty-weight" :description "Add new penalty weight to test" :argname("<n>") :convert(tonumber) :args "*" parser:option "--learning-rate" :description "Add new learning rate to test" :argname("<n>") :convert(tonumber) :args "*" parser:option "--spam_action" :description "Spam action" :argname("<act>") :default("reject") parser:option "--learning_rate_decay" :description "Learn rate decay (for some algs)" :argname("<n>") :convert(tonumber) :default(0.0) parser:option "--weight_decay" :description "Weight decay (for some algs)" :argname("<n>") :convert(tonumber) :default(0.0) parser:option "--l1" :description "L1 regularization penalty" :argname("<n>") :convert(tonumber) :default(0.0) parser:option "--l2" :description "L2 regularization penalty" :argname("<n>") :convert(tonumber) :default(0.0) local function make_dataset_from_logs(logs, all_symbols, spam_score) local inputs = {} local outputs = {} for _, log in pairs(logs) do log = lua_util.rspamd_str_split(log, " ") if log[1] == "SPAM" then outputs[#outputs+1] = 1 else outputs[#outputs+1] = 0 end local symbols_set = {} for i=4,#log do if not ignore_symbols[ log[i] ] then symbols_set[log[i] ] = true end end local input_vec = {} for index, symbol in pairs(all_symbols) do if symbols_set[symbol] then input_vec[index] = 1 else input_vec[index] = 0 end end inputs[#inputs + 1] = input_vec end return inputs,outputs end local function init_weights(all_symbols, original_symbol_scores) end local function shuffle(logs, messages) local size = #logs for i = size, 1, -1 do local rand = math.random(size) logs[i], logs[rand] = logs[rand], logs[i] messages[i], messages[rand] = messages[rand], messages[i] end end local function split_logs(logs, messages, split_percent) if not split_percent then split_percent = 60 end local split_index = math.floor(#logs * split_percent / 100) local test_logs = {} local train_logs = {} local test_messages = {} local train_messages = {} for i=1,split_index do table.insert(train_logs, logs[i]) table.insert(train_messages, messages[i]) end for i=split_index + 1, #logs do table.insert(test_logs, logs[i]) table.insert(test_messages, messages[i]) end return {train_logs,train_messages}, {test_logs,test_messages} end local function stitch_new_scores(all_symbols, new_scores) local new_symbol_scores = {} for idx, symbol in pairs(all_symbols) do new_symbol_scores[symbol] = new_scores[idx] end return new_symbol_scores end local function update_logs(logs, symbol_scores) for i, log in ipairs(logs) do log = lua_util.rspamd_str_split(log, " ") local score = 0 for j=4,#log do log[j] = log[j]:gsub("%s+", "") score = score + (symbol_scores[log[j] ] or 0) end log[2] = lua_util.round(score, 2) logs[i] = table.concat(log, " ") end return logs end local function write_scores(new_symbol_scores, file_path) local file = assert(io.open(file_path, "w")) local new_scores_ucl = ucl.to_format(new_symbol_scores, "ucl") file:write(new_scores_ucl) file:close() end local function print_score_diff(new_symbol_scores, original_symbol_scores) logger.message(string.format("%-35s %-10s %-10s", "SYMBOL", "OLD_SCORE", "NEW_SCORE")) for symbol, new_score in pairs(new_symbol_scores) do logger.message(string.format("%-35s %-10s %-10s", symbol, original_symbol_scores[symbol] or 0, lua_util.round(new_score, 2))) end logger.message("\nClass changes \n") for symbol, new_score in pairs(new_symbol_scores) do if original_symbol_scores[symbol] ~= nil then if (original_symbol_scores[symbol] > 0 and new_score < 0) or (original_symbol_scores[symbol] < 0 and new_score > 0) then logger.message(string.format("%-35s %-10s %-10s", symbol, original_symbol_scores[symbol] or 0, lua_util.round(new_score, 2))) end end end end local function calculate_fscore_from_weights(logs, messages, all_symbols, weights, threshold) local new_symbol_scores = weights:clone() new_symbol_scores = stitch_new_scores(all_symbols, new_symbol_scores) logs = update_logs(logs, new_symbol_scores) local file_stats, _, all_fps, all_fns = rescore_utility.generate_statistics_from_logs(logs, messages, threshold) return file_stats.fscore, all_fps, all_fns end local function print_stats(logs, messages, threshold) local file_stats, _ = rescore_utility.generate_statistics_from_logs(logs, messages, threshold) local file_stat_format = [=[ F-score: %.2f False positive rate: %.2f %% False negative rate: %.2f %% Overall accuracy: %.2f %% Slowest message: %.2f (%s) ]=] logger.message("\nStatistics at threshold: " .. threshold) logger.message(string.format(file_stat_format, file_stats.fscore, file_stats.false_positive_rate, file_stats.false_negative_rate, file_stats.overall_accuracy, file_stats.slowest, file_stats.slowest_file)) end -- training function local function train(dataset, opt, model, criterion, epoch, all_symbols, spam_threshold, initial_weights) end local learning_rates = { 0.01 } local penalty_weights = { 0 } local function get_threshold() local actions = rspamd_config:get_all_actions() if opts['spam-action'] then return (actions[opts['spam-action'] ] or 0),actions['reject'] end return (actions['add header'] or actions['rewrite subject'] or actions['reject']), actions['reject'] end local function handler(args) opts = parser:parse(args) if not opts['log'] then parser:error('no log specified') end local _r,err = rspamd_config:load_ucl(opts['config']) if not _r then logger.errx('cannot parse %s: %s', opts['config'], err) os.exit(1) end _r,err = rspamd_config:parse_rcl({'logging', 'worker'}) if not _r then logger.errx('cannot process %s: %s', opts['config'], err) os.exit(1) end local threshold,reject_score = get_threshold() local logs,messages = rescore_utility.get_all_logs(opts['log']) if opts['ignore-symbol'] then local function add_ignore(s) ignore_symbols[s] = true end if type(opts['ignore-symbol']) == 'table' then for _,s in ipairs(opts['ignore-symbol']) do add_ignore(s) end else add_ignore(opts['ignore-symbol']) end end if opts['learning-rate'] then learning_rates = {} local function add_rate(r) if tonumber(r) then table.insert(learning_rates, tonumber(r)) end end if type(opts['learning-rate']) == 'table' then for _,s in ipairs(opts['learning-rate']) do add_rate(s) end else add_rate(opts['learning-rate']) end end if opts['penalty-weight'] then penalty_weights = {} local function add_weight(r) if tonumber(r) then table.insert(penalty_weights, tonumber(r)) end end if type(opts['penalty-weight']) == 'table' then for _,s in ipairs(opts['penalty-weight']) do add_weight(s) end else add_weight(opts['penalty-weight']) end end local all_symbols = rescore_utility.get_all_symbols(logs, ignore_symbols) local original_symbol_scores = rescore_utility.get_all_symbol_scores(rspamd_config, ignore_symbols) -- Display hit frequencies if opts['freq'] then local _, all_symbols_stats = rescore_utility.generate_statistics_from_logs(logs, messages, threshold) local t = {} for _, symbol_stats in pairs(all_symbols_stats) do table.insert(t, symbol_stats) end local function compare_symbols(a, b) if (a.spam_overall ~= b.spam_overall) then return b.spam_overall < a.spam_overall end if (b.spam_hits ~= a.spam_hits) then return b.spam_hits < a.spam_hits end return b.ham_hits < a.ham_hits end table.sort(t, compare_symbols) logger.message(string.format("%-40s %6s %6s %6s %6s %6s %6s %6s", "NAME", "HITS", "HAM", "HAM%", "SPAM", "SPAM%", "S/O", "OVER%")) for _, symbol_stats in pairs(t) do logger.message( string.format("%-40s %6d %6d %6.2f %6d %6.2f %6.2f %6.2f", symbol_stats.name, symbol_stats.no_of_hits, symbol_stats.ham_hits, lua_util.round(symbol_stats.ham_percent,2), symbol_stats.spam_hits, lua_util.round(symbol_stats.spam_percent,2), lua_util.round(symbol_stats.spam_overall,2), lua_util.round(symbol_stats.overall, 2) ) ) end -- Print file statistics print_stats(logs, messages, threshold) -- Work out how many symbols weren't seen in the corpus local symbols_no_hits = {} local total_symbols = 0 for sym in pairs(original_symbol_scores) do total_symbols = total_symbols + 1 if (all_symbols_stats[sym] == nil) then table.insert(symbols_no_hits, sym) end end if (#symbols_no_hits > 0) then table.sort(symbols_no_hits) -- Calculate percentage of rules with no hits local nhpct = lua_util.round((#symbols_no_hits/total_symbols)*100,2) logger.message( string.format('\nFound %s (%-.2f%%) symbols out of %s with no hits in corpus:', #symbols_no_hits, nhpct, total_symbols ) ) for _, symbol in pairs(symbols_no_hits) do logger.messagex('%s', symbol) end end return end shuffle(logs, messages) local train_logs, validation_logs = split_logs(logs, messages,70) local cv_logs, test_logs = split_logs(validation_logs[1], validation_logs[2], 50) local dataset = make_dataset_from_logs(train_logs[1], all_symbols, reject_score) -- Start of perceptron training local input_size = #all_symbols local linear_module = nn.Linear(input_size, 1, false) local activation = nn.Sigmoid() local perceptron = nn.Sequential() perceptron:add(linear_module) perceptron:add(activation) local criterion = nn.MSECriterion() --criterion.sizeAverage = false local best_fscore = -math.huge local best_weights = linear_module.weight[1]:clone() local best_learning_rate local best_weight_decay local all_fps local all_fns for _,lr in ipairs(learning_rates) do for _,wd in ipairs(penalty_weights) do linear_module.weight[1] = init_weights(all_symbols, original_symbol_scores) local initial_weights = linear_module.weight[1]:clone() opts.learning_rate = lr opts.weight_decay = wd for i=1,tonumber(opts.iters) do train(dataset, opts, perceptron, criterion, i, all_symbols, threshold, initial_weights) end local fscore, fps, fns = calculate_fscore_from_weights(cv_logs[1], cv_logs[2], all_symbols, linear_module.weight[1], threshold) logger.messagex("Cross-validation fscore=%s, learning rate=%s, weight decay=%s", fscore, lr, wd) if best_fscore < fscore then best_learning_rate = lr best_weight_decay = wd best_fscore = fscore best_weights = linear_module.weight[1]:clone() all_fps = fps all_fns = fns end end end -- End perceptron training local new_symbol_scores = best_weights new_symbol_scores = stitch_new_scores(all_symbols, new_symbol_scores) if opts["output"] then write_scores(new_symbol_scores, opts["output"]) end if opts["diff"] then print_score_diff(new_symbol_scores, original_symbol_scores) end -- Pre-rescore test stats logger.message("\n\nPre-rescore test stats\n") test_logs[1] = update_logs(test_logs[1], original_symbol_scores) print_stats(test_logs[1], test_logs[2], threshold) -- Post-rescore test stats test_logs[1] = update_logs(test_logs[1], new_symbol_scores) logger.message("\n\nPost-rescore test stats\n") print_stats(test_logs[1], test_logs[2], threshold) logger.messagex('Best fscore=%s, best learning rate=%s, best weight decay=%s', best_fscore, best_learning_rate, best_weight_decay) -- Show all FPs/FNs, useful for corpus checking and rule creation/modification if (all_fps and #all_fps > 0) then logger.message("\nFalse-Positives:") for _, fp in pairs(all_fps) do logger.messagex('%s', fp) end end if (all_fns and #all_fns > 0) then logger.message("\nFalse-Negatives:") for _, fn in pairs(all_fns) do logger.messagex('%s', fn) end end end return { handler = handler, description = parser._description, name = 'rescore' } --]] return nil