content
stringlengths
5
1.05M
-- Copyright 2017 Michael Forney. See LICENSE -- Myrddin LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S, V = lpeg.P, lpeg.R, lpeg.S, lpeg.V local M = {_NAME = 'myrddin'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = '//' * l.nonnewline_esc^0 local block_comment = P{ V'part' * P'*/'^-1, part = '/*' * (V'full' + (l.any - '/*' - '*/'))^0, full = V'part' * '*/', } local comment = token(l.COMMENT, line_comment + block_comment) -- Strings. local sq_str = l.delimited_range("'", true) local dq_str = l.delimited_range('"', true) local string = token(l.STRING, sq_str + dq_str) -- Numbers. local digit = l.digit + '_' local bdigit = R'01' + '_' local xdigit = l.xdigit + '_' local odigit = R'07' + '_' local integer = '0x' * xdigit^1 + '0o' * odigit^1 + '0b' * bdigit^1 + digit^1 local float = digit^1 * (('.' * digit^1) * (S'eE' * S'+-'^-1 * digit^1)^-1 + ('.' * digit^1)^-1 * S'eE' * S'+-'^-1 * digit^1) local number = token(l.NUMBER, float + integer) -- Keywords. local keyword = token(l.KEYWORD, word_match{ 'break', 'const', 'continue', 'elif', 'else', 'extern', 'false', 'for', 'generic', 'goto', 'if', 'impl', 'in', 'match', 'pkg', 'pkglocal', 'sizeof', 'struct', 'trait', 'true', 'type', 'union', 'use', 'var', 'while', }) -- Types. local type = token(l.TYPE, word_match{ 'void', 'bool', 'char', 'byte', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64', 'uint64', 'int', 'uint', 'flt32', 'flt64', } + '@' * l.word) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Operators. local operator = token(l.OPERATOR, S'`#_+-/*%<>~!=^&|~:;,.()[]{}') M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'type', type}, {'identifier', identifier}, {'string', string}, {'comment', comment}, {'number', number}, {'operator', operator}, } return M
---- -- @file PhysicsShapeSphere ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsShapeSphere:calculateSerializeBufferSize() end ---- Brief description. -- <#Description#> -- @param btSerializer <#btSerializer description#> -- @return <#return value description#> function PhysicsShapeSphere:serialize(btSerializer) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsShapeSphere:getClassName() end ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsShapeSphere:getType() end ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsShapeSphere:getNumVertices() end ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsShapeSphere:getNumEdges() end ---- Brief description. -- <#Description#> -- @param i <#i description#> -- @param pa <#pa description#> -- @param pb <#pb description#> -- @return <#return value description#> function PhysicsShapeSphere:getEdge(i, pa, pb) end ---- Brief description. -- <#Description#> -- @param i <#i description#> -- @param vtx <#vtx description#> -- @return <#return value description#> function PhysicsShapeSphere:getVertex(i, vtx) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsShapeSphere:getNumPlanes() end ---- Brief description. -- <#Description#> -- @param planeNormal <#planeNormal description#> -- @param planeSupport <#planeSupport description#> -- @param i <#i description#> -- @return <#return value description#> function PhysicsShapeSphere:getPlane(planeNormal, planeSupport, i) end ---- Brief description. -- <#Description#> -- @param pt <#pt description#> -- @param tolerance <#tolerance description#> -- @return <#return value description#> function PhysicsShapeSphere:isInside(pt, tolerance) end ---- Brief description. -- <#Description#> -- @param radius <#radius description#> -- @return <#return value description#> function PhysicsShapeSphere:setRadius(radius) end ---- Brief description. -- <#Description#> -- @param mass <#mass description#> -- @param inertia <#inertia description#> -- @return <#return value description#> function PhysicsShapeSphere:calculateLocalInertia(mass, inertia) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsShapeSphere:getRadius() end ---- Brief description. -- <#Description#> -- @param radius <#radius description#> -- @return <#return value description#> function PhysicsShapeSphere:setUnscaledRadius(radius) end ---- Brief description. -- <#Description#> -- @param margin <#margin description#> -- @return <#return value description#> function PhysicsShapeSphere:setMargin(margin) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function PhysicsShapeSphere:getMargin() end ---- Brief description. -- <#Description#> -- @param size <#size description#> -- @return <#return value description#> function NJLI.PhysicsShapeSphere.createArray(size) end ---- Brief description. -- <#Description#> -- @param array <#array description#> -- @return <#return value description#> function NJLI.PhysicsShapeSphere.destroyArray(array) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function NJLI.PhysicsShapeSphere.create() end ---- Brief description. -- <#Description#> -- @param builder <#builder description#> -- @return <#return value description#> function NJLI.PhysicsShapeSphere.create(builder) end ---- Brief description. -- <#Description#> -- @param object <#object description#> -- @return <#return value description#> function NJLI.PhysicsShapeSphere.clone(object) end ---- Brief description. -- <#Description#> -- @param object <#object description#> -- @return <#return value description#> function NJLI.PhysicsShapeSphere.copy(object) end ---- Brief description. -- <#Description#> -- @param object <#object description#> -- @return <#return value description#> function NJLI.PhysicsShapeSphere.destroy(object) end ---- Brief description. -- <#Description#> -- @param object <#object description#> -- @param L <#L description#> -- @param stack_index <#stack_index description#> -- @return <#return value description#> function NJLI.PhysicsShapeSphere.load(object, L, stack_index) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function NJLI.PhysicsShapeSphere.type() end
-- Assets for fonts do local asset = am.asset.new("basic") :add_texture("data/textures/fontBasic.png") am.gfx_engine.asset(asset) asset = am.asset.new("arial") :add_texture("data/textures/fontArial.png") :texture_window_pixel({right_x = 256}) am.gfx_engine.asset(asset) end
-- local dbg = require("debugger") -- dbg.auto_where = 2 local stub_vim = require'spec.helpers.stub_vim'.stub_vim local complete = require'cccomplete'.complete local api = require'nvimapi' local r = require'spec.helpers.random' insulate("default completion", function() stub_vim{lines = {"", "# a comment", ""}, cursor = {2, 3}, ft = "elixir"} complete() it("has added and modified the lines", function() assert.are.same({"", "# a comment do", " ", "end", ""}, api.lines(1, 5)) end) end) insulate("first pipe", function() stub_vim{lines = {" hello >"}, cursor = {1, 999}, ft = "elixir"} complete() it("has added a pipe", function() assert.are.same({" hello", " |> "}, api.lines(1, 999)) assert.are.same({2, 999}, api.cursor()) end) end) insulate("general case", function() local now = r.random_string("time_") local time_command = 'strftime("%F %T", localtime())' stub_vim{lines = {" hello >", "it's now %datetime"}, cursor = {2, 999}, ft = "elixir", evaluation = {time_command, now}} complete() it("expands the %datetime word #wip", function() assert.are.same({" hello >", "it's now " .. now}, api.buffer()) assert.are.same({2, 999}, api.cursor()) end) end) insulate("regression #1, iex> cccompletion", function() stub_vim{lines = {" hello >", " iex>"}, cursor = {2, 100}, ft = "elixir"} complete() it("does not yet add another line", function() assert.are.same({" hello >", " iex(0)> "}, api.buffer()) assert.are.same({2, 999}, api.cursor()) end) end) insulate("implementation #3 doc and moduledoc", function() context("doc", function() stub_vim{lines = {" hello >", " doc"}, cursor = {2, 100}, ft = "elixir"} complete() it("does not yet add another line", function() assert.are.same({" hello >", ' @doc """', ' ', ' """'}, api.buffer()) assert.are.same({3, 999}, api.cursor()) end) end) context("moduledoc", function() stub_vim{lines = {" hello >", " moduledoc"}, cursor = {2, 100}, ft = "elixir"} complete() it("does not yet add another line", function() assert.are.same({" hello >", ' @moduledoc """', ' ', ' """'}, api.buffer()) assert.are.same({3, 999}, api.cursor()) end) end) end)
#!/usr/bin/env lua -- Image filtering and texturing local cl = require("mooncl") local gl = require("moongl") local glfw = require("moonglfw") local mi = require("moonimage") local sharpen = arg[1] == 'sharpen' local kernelsourcefile = sharpen and "texture_filter.cl" or "transp_filter.cl" if not sharpen then print("To apply the sharpening filter, run as:\n$ "..arg[0].." sharpen") end local vshader = [[ #version 330 core in vec3 in_coords; in vec2 in_texcoords; out vec2 texcoords; void main(void) { texcoords = in_texcoords; gl_Position = vec4(in_coords, 1.0); } ]] local fshader = [[ #version 330 core uniform sampler2D tex; in vec2 texcoords; out vec4 new_color; void main() { vec3 color = vec3(texture(tex, texcoords.st)); new_color = vec4(color, 1.0); } ]] local function select_device() -- Search for a device in a platform that supports CL/GL interoperation. local platforms = cl.get_platform_ids() for _, platform in ipairs(platforms) do if cl.is_extension_supported(platform, "cl_khr_gl_sharing") then local device = cl.get_device_ids(platform, cl.DEVICE_TYPE_ALL)[1] return device, platform end end error("Cannot find OpenCL device that supports cl_khr_gl_sharing") end local function create_context(platform, devices, window) -- Create a CL context tied to the window's GL context. local glcontext, system = glfw.get_context(window) local contextprops = { gl_context = glcontext } if system == "glx" then contextprops.glx_display = glfw.get_x11_display(window) -- else if system == "wgl" then -- contextprops.wgl_hdc = glfw.get_ @@?!?! else error("System '"..system.." is not supported by this example") end return cl.create_context(platform, devices, contextprops) end -- Initialize OpenGL ---------------------------------------------------------- glfw.version_hint(3, 3, 'core') local window = glfw.create_window(233, 90, "Texture Filter") glfw.make_context_current(window) gl.init() gl.enable('depth test') gl.clear_color(1.0, 1.0, 1.0, 1.0) -- Create and compile shaders local prog, vs, fs = gl.make_program_s('vertex', vshader, 'fragment', fshader) gl.bind_attrib_location(prog, 0, "in_coords") gl.bind_attrib_location(prog, 1, "in_texcoords") gl.delete_shaders(vs, fs) gl.use_program(prog) -- Initialize OpenCL ---------------------------------------------------------- local device, platform = select_device() local context = create_context(platform, {device}, window) --program = cl.create_program_with_sourcefile(context, "transp_filter.cl") local program = cl.create_program_with_sourcefile(context, kernelsourcefile) cl.build_program(program, {device}) local queue = cl.create_command_queue(context, device) local kernel = cl.create_kernel(program, "texture_filter") -- Read pixel data local data, width, height = mi.load("car.png", 'y') -- Create the input image object from the PNG data local in_texture = cl.create_image(context, cl.MEM_READ_ONLY | cl.MEM_COPY_HOST_PTR, { channel_order = 'r', channel_type = 'unsigned int8' }, { type = 'image2d', width = width, height =height }, data) -- Create GL texture ----------------------------------------------------------- local texture = gl.new_texture('2d') gl.pixel_store('unpack alignment', 1) gl.texture_parameter('2d', 'wrap s', 'repeat') gl.texture_parameter('2d', 'wrap t', 'repeat') gl.texture_parameter('2d', 'mag filter', 'linear') gl.texture_parameter('2d', 'min filter', 'linear') -- Create GL buffers ----------------------------------------------------------- local vertex_coords = gl.pack('float', { -1.0, -1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, -1.0, 0.0 }) local tex_coords = gl.pack('float', { 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0 }) local vao = gl.new_vertex_array() -- VBO to hold vertex coordinates local vbo1 = gl.new_buffer('array') gl.buffer_data('array', vertex_coords, 'static draw') gl.vertex_attrib_pointer(0, 3, 'float', false, 0, 0) gl.enable_vertex_attrib_array(0) -- VBO to hold texture coordinates local vbo2 = gl.new_buffer('array') gl.buffer_data('array', tex_coords, 'static draw') gl.vertex_attrib_pointer(1, 2, 'float', false, 0, 0) gl.enable_vertex_attrib_array(1) gl.unbind_vertex_array() -- Create and configure pixel buffer local pbo = gl.new_buffer('array') gl.buffer_data('array', width*height, 'static draw') gl.unbind_buffer('array') -- Create CL buffer from GL buffer --------------------------------------------- local out_buffer = cl.create_from_gl_buffer(context, cl.MEM_WRITE_ONLY, pbo) -- Execute the kernel ---------------------------------------------------------- local function execute_kernel() -- Complete OpenGL processing gl.finish() -- Execute the kernel cl.enqueue_acquire_gl_objects(queue, {out_buffer}) cl.set_kernel_arg(kernel, 0, in_texture) cl.set_kernel_arg(kernel, 1, out_buffer) local kernel_event = cl.enqueue_ndrange_kernel(queue, kernel, 2, nil, {width, height}, nil, nil, true) cl.wait_for_events({kernel_event}) cl.enqueue_release_gl_objects(queue, {out_buffer}) cl.finish(queue) cl.release_event(kernel_event) -- Copy pixels from pbo to texture gl.bind_buffer('pixel unpack', pbo) gl.texture_image('2d', 0, 'red', 'red', 'ubyte', 0, width, height) gl.active_texture(0) end -- Set callback functions ------------------------------------------------------ glfw.set_window_size_callback(window, function(window, w, h) gl.viewport(0, 0, w, h) end) glfw.set_key_callback(window, function(window, key, scancode, action) if (key == 'escape' or key == 'q') and action == 'press' then glfw.set_window_should_close(window, true) -- will cause exiting the loop end end) -- Main loop ------------------------------------------------------------------- execute_kernel() collectgarbage() collectgarbage('stop') while not glfw.window_should_close(window) do glfw.wait_events_timeout(1/60) gl.clear('color', 'depth') gl.use_program(prog) gl.bind_vertex_array(vao) gl.bind_texture('2d', texture) gl.draw_arrays('triangle fan', 0, 4) gl.unbind_vertex_array() gl.use_program(0) glfw.swap_buffers(window) collectgarbage('step') end
-- Copyright (c) 2020 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT describe("game.rules", function() local rules = require "game.rules" it("has rules for the start of the turn", function() assert.is_function(rules.start_turn) end) it("has rules for the end of the turn", function() assert.is_function(rules.end_turn) end) it("has rules for assigning hero to quest", function() assert.is_function(rules.assign_hero_to_quest) end) end)
ys = ys or {} ys.Battle.BattleBuffHealingSteal = class("BattleBuffHealingSteal", ys.Battle.BattleBuffEffect) ys.Battle.BattleBuffHealingSteal.__name = "BattleBuffHealingSteal" ys.Battle.BattleBuffHealingSteal.FX_TYPE = ys.Battle.BattleBuffEffect.FX_TYPE_LINK ys.Battle.BattleBuffHealingSteal.Ctor = function (slot0, slot1) slot0.super.Ctor(slot0, slot1) end ys.Battle.BattleBuffHealingSteal.SetArgs = function (slot0, slot1, slot2) slot0._stealRate = slot0._tempData.arg_list.stealingRate or 1 slot0._absorbRate = slot3.arsorbRate or 1 end ys.Battle.BattleBuffHealingSteal.onTakeHealing = function (slot0, slot1, slot2, slot3) slot4 = slot3.damage if slot2:GetCaster() and slot5:IsAlive() and slot5 ~= slot1 then slot3.damage = slot4 - math.ceil(slot4 * slot0._stealRate) slot5:UpdateHP(math.ceil(slot5:GetAttrByName("healingRate") * math.ceil(slot4 * slot0._stealRate) * slot0._absorbRate), { isMiss = false, isCri = false, isHeal = true, isShare = false }) end end return
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild -- -- This file is compatible with Lua 5.3 local class = require("class") require("kaitaistruct") local enum = require("enum") EnumIntRangeU = class.class(KaitaiStruct) EnumIntRangeU.Constants = enum.Enum { zero = 0, int_max = 4294967295, } function EnumIntRangeU:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function EnumIntRangeU:_read() self.f1 = EnumIntRangeU.Constants(self._io:read_u4be()) self.f2 = EnumIntRangeU.Constants(self._io:read_u4be()) end
-- Copyright 2021 SmartThings -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local capabilities = require "st.capabilities" --- @type st.utils local utils = require "st.utils" --- @type st.zwave.CommandClass local cc = require "st.zwave.CommandClass" --- @type st.zwave.CommandClass.Meter local Meter = (require "st.zwave.CommandClass.Meter")({version=3}) --- @type st.zwave.CommandClass.SensorMultilevel local SensorMultilevel = (require "st.zwave.CommandClass.SensorMultilevel")({version=5}) --- @type st.zwave.CommandClass.SwitchMultilevel local SwitchMultilevel = (require "st.zwave.CommandClass.SwitchMultilevel")({version=4}) --- @type st.zwave.CommandClass.SwitchBinary local SwitchBinary = (require "st.zwave.CommandClass.SwitchBinary")({version=1}) local constants = require "qubino-switches/constants/qubino-constants" local QUBINO_FINGERPRINTS = { {mfr = 0x0159, prod = 0x0001, model = 0x0051, deviceProfile = "qubino-flush-dimmer"}, -- Qubino Flush Dimmer {mfr = 0x0159, prod = 0x0001, model = 0x0052, deviceProfile = "qubino-din-dimmer"}, -- Qubino DIN Dimmer {mfr = 0x0159, prod = 0x0001, model = 0x0053, deviceProfile = "qubino-flush-dimmer-0-10V"}, -- Qubino Flush Dimmer 0-10V {mfr = 0x0159, prod = 0x0001, model = 0x0055, deviceProfile = "qubino-mini-dimmer"}, -- Qubino Mini Dimmer {mfr = 0x0159, prod = 0x0002, model = 0x0051, deviceProfile = "qubino-flush2-relay"}, -- Qubino Flush 2 Relay {mfr = 0x0159, prod = 0x0002, model = 0x0052, deviceProfile = "qubino-flush1-relay"}, -- Qubino Flush 1 Relay {mfr = 0x0159, prod = 0x0002, model = 0x0053, deviceProfile = "qubino-flush1d-relay"} -- Qubino Flush 1D Relay } local function getDeviceProfile(device, isTemperatureSensorOnboard) local newDeviceProfile for _, fingerprint in ipairs(QUBINO_FINGERPRINTS) do if device:id_match(fingerprint.mfr, fingerprint.prod, fingerprint.model) then newDeviceProfile = fingerprint.deviceProfile if(isTemperatureSensorOnboard) then return newDeviceProfile.."-temperature" else return newDeviceProfile end end end return nil end local function can_handle_qubino_flush_relay(opts, driver, device, cmd, ...) return device.zwave_manufacturer_id == constants.QUBINO_MFR end local function add_temperature_sensor_if_needed(device) if not (device:supports_capability_by_id(capabilities.temperatureMeasurement.ID)) then local new_profile = getDeviceProfile(device, true) device:try_update_metadata({profile = new_profile}) end end local function sensor_multilevel_report(self, device, cmd) if (cmd.args.sensor_type == SensorMultilevel.sensor_type.TEMPERATURE) then local scale = 'C' if (cmd.args.sensor_value > constants.TEMP_SENSOR_WORK_THRESHOLD) then add_temperature_sensor_if_needed(device) if (cmd.args.scale == SensorMultilevel.scale.temperature.FARENHEIT) then scale = 'F' end device:emit_event_for_endpoint( cmd.src_channel, capabilities.temperatureMeasurement.temperature({value = cmd.args.sensor_value, unit = scale}) ) end end end local do_refresh = function(self, device) if device:supports_capability_by_id(capabilities.switchLevel.ID) then device:send(SwitchMultilevel:Get({})) end for component, _ in pairs(device.profile.components) do if device:supports_capability_by_id(capabilities.powerMeter.ID, component) then device:send_to_component(Meter:Get({scale = Meter.scale.electric_meter.WATTS}), component) end if device:supports_capability_by_id(capabilities.energyMeter.ID, component) then device:send_to_component(Meter:Get({scale = Meter.scale.electric_meter.KILOWATT_HOURS}), component) end if device:supports_capability_by_id(capabilities.switch.ID, component) then device:send_to_component(SwitchBinary:Get({}), component) end end if device:supports_capability_by_id(capabilities.temperatureMeasurement.ID) then if device.profile.components["extraTemperatureSensor"] ~= nil then device:send_to_component(SensorMultilevel:Get({sensor_type = SensorMultilevel.sensor_type.TEMPERATURE}), "extraTemperatureSensor") else device:send(SensorMultilevel:Get({sensor_type = SensorMultilevel.sensor_type.TEMPERATURE})) end end end local function device_added(self, device) do_refresh(self, device) end local qubino_relays = { NAME = "Qubino Relays", can_handle = can_handle_qubino_flush_relay, zwave_handlers = { [cc.SENSOR_MULTILEVEL] = { [SensorMultilevel.REPORT] = sensor_multilevel_report } }, capability_handlers = { [capabilities.refresh.ID] = { [capabilities.refresh.commands.refresh.NAME] = do_refresh } }, lifecycle_handlers = { added = device_added }, sub_drivers = { require("qubino-switches/qubino-relays"), require("qubino-switches/qubino-dimmer") } } return qubino_relays
function setPlayerScore(player,score) if (player) and (score) then triggerServerEvent("cSetPlayerScore",player,player,score) end end function givePlayerScore(player,score) if (player) and (score) then triggerServerEvent("cGivePlayerScore",player,player,score) end end function takePlayerScore(player,score) if (player) and (score) then triggerServerEvent("cGivePlayerScore",player,player,score) end end function resetPlayerScore(player) if (player) then triggerServerEvent("cResetPlayerScore",player,player) end end
project "spdlog" kind "StaticLib" language "C++" cppdialect "C++14" targetdir "%{BUILD_DIRECTORY}/bin/%{cfg.buildcfg}" objdir "%{BUILD_DIRECTORY}/bin/obj/%{cfg.buildcfg}" files { "include/**.h", "src/**.cpp", } includedirs { "%{DependencyIncludes.spdlog}", } defines { "SPDLOG_COMPILED_LIB", } filter "configurations:Debug" runtime "Debug" symbols "On" filter "configurations:Release" defines { "NDEBUG" } runtime "Release" optimize "On"
local socket = require('socket') local sys = require('posix.sys') local zlog = require('zlog') require('util') function get_args() local opts, args = getopt(arg, '', {'--local-address=', '--remote-address=', '--timeout='}) local addr = assert(opts['--local-address'], 'must have option --local-address') local ip, port = assert(string.match(addr, '^([^:]+):(%d+)$')) local_address = { ip, tonumber(port) } addr = assert(opts['--remote-address'], 'must have option --remote-address') ip, port = assert(string.match(addr, '^([^:]+):(%d+)$')) remote_address = { ip, tonumber(port) } timeout = tonumber(opts['--timeout']) timeout = (timeout and timeout>0) and timeout or -1 end xpcall(get_args, function(errmsg) print(errmsg) print('usage: lua '..arg[0]..' --local-address=local-ip:port --remote-address=remote-ip:port [--timeout=-1]') print('example:\nlua '..arg[0]..' --local-address=*:6666 --remote-address=192.168.17.234:5672 --timeout=30') os.exit() end) local server = socket.socket() assert(server:bind(local_address)) assert(server:listen()) sys.signal(sys.SIGCHLD, sys.SIG_IGN) print('process running to background, pid save into tcp_proxy.pid') sys.daemon() local f_pid = io.open('tcp_proxy.pid', 'w') if f_pid then f_pid:write(sys.getpid()) f_pid:close() end zlog.init('zlog.cfg', 'tcp_proxy') zlog.info('tcp_proxy process start ...') function do_proxy(c) local s = socket.socket() local ok, err = s:connect(remote_address) if not ok then zlog.error('connect remote address failed: '..err) c:close() return -1 end zlog.info('connect to '..table.concat(s:getpeername(), ':')) local proxy = { [c:fileno()]={reader=c, writer=s}, [s:fileno()]={reader=s, writer=c} } local poll, transfer = socket.PollSelector(), true poll:register(c:fileno(), socket.POLLIN) poll:register(s:fileno(), socket.POLLIN) while transfer do transfer = false for fd,revent in poll:select(timeout) do local buffer = proxy[fd].reader:recv(4096) if not buffer or buffer=='' then transfer = false break end proxy[fd].writer:send(buffer) transfer = true zlog.debug(string.format('%s -> %s: %d bytes', table.concat(proxy[fd].reader:getpeername(), ':'), table.concat(proxy[fd].writer:getpeername(), ':'), #buffer)) end end zlog.info('session end') c:close() s:close() return 0 end while true do local client, addr = server:accept() if client then local pid, err = sys.fork() if pid < 0 then zlog.error('fork new session failed: '..err) elseif pid == 0 then server:close() sys._exit(do_proxy(client)) else zlog.info(string.format('session [%d] begin: accept socket %s', pid, table.concat(addr,':'))) end client:close() end end
theaterManagerConvoTemplate = ConvoTemplate:new { initialScreen = "", templateType = "Lua", luaClassHandler = "TheaterManagerConvoHandler", screens = {} } init_not_entertainer = ConvoScreen:new { id = "init_not_entertainer", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_2a8b6bf", -- Only entertainers and crew should be backstage. What are you doing here? stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_not_entertainer); init_completed_both = ConvoScreen:new { id = "init_completed_both", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_e5438cc6", -- Welcome back! I still can't tell you how impressed I am with your performances. You truly are a credit to the entertainment professions. Best of luck to you in the future, friend! stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_completed_both); init_failed_audition_timer = ConvoScreen:new { id = "init_failed_audition_timer", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_3936bc63", -- Oh, you didn't pass the audition? That's too bad. We can set you up with another audition, but not until twenty-four hours have passed since your last audition. Come back then and we'll talk. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_failed_audition_timer); init_failed_performance_timer = ConvoScreen:new { id = "init_failed_performance_timer", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_aa18ac6", -- It looks like your previous show didn't go over so well. That's too bad. You can try the performance again, but not until twenty-four hours have passed since your last one. Come back then and we'll talk. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_failed_performance_timer); init_event_in_progress = ConvoScreen:new { id = "init_event_in_progress", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_d66dc712", -- Too busy to talk right now. I'm very busy, sorry. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_event_in_progress); init_completed_one = ConvoScreen:new { id = "init_completed_one", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_95037778", -- Oh, hello! Welcome back, friend. Are you looking to participate in another performance? stopConversation = "false", options = { -- Handled by convo handler --{"@conversation/quest_crowd_pleaser_manager:s_dda95847", "full_on_dance or full_on_music"}, -- Is that possible? --{"@conversation/quest_crowd_pleaser_manager:s_c5a66e82", "come_see_me"}, -- No, not really. } } theaterManagerConvoTemplate:addScreen(init_completed_one); come_see_me = ConvoScreen:new { id = "come_see_me", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_67e4d556", -- OK... Well, if you ever need any more work, just come see me. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(come_see_me); full_on_dance = ConvoScreen:new { id = "full_on_dance", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_919f9d5a", -- Well, I'll be honest with you. Ever since your show, every hack that thinks he can dance a step has come here to perform. So we're all full on dance shows, but we still have a few spots open for a musical show if you're interested. stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_39aa9593", "still_must_audition_music"}, -- Sure, I can give it a try. {"@conversation/quest_crowd_pleaser_manager:s_2883b989", "ill_be_here"}, -- No, that's not really something I want to do. } } theaterManagerConvoTemplate:addScreen(full_on_dance); full_on_music = ConvoScreen:new { id = "full_on_music", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_a84a3743", -- Well, I'll be honest with you. Ever since your show, every hack that thinks he can play a note has come here to perform. So we're all full on musical shows, but we still have a few spots open for a dance show if you're interested. stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_39aa9593", "still_must_audition_dance"}, -- Sure, I can give it a try. {"@conversation/quest_crowd_pleaser_manager:s_2883b989", "ill_be_here"}, -- No, that's not really something I want to do. } } theaterManagerConvoTemplate:addScreen(full_on_music); ill_be_here = ConvoScreen:new { id = "ill_be_here", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_1b58131a", -- Alright. If you change your mind, I'll be here. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(ill_be_here); still_must_audition_dance = ConvoScreen:new { id = "still_must_audition_dance", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_70da1c6a", -- OK. You'll still need to audition though. Is that acceptable? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_9739cb4c", "prep_second_audition_dance"}, -- Yes, that's fine. {"@conversation/quest_crowd_pleaser_manager:s_2883b989", "i_understand"}, -- No way. I don't want to go through that again. } } theaterManagerConvoTemplate:addScreen(still_must_audition_dance); still_must_audition_music = ConvoScreen:new { id = "still_must_audition_music", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_70da1c6a", -- OK. You'll still need to audition though. Is that acceptable? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_9739cb4c", "prep_second_audition_music"}, -- Yes, that's fine. {"@conversation/quest_crowd_pleaser_manager:s_2883b989", "i_understand"}, -- No way. I don't want to go through that again. } } theaterManagerConvoTemplate:addScreen(still_must_audition_music); prep_second_audition_dance = ConvoScreen:new { id = "prep_second_audition_dance", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_14556b51", -- OK. Go ahead and make your preparations. You know the drill. Just come back and talk with me when you're ready to audition. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(prep_second_audition_dance); prep_second_audition_music = ConvoScreen:new { id = "prep_second_audition_music", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_14556b51", -- OK. Go ahead and make your preparations. You know the drill. Just come back and talk with me when you're ready to audition. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(prep_second_audition_music); i_understand = ConvoScreen:new { id = "i_understand", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_56d2a81f", -- I understand. Come back if you change your mind. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(i_understand); init_start_second_audition = ConvoScreen:new { id = "init_start_second_audition", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_472f2a5e", -- You're here for an audition, yes? Are you ready to get started now? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_4a1d2431", "second_audition_starts_in_30"}, -- Yes, I'm ready. {"@conversation/quest_crowd_pleaser_manager:s_f3d46f0b", "come_back_when_ready"}, -- No, not quite yet. } } theaterManagerConvoTemplate:addScreen(init_start_second_audition); second_audition_starts_in_30 = ConvoScreen:new { id = "second_audition_starts_in_30", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_274a8930", -- Alright, I'll go ahead and get things set up. You'd better hurry up and get onstage. The audition will start in thirty seconds. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(second_audition_starts_in_30); init_first_time = ConvoScreen:new { id = "init_first_time", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_37b822c1", -- Hello there! You're a member of the entertainment industry are you not? I've got an offer for you if you're interested. stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_499afb89", "looking_for_acts"}, -- What is your offer? {"@conversation/quest_crowd_pleaser_manager:s_2883b989", "suit_yourself"}, -- Not right now, thanks. } } theaterManagerConvoTemplate:addScreen(init_first_time); suit_yourself = ConvoScreen:new { id = "suit_yourself", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_82b273a8", -- Suit yourself. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(suit_yourself); looking_for_acts = ConvoScreen:new { id = "looking_for_acts", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_c08ff946", -- I'm looking for some new solo acts to perform here at the theater. I've been scouring the city trying to find fresh new talent to put on some live shows. Would you possibly be interested in doing a performance series? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_a2fae368", "first_must_pass_audition"}, -- Sure, that sounds like a lot of fun. {"@conversation/quest_crowd_pleaser_manager:s_388438a6", "youll_be_compensated"}, -- How much will I get paid? {"@conversation/quest_crowd_pleaser_manager:s_1343b0ab", "suit_yourself"}, -- Nah, doesn't really sound like something I want to do. } } theaterManagerConvoTemplate:addScreen(looking_for_acts); first_must_pass_audition = ConvoScreen:new { id = "first_must_pass_audition", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_7b9543aa", -- Let's not get ahead of ourselves. First, you must pass an audition. We can't just have anyone getting up on the stage now, can we? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_9288900f", "make_audition_preperations"}, -- I understand. {"@conversation/quest_crowd_pleaser_manager:s_64d20f97", "suit_yourself"}, -- Audition? Uh, I'd rather not be judged. } } theaterManagerConvoTemplate:addScreen(first_must_pass_audition); make_audition_preperations = ConvoScreen:new { id = "make_audition_preperations", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_705ff1a9", -- Excellent. Make whatever preparations you feel are necessary, and then come back to me when you are ready to start the audition. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(make_audition_preperations); youll_be_compensated = ConvoScreen:new { id = "youll_be_compensated", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_a2ce6dd9", -- That's all you youngsters are worried about these days, isn't it? Don't worry, you'll be compensated for your time. stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_8e4955d6", "first_must_pass_audition"}, -- OK, count me in. {"@conversation/quest_crowd_pleaser_manager:s_64d20f97", "suit_yourself"}, -- Nah, it's not for me. } } theaterManagerConvoTemplate:addScreen(youll_be_compensated); init_start_audition = ConvoScreen:new { id = "init_start_audition", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_472f2a5e", -- You're here for an audition, yes? Are you ready to get started now? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_4a1d2431", "what_type_of_audition"}, -- Yes, I'm ready. {"@conversation/quest_crowd_pleaser_manager:s_f3d46f0b", "come_back_when_ready"}, -- No, not quite yet. } } theaterManagerConvoTemplate:addScreen(init_start_audition); come_back_when_ready = ConvoScreen:new { id = "come_back_when_ready", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_303aa95e", -- Alright. Come back when you're ready. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(come_back_when_ready); what_type_of_audition = ConvoScreen:new { id = "what_type_of_audition", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_1204a0c6", -- I see. Now, do you want to audition as a musician or a dancer? stopConversation = "false", options = { -- Handled in convo handler, checks to see if player has skills needed --{"@conversation/quest_crowd_pleaser_manager:s_183e8ee4", ""}, -- As a musician. --{"@conversation/quest_crowd_pleaser_manager:s_9172f29c", ""}, -- As a dancer. --{"@conversation/quest_crowd_pleaser_manager:s_c73756f7", "come_back_when_ready"}, -- On second thought, I'm not quite ready yet. } } theaterManagerConvoTemplate:addScreen(what_type_of_audition); not_skilled_enough = ConvoScreen:new { id = "not_skilled_enough", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_1c296980", -- It doesn't look like you're skilled enough to perform yet. Go practice a little more and come back when you're ready to try again. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(not_skilled_enough); someone_on_stage = ConvoScreen:new { id = "someone_on_stage", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_57f90c0e", -- Hm... it looks like someone else is on stage right now. Try back again in a little while and we'll see if we can get you set up. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(someone_on_stage); audition_starts_in_30_music = ConvoScreen:new { id = "audition_starts_in_30_music", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_274a8930", -- Alright, I'll go ahead and get things set up. You'd better hurry up and get onstage. The audition will start in thirty seconds. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(audition_starts_in_30_music); audition_starts_in_30_dance = ConvoScreen:new { id = "audition_starts_in_30_dance", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_274a8930", -- Alright, I'll go ahead and get things set up. You'd better hurry up and get onstage. The audition will start in thirty seconds. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(audition_starts_in_30_dance); init_passed_audition = ConvoScreen:new { id = "init_passed_audition", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_857ede28", -- Hey! I hear that you passed the audition! That's fantastic. Here, let me give you a payment in advance for your up-coming performances. You deserve a break now, though. Come back later and we'll discuss what needs to be done next. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_passed_audition); init_first_advertising = ConvoScreen:new { id = "init_first_advertising", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_937f2001", -- Back already, huh? I don't blame you for wanting to get started. stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_694f2644", "first_show_advertising"}, -- OK, so what do we do next? {"@conversation/quest_crowd_pleaser_manager:s_414898b2", "come_back_when_you_are"}, -- I'm not quite ready yet. } } theaterManagerConvoTemplate:addScreen(init_first_advertising); come_back_when_you_are = ConvoScreen:new { id = "come_back_when_you_are", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_fa31756f", -- OK, come back when you are. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(come_back_when_you_are); first_show_advertising = ConvoScreen:new { id = "first_show_advertising", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_353af024", -- Well, before you put on your first show, we need to do some advertising. You know, what good is a show if nobody comes to see it? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_8ddf8010", "go_out_and_promote"}, -- How do we do that? {"@conversation/quest_crowd_pleaser_manager:s_e8276d66", "come_back_whenever"}, -- That sounds pretty hard, maybe I'll come back later. } } theaterManagerConvoTemplate:addScreen(first_show_advertising); come_back_whenever = ConvoScreen:new { id = "come_back_whenever", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_f72be127", -- Alright. Come back whenever you're ready. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(come_back_whenever); go_out_and_promote = ConvoScreen:new { id = "go_out_and_promote", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_4dbb8ff6", -- I'll take care of all the promotions on this end, but you need to go out and promote yourself, if you know what I'm saying. Get your name out there on the streets... get people talking. stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_34bf7b50", "should_be_simple"}, -- I see. Just tell me what I need to do. {"@conversation/quest_crowd_pleaser_manager:s_e8276d66", "come_back_when_more_time"}, -- I don't really have time for that right now. } } theaterManagerConvoTemplate:addScreen(go_out_and_promote); come_back_when_more_time = ConvoScreen:new { id = "come_back_when_more_time", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_b1522710", -- I see. Well, come back when you have more time and we'll get started. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(come_back_when_more_time); should_be_simple = ConvoScreen:new { id = "should_be_simple", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_2224e2b8", -- It should be quite simple. Just go out there and do a little performance routine for some people. I think that if you were to entertain ten people, that would be enough. Are you ready to do this now? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_7943785d", "go_entertain_ten"}, -- Sure, no time like the present. {"@conversation/quest_crowd_pleaser_manager:s_350a3257", "come_back_when_more_time"}, -- Not right now, I've got some stuff to do first. } } theaterManagerConvoTemplate:addScreen(should_be_simple); go_entertain_ten = ConvoScreen:new { id = "go_entertain_ten", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_8b00fbc4", -- OK, I'll get the promotions started, you just go out and entertain ten people. Then come back here and we'll talk about getting the concert started. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(go_entertain_ten); init_hasnt_entertained_ten = ConvoScreen:new { id = "init_hasnt_entertained_ten", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_810fffd0", -- Oh, you're back. But I don't think you've finished your promotional campaign have you? Come back when you're done and we'll talk about your show. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_hasnt_entertained_ten); init_entertained_ten = ConvoScreen:new { id = "init_entertained_ten", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_2b8d253d", -- Excellent work. I'm starting to hear the buzz about your performance! We should be able to put on the show whenever you're ready. Go make your preparations, then come speak with me again when you want to begin. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_entertained_ten); init_first_show = ConvoScreen:new { id = "init_first_show", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_b5131941", -- Ready to start the show, are you? Don't worry if you're nervous. Everybody gets like that the first time they're on stage. stopConversation = "false", options = { -- Handled by convo handler in case someone is on stage --{"@conversation/quest_crowd_pleaser_manager:s_1377703a", "starts_in_two_min"}, -- Yes, I'm ready. Let's get this show on the road. --{"@conversation/quest_crowd_pleaser_manager:s_4365b273", "stomach_of_steel"}, -- I'm not nervous. --{"@conversation/quest_crowd_pleaser_manager:s_d730c5dd", "take_your_time"}, -- No, I'm not quite ready yet. } } theaterManagerConvoTemplate:addScreen(init_first_show); take_your_time = ConvoScreen:new { id = "take_your_time", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_ab1c9c5f", -- That's fine. Take your time. Just come back when you're ready. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(take_your_time); stomach_of_steel = ConvoScreen:new { id = "stomach_of_steel", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_85b97ed7", -- Sure, sure. You've got a stomach of pure steel. So, are you ready to get started? stopConversation = "false", options = { -- Handled by convo handler in case someone is on stage --{"@conversation/quest_crowd_pleaser_manager:s_1377703a", "starts_in_two_min"}, -- Yes, I'm ready. Let's get this show on the road. --{"@conversation/quest_crowd_pleaser_manager:s_d730c5dd", "take_your_time"}, -- No, I'm not quite ready yet. } } theaterManagerConvoTemplate:addScreen(stomach_of_steel); starts_in_two_min = ConvoScreen:new { id = "starts_in_two_min", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_db3a3e40", -- Good. I'll let the crew know so that they can start setting up. The performance will start in two minutes. You may speak with the audience beforehand if you like, but you must be on the stage when the show starts, alright? stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(starts_in_two_min); init_completed_first_show = ConvoScreen:new { id = "init_completed_first_show", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_cad51774", -- You've completed your first show! Congratulations, the audience loved you. Let me give you another advance for your next performance. Come back and see me again when you're ready to talk about your next show. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_completed_first_show); init_second_advertising = ConvoScreen:new { id = "init_second_advertising", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_ed9c9f8d", -- Oh yes. You're ready to get going for your next show. Let's not get too ahead of ourselves, though. You need to go out and do some more promotion before the next performance. stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_847c3be4", "show_will_be_bigger"}, -- More promotion? {"@conversation/quest_crowd_pleaser_manager:s_6b02387e", "ok_come_back"}, -- I see. I'm not ready for that yet. } } theaterManagerConvoTemplate:addScreen(init_second_advertising); ok_come_back = ConvoScreen:new { id = "ok_come_back", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_fa31756f", -- OK, come back when you are. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(ok_come_back); show_will_be_bigger = ConvoScreen:new { id = "show_will_be_bigger", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_58ea419", -- Indeed! This show will be even bigger than the last one! If the next show is as good as the last, you'll be on your way to the top! stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_3e04f6f", "performance_for_twenty"}, -- Alright. What do I need to do this time? {"@conversation/quest_crowd_pleaser_manager:s_11a3b43", "come_back_whenever"}, -- I'll have to come back later. } } theaterManagerConvoTemplate:addScreen(show_will_be_bigger); performance_for_twenty = ConvoScreen:new { id = "performance_for_twenty", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_c9770db7", -- I would think that if you were to go out and do a performance routine for at least twenty people, that would be sufficient. Remember, the more people that get a taste of your act, the more tickets we'll sell! stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_b6dac7cf", "go_entertain_twenty"}, -- OK, I'll get started on that now. {"@conversation/quest_crowd_pleaser_manager:s_a820a6d1", "come_back_when_more_time"}, -- I'll have to come back later. } } theaterManagerConvoTemplate:addScreen(performance_for_twenty); come_back_when_more_time = ConvoScreen:new { id = "come_back_when_more_time", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_b1522710", -- I see. Well, come back when you have more time and we'll get started. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(come_back_when_more_time); go_entertain_twenty = ConvoScreen:new { id = "go_entertain_twenty", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_f66a7b69", -- Just go out and entertain twenty people. That should be enough. Then come back and we'll talk about your next show. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(go_entertain_twenty); init_hasnt_entertained_twenty = ConvoScreen:new { id = "init_hasnt_entertained_twenty", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_3d244a46", -- You haven't completed your promotional assignment have you? Come back when you're done and we'll talk about your next performance. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_hasnt_entertained_twenty); init_entertained_twenty = ConvoScreen:new { id = "init_entertained_twenty", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_f29e46b6", -- Great work! Really great work! I'm starting to hear a lot of people talk about you! I've got a feeling that this show is going to be fantastic. stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_7b58a334", "whenever_you_like"}, -- When can we get started with the next show? } } theaterManagerConvoTemplate:addScreen(init_entertained_twenty); whenever_you_like = ConvoScreen:new { id = "whenever_you_like", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_1e0d968c", -- Whenever you like. Just go make yourself ready and speak to me again when you want to start. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(whenever_you_like); init_second_show = ConvoScreen:new { id = "init_second_show", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_3cdabd0e", -- What? Oh, hello there. I'm sorry, it's recently become rather busy. What can I do for you? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_1dc24a1", "open_slot_coming_up"}, -- I'm here to talk about my next performance. {"@conversation/quest_crowd_pleaser_manager:s_3ef23ade", "ok_thats_fine"}, -- Sorry. I'll come back later. } } theaterManagerConvoTemplate:addScreen(init_second_show); ok_thats_fine = ConvoScreen:new { id = "ok_thats_fine", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_a19891a9", -- OK, that's fine. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(ok_thats_fine); open_slot_coming_up = ConvoScreen:new { id = "open_slot_coming_up", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_250ebca6", -- Oh yes, I see, I see. Yes, we do have an open slot coming up here very shortly. Are you ready to get started with your show now? stopConversation = "false", options = { -- Handled by convo handler in case someone is on stage --{"@conversation/quest_crowd_pleaser_manager:s_59a59142", ""}, -- As ready as I'll ever be. --{"@conversation/quest_crowd_pleaser_manager:s_fb55e1c0", "nervous_come_back"}, -- Actually I'm not quite ready yet. } } theaterManagerConvoTemplate:addScreen(open_slot_coming_up); nervous_come_back = ConvoScreen:new { id = "nervous_come_back", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_38a3b1e2", -- Nervous? I understand. Just come back when you're ready and we'll get you up on stage. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(nervous_come_back); starts_in_two_and_a_half = ConvoScreen:new { id = "starts_in_two_and_a_half", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_e66da464", -- Good. I'll let the crew know so that they can start setting up. The performance will start in two and a half minutes. You may speak with the audience beforehand if you like, but you must be on the stage when the show starts, alright? stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(starts_in_two_and_a_half); init_completed_second_show = ConvoScreen:new { id = "init_completed_second_show", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_1a0fba4e", -- Wow, that was a great act! Really! Here, I'm supposed to give you an advance for your next performance. Go get some rest, and come see me whenever you want to talk about your next show. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_completed_second_show); init_third_advertising = ConvoScreen:new { id = "init_third_advertising", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_ffa16d1d", -- You're here about your next show aren't you? Sure, sure, I understand. You'll need to go out and do some more promotion before you get started with the next performance, though. Is that alright? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_1dc24a1", "biggest_performance_ever"}, -- That's fine. I don't mind doing the promotions. {"@conversation/quest_crowd_pleaser_manager:s_2f3d57d6", "part_of_the_business"}, -- I don't really like doing the promotions. {"@conversation/quest_crowd_pleaser_manager:s_1fe0d27c", "alright_come_back_when_time"}, -- I don't have time for that stuff now. } } theaterManagerConvoTemplate:addScreen(init_third_advertising); alright_come_back_when_time = ConvoScreen:new { id = "alright_come_back_when_time", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_942ddb10", -- Alright, come back when you have the time. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(alright_come_back_when_time); part_of_the_business = ConvoScreen:new { id = "part_of_the_business", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_fe82f47f", -- Advertising and promotion is part of the business kid. Now are you ready to go out there and spread the word, or not? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_a99397a", "biggest_performance_ever"}, -- Yeah, I guess so. {"@conversation/quest_crowd_pleaser_manager:s_da9a29e9", "alright_come_back_when_ready"}, -- No, not yet. } } theaterManagerConvoTemplate:addScreen(part_of_the_business); alright_come_back_when_ready = ConvoScreen:new { id = "alright_come_back_when_ready", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_f72be127", -- Alright. Come back whenever you're ready. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(alright_come_back_when_ready); biggest_performance_ever = ConvoScreen:new { id = "biggest_performance_ever", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_668b00bf", -- That's fantastic. This is going to be your biggest performance ever! I can feel it! stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_57c8489e", "performance_for_thirty"}, -- What should I do? {"@conversation/quest_crowd_pleaser_manager:s_ad679858", "alright_come_back_when_ready"}, -- I changed my mind. I'm not ready yet. } } theaterManagerConvoTemplate:addScreen(biggest_performance_ever); performance_for_thirty = ConvoScreen:new { id = "performance_for_thirty", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_7cef0609", -- Here's what you do. Go out and do a small performance routine for thirty people. Soon, everybody should be talking about you, and if the word is good, we might even have a sell out show! stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_c6403b16", "go_entertain_thirty"}, -- OK, I'll go get started. {"@conversation/quest_crowd_pleaser_manager:s_d0fc43d", "alright_come_back_when_time"}, -- Hm. I don't have time for that right now. } } theaterManagerConvoTemplate:addScreen(performance_for_thirty); go_entertain_thirty = ConvoScreen:new { id = "go_entertain_thirty", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_bba5f6f2", -- Excellent. Just go out and entertain thirty people. After that, no more promotional work, I promise. Then come back and we'll talk about your next show. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(go_entertain_thirty); init_hasnt_entertained_thirty = ConvoScreen:new { id = "init_hasnt_entertained_thirty", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_664ead2a", -- I'm hearing people talk about your upcoming show, but it's not enough. Go finish your promotional job, and then we'll discuss your performance. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_hasnt_entertained_thirty); init_entertained_thirty = ConvoScreen:new { id = "init_entertained_thirty", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_b5c6a62d", -- Wow... this is fantastic! Everybody in town is talking about you! We'll have a sold out show for sure! Go make your preparations and come back whenever you're ready to start the performance! stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_entertained_thirty); init_third_show = ConvoScreen:new { id = "init_third_show", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_16e98373", -- Ah, you're here about your last show? stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_36a4e374", "set_up_if_ready"}, -- Yes, I am. {"@conversation/quest_crowd_pleaser_manager:s_55e428e8", "last_of_series"}, -- Last show? {"@conversation/quest_crowd_pleaser_manager:s_3ef23ade", "ok_thats_fine"}, -- Sorry, I'll come back later. } } theaterManagerConvoTemplate:addScreen(init_third_show); last_of_series = ConvoScreen:new { id = "last_of_series", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_2cf69669", -- That's right. This is the last show scheduled for your concert series. But don't worry, for an entertainer such as yourself, I'm sure that there will be many opportunities for you in the future. stopConversation = "false", options = { {"@conversation/quest_crowd_pleaser_manager:s_61657d0f", "set_up_if_ready"}, -- I see. {"@conversation/quest_crowd_pleaser_manager:s_fd047f06", "alright_come_back_when_ready"}, -- I'd better come back later then. } } theaterManagerConvoTemplate:addScreen(last_of_series); set_up_if_ready = ConvoScreen:new { id = "set_up_if_ready", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_b751f222", -- If you're ready now, I'll go ahead and start getting things set up. What do you say? stopConversation = "false", options = { -- Handled by convo handler in case someone is on stage --{"@conversation/quest_crowd_pleaser_manager:s_dd4bb16d", "starts_in_three"}, -- Let's do it! --{"@conversation/quest_crowd_pleaser_manager:s_d730c5dd", "take_your_time"}, -- No, I'm not quite ready yet. } } theaterManagerConvoTemplate:addScreen(set_up_if_ready); starts_in_three = ConvoScreen:new { id = "starts_in_three", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_86731ce6", -- Good. I'll let the crew know so that they can start setting up. The performance will start in three minutes. You may speak with the audience beforehand if you like, but you must be on the stage when the show starts, alright? stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(starts_in_three); init_completed_third_show = ConvoScreen:new { id = "init_completed_third_show", leftDialog = "@conversation/quest_crowd_pleaser_manager:s_7223d3c0", -- Amazing. Simply amazing. You truly are one of the best performers I've seen in a long time. Here's a bonus for doing so well. Also, one of our regular performers has offered to teach you a new act. Maybe you can use it at your next show. stopConversation = "true", options = {} } theaterManagerConvoTemplate:addScreen(init_completed_third_show); addConversationTemplate("theaterManagerConvoTemplate", theaterManagerConvoTemplate);
return PlaceObj("ModDef", { "title", "Fix Project Morpheus Particle Fell Down", "version", 1, "version_major", 0, "version_minor", 1, "saved", 0, "image", "Preview.png", "id", "ChoGGi_FixProjectMorpheusParticleFellDown", "steam_id", "1576281619", "pops_any_uuid", "fed5b2b8-b74e-4e10-b2f1-190ad5c8b6ba", "author", "ChoGGi", "lua_revision", 249143, "code", { "Code/Script.lua", }, "description", [[This one has been in since release... On load, and once a day it'll check if the blue growing thing has fallen off any morph towers, and re-attach if any have.]], })
return {'pks'}
local NPC = {}; NPC.Name = "Genetec"; NPC.ID = 15; NPC.Model = Model("models/players/perp2/m_4_01.mdl"); NPC.Invisible = false; // Used for ATM Machines, Casino Tables, etc. NPC.Location = Vector(-9687.8604, 9193.0713, 72.0313); NPC.Angles = Angle(0, 90, 0.000000); NPC.ShowChatBubble = "Normal"; NPC.Sequence = 228; // This is always local player. function NPC.OnTalk ( ) GAMEMODE.DialogPanel:SetDialog("Welcome to GeneTech."); GAMEMODE.DialogPanel:AddDialog('What do you guys do around here?', NPC.What) GAMEMODE.DialogPanel:AddDialog("", LEAVE_DIALOG) GAMEMODE.DialogPanel:Show(); end function NPC.What ( ) GAMEMODE.DialogPanel:SetDialog("We manipulate your genes to allow you to choose what you'll be adept at. We can also insert specialized genes into your genome to allow you to be skilled in multiple fields."); GAMEMODE.DialogPanel:AddDialog('Sounds expensive. How much are we talking?', NPC.Cost) GAMEMODE.DialogPanel:AddDialog("I doubt I'm rich enough for this.", LEAVE_DIALOG) end function NPC.Cost ( ) local cost = (((GAMEMODE.MaxGenes - 5) - (GAMEMODE.MaxGenes - LocalPlayer():GetNumGenes())) + 1) * GAMEMODE.NewGenePrice GAMEMODE.DialogPanel:SetDialog("Yes, it is quite. This cutting-edge technology will cost you no less than " .. DollarSign() .. GAMEMODE.GeneResetPrice .. " dollars to reset your genome, and " .. DollarSign() .. cost .. " to insert new genes. Also, every time we insert new genes, it will get more difficult, raising the price. We only take check or debit card.\n\n(This cost will be taken out of your bank account.)"); GAMEMODE.DialogPanel:AddDialog("That's nothing! Let me manipulate my genome, please! (Reset your genes)", NPC.Reset); GAMEMODE.DialogPanel:AddDialog("That's nothing! Add some new genes to me, please! (Add more gene points)", NPC.Add); GAMEMODE.DialogPanel:AddDialog("<Whistle> I think I should leave now.", LEAVE_DIALOG); end function NPC.Add ( ) local cost = (((GAMEMODE.MaxGenes - 5) - (GAMEMODE.MaxGenes - LocalPlayer():GetNumGenes())) + 1) * GAMEMODE.NewGenePrice if LocalPlayer():GetBank() >= cost then if LocalPlayer():GetNumGenes() < GAMEMODE.MaxGenes then GAMEMODE.DialogPanel:SetDialog("<5 Hours Later> There you go, sir. Enjoy your new mastery of any field desirable."); RunConsoleCommand('perp_s_b', LocalPlayer():UniqueID()); GAMEMODE.DialogPanel:AddDialog("Thanks!", LEAVE_DIALOG); LocalPlayer():SetPrivateInt("gpoints", LocalPlayer():GetPrivateInt("gpoints", 0) + 1, true); LocalPlayer():TakeBank(cost); else GAMEMODE.DialogPanel:SetDialog("Ahh, it appears our technicians cannot add any more genes, as we've already stuffed your genome to it's maximum. Sorry."); GAMEMODE.DialogPanel:AddDialog("That's lame.", LEAVE_DIALOG); end else GAMEMODE.DialogPanel:SetDialog("What do you mean that's nothing? You don't even have that much in your bank!\n\n(You can only pay for this out of your bank account.)"); GAMEMODE.DialogPanel:AddDialog("Dang, you caught me.", LEAVE_DIALOG); end end function NPC.Reset ( ) if LocalPlayer():GetBank() >= GAMEMODE.GeneResetPrice then GAMEMODE.DialogPanel:SetDialog("<5 Hours Later> There you go, sir. Should be ready for you to choose your adeptness."); RunConsoleCommand('perp_s_r'); LocalPlayer():SetPrivateInt("gpoints", LocalPlayer():GetNumGenes(), true); LocalPlayer():TakeBank(GAMEMODE.GeneResetPrice); LocalPlayer():ResetGenes(true); GAMEMODE.DialogPanel:AddDialog("Thanks!", LEAVE_DIALOG); else GAMEMODE.DialogPanel:SetDialog("What do you mean that's nothing? You don't even have that much!\n\n(You can only pay for this out of your bank account.)"); GAMEMODE.DialogPanel:AddDialog("Dang, you caught me.", LEAVE_DIALOG); end end GAMEMODE:LoadNPC(NPC);
assets = { Asset("ANIM", "anim/phonograph.zip"), Asset("SOUND", "sound/maxwell.fsb"), Asset("SOUND", "sound/music.fsb"), Asset("SOUND", "sound/gramaphone.fsb") } local function play(inst) inst.AnimState:PlayAnimation("play_loop", true) inst.SoundEmitter:PlaySound(inst.songToPlay, "ragtime") if inst.components.playerprox then inst:RemoveComponent("playerprox") end inst:PushEvent("turnedon") end local function stop(inst) inst.AnimState:PlayAnimation("idle") inst.SoundEmitter:KillSound("ragtime") inst.SoundEmitter:PlaySound("dontstarve/music/gramaphone_end") inst:PushEvent("turnedoff") end local function fn() local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() local sound = inst.entity:AddSoundEmitter() MakeObstaclePhysics(inst, 0.1) anim:SetBank("phonograph") anim:SetBuild("phonograph") anim:PlayAnimation("idle") inst.songToPlay = "dontstarve/maxwell/ragtime" inst:AddTag("maxwellphonograph") inst:AddComponent("inspectable") inst:AddComponent("machine") inst.components.machine.turnonfn = play inst.components.machine.turnofffn = stop inst.entity:SetCanSleep(false) inst:AddComponent("playerprox") inst.components.playerprox:SetDist(600, 615) inst.components.playerprox:SetOnPlayerNear(function() inst.components.machine:TurnOn() end) return inst end return Prefab("common/objects/maxwellphonograph", fn, assets)
local high = {} local low = {} high = setmetatable(high, { __band = function(_, o) return o end, __bor = function() return high end, __bnot = function() return low end, __bxor = function(_, o) if o == low then return high else return low end end, __tostring = function() return '1' end, }) low = setmetatable(low, { __band = function() return low end, __bor = function(_, o) return o end, __bnot = function() return high end, __bxor = function(_, o) if o == high then return high else return low end end, __tostring = function() return '0' end, }) return { H = high, L = low, }
function test1() local thing = nil -- MISSED BY LUACOV print("test1") end test1() function test2() local stuff = function (x) return x end local thing = stuff({ b = { name = 'bob', }, -- comment }) -- MISSED BY LUACOV print("test2") end test2() function test3() if true then -- MISSED BY LUACOV print("test3") end end test3() function test4() while true do -- MISSED BY LUACOV print("test4") break end end test4() -- My own addition: function test5() local stuff = function (x) return x end local thing = stuff({ b = { name = 'bob', }, -- comment } ) -- MISSED BY LUACOV print("test5") end test5() function test6() -- MISSED BY LUACOV if true then -- MISSED BY LUACOV end -- MISSED BY LUACOV print("test6") end test6() function test7() local a, b = 1,2 if a < b then -- MISSED BY LUACOV a = b end -- MISSED BY LUACOV print("test7") end test7() function test8() local a,b = 1,2 if a < b then a = b end; -- MISSED BY LUACOV local function foo(f) f() end foo(function() a = b end) -- MISSED BY LUACOV print("test8") end test8() function test9() local function foo(f) return function() -- MISSED BY LUACOV a = a end end foo()() print("test9") end test9() function test10() local s = { a = 1; -- MISSED BY LUACOV b = 2, -- MISSED BY LUACOV c = 3 -- MISSED BY LUACOV } print("test10") end test10() function test11() local function foo(f) return 1, 2, function() -- MISSED BY LUACOV a = a end end local a,b,c = foo() c() print("test11") end test11()
-- AreCoordsCollidingWithExterior() local OwnedHouse = nil local AvailableHouses = {} local blips = {} local Knockings = {} --[[Citizen['CreateThread'](function() while true do Wait(0) DrawEdge(PlayerPedId()) local coords = GetEntityCoords(PlayerPedId()) local found, coords, heading = GetClosestVehicleNodeWithHeading(coords.x, coords.y, coords.z, 3.0, 100.0, 2.5) if IsControlJustReleased(0, 38) then SetEntityCoords(PlayerPedId(), coords) SetEntityHeading(PlayerPedId(), heading) end end end)]] Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Wait(0) end while ESX.GetPlayerData().job == nil do Wait(0) end TriggerServerEvent('loaf_housing:getOwned') while OwnedHouse == nil do Wait(0) end if Config.IKEABlip['Enabled'] then local blip = AddBlipForCoord(Config.Furnituring['enter']) SetBlipSprite(blip, Config.IKEABlip['Sprite']) SetBlipColour(blip, Config.IKEABlip['Colour']) SetBlipAsShortRange(blip, true) SetBlipScale(blip, Config.IKEABlip['Scale']) BeginTextCommandSetBlipName("STRING") AddTextComponentString(Strings['ikea']) EndTextCommandSetBlipName(blip) table.insert(blips, blip) end while true do Wait(500) for k, v in pairs(Config.Houses) do if Vdist2(GetEntityCoords(PlayerPedId()), v['door']) <= 2.5 then local text = 'error' while Vdist2(GetEntityCoords(PlayerPedId()), v['door']) <= 2.5 do if OwnedHouse.houseId == k then text = (Strings['Press_E']):format(Strings['Manage_House']) else if not AvailableHouses[k] then if OwnedHouse.houseId ~= 0 then text = Strings['Must_Sell'] else text = (Strings['Press_E']):format((Strings['Buy_House']):format(k)) end else text = (Strings['Press_E']):format(Strings['Knock_House']) end end HelpText(text, v['door']) if IsControlJustReleased(0, 38) then if OwnedHouse.houseId == k then ESX.UI.Menu.CloseAll() elements = { {label = Strings['Enter_House'], value = 'enter'}, {label = (Strings['Sell_House']):format(math.floor(Config.Houses[OwnedHouse.houseId]['price']*(Config.SellPercentage/100))), value = 'sell'}, } if Config.EnableGarage then table.insert(elements, {label = Strings['Garage'], value = 'garage'}) end ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'manage_house', { title = Strings['Manage_House'], align = 'top-left', elements = elements }, function(data, menu) if data.current.value == 'enter' then TriggerServerEvent('loaf_housing:enterHouse', k) menu.close() elseif data.current.value == 'garage' then local coords = Config.Houses[OwnedHouse.houseId]['door'] local found, coords, heading = GetClosestVehicleNodeWithHeading(coords.x, coords.y, coords.z, 3.0, 100.0, 2.5) if found then ESX.UI.Menu.CloseAll() TriggerServerEvent('esx_garage:viewVehicles', coords, heading, 'housing') return else ESX.ShowNotification(Strings['No_Spawn']) end elseif data.current.value == 'sell' then ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'sell', { title = (Strings['Sell_Confirm']):format(math.floor(Config.Houses[OwnedHouse.houseId]['price']*(Config.SellPercentage/100))), align = 'top-left', elements = { {label = Strings['yes'], value = 'yes'}, {label = Strings['no'], value = 'no'} }, }, function(data2, menu2) if data2.current.value == 'yes' then TriggerServerEvent('loaf_housing:sellHouse') ESX.UI.Menu.CloseAll() Wait(5000) else menu2.close() end end, function(data2, menu2) menu2.close() end) end end, function(data, menu) menu.close() end) else if not AvailableHouses[k] and OwnedHouse.houseId == 0 then ESX.UI.Menu.CloseAll() ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'buy', { title = (Strings['Buy_House_Confirm']):format(k, v['price']), align = 'top-left', elements = { {label = Strings['yes'], value = 'yes'}, {label = Strings['no'], value = 'no'} }, }, function(data, menu) if data.current.value == 'yes' then TriggerServerEvent('loaf_housing:buyHouse', k) ESX.UI.Menu.CloseAll() Wait(5000) else menu.close() end end, function(data, menu) menu.close() end) else if AvailableHouses[k] then TriggerServerEvent('loaf_housing:knockDoor', k) while Vdist2(GetEntityCoords(PlayerPedId()), v['door']) <= 4.5 do Wait(0) HelpText(Strings['Waiting_Owner'], v['door']) end TriggerServerEvent('loaf_housing:unKnockDoor', k) end end end Wait(5000) end Wait(0) end else if OwnedHouse.houseId == k then local coords = v['door'] local found, coords, heading = GetClosestVehicleNodeWithHeading(coords.x, coords.y, coords.z, 3.0, 100.0, 2.5) if found then while #(GetEntityCoords(PlayerPedId()) - coords) <= 45.0 and IsPedInAnyVehicle(PlayerPedId(), false) and Config.EnableGarage do Wait(0) DrawMarker(1, coords-vector3(0.0, 0.0, 0.5), vector3(0.0, 0.0, 0.0), vector3(0.0, 0.0, 0.0), vector3(1.0, 1.0, 1.2), 255, 255, 25, 150, false, false, 2, false, false, false) if #(GetEntityCoords(PlayerPedId()) - coords) <= 5.0 and IsPedInAnyVehicle(PlayerPedId(), false) and Config.EnableGarage then HelpText(Strings['Store_Garage'], coords) if IsControlJustReleased(0, 38) then TriggerEvent('esx_garage:storeVehicle', 'housing') end end end end end end end end end) Citizen.CreateThread(function() while OwnedHouse == nil do Wait(0) end while true do Wait(0) local dist = Vdist2(GetEntityCoords(PlayerPedId()), Config.Furnituring['enter']) if dist <= 50.0 then DrawMarker(27, Config.Furnituring['enter'], vector3(0.0, 0.0, 0.0), vector3(0.0, 0.0, 0.0), vector3(1.0, 1.0, 1.0), 255, 0, 255, 150, false, false, 2, false, false, false) if dist <= 1.5 then HelpText((Strings['Press_E']):format(Strings['Buy_Furniture']), Config.Furnituring['enter']) if IsControlJustReleased(0, 38) then FreezeEntityPosition(PlayerPedId(), true) local currentcategory = 1 local category = Config.Furniture['Categories'][currentcategory] local current = 1 local cooldown = GetGameTimer() local model = GetHashKey(Config.Furniture[category[1]][current][2]) if IsModelValid(model) then local startedLoading = GetGameTimer() while not HasModelLoaded(model) do RequestModel(model) Wait(0) if GetGameTimer() - startedLoading >= 1500 then ESX.ShowNotification(('El modelo (%s) esta tardando mucho en cargar, contacta con un administrador!'):format(Config.Furniture[category[1]][current][2])) break end end furniture = CreateObject(model, Config.Furnituring['teleport']) SetEntityHeading(furniture, 0.0) else ESX.ShowNotification(('El modelo (%s) no es valido. Contacta a un administrador!'):format(Config.Furniture[category[1]][current][2])) end local cam = CreateCam("DEFAULT_SCRIPTED_Camera", 1) SetCamCoord(cam, GetOffsetFromEntityInWorldCoords(furniture, 0.0, -5.0, 4.0)) PointCamAtCoord(cam, GetEntityCoords(furniture)) RenderScriptCams(1, 0, 0, 1, 1) SetCamActive(cam, true) FreezeEntityPosition(PlayerPedId(), true) while true do Wait(0) HelpText((Strings['Buying_Furniture']):format(category[2], Config.Furniture[category[1]][current][1], Config.Furniture[category[1]][current][3])) DrawText3D(GetEntityCoords(furniture), ('%s (~g~$%s~w~)'):format(Config.Furniture[category[1]][current][1], Config.Furniture[category[1]][current][3]), 0.5) DisableControlAction(0, 24) DisableControlAction(0, 25) DisableControlAction(0, 14) DisableControlAction(0, 15) DisableControlAction(0, 16) DisableControlAction(0, 17) NetworkOverrideClockTime(15, 0, 0) ClearOverrideWeather() ClearWeatherTypePersist() SetWeatherTypePersist('EXTRASUNNY') SetWeatherTypeNow('EXTRASUNNY') SetWeatherTypeNowPersist('EXTRASUNNY') if IsControlJustReleased(0, 194) then break elseif IsControlJustReleased(0, 172) then if Config.Furniture['Categories'][currentcategory + 1] then category = Config.Furniture['Categories'][currentcategory + 1] currentcategory = currentcategory + 1 current = 1 else category = Config.Furniture['Categories'][1] currentcategory = 1 current = 1 end DeleteObject(furniture) model = GetHashKey(Config.Furniture[category[1]][current][2]) if IsModelValid(model) then local startedLoading = GetGameTimer() while not HasModelLoaded(model) do RequestModel(model) Wait(0) if GetGameTimer() - startedLoading >= 1500 then ESX.ShowNotification(('El modelo (%s) esta tardando mucho en cargar, contacta con un administrador!'):format(Config.Furniture[category[1]][current][2])) break end end furniture = CreateObject(model, Config.Furnituring['teleport']) SetEntityHeading(furniture, 0.0) else ESX.ShowNotification(('El modelo (%s) no es valido. Contacta a un administrador!'):format(Config.Furniture[category[1]][current][2])) end elseif IsControlPressed(0, 34) then SetEntityHeading(furniture, GetEntityHeading(furniture) + 0.25) elseif IsControlPressed(0, 35) then SetEntityHeading(furniture, GetEntityHeading(furniture) - 0.25) elseif IsDisabledControlPressed(0, 96) then local currentCoord = GetCamCoord(cam) if currentCoord.z + 0.1 <= GetOffsetFromEntityInWorldCoords(furniture, 0.0, -5.0, 4.5).z then currentCoord = vector3(currentCoord.x, currentCoord.y, currentCoord.z + 0.1) SetCamCoord(cam, currentCoord) end elseif IsDisabledControlPressed(0, 97) then print('hej') local currentCoord = GetCamCoord(cam) print(currentCoord) if currentCoord.z - 0.1 >= GetOffsetFromEntityInWorldCoords(furniture, 0.0, -5.0, 0.1).z then currentCoord = vector3(currentCoord.x, currentCoord.y, currentCoord.z - 0.1) print(currentCoord) SetCamCoord(cam, currentCoord) end elseif IsControlPressed(0, 33) then local fov = GetCamFov(cam) if fov + 0.1 >= 129.9 then fov = 129.9 else fov = fov + 0.1 end SetCamFov(cam, fov) elseif IsControlPressed(0, 32) then local fov = GetCamFov(cam) if fov - 0.1 <= 1.1 then fov = 1.1 else fov = fov - 0.1 end SetCamFov(cam, fov) elseif IsControlJustReleased(0, 173) then if Config.Furniture['Categories'][currentcategory - 1] then category = Config.Furniture['Categories'][currentcategory - 1] currentcategory = currentcategory - 1 current = 1 else category = Config.Furniture['Categories'][#Config.Furniture['Categories']] currentcategory = #Config.Furniture['Categories'] current = 1 end DeleteObject(furniture) model = GetHashKey(Config.Furniture[category[1]][current][2]) if IsModelValid(model) then local startedLoading = GetGameTimer() while not HasModelLoaded(model) do RequestModel(model) Wait(0) if GetGameTimer() - startedLoading >= 1500 then ESX.ShowNotification(('El modelo (%s) esta tardando mucho en cargar, contacta con un administrador!'):format(Config.Furniture[category[1]][current][2])) break end end furniture = CreateObject(model, Config.Furnituring['teleport']) SetEntityHeading(furniture, 0.0) else ESX.ShowNotification(('El modelo (%s) no es valido. Contacta a un administrador!'):format(Config.Furniture[category[1]][current][2])) end elseif IsControlJustReleased(0, 191) then local answered = false ESX.UI.Menu.CloseAll() ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'buy_furniture', { title = (Strings['Confirm_Purchase']):format(Config.Furniture[category[1]][current][1], Config.Furniture[category[1]][current][3]), align = 'center', elements = { {label = Strings['yes'], value = 'yes'}, {label = Strings['no'], value = 'no'} }, }, function(data, menu) menu.close() if data.current.value == 'yes' then TriggerServerEvent('loaf_housing:buy_furniture', currentcategory, current) DoScreenFadeOut(250) Wait(1500) DoScreenFadeIn(500) end answered = true end, function(data, menu) answered = true menu.close() end ) while not answered do Wait(0) end elseif IsControlPressed(0, 190) and cooldown < GetGameTimer() then if Config.Furniture[category[1]][current + 1] then current = current + 1 else current = 1 end DeleteObject(furniture) model = GetHashKey(Config.Furniture[category[1]][current][2]) if IsModelValid(model) then local startedLoading = GetGameTimer() while not HasModelLoaded(model) do RequestModel(model) Wait(0) if GetGameTimer() - startedLoading >= 1500 then ESX.ShowNotification(('El modelo (%s) esta tardando mucho en cargar, contacta con un administrador!'):format(Config.Furniture[category[1]][current][2])) break end end furniture = CreateObject(model, Config.Furnituring['teleport']) SetEntityHeading(furniture, 0.0) else ESX.ShowNotification(('El modelo (%s) no es valido. Contacta a un administrador!'):format(Config.Furniture[category[1]][current][2])) end cooldown = GetGameTimer() + 250 elseif IsControlPressed(0, 189) and cooldown < GetGameTimer() then if Config.Furniture[category[1]][current - 1] then current = current - 1 else current = #Config.Furniture[category[1]] end DeleteObject(furniture) model = GetHashKey(Config.Furniture[category[1]][current][2]) if IsModelValid(model) then local startedLoading = GetGameTimer() while not HasModelLoaded(model) do RequestModel(model) Wait(0) if GetGameTimer() - startedLoading >= 1500 then ESX.ShowNotification(('El modelo (%s) esta tardando mucho en cargar, contacta con un administrador!'):format(Config.Furniture[category[1]][current][2])) break end end furniture = CreateObject(model, Config.Furnituring['teleport']) SetEntityHeading(furniture, 0.0) else ESX.ShowNotification(('El modelo (%s) no es valido. Contacta a un administrador!'):format(Config.Furniture[category[1]][current][2])) end cooldown = GetGameTimer() + 250 end end FreezeEntityPosition(PlayerPedId(), false) DeleteObject(furniture) RenderScriptCams(false, false, 0, true, false) DestroyCam(cam) end end end end end) RegisterNetEvent('loaf_housing:spawnHouse') AddEventHandler('loaf_housing:spawnHouse', function(coords, furniture) local prop = Config.Houses[OwnedHouse.houseId]['prop'] local house = EnterHouse(Config.Props[prop], coords) local placed_furniture = {} for k, v in pairs(OwnedHouse['furniture']) do local model = GetHashKey(v['object']) while not HasModelLoaded(model) do RequestModel(model) Wait(0) end local object = CreateObject(model, GetOffsetFromEntityInWorldCoords(house, vector3(v['offset'][1], v['offset'][2], v['offset'][3])), false, false, false) SetEntityHeading(object, v['heading']) FreezeEntityPosition(object, true) SetEntityCoordsNoOffset(object, GetOffsetFromEntityInWorldCoords(house, vector3(v['offset'][1], v['offset'][2], v['offset'][3]))) table.insert(placed_furniture, object) end SetEntityHeading(house, 0.0) local exit = GetOffsetFromEntityInWorldCoords(house, Config.Offsets[prop]['door']) local storage = GetOffsetFromEntityInWorldCoords(house, Config.Offsets[prop]['storage']) TriggerServerEvent('loaf_housing:setInstanceCoords', exit, coords, prop, OwnedHouse['furniture']) DoScreenFadeOut(750) while not IsScreenFadedOut() do Wait(0) end for i = 1, 25 do SetEntityCoords(PlayerPedId(), exit) Wait(50) end while IsEntityWaitingForWorldCollision(PlayerPedId()) do SetEntityCoords(PlayerPedId(), exit) Wait(50) end DoScreenFadeIn(1500) local in_house = true ClearPedWetness(PlayerPedId()) while in_house do NetworkOverrideClockTime(15, 0, 0) ClearOverrideWeather() ClearWeatherTypePersist() SetWeatherTypePersist('EXTRASUNNY') SetWeatherTypeNow('EXTRASUNNY') SetWeatherTypeNowPersist('EXTRASUNNY') DrawMarker(27, exit, vector3(0.0, 0.0, 0.0), vector3(0.0, 0.0, 0.0), vector3(1.0, 1.0, 1.0), 255, 0, 255, 150, false, false, 2, false, false, false) DrawMarker(27, storage, vector3(0.0, 0.0, 0.0), vector3(0.0, 0.0, 0.0), vector3(1.0, 1.0, 1.0), 255, 0, 255, 150, false, false, 2, false, false, false) if Vdist2(GetEntityCoords(PlayerPedId()), storage) <= 2.0 then HelpText((Strings['Press_E']):format(Strings['Storage']), storage) if IsControlJustReleased(0, 38) and Vdist2(GetEntityCoords(PlayerPedId()), storage) <= 2.0 then ESX.UI.Menu.CloseAll() ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'storage', { title = Strings['Storage_Title'], align = 'top-left', elements = { {label = Strings['Items'], value = 'i'}, {label = Strings['Weapons'], value = 'w'} }, }, function(data, menu) if data.current.value == 'i' then itemStorage(OwnedHouse.houseId) elseif data.current.value == 'w' then weaponStorage(OwnedHouse.houseId) end end, function(data, menu) menu.close() end) end end if Vdist2(GetEntityCoords(PlayerPedId()), exit) <= 1.5 then HelpText((Strings['Press_E']):format(Strings['Manage_Door']), exit) if IsControlJustReleased(0, 38) then ESX.UI.Menu.CloseAll() local elements = { {label = Strings['Accept'], value = 'accept'}, {label = Strings['Furnish'], value = 'furnish'}, {label = Strings['Re_Furnish'], value = 'refurnish'}, {label = Strings['Exit'], value = 'exit'}, } ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'manage_door', { title = Strings['Manage_Door'], align = 'top-left', elements = elements, }, function(data, menu) if data.current.value == 'exit' then ESX.TriggerServerCallback('loaf_housing:hasGuests', function(has) if not has then ESX.UI.Menu.CloseAll() TriggerServerEvent('loaf_housing:deleteInstance') Wait(3500) in_house = false return else ESX.ShowNotification(Strings['Guests']) end end) elseif data.current.value == 'refurnish' then ESX.TriggerServerCallback('loaf_housing:hasGuests', function(has) if not has then local elements = {} for k, v in pairs(OwnedHouse['furniture']) do table.insert(elements, {label = (Strings['Remove']):format(v['name'], k), value = k}) end local editing = true ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'edit_furniture', { title = Strings['Re_Furnish'], align = 'top-left', elements = elements, }, function(data2, menu2) DeleteObject(placed_furniture[data2.current.value]) if furniture[OwnedHouse['furniture'][data2.current.value]['object']] then furniture[OwnedHouse['furniture'][data2.current.value]['object']]['amount'] = furniture[OwnedHouse['furniture'][data2.current.value]['object']]['amount'] + 1 else furniture[OwnedHouse['furniture'][data2.current.value]['object']] = {amount = 1, name = OwnedHouse['furniture'][data2.current.value]['name']} end table.remove(OwnedHouse['furniture'], data2.current.value) for k, v in pairs(placed_furniture) do DeleteObject(v) end placed_furniture = {} for k, v in pairs(OwnedHouse['furniture']) do local model = GetHashKey(v['object']) while not HasModelLoaded(model) do RequestModel(model) Wait(0) end local object = CreateObject(model, GetOffsetFromEntityInWorldCoords(house, vector3(v['offset'][1], v['offset'][2], v['offset'][3])), true, false, true) SetEntityHeading(object, v['heading']) FreezeEntityPosition(object, true) SetEntityCoordsNoOffset(object, GetOffsetFromEntityInWorldCoords(house, vector3(v['offset'][1], v['offset'][2], v['offset'][3]))) table.insert(placed_furniture, object) end TriggerServerEvent('loaf_housing:furnish', OwnedHouse, furniture) menu2.close() editing = false end, function(data2, menu2) editing = false menu2.close() end) while editing do Wait(0) for k, v in pairs(placed_furniture) do DrawText3D(GetEntityCoords(v), ('%s (#%s)'):format(OwnedHouse['furniture'][k]['name'], k), 0.3) end end else ESX.ShowNotification(Strings['Guests']) end end) elseif data.current.value == 'furnish' then ESX.TriggerServerCallback('loaf_housing:hasGuests', function(has) if not has then local elements = {} for k, v in pairs(furniture) do table.insert(elements, {label = ('x%s %s'):format(v['amount'], v['name']), value = k, name = v['name']}) end ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'furnish', { title = Strings['Furnish'], align = 'top-left', elements = elements, }, function(data2, menu2) ESX.UI.Menu.CloseAll() local model = GetHashKey(data2.current.value) while not HasModelLoaded(model) do RequestModel(model) Wait(0) end local object = CreateObject(model, GetOffsetFromEntityInWorldCoords(house, Config.Offsets[prop]['spawn_furniture']), true, false, true) SetEntityCollision(object, false, false) SetEntityHasGravity(object, false) Wait(250) while true do Wait(0) HelpText(Strings['Furnishing']) ESX.UI.Menu.CloseAll() -- test DisableControlAction(0, 24) DisableControlAction(0, 25) DisableControlAction(0, 14) DisableControlAction(0, 15) DisableControlAction(0, 16) DisableControlAction(0, 17) -- DrawEdge(object) -- w.i.p DrawText3D(GetEntityCoords(object), ('%s, %s: %s'):format(data2.current.name, Strings['Rotation'], string.format("%.2f", GetEntityHeading(object))), 0.3) if IsControlPressed(0, 172) then SetEntityCoords(object, GetOffsetFromEntityInWorldCoords(object, 0.0, 0.01, 0.0)) elseif IsControlPressed(0, 173) then SetEntityCoords(object, GetOffsetFromEntityInWorldCoords(object, 0.0, -0.01, 0.0)) elseif IsControlPressed(0, 96) then SetEntityCoords(object, GetOffsetFromEntityInWorldCoords(object, 0.0, 0.0, 0.01)) elseif IsControlPressed(0, 97) then SetEntityCoords(object, GetOffsetFromEntityInWorldCoords(object, 0.0, 0.0, -0.01)) elseif IsControlPressed(0, 174) then SetEntityCoords(object, GetOffsetFromEntityInWorldCoords(object, -0.01, 0.0, 0.0)) elseif IsControlPressed(0, 175) then SetEntityCoords(object, GetOffsetFromEntityInWorldCoords(object, 0.01, 0.0, 0.0)) elseif IsDisabledControlPressed(0, 24) then SetEntityHeading(object, GetEntityHeading(object)+0.5) elseif IsDisabledControlPressed(0, 25) then SetEntityHeading(object, GetEntityHeading(object)-0.5) elseif IsControlJustReleased(0, 47) then local objCoords, houseCoords = GetEntityCoords(object), GetEntityCoords(house) local houseHeight = GetEntityHeight(house, GetEntityCoords(house), true, false) SetEntityCoords(object, objCoords.x, objCoords.y, (objCoords.z-(objCoords.z-houseCoords.z))+houseHeight) elseif IsControlPressed(0, 215) then local objCoords, houseCoords = GetEntityCoords(object), GetEntityCoords(house) local furn_offs = objCoords - houseCoords local furnished = {['offset'] = {furn_offs.x, furn_offs.y, furn_offs.z}, ['object'] = data2.current.value, ['name'] = data2.current.name, ['heading'] = GetEntityHeading(object)} table.insert(OwnedHouse['furniture'], furnished) if furniture[data2.current.value]['amount'] > 1 then furniture[data2.current.value]['amount'] = furniture[data2.current.value]['amount'] - 1 else -- ugly code, idk how to improve ¯\_(ツ)_/¯ couldn't get table.remove to work on this shit local oldFurniture = furniture furniture = {} for k, v in pairs(oldFurniture) do if k ~= data2.current.value then furniture[k] = v end end end DeleteObject(object) for k, v in pairs(placed_furniture) do DeleteObject(v) end placed_furniture = {} for k, v in pairs(OwnedHouse['furniture']) do local model = GetHashKey(v['object']) while not HasModelLoaded(model) do RequestModel(model) Wait(0) end local object = CreateObject(model, GetOffsetFromEntityInWorldCoords(house, vector3(v['offset'][1], v['offset'][2], v['offset'][3])), true, false, true) SetEntityHeading(object, v['heading']) FreezeEntityPosition(object, true) SetEntityCoordsNoOffset(object, GetOffsetFromEntityInWorldCoords(house, vector3(v['offset'][1], v['offset'][2], v['offset'][3]))) table.insert(placed_furniture, object) end TriggerServerEvent('loaf_housing:furnish', OwnedHouse, furniture) break elseif IsControlPressed(0, 202) then DeleteObject(object) break end end end, function(data2, menu2) menu2.close() end) else ESX.ShowNotification(Strings['Guests']) end end) elseif data.current.value == 'accept' then local elements = {} for k, v in pairs(Knockings) do table.insert(elements, v) end ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'let_in', { title = Strings['Let_In'], align = 'top-left', elements = elements, }, function(data2, menu2) if Knockings[data2.current.value] then TriggerServerEvent('loaf_housing:letIn', data2.current.value, storage) end menu2.close() end, function(data2, menu2) menu2.close() end) end end, function(data, menu) menu.close() end) end end Wait(0) end DeleteObject(house) for k, v in pairs(placed_furniture) do DeleteObject(v) end end) RegisterNetEvent('loaf_housing:leaveHouse') AddEventHandler('loaf_housing:leaveHouse', function(house) DoScreenFadeOut(750) while not IsScreenFadedOut() do Wait(0) end SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) for i = 1, 25 do SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) Wait(50) end while IsEntityWaitingForWorldCollision(PlayerPedId()) do SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) Wait(50) end DoScreenFadeIn(1500) end) RegisterNetEvent('loaf_housing:knockAccept') AddEventHandler('loaf_housing:knockAccept', function(coords, house, storage, spawnpos, furniture, host) local prop = Config.Houses[house]['prop'] prop = EnterHouse(Config.Props[prop], spawnpos) local placed_furniture = {} for k, v in pairs(furniture) do local model = GetHashKey(v['object']) while not HasModelLoaded(model) do RequestModel(model) Wait(0) end local object = CreateObject(model, GetOffsetFromEntityInWorldCoords(prop, vector3(v['offset'][1], v['offset'][2], v['offset'][3])), false, false, false) SetEntityHeading(object, v['heading']) FreezeEntityPosition(object, true) table.insert(placed_furniture, object) end SetEntityHeading(prop, 0.0) while not DoesEntityExist(prop) do Wait(0) end DoScreenFadeOut(750) while not IsScreenFadedOut() do Wait(0) end SetEntityCoords(PlayerPedId(), coords) for i = 1, 25 do SetEntityCoords(PlayerPedId(), coords) Wait(50) end while IsEntityWaitingForWorldCollision(PlayerPedId()) do SetEntityCoords(PlayerPedId(), coords) Wait(50) end DoScreenFadeIn(1500) local timer = GetGameTimer() + 500 local delete = false while true do Wait(0) if timer <= GetGameTimer() then timer = GetGameTimer() + 500 ESX.TriggerServerCallback('loaf_housing:hostOnline', function(online) if not online then delete = true end end, host) end if delete then ESX.UI.Menu.CloseAll() DoScreenFadeOut(750) for k, v in pairs(placed_furniture) do DeleteObject(v) end while not IsScreenFadedOut() do Wait(0) end SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) for i = 1, 25 do SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) Wait(50) end while IsEntityWaitingForWorldCollision(PlayerPedId()) do SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) Wait(50) end DeleteObject(prop) DoScreenFadeIn(1500) ESX.ShowNotification(Strings['Host_Left']) return end DrawMarker(27, coords, vector3(0.0, 0.0, 0.0), vector3(0.0, 0.0, 0.0), vector3(1.0, 1.0, 1.0), 255, 0, 255, 150, false, false, 2, false, false, false) DrawMarker(27, storage, vector3(0.0, 0.0, 0.0), vector3(0.0, 0.0, 0.0), vector3(1.0, 1.0, 1.0), 255, 0, 255, 150, false, false, 2, false, false, false) if Vdist2(GetEntityCoords(PlayerPedId()), coords) <= 1.5 then HelpText((Strings['Press_E']):format(Strings['Exit']), coords) if IsControlJustReleased(0, 38) then ESX.UI.Menu.CloseAll() DoScreenFadeOut(750) for k, v in pairs(placed_furniture) do DeleteObject(v) end while not IsScreenFadedOut() do Wait(0) end SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) for i = 1, 25 do SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) Wait(50) end while IsEntityWaitingForWorldCollision(PlayerPedId()) do SetEntityCoords(PlayerPedId(), Config.Houses[house]['door']) Wait(50) end DeleteObject(prop) DoScreenFadeIn(1500) TriggerServerEvent('loaf_housing:leaveHouse', house) return end end if Vdist2(GetEntityCoords(PlayerPedId()), storage) <= 2.0 then HelpText((Strings['Press_E']):format(Strings['Storage']), storage) if IsControlJustReleased(0, 38) and Vdist2(GetEntityCoords(PlayerPedId()), storage) <= 2.0 then ESX.UI.Menu.CloseAll() ESX.UI.Menu.Open( 'default', GetCurrentResourceName(), 'storage', { title = Strings['Storage_Title'], align = 'top-left', elements = { {label = Strings['Items'], value = 'i'}, {label = Strings['Weapons'], value = 'w'} }, }, function(data, menu) if data.current.value == 'i' then itemStorage(house) elseif data.current.value == 'w' then weaponStorage(house) end end, function(data, menu) menu.close() end) end end end end) RegisterNetEvent('loaf_housing:reloadHouses') AddEventHandler('loaf_housing:reloadHouses', function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Wait(0) end while ESX.GetPlayerData().job == nil do Wait(0) end TriggerServerEvent('loaf_housing:getOwned') end) RegisterNetEvent('loaf_housing:knockedDoor') AddEventHandler('loaf_housing:knockedDoor', function(src) ESX.ShowNotification(Strings['Someone_Knocked']) if not Knockings[src] then Knockings[src] = {label = (Strings['Accept_Player']):format(GetPlayerName(GetPlayerFromServerId(src))), value = src} end end) RegisterNetEvent('loaf_housing:removeDoorKnock') AddEventHandler('loaf_housing:removeDoorKnock', function(src) local newTable = {} for k, v in pairs(Knockings) do if v.value ~= src then table.remove(newTable, v) end end Knockings = newTable end) RegisterNetEvent('loaf_housing:setHouse') AddEventHandler('loaf_housing:setHouse', function(house, purchasedHouses) OwnedHouse = house for k, v in pairs(blips) do RemoveBlip(v) end for k, v in pairs(purchasedHouses) do if v.houseid ~= OwnedHouse.houseId then AvailableHouses[v.houseid] = v.houseid end end for k, v in pairs(Config.Houses) do if OwnedHouse.houseId == k then CreateBlip(v['door'], 40, 3, 0.75, Strings['Your_House']) else if not AvailableHouses[k] then if Config.AddHouseBlips then CreateBlip(v['door'], 374, 0, 0.45, '') end else if Config.AddBoughtHouses then CreateBlip(v['door'], 374, 2, 0.45, Strings['Player_House']) end end end end end) EnterHouse = function(prop, coords) local obj = CreateObject(prop, coords, false) FreezeEntityPosition(obj, true) return obj end HelpText = function(msg, coords) if not coords or not Config.Use3DText then AddTextEntry(GetCurrentResourceName(), msg) DisplayHelpTextThisFrame(GetCurrentResourceName(), false) else DrawText3D(coords, string.gsub(msg, "~INPUT_CONTEXT~", "~r~[~w~E~r~]~w~"), 0.35) end end CreateBlip = function(coords, sprite, colour, scale, text) local blip = AddBlipForCoord(coords) SetBlipSprite(blip, sprite) SetBlipColour(blip, colour) SetBlipAsShortRange(blip, true) SetBlipScale(blip, scale) BeginTextCommandSetBlipName("STRING") AddTextComponentString(text) EndTextCommandSetBlipName(blip) table.insert(blips, blip) end --[[DrawText3D = function(coords, text, scale) local onScreen, _x, _y = World3dToScreen2d(coords.x, coords.y, coords.z) if onScreen then SetTextScale(scale, scale) SetTextFont(4) SetTextProportional(1) SetTextColour(255, 255, 255, 255) SetTextEntry("STRING") SetTextCentre(1) SetTextOutline() AddTextComponentString(text) DrawText(_x, _y) end end]] rgb = function(speed) local result = {} local n = GetGameTimer() / 200 result.r = math.floor(math.sin(n * speed + 0) * 127 + 128) result.g = math.floor(math.sin(n * speed + 2) * 127 + 128) result.b = math.floor(math.sin(n * speed + 4) * 127 + 128) return result end DrawEdge = function(entity) local left, right = GetModelDimensions(GetEntityModel(entity)) local leftoffset, rightoffset = GetOffsetFromEntityInWorldCoords(entity, left.x, left.y, left.z), GetOffsetFromEntityInWorldCoords(entity, right.x, right.y, right.z) local coords = GetEntityCoords(entity) local color = rgb(0.5) -- DrawBox(GetOffsetFromEntityInWorldCoords(entity, left.x, left.y, left.z), GetOffsetFromEntityInWorldCoords(entity, right.x, right.y, right.z), 255, 255, 255, 50) --DrawBox(coords+left, coords+right, 255, 255, 255, 50) DrawLine(rightoffset, rightoffset.x, rightoffset.y, leftoffset.z, color.r, color.g, color.b, 255) DrawLine(leftoffset, leftoffset.x, leftoffset.y, rightoffset.z, color.r, color.g, color.b, 255) DrawLine(leftoffset.x, rightoffset.y, leftoffset.z, leftoffset.x, rightoffset.y, rightoffset.z, color.r, color.g, color.b, 255) DrawLine(rightoffset.x, leftoffset.y, leftoffset.z, rightoffset.x, leftoffset.y, rightoffset.z, color.r, color.g, color.b, 255) DrawLine(rightoffset.x, leftoffset.y, leftoffset.z, leftoffset, color.r, color.g, color.b, 255) DrawLine(rightoffset.x, rightoffset.y, leftoffset.z, leftoffset.x, rightoffset.y, leftoffset.z, color.r, color.g, color.b, 255) DrawLine(rightoffset.x, rightoffset.y, rightoffset.z, leftoffset.x, rightoffset.y, rightoffset.z, color.r, color.g, color.b, 255) DrawLine(leftoffset.x, leftoffset.y, rightoffset.z, rightoffset.x, leftoffset.y, rightoffset.z, color.r, color.g, color.b, 255) DrawLine(leftoffset.x, leftoffset.y, rightoffset.z, leftoffset.x, rightoffset.y, rightoffset.z, color.r, color.g, color.b, 255) DrawLine(rightoffset.x, rightoffset.y, rightoffset.z, rightoffset.x, leftoffset.y, rightoffset.z, color.r, color.g, color.b, 255) DrawLine(leftoffset.x, leftoffset.y, leftoffset.z, leftoffset.x, rightoffset.y, leftoffset.z, color.r, color.g, color.b, 255) DrawLine(rightoffset.x, rightoffset.y, leftoffset.z, rightoffset.x, leftoffset.y, leftoffset.z, color.r, color.g, color.b, 255) --[[DrawLine(coords+left, (coords+left).x, (coords+left).y, (coords+right).z, color.r, color.g, color.b, 255) DrawLine(coords+right, (coords+right).x, (coords+right).y, (coords+left).z, color.r, color.g, color.b, 255) DrawLine(coords.x+left.x, coords.y+right.y, coords.z+left.z, coords.x+left.x, coords.y+right.y, coords.z+right.z, color.r, color.g, color.b, 255) DrawLine(coords.x+right.x, coords.y+left.y, coords.z+left.z, coords.x+right.x, coords.y+left.y, coords.z+right.z, color.r, color.g, color.b, 255) DrawLine(coords.x+right.x, coords.y+left.y, coords.z+left.z, coords+left, color.r, color.g, color.b, 255) DrawLine(coords.x+right.x, coords.y+right.y, coords.z+left.z, coords.x+left.x, coords.y+right.y, coords.z+left.z, color.r, color.g, color.b, 255) DrawLine(coords.x+right.x, coords.y+right.y, coords.z+right.z, coords.x+left.x, coords.y+right.y, coords.z+right.z, color.r, color.g, color.b, 255) DrawLine(coords.x+left.x, coords.y+left.y, coords.z+right.z, coords.x+right.x, coords.y+left.y, coords.z+right.z, color.r, color.g, color.b, 255) DrawLine(coords.x+left.x, coords.y+left.y, coords.z+right.z, coords.x+left.x, coords.y+right.y, coords.z+right.z, color.r, color.g, color.b, 255) DrawLine(coords.x+right.x, coords.y+right.y, coords.z+right.z, coords.x+right.x, coords.y+left.y, coords.z+right.z, color.r, color.g, color.b, 255) DrawLine(coords.x+left.x, coords.y+left.y, coords.z+left.z, coords.x+left.x, coords.y+right.y, coords.z+left.z, color.r, color.g, color.b, 255) DrawLine(coords.x+right.x, coords.y+right.y, coords.z+left.z, coords.x+right.x, coords.y+left.y, coords.z+left.z, color.r, color.g, color.b, 255)]] end
--*********************************************************** --** THE INDIE STONE ** --** Author: Yuri ** --*********************************************************** require "DebugUIs/DebugMenu/Statistic/StatisticChart" ---@class StatisticChartDiskOperations : StatisticChart StatisticChartDiskOperations = StatisticChart:derive("StatisticChartDiskOperations"); StatisticChartDiskOperations.instance = nil; StatisticChartDiskOperations.shiftDown = 0; StatisticChartDiskOperations.eventsAdded = false; function StatisticChartDiskOperations.doInstance() if StatisticChartDiskOperations.instance==nil then StatisticChartDiskOperations.instance = StatisticChartDiskOperations:new (100, 100, 900, 400, getPlayer()); StatisticChartDiskOperations.instance:initialise(); StatisticChartDiskOperations.instance:instantiate(); end StatisticChartDiskOperations.instance:addToUIManager(); StatisticChartDiskOperations.instance:setVisible(false); return StatisticChartDiskOperations.instance; end function StatisticChartDiskOperations.OnOpenPanel() if StatisticChartDiskOperations.instance==nil then StatisticChartDiskOperations.instance = StatisticChartDiskOperations:new (100, 100, 900, 400, getPlayer()); StatisticChartDiskOperations.instance:initialise(); StatisticChartDiskOperations.instance:instantiate(); end StatisticChartDiskOperations.instance:addToUIManager(); StatisticChartDiskOperations.instance:setVisible(true); StatisticChartDiskOperations.instance.title = "Statistic Chart Disk Operations" return StatisticChartDiskOperations.instance; end StatisticChartDiskOperations.OnServerStatisticReceived = function() if StatisticChartDiskOperations.instance~=nil then StatisticChartDiskOperations.instance:updateValues() end end Events.OnServerStatisticReceived.Add(StatisticChartDiskOperations.OnServerStatisticReceived); function StatisticChartDiskOperations:createChildren() StatisticChart.createChildren(self); local labelWidth = 250 x = self.historyM1:getX() y = self.historyM1:getY()+self.historyM1:getHeight() y = y+8; y = self:addLabelValue(x+5, y, labelWidth, "value","load","load:",0); y = self:addLabelValue(x+5, y, labelWidth, "value","save","save:",0); end function StatisticChartDiskOperations:initVariables() StatisticChart.initVariables(self); self:addVarInfo("load","load",-1,100,"loadCellFromDisk"); self:addVarInfo("save","save",-1,100,"saveCellToDisk"); end function StatisticChartDiskOperations:updateValues() StatisticChart.updateValues(self); local minmax1 = self.historyM1:calcMinMax(1); local minmax2 = self.historyM1:calcMinMax(2); self.historyM1:applyMinMax(minmax1, 1); self.historyM1:applyMinMax(minmax2, 2); end
---@class UnityEngine.Space : System.Enum ---@field value__ int ---@field World UnityEngine.Space ---@field Self UnityEngine.Space local m = {} UnityEngine = {} UnityEngine.Space = m return m
test_run = require('test_run').new() test_run:cmd("push filter ".."'\\.lua.*:[0-9]+: ' to '.lua:<line>\"]: '") crypto = require('crypto') type(crypto) ciph = crypto.cipher.aes128.cbc pass = '1234567887654321' iv = 'abcdefghijklmnop' enc = ciph.encrypt('test', pass, iv) enc ciph.decrypt(enc, pass, iv) -- Failing scenarios. crypto.cipher.aes128.cbc.encrypt('a') crypto.cipher.aes128.cbc.encrypt('a', '123456', '435') crypto.cipher.aes128.cbc.encrypt('a', '1234567887654321') crypto.cipher.aes128.cbc.encrypt('a', '1234567887654321', '12') crypto.cipher.aes256.cbc.decrypt('a') crypto.cipher.aes256.cbc.decrypt('a', '123456', '435') crypto.cipher.aes256.cbc.decrypt('a', '12345678876543211234567887654321') crypto.cipher.aes256.cbc.decrypt('12', '12345678876543211234567887654321', '12') crypto.cipher.aes192.cbc.decrypt.new('123456788765432112345678', '12345') -- Set key after codec creation. c = crypto.cipher.aes128.cbc.encrypt.new() key = '1234567812345678' iv = key c:init(key) c:update('plain') c:result() c:init(nil, iv) cipher = c:update('plain ') cipher = cipher..c:update('next plain') cipher = cipher..c:result() crypto.cipher.aes128.cbc.decrypt(cipher, key, iv) -- Reuse. key2 = '8765432187654321' iv2 = key2 c:init(key2, iv2) cipher = c:update('new plain ') cipher = cipher..c:update('next new plain') cipher = cipher..c:result() crypto.cipher.aes128.cbc.decrypt(cipher, key2, iv2) crypto.cipher.aes100.efb crypto.cipher.aes256.nomode crypto.digest.nodigest -- Check that GC really drops unused codecs and streams, and -- nothing crashes. weak = setmetatable({obj = c}, {__mode = 'v'}) c = nil collectgarbage('collect') weak.obj bad_pass = '8765432112345678' bad_iv = '123456abcdefghij' ciph.decrypt(enc, bad_pass, iv) ciph.decrypt(enc, pass, bad_iv) test_run:cmd("clear filter")
local addonName, RIC = ... local L = LibStub("AceLocale-3.0"):GetLocale(addonName) function RIC.getOptions() -- OPTIONS local options = { name = addonName, handler = RIC, type = 'group', args = { general = { name = "General", type = "group", args = { invitebreak = { name = "Invites", type = "header", order = 0, }, sendinvites = { name = "Send invites", desc = "Activate to send out invites during the invite phase. If deactivated, players MUST be manually invited or invite themselves using a whisper keyword!", type = "toggle", order = 5, width = "full", set = function(info, val) RIC.db.profile.SendInvites = val; if val == false then RIC.db.profile.InviteIntervalActive = false end end, get = function(info) return RIC.db.profile.SendInvites end }, inviteintervalactive = { name = "Periodic invites:", desc = "Activate to send out invites regularly during the invite phase, to all people still missing after starting the invite phase. If deactivated, invites are only sent out once for each player", type = "toggle", order = 10, set = function(info, val) RIC.db.profile.InviteIntervalActive = val; end, get = function(info) return RIC.db.profile.InviteIntervalActive end, disabled = function() return (not RIC.db.profile.SendInvites) end, }, inviteinterval = { name = "Invite interval (seconds)", desc = "How often invites are sent out to those not in the raid yet. Lower times means people wait less for an invite, but they will get a lot of invite requests and possibly warnings.", type = "range", order = 11, min = 70.0, max = 1500, set = function(info, val) RIC.db.profile.InviteInterval = val; end, get = function(info) return RIC.db.profile.InviteInterval end, disabled = function() return not (RIC.db.profile.InviteIntervalActive and RIC.db.profile.SendInvites) end, }, invitedelay = { name = "Delay initial invites:", desc = "Amount of seconds to wait after starting invite phase before initial invites are sent out (set to 0 to disable delay). Can be useful for your raiders to leave their groups once they see the invite announcement in guild chat", type = "range", width = "full", order = 13, min = 0.0, max = 20, step = 1, set = function(info, val) RIC.db.profile.InviteDelay = val; end, get = function(info) return RIC.db.profile.InviteDelay end, disabled = function() return not (RIC.db.profile.SendInvites and RIC.db.profile.SendInvites) end, }, inviteungrouped = { name = "Invite ungrouped", desc = "Disable to prevent sending any invites to people on the roster list that are NOT assigned to any group (viewed as bench players)", type = "toggle", order = 20, set = function(info, val) RIC.db.profile.InviteUngrouped = val; end, get = function(info) return RIC.db.profile.InviteUngrouped end, disabled = function() return (not RIC.db.profile.SendInvites) end, }, otherbreak = { name = "Other settings", type = "header", order = 30, }, masterlooter = { name = "Set to master looter", desc = "Set raid to master looter when starting the invite phase", type = "toggle", order = 35, set = function(info, val) RIC.db.profile.MasterLooter = val; end, get = function(info) return RIC.db.profile.MasterLooter end }, } }, gui = { name = "GUI", type = "group", args = { showcharrealms = { name = "Show player realms", desc = "Show realm names for all characters displayed in the addon, e.g. display 'Tim-Patchwerk' instead of just 'Tim'", type = "toggle", set = function(info, val) RIC.db.profile.ShowCharRealms = val; end, get = function(info) return RIC.db.profile.ShowCharRealms end }, minimapshow = { name = "Hide minimap icon", desc = "Tick to hide minimap icon", type = "toggle", set = function(info, val) RIC.db.profile.hide = val RIC.MinimapButton_Update() end, get = function(info) return RIC.db.profile.hide end }, mainframescale = { name = "Overall scale", desc = "Scales the size of the addon frame", type = "range", min = 0.4, max = 2.0, set = function(info, val) RIC.db.profile.MainFrameScale = val RIC.setScale() end, get = function(info) return RIC.db.profile.MainFrameScale end }, } }, notifications = { name = "Notifications", type = "group", args = { notifyinvitephasestart = { name = "Announce start of invite phase:", desc = "Announces start of invite phase to guild", type = "toggle", width = "full", order = 0, set = function(info, val) RIC.db.profile.NotifyInvitePhaseStart = val; end, get = function(info) return RIC.db.profile.NotifyInvitePhaseStart end }, notifyinvitephasestartmsg = { name = "Message:", desc = "Message sent to the guild when invite phase starts", type = "input", width = "full", multiline = 0, order = 1, set = function(info, val) RIC.db.profile.Lp["Invite_Start"] = val end, get = function(info) return RIC.db.profile.Lp["Invite_Start"] end, disabled = function() return (not RIC.db.profile.NotifyInvitePhaseStart) end, }, notifyinvitephaseend = { name = "Announce end of invite phase:", desc = "Announces end of invite phase to guild", type = "toggle", width = "full", order = 5, set = function(info, val) RIC.db.profile.NotifyInvitePhaseEnd = val; end, get = function(info) return RIC.db.profile.NotifyInvitePhaseEnd end }, notifyinvitephaseendmsg = { name = "Message:", desc = "Message sent to the guild when invite phase ends", type = "input", width = "full", multiline = 0, order = 6, set = function(info, val) RIC.db.profile.Lp["Invite_End"] = val end, get = function(info) return RIC.db.profile.Lp["Invite_End"] end, disabled = function() return (not RIC.db.profile.NotifyInvitePhaseEnd) end, }, hidenotifications = { name = "Hide ALL outgoing notifications", desc = "Hides ALL whispers sent by this addon to other players that notify them about various issues (invite failures etc.). " .. "This prevents addon whispers to other people from spamming your chat window, " .. "but might make you miss problems with your raiders (e.g. person still in another group), so use with care", type = "toggle", order = 20, set = function(info, val) RIC.db.profile.HideOutgoingWhispers = val; end, get = function(info) return RIC.db.profile.HideOutgoingWhispers end }, } }, playerchecks = { name = "Player checks", type = "group", args = { durabilitytoggle = { name = "Durability warning", desc = "Enable this to check the gear durability of players joining the raid, to send them a message if their equipment is broken", type = "toggle", order = 0, set = function(info, val) RIC.db.profile.Durability_Warning = val; end, get = function(info) return RIC.db.profile.Durability_Warning end }, durabilitythreshold = { name = "Durability threshold (%)", desc = "Warn the player when the average gear durability is below this amount (%)", type = "range", order = 1, disabled = function() return (not RIC.db.profile.Durability_Warning) end, min = 1.0, max = 99.0, set = function(info, val) RIC.db.profile.Durability_Threshold = val; end, get = function(info) return RIC.db.profile.Durability_Threshold end }, durabilityinvitephase = { name = "Only during invite phase", desc = "Only check gear durability of players that join when invite phase is active", type = "toggle", order = 2, disabled = function() return (not RIC.db.profile.Durability_Warning) end, set = function(info, val) RIC.db.profile.Durability_Invite_Phase = val; end, get = function(info) return RIC.db.profile.Durability_Invite_Phase end }, } }, codewords = { name = "Codewords", type = "group", args = { codewordlist = { name = "List of codewords", desc = "Enter the codewords (one per line) that people can whisper you to get themselves invited to the raid. It is enough for one codeword to be contained in the whisper message to get an invite.", type = "input", width = "full", multiline = 6, order = 1, set = function(info, val) RIC.db.profile.Codewords = RIC._Codewords_Handler.buildCodeWords(val) end, get = function(info) return RIC._Codewords_Handler.getCodeWordsString(RIC.db.profile.Codewords) end }, restrictions = { name = "Restrictions", type = "group", args = { whitelist = { name = "Whitelist players", desc = "List names (one player per line) of characters whose codeword whispers should always be accepted (meaning all permission checks such as being on the roster or in the guild are skipped)", type = "input", width = "full", multiline = 6, order = 1, set = function(info, val) RIC.db.realm.Whitelist = RIC._Codewords_Handler.buildPlayerList(val) end, get = function(info) return RIC._Codewords_Handler.getPlayerListString(RIC.db.realm.Whitelist) end }, blacklist = { name = "Blacklist players", desc = "List names (one player per line) of characters whose codeword whispers should always be ignored (except if they are also on the whitelist)", type = "input", width = "full", multiline = 6, order = 2, set = function(info, val) RIC.db.realm.Blacklist = RIC._Codewords_Handler.buildPlayerList(val) end, get = function(info) return RIC._Codewords_Handler.getPlayerListString(RIC.db.realm.Blacklist) end }, onlyingroup = { name = "Only in group", desc = "Only accept codewords when you are already in group. " .. "When active, people can not force you to start a new group by whispering you, " .. "instead the request is ignored silently. " .. "Exception: This restriction does not apply when the invite phase is active.", type = "toggle", order = 5, set = function(info, val) RIC.db.profile.CodewordOnlyInGroup = val; end, get = function(info) return RIC.db.profile.CodewordOnlyInGroup end }, onlyduringinvite = { name = "Only during invite phase", desc = "Only accept codewords when you are currently in the invite phase", type = "toggle", order = 6, set = function(info, val) RIC.db.profile.CodewordOnlyDuringInvite = val; if (val == false) then RIC.db.profile.CodewordNotifyEnd = false end end, get = function(info) return RIC.db.profile.CodewordOnlyDuringInvite end }, onlyfromguild = { name = "Only for guild members", desc = "Only accept codewords from guild members", type = "toggle", order = 7, set = function(info, val) RIC.db.profile.GuildWhispersOnly = val; end, get = function(info) return RIC.db.profile.GuildWhispersOnly end }, onlyfromroster = { name = "Only for roster players", desc = "Only accept codewords from people on the current roster", type = "toggle", order = 8, set = function(info, val) RIC.db.profile.RosterWhispersOnly = val; end, get = function(info) return RIC.db.profile.RosterWhispersOnly end }, } }, sendguildmessagestart = { name = "Notify guild at invite start", desc = "Send a guild message containing the usable codewords when starting the invite phase", type = "toggle", order = 4, set = function(info, val) RIC.db.profile.CodewordNotifyStart = val; end, get = function(info) return RIC.db.profile.CodewordNotifyStart end }, sendguildmessageend = { name = "Notify guild at invite end", desc = "When stopping the invite phase, inform the guild that codewords are not longer accepted anymore.", type = "toggle", order = 5, disabled = function() return (not RIC.db.profile.CodewordOnlyDuringInvite) end, set = function(info, val) RIC.db.profile.CodewordNotifyEnd = val; end, get = function(info) return RIC.db.profile.CodewordNotifyEnd end }, invitewhispercheck = { name = "Exact match", desc = "Toggle this on if you only want to invite people that whisper you EXACTLY one of the codewords (ignoring upper/lowercase). When this is off, the whisper message only needs to CONTAIN one of the codewords.", type = "toggle", order = 7, set = function(info, val) RIC.db.profile.CodewordExactMatch = val; end, get = function(info) return RIC.db.profile.CodewordExactMatch end }, hidecodewordwhispers = { name = "Hide codeword whispers", desc = "Hide incoming whispers from your chat that contain NOTHING but a codeword. When activated, the addon still processes these whispers normally, they are just hidden from your view.", type = "toggle", order = 8, set = function(info, val) RIC.db.profile.CodewordHide = val; end, get = function(info) return RIC.db.profile.CodewordHide end }, } } }, } -- DATABASE DEFAULT CONFIG VALUES local defaults = { profile = { GuildWhispersOnly = false, RosterWhispersOnly = false, Durability_Warning = true, Durability_Threshold = 80, Durability_Invite_Phase = false, minimapPos = 0, -- default position of the minimap icon in degrees hide = false, -- Minimap hide MainFrameScale = 1, NotifyInvitePhaseStart = true, NotifyInvitePhaseEnd = false, MasterLooter = false, HideOutgoingWhispers = false, Codewords = {"invite"}, CodewordExactMatch = false, CodewordOnlyDuringInvite = true, CodewordOnlyInGroup = true, CodewordNotifyStart = true, CodewordNotifyEnd = false, CodewordHide = true, ShowOffline = true, DisplayRanks = {true, true, true, true, true, true, true, true, true, true}, SendInvites = true, InviteIntervalActive = true, InviteInterval = 120.0, InviteDelay = 2.0, InviteUngrouped = true, ShowCharRealms = false, Lp = L -- Load standard localised strings into profile so user can customise messages }, realm = { RosterList = {["Default Roster"] = {}}, CurrentRoster = "Default Roster", KnownPlayerClasses = {}, Blacklist={}, Whitelist={} } } return options, defaults end
object_tangible_food_generic_dish_trimpian = object_tangible_food_generic_shared_dish_trimpian:new { } ObjectTemplates:addTemplate(object_tangible_food_generic_dish_trimpian, "object/tangible/food/generic/dish_trimpian.iff")
--[[ Record a greeting. ]] -- The greeting name to record. greeting = args(1) -- Mailbox info. mailbox = storage("login_settings", "mailbox_number") mailbox_directory = profile.mailboxes_dir .. "/" .. mailbox mailbox_provisioned = storage("mailbox_settings", "mailbox_provisioned") return { -- Provision the mailbox if it's not provisioned yet. { action = "conditional", value = mailbox_provisioned, compare_to = "no", comparison = "equal", if_true = "sub:provision_mailbox " .. mailbox .. "," .. profile.domain, }, { action = "play_phrase", phrase = "record_greeting", phrase_arguments = greeting, keys = { ["#"] = ":break", }, }, { action = "wait", milliseconds = 500, }, -- Record to a temporary file. { action = "record", location = mailbox_directory, filename = greeting .. ".tmp.wav", pre_record_sound = "phrase:beep", max_length = profile.max_greeting_length, silence_secs = profile.recording_silence_end, silence_threshold = profile.recording_silence_threshold, keys = { ["#"] = ":break", }, }, { action = "call_sequence", sequence = "record_greeting_thank_you " .. greeting, }, }
--------- -- GUI -- --------- GUI = { button = {}, combobox = {}, edit = {}, gridlist = {}, image = {}, label = {}, memo = {}, scrollbar = {}, scrollpane = {}, tab = {}, tabpanel = {}, window = {} } function clientStart() local screenW, screenH = guiGetScreenSize() ----------------- -- Now Playing -- ----------------- GUI.window[1] = guiCreateWindow((screenW - 384) / 2, (screenH - 384) / 2, 384, 384, "Event Manager", false) guiWindowSetSizable(GUI.window[1], false) GUI.button[1] = guiCreateButton(160, 352, 64, 24, "Close", false, GUI.window[1]) addEventHandler("onClientGUIClick",GUI.button[1],windowVisibility,false) GUI.tabpanel[1] = guiCreateTabPanel(8, 24, 368, 320, false, GUI.window[1]) GUI.tab[1] = guiCreateTab("Now playing", GUI.tabpanel[1]) GUI.label[1] = guiCreateLabel(8, 8, 80, 16, "Current event:", false, GUI.tab[1]) guiLabelSetHorizontalAlign(GUI.label[1], "left", false) guiLabelSetVerticalAlign(GUI.label[1], "center") GUI.label[2] = guiCreateLabel(96, 8, 264, 16, "", false, GUI.tab[1]) guiLabelSetHorizontalAlign(GUI.label[2], "left", false) guiLabelSetVerticalAlign(GUI.label[2], "center") GUI.label[3] = guiCreateLabel(8, 32, 96, 16, "Upcoming maps:", false, GUI.tab[1]) guiLabelSetHorizontalAlign(GUI.label[3], "left", false) guiLabelSetVerticalAlign(GUI.label[3], "center") GUI.gridlist[1] = guiCreateGridList(8, 56, 352, 196, false, GUI.tab[1]) guiGridListAddColumn(GUI.gridlist[1], "#", 0.1) guiGridListAddColumn(GUI.gridlist[1], "Map name", 0.5) guiGridListAddColumn(GUI.gridlist[1], "Author", 0.3) guiGridListSetSortingEnabled(GUI.gridlist[1], false) GUI.button[2] = guiCreateButton(296, 32, 64, 16, "Refresh", false, GUI.tab[1]) addEventHandler("onClientGUIClick",GUI.button[2],updateQueueInfo,false) GUI.button[3] = guiCreateButton(120, 260, 128, 24, "Tweak current event", false, GUI.tab[1]) addEventHandler("onClientGUIClick",GUI.button[3],windowVisibility,false) guiSetVisible(GUI.window[1],false) -------------- -- Overview -- -------------- GUI.tab[2] = guiCreateTab("Overview", GUI.tabpanel[1]) GUI.gridlist[4] = guiCreateGridList(8, 8, 352, 244, false, GUI.tab[2]) guiGridListAddColumn(GUI.gridlist[4], "Event name", 0.5) guiGridListAddColumn(GUI.gridlist[4], "Maps", 0.4) guiGridListSetSortingEnabled(GUI.gridlist[4], true) GUI.button[13] = guiCreateButton(8, 260, 112, 24, "Start event", false, GUI.tab[2]) addEventHandler("onClientGUIClick",GUI.button[13],startEvent,false) GUI.button[11] = guiCreateButton(128, 260, 112, 24, "Edit event", false, GUI.tab[2]) addEventHandler("onClientGUIClick",GUI.button[11],windowVisibility,false) GUI.button[12] = guiCreateButton(248, 260, 112, 24, "Delete event", false, GUI.tab[2]) addEventHandler("onClientGUIClick",GUI.button[12],deleteEvent,false) ------------ -- Create -- ------------ GUI.tab[3] = guiCreateTab("Create", GUI.tabpanel[1]) GUI.label[6] = guiCreateLabel(8, 8, 96, 16, "Event name:", false, GUI.tab[3]) guiLabelSetHorizontalAlign(GUI.label[6], "left", false) guiLabelSetVerticalAlign(GUI.label[6], "center") GUI.edit[2] = guiCreateEdit(8, 32, 352, 24, "", false, GUI.tab[3]) guiSetEnabled(GUI.edit[2], true) GUI.button[10] = guiCreateButton(120, 260, 128, 24, "Create event", false, GUI.tab[3]) addEventHandler("onClientGUIClick",GUI.button[10],createEvent,false) ------------------------- -- Window event editor -- ------------------------- GUI.window[2] = guiCreateWindow((screenW - 800) / 2, (screenH - 640) / 2, 800, 640, "Event editor", false) guiWindowSetSizable(GUI.window[2], false) GUI.gridlist[2] = guiCreateGridList(32, 128, 320, 384, false, GUI.window[2]) guiGridListAddColumn(GUI.gridlist[2], "Map name", 0.5) guiGridListAddColumn(GUI.gridlist[2], "Author", 0.4) guiGridListAddColumn(GUI.gridlist[2], "resname", 0.4) guiGridListSetSortingEnabled(GUI.gridlist[2], false) addEventHandler("onClientGUIClick",GUI.gridlist[2],eventButtons,false) GUI.gridlist[3] = guiCreateGridList(448, 128, 320, 384, false, GUI.window[2]) guiGridListAddColumn(GUI.gridlist[3], "#", 0.1) guiGridListAddColumn(GUI.gridlist[3], "Map name", 0.5) guiGridListAddColumn(GUI.gridlist[3], "Author", 0.3) guiGridListAddColumn(GUI.gridlist[3], "resname", 0.4) guiGridListSetSortingEnabled(GUI.gridlist[3], false) addEventHandler("onClientGUIClick",GUI.gridlist[3],eventButtons,false) GUI.label[4] = guiCreateLabel(144, 104, 96, 16, "Server maps list:", false, GUI.window[2]) guiLabelSetHorizontalAlign(GUI.label[4], "left", false) guiLabelSetVerticalAlign(GUI.label[4], "center") GUI.label[5] = guiCreateLabel(448, 104, 320, 16, "Current event maps:", false, GUI.window[2]) guiLabelSetHorizontalAlign(GUI.label[5], "center", false) guiLabelSetVerticalAlign(GUI.label[5], "center") GUI.button[5] = guiCreateButton(368, 288, 64, 24, "Add", false, GUI.window[2]) addEventHandler("onClientGUIClick",GUI.button[5],eventAdd,false) guiSetEnabled(GUI.button[5], false) GUI.button[6] = guiCreateButton(368, 328, 64, 24, "Remove", false, GUI.window[2]) addEventHandler("onClientGUIClick",GUI.button[6],eventRemove,false) guiSetEnabled(GUI.button[6], false) GUI.button[7] = guiCreateButton(576, 528, 64, 24, "Move up", false, GUI.window[2]) addEventHandler("onClientGUIClick",GUI.button[7],eventMove,false) guiSetEnabled(GUI.button[7], false) GUI.button[8] = guiCreateButton(540, 560, 64, 24, "Move to", false, GUI.window[2]) addEventHandler("onClientGUIClick",GUI.button[8],eventMove,false) guiSetEnabled(GUI.button[8], false) GUI.edit[1] = guiCreateEdit(612, 560, 64, 24, "", false, GUI.window[2]) guiSetEnabled(GUI.edit[1], false) GUI.label[7] = guiCreateLabel(40, 528, 40, 24, "Search:", false, GUI.window[2]) guiLabelSetHorizontalAlign(GUI.label[7], "left", false) guiLabelSetVerticalAlign(GUI.label[7], "center") GUI.edit[3] = guiCreateEdit(88, 528, 256, 24, "", false, GUI.window[2]) guiSetEnabled(GUI.edit[3], true) addEventHandler("onClientGUIChanged",GUI.edit[3],handleSearches) GUI.button[9] = guiCreateButton(576, 592, 64, 24, "Move down", false, GUI.window[2]) addEventHandler("onClientGUIClick",GUI.button[9],eventMove,false) guiSetEnabled(GUI.button[9], false) GUI.button[4] = guiCreateButton(368, 608, 64, 24, "Close", false, GUI.window[2]) addEventHandler("onClientGUIClick",GUI.button[4],windowVisibility,false) guiSetVisible(GUI.window[2],false) end addEventHandler("onClientResourceStart",resourceRoot,clientStart)
local function on_player_selected_area(event) if event.item == "sweeper-tool" then for _, entity in pairs(event.entities) do entity.destroy{do_cliff_correction = false, raise_destroy = true} end end end script.on_event(defines.events.on_player_selected_area, on_player_selected_area)
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf" module('users_pb') local USERS_INFO = protobuf.Descriptor(); local USERS_INFO_USERID_FIELD = protobuf.FieldDescriptor(); local USERS_INFO_MONEY_FIELD = protobuf.FieldDescriptor(); local USERS_INFO_EXP_FIELD = protobuf.FieldDescriptor(); local USERS_INFO_LEVEL_FIELD = protobuf.FieldDescriptor(); local USERS_INFO_RANKSOCRE_FIELD = protobuf.FieldDescriptor(); local USERS_INFO_GEM_FIELD = protobuf.FieldDescriptor(); local USERS_INFO_HEAD_FIELD = protobuf.FieldDescriptor(); local USERS_INFO_AWARDKEY_FIELD = protobuf.FieldDescriptor(); USERS_INFO_USERID_FIELD.name = "userid" USERS_INFO_USERID_FIELD.full_name = ".users.users_info.userid" USERS_INFO_USERID_FIELD.number = 1 USERS_INFO_USERID_FIELD.index = 0 USERS_INFO_USERID_FIELD.label = 2 USERS_INFO_USERID_FIELD.has_default_value = false USERS_INFO_USERID_FIELD.default_value = 0 USERS_INFO_USERID_FIELD.type = 5 USERS_INFO_USERID_FIELD.cpp_type = 1 USERS_INFO_MONEY_FIELD.name = "money" USERS_INFO_MONEY_FIELD.full_name = ".users.users_info.money" USERS_INFO_MONEY_FIELD.number = 2 USERS_INFO_MONEY_FIELD.index = 1 USERS_INFO_MONEY_FIELD.label = 1 USERS_INFO_MONEY_FIELD.has_default_value = false USERS_INFO_MONEY_FIELD.default_value = 0 USERS_INFO_MONEY_FIELD.type = 5 USERS_INFO_MONEY_FIELD.cpp_type = 1 USERS_INFO_EXP_FIELD.name = "exp" USERS_INFO_EXP_FIELD.full_name = ".users.users_info.exp" USERS_INFO_EXP_FIELD.number = 3 USERS_INFO_EXP_FIELD.index = 2 USERS_INFO_EXP_FIELD.label = 1 USERS_INFO_EXP_FIELD.has_default_value = false USERS_INFO_EXP_FIELD.default_value = 0 USERS_INFO_EXP_FIELD.type = 5 USERS_INFO_EXP_FIELD.cpp_type = 1 USERS_INFO_LEVEL_FIELD.name = "level" USERS_INFO_LEVEL_FIELD.full_name = ".users.users_info.level" USERS_INFO_LEVEL_FIELD.number = 4 USERS_INFO_LEVEL_FIELD.index = 3 USERS_INFO_LEVEL_FIELD.label = 1 USERS_INFO_LEVEL_FIELD.has_default_value = false USERS_INFO_LEVEL_FIELD.default_value = 0 USERS_INFO_LEVEL_FIELD.type = 5 USERS_INFO_LEVEL_FIELD.cpp_type = 1 USERS_INFO_RANKSOCRE_FIELD.name = "ranksocre" USERS_INFO_RANKSOCRE_FIELD.full_name = ".users.users_info.ranksocre" USERS_INFO_RANKSOCRE_FIELD.number = 5 USERS_INFO_RANKSOCRE_FIELD.index = 4 USERS_INFO_RANKSOCRE_FIELD.label = 1 USERS_INFO_RANKSOCRE_FIELD.has_default_value = false USERS_INFO_RANKSOCRE_FIELD.default_value = 0 USERS_INFO_RANKSOCRE_FIELD.type = 5 USERS_INFO_RANKSOCRE_FIELD.cpp_type = 1 USERS_INFO_GEM_FIELD.name = "gem" USERS_INFO_GEM_FIELD.full_name = ".users.users_info.gem" USERS_INFO_GEM_FIELD.number = 6 USERS_INFO_GEM_FIELD.index = 5 USERS_INFO_GEM_FIELD.label = 1 USERS_INFO_GEM_FIELD.has_default_value = false USERS_INFO_GEM_FIELD.default_value = 0 USERS_INFO_GEM_FIELD.type = 5 USERS_INFO_GEM_FIELD.cpp_type = 1 USERS_INFO_HEAD_FIELD.name = "head" USERS_INFO_HEAD_FIELD.full_name = ".users.users_info.head" USERS_INFO_HEAD_FIELD.number = 7 USERS_INFO_HEAD_FIELD.index = 6 USERS_INFO_HEAD_FIELD.label = 1 USERS_INFO_HEAD_FIELD.has_default_value = false USERS_INFO_HEAD_FIELD.default_value = 0 USERS_INFO_HEAD_FIELD.type = 5 USERS_INFO_HEAD_FIELD.cpp_type = 1 USERS_INFO_AWARDKEY_FIELD.name = "awardkey" USERS_INFO_AWARDKEY_FIELD.full_name = ".users.users_info.awardkey" USERS_INFO_AWARDKEY_FIELD.number = 8 USERS_INFO_AWARDKEY_FIELD.index = 7 USERS_INFO_AWARDKEY_FIELD.label = 1 USERS_INFO_AWARDKEY_FIELD.has_default_value = false USERS_INFO_AWARDKEY_FIELD.default_value = 0 USERS_INFO_AWARDKEY_FIELD.type = 5 USERS_INFO_AWARDKEY_FIELD.cpp_type = 1 USERS_INFO.name = "users_info" USERS_INFO.full_name = ".users.users_info" USERS_INFO.nested_types = {} USERS_INFO.enum_types = {} USERS_INFO.fields = {USERS_INFO_USERID_FIELD, USERS_INFO_MONEY_FIELD, USERS_INFO_EXP_FIELD, USERS_INFO_LEVEL_FIELD, USERS_INFO_RANKSOCRE_FIELD, USERS_INFO_GEM_FIELD, USERS_INFO_HEAD_FIELD, USERS_INFO_AWARDKEY_FIELD} USERS_INFO.is_extendable = false USERS_INFO.extensions = {} users_info = protobuf.Message(USERS_INFO)
local vmf = get_mod("VMF") -- Constants used as parameters in some 'chat_manager's functions local CHANNEL_ID = 1 local MESSAGE_SENDER = "" local LOCAL_PLAYER_ID = 0 -- VT2 only local LOCALIZATION_PARAMETERS = {} -- VT2 only local LOCALIZE = false -- VT2 only local LOCALIZE_PARAMETERS = false -- VT2 only local LOCALIZATION_PARAM = "" -- VT1 only local IS_SYSTEM_MESSAGE = false local POP_CHAT = true local IS_DEV = true -- ##################################################################################################################### -- ##### Local functions ############################################################################################### -- ##################################################################################################################### local function send_system_message(peer_id, message) if VT1 then RPC.rpc_chat_message(peer_id, CHANNEL_ID, MESSAGE_SENDER, message, LOCALIZATION_PARAM, IS_SYSTEM_MESSAGE, POP_CHAT, IS_DEV) else RPC.rpc_chat_message(peer_id, CHANNEL_ID, MESSAGE_SENDER, LOCAL_PLAYER_ID, message, LOCALIZATION_PARAMETERS, LOCALIZE, LOCALIZE_PARAMETERS, IS_SYSTEM_MESSAGE, POP_CHAT, IS_DEV) end end local function add_system_message_to_chat(chat_manager, message) if VT1 then chat_manager:_add_message_to_list(CHANNEL_ID, MESSAGE_SENDER, message, IS_SYSTEM_MESSAGE, POP_CHAT, IS_DEV) else chat_manager:_add_message_to_list(CHANNEL_ID, MESSAGE_SENDER, LOCAL_PLAYER_ID, message, IS_SYSTEM_MESSAGE, POP_CHAT, IS_DEV) end end -- ##################################################################################################################### -- ##### VMFMod ######################################################################################################## -- ##################################################################################################################### --[[ Broadcasts the message to all players in a lobby. * message [string]: message to broadcast --]] function VMFMod:chat_broadcast(message) local chat = Managers.chat if chat and chat:has_channel(1) then if chat.is_server then local members = chat:channel_members(CHANNEL_ID) local my_peer_id = chat.my_peer_id for _, member_peer_id in pairs(members) do if member_peer_id ~= my_peer_id then send_system_message(member_peer_id, message) end end else local host_peer_id = chat.host_peer_id if host_peer_id then send_system_message(host_peer_id, message) end end add_system_message_to_chat(chat, message) end end --[[ Sends the message to a selected player. Only the host can use this method. * peer_id [peer_id]: peer_id of the player who will recieve the message (can't be host's peer_id) * message [string] : message to send --]] function VMFMod:chat_whisper(peer_id, message) local chat = Managers.chat if chat and chat:has_channel(1) and chat.is_server and peer_id ~= chat.host_peer_id then send_system_message(peer_id, message) end end
local path_sep = "/" if vim.fn.has("win32") == 1 or vim.fn.has("win64") == 1 then path_sep = "\\" end local M = {} function M.path_concat(left, right) local l = left local r = right if left[#left] == path_sep then l = left:sub(1, #left - 1) end if right[#right] == path_sep then r = right:sub(2) end return l .. path_sep .. r end function M.path_parent(path) if not path or #path == "" then return end local temp = vim.split(path, path_sep, true) if #temp == 1 then return "" end local parent = table.concat(temp, path_sep, 1, #temp - 1) return parent end M.parse_arg = function(...) local others = select(1, ...) if not others then return {ret = false} end local mine = select(2, ...) if not mine then mine = "." end others = vim.fn.glob(others) mine = vim.fn.glob(mine) return {ret = true, mine = mine, others = others} end M.cmdcomplete = function(A, L, P) local cwd = vim.fn.getcwd() if #A == 0 then return {cwd} end if cwd == A then return end local paths = vim.fn.glob(A .. "*") if not paths or #paths == 0 then return end paths = vim.split(paths, "\n") local ret = {} for _, path in ipairs(paths) do if vim.fn. getftype(path) == "dir" then table.insert(ret, path) end end return ret end return M
function Esp(player, username) if player ~= game:service("Players").LocalPlayer then if player.Character then local torso = player.Character:FindFirstChild("Torso") if torso then local base = Instance.new("BillboardGui") local esP = Instance.new("Frame", base) base.AlwaysOnTop = true base.Enabled = true base.Size = UDim2.new(4.5,0,6,0) base.StudsOffset = Vector3.new(0, -0.6, 0) esP.BackgroundColor3 = Color3.new(0,255,255) esP.BackgroundTransparency = 0.8 esP.BorderSizePixel = 1 esP.Size = UDim2.new(1,0,1,0) if base and workspace.CurrentCamera then base.Name = username base.Parent = workspace.CurrentCamera base.Adornee = torso end end end end end function CheckEsp() for x,player in pairs(game:service("Players"):GetPlayers()) do if player then if player.TeamColor ~= game:service("Players").LocalPlayer.TeamColor then local char = player.Character if char then local torso = char:FindFirstChild("Torso") if torso then local currentcam = workspace.CurrentCamera local playerName = player.Name if currentcam:FindFirstChild(playerName) == nil then Esp(player, playerName) end end end end end end end while wait(1) do CheckEsp() end
local script_data = { has_checked = false, networks = {}, switches = {} } local map = {} local function new_entity_entry(entity) local base = { entity_number = entity.unit_number, prev = {input = {}, output = {}} } if script_data.networks[entity.electric_network_id] then base.prev = script_data.networks[entity.electric_network_id].prev end script_data.networks[entity.electric_network_id] = base map[entity.unit_number] = entity end local function find_entity(unit_number, entity_type) if map[unit_number] then return map[unit_number] end for _, surface in pairs(game.surfaces) do local ents = surface.find_entities_filtered({type = entity_type}) for _, entity in pairs(ents) do if entity.unit_number == unit_number then map[entity.unit_number] = entity return entity end end end end local function rescan_worlds() local networks = script_data.networks local invalids = {} local remove = {} for idx, network in pairs(networks) do if network.entity then network.entity_number = network.entity.unit_number network.entity = nil end if network.entity_number then local assoc = find_entity(network.entity_number, "electric-pole") if not assoc then invalids[idx] = true end else remove[idx] = true end end for _, surface in pairs(game.surfaces) do local ents = surface.find_entities_filtered({type = "electric-pole"}) for _, entity in pairs(ents) do if not networks[entity.electric_network_id] or invalids[entity.electric_network_id] then new_entity_entry(entity) invalids[entity.electric_network_id] = nil end end end if table_size(remove) > 0 then for idx, _ in pairs(remove) do networks[idx] = nil end end end local function get_ignored_networks_by_switches() local ignored = {} local max = math.max for switch_id, val in pairs(script_data.switches) do -- assume old entity if val ~= 1 and val and val.valid then script_data.switches[val.unit_number] = 1 script_data.switches[switch_id] = nil end local switch = find_entity(switch_id, "power-switch") if switch.power_switch_state and #switch.neighbours.copper > 1 then local network = max(switch.neighbours.copper[1].electric_network_id, switch.neighbours.copper[2].electric_network_id) ignored[network] = true end end return ignored end local lib = { on_build = function(event) local entity = event.entity or event.created_entity if entity and entity.type == "electric-pole" then if not script_data.networks[entity.electric_network_id] then new_entity_entry(entity) end elseif entity and entity.type == "power-switch" then script_data.switches[entity.unit_number] = 1 map[entity.unit_number] = entity end end, on_destroy = function(event) local entity = event.entity if entity.type == "electric-pole" then local pos = entity.position local max = entity.prototype and entity.prototype.max_wire_distance or game.max_electric_pole_connection_distance local area = {{pos.x - max, pos.y - max}, {pos.x + max, pos.y + max}} local surface = entity.surface local networks = script_data.networks local current_idx = entity.electric_network_id -- Make sure to create the new network ids before collecting new info if entity.neighbours.copper then entity.disconnect_neighbour() end local finds = surface.find_entities_filtered({type = "electric-pole", area = area}) for _, new_entity in pairs(finds) do if new_entity ~= entity then if new_entity.electric_network_id == current_idx or not networks[new_entity.electric_network_id] then -- here we need to add the new_entity new_entity_entry(new_entity) end end end elseif entity.type == "power-switch" then script_data.switches[entity.unit_number] = nil end -- if some unexpected stuff occurs, try enabling rescan_worlds -- rescan_worlds() end, on_load = function() script_data = global.power_data or script_data end, on_init = function() global.power_data = global.power_data or script_data end, on_configuration_changed = function(event) if global.power_data == nil then global.power_data = script_data end if global.power_data.switches == nil then global.power_data.switches = {} end -- Basicly only when first added or version changed -- Power network is added in .10 if not script_data.has_checked then -- scan worlds rescan_worlds() script_data.has_checked = true end end, on_tick = function(event) if event.tick then local ignored = get_ignored_networks_by_switches() power_production_input:reset() power_production_output:reset() for idx, network in pairs(script_data.networks) do -- reset old style in case it still is old if network.entity then network.entity_number = network.entity.unit_number network.entity = nil end local entity = find_entity(network.entity_number, "electric-pole") if not entity then rescan_worlds() entity = find_entity(network.entity_number, "electric-pole") end if entity and entity.valid and not ignored[entity.electric_network_id] and entity.electric_network_id == idx then local force_name = entity.force.name local surface_name = entity.surface.name for name, n in pairs(entity.electric_network_statistics.input_counts) do power_production_input:set(n, {force_name, name, idx, surface_name}) end for name, n in pairs(entity.electric_network_statistics.output_counts) do power_production_output:set(n, {force_name, name, idx, surface_name}) end elseif entity and entity.valid and entity.electric_network_id ~= idx then -- assume this network has been merged with some other so unset script_data.networks[idx] = nil elseif entity and not entity.valid then -- Invalid entity remove anyhow script_data.networks[idx] = nil end end end end, } return lib
local plugin = plugin if not plugin then --// 플러그인이 아닌데 이 코드가 실행되면 바로 멈춰줌(태스팅 모드에서) return end local AppInfo = { -- APP INFO ["AppIcon"] = "http://www.roblox.com/asset/?id=6007972232"; ["AppIconLight"] = "http://www.roblox.com/asset/?id=6007972463"; -- for toolbar light mode ["AppName"] = "Taskbar"; ["AppId"] = "qwreey.plugins.taskbar"; -- PLUGIN GROUP ["ToolbarId"] = "qwreey.plugins.toolbarprovider"; ["ToolbarName"] = "Qwreey's plugins"; --BUTTON ["ButtonText"] = "Task bar"; ["ButtonHoverText"] = nil; -- INTERFACE ["InterfaceMiniSize"] = {X=150,Y=36}; ["InterfaceInitSize"] = {X=220,Y=300}; ["InterfaceDefaultFace"] = Enum.InitialDockState.Bottom; -- OTHER ["Version"] = 2; ["SplashIconSize"] = UDim2.new(0,70,0,70); ["BypassSplash"] = true; } -------------- --import -------------- --// 로블록스 서비스 불러오기(import) local PluginGuiService = game:GetService("PluginGuiService") local TextService = game:GetService("TextService") --// 모듈 불러오기 local MaterialUI = require(script.lib.MaterialUI) local Data = require(script.lib.Data):SetUp(plugin) local AdvancedTween = require(script.lib.AdvancedTween) local ToolbarCombiner = require(script.lib.ToolbarCombiner) local License = require(script.License) local LicenseViewer = require(script.res.LicenseViewer) local Language = require(script.res.Language) -------------- --Make plugin -------------- --// 플긴 버전 저장 local OldVersion = Data:Load("LastVersioni") Data:Save("LastVersion",AppInfo.Version) --// 불러오기 local App do local AppModule = require(script.App) App = AppModule:init(plugin,AppInfo,{ MaterialUI = MaterialUI; AdvancedTween = AdvancedTween; ToolbarCombiner = ToolbarCombiner; Language = Language; }) end local Interface = App.Interface --// 라이선스 뷰어 Init LicenseViewer:Init(App.SettingsHandle,MaterialUI,License,Language) -------------- --Data -------------- -------------- --Main Ui -------------- local void = function()end local AppFont = Enum.Font.Gotham local FocusedEffectColor = Color3.fromRGB(20,170,255) local FocusedFrameThickness = 16; local Button_MouseFocusedScale = 1.1 local Button_MouseDownScale = 0.8 local Button_IdleScale = 1 local Button_MarginX = 14 local Button_SizeY = 26 local Button_TextSize = 14 local BLinePadding = 34 local ButtonZIndex = 10 local ShadowZIndex = 20 local BLineZIndex = 30 local LastFocusWindow = nil; local Buttons = {} local AddToScroll = void --// 버튼 눌렀을때 해당 창에 포커스되는 효과 function RunFocusedEffect(PluginGui) local New = MaterialUI.Create("Frame",{ Size = UDim2.new(1,0,1,0); BackgroundTransparency = 1; ZIndex = 2147483647; },{ Left = MaterialUI.Create("Frame",{ ZIndex = 2147483647; BackgroundColor3 = FocusedEffectColor; Size = UDim2.new(0,FocusedFrameThickness,1,0); }); Right = MaterialUI.Create("Frame",{ ZIndex = 2147483647; BackgroundColor3 = FocusedEffectColor; Size = UDim2.new(0,FocusedFrameThickness,1,0); Position = UDim2.new(1,0,0,0); AnchorPoint = Vector2.new(1,0); }); Bottom = MaterialUI.Create("Frame",{ ZIndex = 2147483647; BackgroundColor3 = FocusedEffectColor; Size = UDim2.new(1,0,0,FocusedFrameThickness); }); Top = MaterialUI.Create("Frame",{ ZIndex = 2147483647; BackgroundColor3 = FocusedEffectColor; Size = UDim2.new(1,0,0,FocusedFrameThickness); Position = UDim2.new(0,0,1,0); AnchorPoint = Vector2.new(0,1); }); }); New.Parent = PluginGui local TweenData = { Time = 0.4; Easing = AdvancedTween.EasingFunctions.Exp2; Direction = AdvancedTween.EasingDirection.Out; } --AdvancedTween:RunTweens({New.Left,New.Right,New.Bottom,New.Top},TweenData,{ -- BackgroundTransparency = 1; -- --Size = UDim2.new(0,0,0,0); --}) AdvancedTween:RunTweens({New.Left,New.Right},TweenData,{ Size = UDim2.new(0,0,1,0) }) AdvancedTween:RunTweens({New.Top,New.Bottom},TweenData,{ Size = UDim2.new(1,0,0,0) }) delay(0.4,function() New:Destroy() end) end function AddButton(Window) if Window == Interface then return end local this = { Connection = {}; Scale = nil; } this.Window = Window this.Button = MaterialUI.Create("TextButton",{ NotTagging = true; Parent = script.tmp; Name = "ItemFrame"; BackgroundColor3 = Color3.fromRGB(128, 128, 128); BackgroundTransparency = 1; Size = UDim2.new(0,40,0,Button_SizeY); Text = ""; AutoButtonColor = false; ZIndex = ButtonZIndex; MouseButton1Click = function() LastFocusWindow = this.Window this.Window.Enabled = false RunFocusedEffect(this.Window) end; MouseEnter = function() AdvancedTween:RunTween(this.Scale,{ Time = 0.2; Easing = AdvancedTween.EasingFunctions.Exp2; Direction = AdvancedTween.EasingDirection.Out; },{ Scale = Button_MouseFocusedScale; }) end; MouseLeave = function() AdvancedTween:RunTween(this.Scale,{ Time = 0.2; Easing = AdvancedTween.EasingFunctions.Exp2; Direction = AdvancedTween.EasingDirection.Out; },{ Scale = Button_IdleScale; }) end; MouseButton1Down = function() AdvancedTween:RunTween(this.Scale,{ Time = 0.5; Easing = AdvancedTween.EasingFunctions.Exp2; Direction = AdvancedTween.EasingDirection.Out; },{ Scale = Button_MouseDownScale; }) end; MouseButton1Up = function() AdvancedTween:RunTween(this.Scale,{ Time = 0.35; Easing = AdvancedTween.EasingFunctions.Exp2; Direction = AdvancedTween.EasingDirection.Out; },{ Scale = Button_MouseFocusedScale; }) end; },{ Round = MaterialUI.Create("ImageLabel",{ NotTagging = true; AnchorPoint = Vector2.new(0.5, 0.5); BackgroundTransparency = 1; Position = UDim2.new(0.5, 0, 0.5, 0); Size = UDim2.new(1, 0, 1, 0); ImageColor3 = Color3.fromRGB(128, 128, 128); ImageTransparency = 0.5; ZIndex = ButtonZIndex; WhenCreated = function(new) MaterialUI:SetRound(new,8) end; },{ TextLabel = MaterialUI.Create("TextLabel",{ NotTagging = true; BackgroundColor3 = Color3.fromRGB(255, 255, 255); BackgroundTransparency = 1; Size = UDim2.new(1,0,1,0); ZIndex = ButtonZIndex; Font = AppFont; Text = ""; TextColor3 = Color3.fromRGB(255, 255, 255); TextSize = Button_TextSize; }); Scale = MaterialUI.Create("UIScale",{ NotTagging = true; Scale = 1; WhenCreated = function(new) this.Scale = new end; }); }); },function(this) AddToScroll(this) end); --// 숨기기/보이기 리프래싱 this.EnabledRefresh = function() if LastFocusWindow == this.Window then wait() LastFocusWindow = nil this.Window.Enabled = true return end this.Button.Visible = this.Window.Enabled end this.Connection.EnabledChanged = this.Window:GetPropertyChangedSignal("Enabled"):Connect(this.EnabledRefresh) this.EnabledRefresh() --// 글자 리프래싱 this.ButtonTextRefresh = function() this.Button.Round.TextLabel.Text = this.Window.Title this.Button.Size = UDim2.new( 0, TextService:GetTextSize( this.Window.Title, Button_TextSize, AppFont, Vector2.new(math.huge,math.huge) ).X + Button_MarginX, 0, Button_SizeY ) end this.Connection.TitleChanged = this.Window:GetPropertyChangedSignal("Title"):Connect(this.ButtonTextRefresh) this.ButtonTextRefresh() Buttons[Window] = this return this end function RemoveButton(Window) if Window == Interface then return elseif not Buttons[Window] then return end local this = Buttons[Window] this.Button:Destroy() for i,Connection in pairs(this.Connection) do if not Connection then return end Connection:Disconnect() this.Connection[i] = nil end Buttons[Window] = nil this = nil end PluginGuiService.ChildAdded:Connect(AddButton) PluginGuiService.ChildRemoved:Connect(RemoveButton) for _,Window in pairs(PluginGuiService:GetChildren()) do AddButton(Window) end function LoadGui() for _,Button in pairs(Buttons) do Button.Button.Parent = script.tmp end --// UI 개채를 담을곳 local Store = { ListLayout = nil; BLine = nil; Scroll = nil; Main = nil; } --// 이전의 UI 제거(태마 변경시, 클리어) Interface:ClearAllChildren() MaterialUI:CleanUp() --// 현재 태마 불러오기 MaterialUI.CurrentTheme = tostring(settings().Studio.Theme) --// 위잿 등록 MaterialUI.UseDockWidget(Interface,plugin:GetMouse()) --// UI 만들기 MaterialUI.Create("Frame",{ Parent = Interface; Name = "Main"; BackgroundColor3 = MaterialUI:GetColor(MaterialUI.Colors.Background); Size = UDim2.new(1,0,1,0); WhenCreated = function(this) Store.Main = this end; },{ --// 버튼 담기는 스크롤 Scroll = MaterialUI.Create("ScrollingFrame",{ BackgroundTransparency = 1; Size = UDim2.new(1,0,1,0); ScrollBarThickness = 0; WhenCreated = function(this) AddToScroll = function(new) new.Parent = this end Store.Scroll = this end; },{ ListLayout = MaterialUI.Create("UIListLayout",{ FillDirection = Enum.FillDirection.Horizontal; HorizontalAlignment = Enum.HorizontalAlignment.Center; SortOrder = Enum.SortOrder.LayoutOrder; VerticalAlignment = Enum.VerticalAlignment.Center; Padding = UDim.new(0, 6); },nil,function(this) Store.ListLayout = this this:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(function() if not Store.Scroll then return end Store.Scroll.CanvasSize = UDim2.new( 0, this.AbsoluteContentSize.X, 0, 0 ) end) end); }); Padding = MaterialUI.Create("UIPadding",{ PaddingBottom = UDim.new(0, 4); }); --// 옆쪽 그림자 LShadow = MaterialUI.Create("ImageLabel",{ BackgroundTransparency = 1; Size = UDim2.new(0,80,1,0); Position = UDim2.new(0,0,0,0); AnchorPoint = Vector2.new(0.5,0); ImageColor3 = MaterialUI:GetColor(MaterialUI.Colors.Background); Image = "http://www.roblox.com/asset/?id=3952381184"; ZIndex = ShadowZIndex; }); RShadow = MaterialUI.Create("ImageLabel",{ BackgroundTransparency = 1; Size = UDim2.new(0,80,1,0); Position = UDim2.new(1,0,0,0); AnchorPoint = Vector2.new(0.5,0); ImageColor3 = MaterialUI:GetColor(MaterialUI.Colors.Background); Image = "http://www.roblox.com/asset/?id=3952381184"; ZIndex = ShadowZIndex; }); --// 아랫쪽 라인(데코) BLine = MaterialUI.Create("Frame",{ AnchorPoint = Vector2.new(0.5,0.5); BackgroundColor3 = Color3.fromRGB(128,128,128); BorderSizePixel = 0; Position = UDim2.new(0.5,0,0.5,16); Size = UDim2.new(0,50,0,1); ZIndex = BLineZIndex; WhenCreated = function(this) Store.BLine = this end; }); }) --// 이전 버튼 가져오기 for _,Button in pairs(Buttons) do Button.Button.Parent = Store.Scroll --// 태마 적용 Button.Button.Round.TextLabel.TextColor3 = MaterialUI:GetColor(MaterialUI.Colors.TextColor) end --// 바텀라인 크기 리프레시 local function BLineSizeRefresh() Store.BLine.Size = UDim2.new( 0, math.min( Store.Main.AbsoluteSize.X - BLinePadding, Store.ListLayout.AbsoluteContentSize.X ), 0, 1 ) end Store.Main:GetPropertyChangedSignal("AbsoluteSize"):Connect(BLineSizeRefresh) Store.ListLayout:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(BLineSizeRefresh) BLineSizeRefresh() end --// 처음로드 LoadGui() --// 태마 바뀜 감지 settings().Studio.ThemeChanged:Connect(LoadGui) -------------- --Unload -------------- --// 플러그인 언로드 이벤트 function Unload() pcall(function() end) end plugin.Unloading:Connect(Unload)
local E, C, L = select(2, ...):unpack() if not C.blizzard.custom_position then return end ------------------------------------------------------------------------------------------ -- Set custom position for TalkingHeadFrame ------------------------------------------------------------------------------------------ local Load = CreateFrame("Frame") Load:RegisterEvent("ADDON_LOADED") Load:SetScript("OnEvent", function(_, _, addon) if addon == "Blizzard_TalkingHeadUI" or (addon == E.addonName and IsAddOnLoaded("Blizzard_TalkingHeadUI")) then TalkingHeadFrame.ignoreFramePositionManager = true TalkingHeadFrame:ClearAllPoints() TalkingHeadFrame:SetPoint(unpack(C.blizzard.talking_head_pos)) end end)
require "lib.test.assert" local ArrayQueue = require "lib.structures.queues.ArrayQueue" local queues = {} for _, queue in pairs(queues) do assertTrue(queue:isEmpty()) local aux = {} for i=1,50 do local random_val = math.random() aux[i] = random_val queue:push(random_val) end for i=1,50 do assertEquals(queue:pop(), aux[i]) end end
--[[ TheNexusAvenger Tests the NexusScrollBar class. --]] local NexusUnitTesting = require("NexusUnitTesting") local NexusPluginFramework = require(game:GetService("ReplicatedStorage"):WaitForChild("NexusPluginFramework")) local NexusScrollingFrame = NexusPluginFramework:GetResource("UI.Scroll.NexusScrollingFrame") --[[ Test that the constructor works without failing. --]] NexusUnitTesting:RegisterUnitTest("Constructor",function(UnitTest) local CuT = NexusScrollingFrame.new("Native") UnitTest:AssertEquals(CuT.ClassName,"NexusScrollingFrame","Class name is incorrect.") UnitTest:AssertEquals(CuT.Name,"NexusScrollingFrame","Name is incorrect.") UnitTest:AssertEquals(tostring(CuT),"NexusScrollingFrame","Name is incorrect.") UnitTest:AssertEquals(#CuT:GetChildren(),0,"Children aren't hidden.") end) --[[ Tests that the scrollbars are set up correctly for the Qt5 theme. --]] NexusUnitTesting:RegisterUnitTest("Qt5ThemeSetup",function(UnitTest) --Create a container frame and the component under testing. local Frame = Instance.new("Frame") local WrappedFrame = NexusPluginFramework.new(Frame) local CuT = NexusScrollingFrame.new("Qt5") CuT.Size = UDim2.new(0,200,0,200) CuT.Parent = WrappedFrame --Assert the scroll bar adorn is hidden. UnitTest:AssertEquals(#Frame:GetChildren(),2,"Scroll bar adorn doesn't exist.") UnitTest:AssertEquals(#WrappedFrame:GetChildren(),1,"Scroll bar adorn isn't hidden.") --Get the scroll bars. local ScrollBarAdorn = Frame:FindFirstChild("ScrollBarAdorn") local HorizontalScrollBar = ScrollBarAdorn:FindFirstChild("HorizontalScrollBar") local VerticalScrollBar = ScrollBarAdorn:FindFirstChild("VerticalScrollBar") --Assert the scroll bars are not shown for a canvas size less than frame size. CuT.CanvasSize = UDim2.new(0,150,0,150) UnitTest:AssertFalse(HorizontalScrollBar.Visible,"Scroll bar is visible.") UnitTest:AssertFalse(VerticalScrollBar.Visible,"Scroll bar is visible.") --Assert the scroll bars are correct for only the horizontal scroll bar. CuT.CanvasSize = UDim2.new(0,300,0,150) UnitTest:AssertTrue(HorizontalScrollBar.Visible,"Scroll bar isn't visible.") UnitTest:AssertFalse(VerticalScrollBar.Visible,"Scroll bar is visible.") UnitTest:AssertEquals(HorizontalScrollBar.AbsoluteSize,Vector2.new(198,16),"Size is incorrect.") UnitTest:AssertEquals(HorizontalScrollBar.AbsolutePosition,Vector2.new(1,184),"Position is incorrect.") --Assert the scroll bars are correct for only the vertical scroll bar on the right. CuT.CanvasSize = UDim2.new(0,150,0,300) CuT.VerticalScrollBarPosition = Enum.VerticalScrollBarPosition.Right UnitTest:AssertFalse(HorizontalScrollBar.Visible,"Scroll bar is visible.") UnitTest:AssertTrue(VerticalScrollBar.Visible,"Scroll bar isn't visible.") UnitTest:AssertEquals(VerticalScrollBar.AbsoluteSize,Vector2.new(16,198),"Size is incorrect.") UnitTest:AssertEquals(VerticalScrollBar.AbsolutePosition,Vector2.new(184,1),"Position is incorrect.") --Assert the scroll bars are correct for only the vertical scroll bar on the left. CuT.CanvasSize = UDim2.new(0,150,0,300) CuT.VerticalScrollBarPosition = Enum.VerticalScrollBarPosition.Left UnitTest:AssertFalse(HorizontalScrollBar.Visible,"Scroll bar is visible.") UnitTest:AssertTrue(VerticalScrollBar.Visible,"Scroll bar isn't visible.") UnitTest:AssertEquals(VerticalScrollBar.AbsoluteSize,Vector2.new(16,198),"Size is incorrect.") UnitTest:AssertEquals(VerticalScrollBar.AbsolutePosition,Vector2.new(0,1),"Position is incorrect.") --Assert that both scroll bars are correct for both with vertical on the right. CuT.CanvasSize = UDim2.new(0,300,0,300) CuT.VerticalScrollBarPosition = Enum.VerticalScrollBarPosition.Right UnitTest:AssertTrue(HorizontalScrollBar.Visible,"Scroll bar isn't visible.") UnitTest:AssertTrue(VerticalScrollBar.Visible,"Scroll bar isn't visible.") UnitTest:AssertEquals(HorizontalScrollBar.AbsoluteSize,Vector2.new(182,16),"Size is incorrect.") UnitTest:AssertEquals(HorizontalScrollBar.AbsolutePosition,Vector2.new(1,184),"Position is incorrect.") UnitTest:AssertEquals(VerticalScrollBar.AbsoluteSize,Vector2.new(16,182),"Size is incorrect.") UnitTest:AssertEquals(VerticalScrollBar.AbsolutePosition,Vector2.new(184,1),"Position is incorrect.") --Assert that both scroll bars are correct for both with vertical on the left. CuT.CanvasSize = UDim2.new(0,300,0,300) CuT.VerticalScrollBarPosition = Enum.VerticalScrollBarPosition.Left UnitTest:AssertTrue(HorizontalScrollBar.Visible,"Scroll bar isn't visible.") UnitTest:AssertTrue(VerticalScrollBar.Visible,"Scroll bar isn't visible.") UnitTest:AssertEquals(HorizontalScrollBar.AbsoluteSize,Vector2.new(182,16),"Size is incorrect.") UnitTest:AssertEquals(HorizontalScrollBar.AbsolutePosition,Vector2.new(17,184),"Position is incorrect.") UnitTest:AssertEquals(VerticalScrollBar.AbsoluteSize,Vector2.new(16,182),"Size is incorrect.") UnitTest:AssertEquals(VerticalScrollBar.AbsolutePosition,Vector2.new(0,1),"Position is incorrect.") end) --[[ Creates a scrolling frame in StarterGui. Disabled unless needed. --]] --[[ NexusUnitTesting:RegisterUnitTest("ManualTesting",function(UnitTest) --Create the screen gui. local ScreenGui = Instance.new("ScreenGui") ScreenGui.Parent = game:GetService("StarterGui") --Create the frame. local ScrollingFrame = NexusScrollingFrame.new("Qt5") ScrollingFrame.CanvasSize = UDim2.new(0,800,0,800) ScrollingFrame.Size = UDim2.new(0,420,0,420) ScrollingFrame.Parent = ScreenGui --Create a grid. for i = 0,7 do for j = 0,7 do local Frame = NexusPluginFramework.new("Frame") Frame.BackgroundColor3 = Color3.new(math.random(),math.random(),math.random()) Frame.Size = UDim2.new(0,80,0,80) Frame.Position = UDim2.new(0,(i * 100) + 10,0,(j * 100) + 10) Frame.Parent = ScrollingFrame end end --Wait for the screen gui to be deleted. while ScreenGui.Parent do wait() end end) --]] return true
--- === hs.spotify === --- --- Controls for Spotify music player local spotify = {} local alert = require "hs.alert" local as = require "hs.applescript" local app = require "hs.application" --- hs.spotify.state_paused --- Constant --- Returned by `hs.spotify.getPlaybackState()` to indicates Spotify is paused spotify.state_paused = "kPSp" --- hs.spotify.state_playing --- Constant --- Returned by `hs.spotify.getPlaybackState()` to indicates Spotify is playing spotify.state_playing = "kPSP" --- hs.spotify.state_stopped --- Constant --- Returned by `hs.spotify.getPlaybackState()` to indicates Spotify is stopped spotify.state_stopped = "kPSS" -- Internal function to pass a command to Applescript. local function tell(cmd) local _cmd = 'tell application "Spotify" to ' .. cmd local ok, result = as.applescript(_cmd) if ok then return result else return nil end end --- hs.spotify.playpause() --- Function --- Toggles play/pause of current Spotify track --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.playpause() tell('playpause') end --- hs.spotify.play() --- Function --- Plays the current Spotify track --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.play() tell('play') end --- hs.spotify.pause() --- Function --- Pauses the current Spotify track --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.pause() tell('pause') end --- hs.spotify.next() --- Function --- Skips to the next Spotify track --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.next() tell('next track') end --- hs.spotify.previous() --- Function --- Skips to previous Spotify track --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.previous() tell('previous track') end --- hs.spotify.displayCurrentTrack() --- Function --- Displays information for current track on screen --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.displayCurrentTrack() local artist = tell('artist of the current track') or "Unknown artist" local album = tell('album of the current track') or "Unknown album" local track = tell('name of the current track') or "Unknown track" alert.show(track .."\n".. album .."\n".. artist, 1.75) end --- hs.spotify.getCurrentArtist() --- Function --- Gets the name of the artist of the current track --- --- Parameters: --- * None --- --- Returns: --- * A string containing the Artist of the current track, or nil if an error occurred function spotify.getCurrentArtist() return tell('artist of the current track') end --- hs.spotify.getCurrentAlbum() --- Function --- Gets the name of the album of the current track --- --- Parameters: --- * None --- --- Returns: --- * A string containing the Album of the current track, or nil if an error occurred function spotify.getCurrentAlbum() return tell('album of the current track') end --- hs.spotify.getCurrentTrack() --- Function --- Gets the name of the current track --- --- Parameters: --- * None --- --- Returns: --- * A string containing the name of the current track, or nil if an error occurred function spotify.getCurrentTrack() return tell('name of the current track') end --- hs.spotify.getPlaybackState() --- Function --- Gets the current playback state of Spotify --- --- Parameters: --- * None --- --- Returns: --- * A string containing one of the following constants: --- - `hs.spotify.state_stopped` --- - `hs.spotify.state_paused` --- - `hs.spotify.state_playing` function spotify.getPlaybackState() return tell('get player state') end --- hs.spotify.isRunning() --- Function --- Returns whether Spotify is currently open. Most other functions in hs.spotify will automatically start the application, so this function can be used to guard against that. --- --- Parameters: --- * None --- --- Returns: --- * A boolean value indicating whether the Spotify application is running. function spotify.isRunning() return app.get("Spotify") ~= nil end --- hs.spotify.isPlaying() --- Function --- Returns whether Spotify is currently playing --- --- Parameters: --- * None --- --- Returns: --- * A boolean value indicating whether Spotify is currently playing a track, or nil if an error occurred (unknown player state). Also returns false if the application is not running function spotify.isPlaying() -- We check separately to avoid starting the application if it's not running if not hs.spotify.isRunning() then return false end state = hs.spotify.getPlaybackState() if state == hs.spotify.state_playing then return true elseif state == hs.spotify.state_paused or state == hs.spotify.state_stopped then return false else -- unknown state return nil end end --- hs.spotify.getVolume() --- Function --- Gets the Spotify volume setting --- --- Parameters: --- * None --- --- Returns: --- * A number containing the volume Spotify is set to between 1 and 100 function spotify.getVolume() return tell'sound volume' end --- hs.spotify.setVolume(vol) --- Function --- Sets the Spotify volume setting --- --- Parameters: --- * vol - A number between 1 and 100 --- --- Returns: --- * None function spotify.setVolume(v) v=tonumber(v) if not v then error('volume must be a number 1..100',2) end return tell('set sound volume to '..math.min(100,math.max(0,v))) end --- hs.spotify.volumeUp() --- Function --- Increases the volume by 5 --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.volumeUp() return spotify.setVolume(spotify.getVolume()+5) end --- hs.spotify.volumeDown() --- Function --- Reduces the volume by 5 --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.volumeDown() return spotify.setVolume(spotify.getVolume()-5) end --- hs.spotify.getPosition() --- Function --- Gets the playback position (in seconds) in the current song --- --- Parameters: --- * None --- --- Returns: --- * A number indicating the current position in the song function spotify.getPosition() return tell('player position') end --- hs.spotify.setPosition(pos) --- Function --- Sets the playback position in the current song --- --- Parameters: --- * pos - A number containing the position (in seconds) to jump to in the current song --- --- Returns: --- * None function spotify.setPosition(p) p=tonumber(p) if not p then error('position must be a number in seconds',2) end return tell('set player position to '..p) end --- hs.spotify.getDuration() --- Function --- Gets the duration (in seconds) of the current song --- --- Parameters: --- * None --- --- Returns: --- * The number of seconds long the current song is, 0 if no song is playing function spotify.getDuration() local duration = tonumber(tell('duration of current track')) return duration ~= nil and duration / 1000 or 0 end --- hs.spotify.ff() --- Function --- Skips the playback position forwards by 5 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.ff() return spotify.setPosition(spotify.getPosition()+5) end --- hs.spotify.rw --- Function --- Skips the playback position backwards by 5 seconds --- --- Parameters: --- * None --- --- Returns: --- * None function spotify.rw() return spotify.setPosition(spotify.getPosition()-5) end return spotify
local Timer = class("Timer") function Timer:initialize() self.updateList = {} self.timeouts = {} end function Timer:onNextUpdate(cb) table.insert(self.updateList, cb) end function Timer:setTimeout(cb, delay) table.insert(self.timeouts, {cb = cb, delay = love.timer.getTime() + delay}) end function Timer:clearUpdates() table.clear(self.timeouts) table.clear(self.updateList) end function Timer:update(dt) while (#self.updateList > 0) do self.updateList[1]() table.remove(self.updateList, 1) end local tmp = {} for k,v in pairs(self.timeouts) do if (love.timer.getTime() > v.delay) then v.cb() else table.insert(tmp, v) end end table.clear(self.timeouts) table.copyto(tmp, self.timeouts) end return Timer
local technology = table.deepcopy(data.raw["technology"]["effect-transmission"]) technology.upgrade = "true" if settings.startup["wret-overload-enable-beaconmk2"].value == true then data:extend{ technology, --effect transmission 2 (beacon mk 2) { name = "effect-transmission-2", type = "technology", icon = data.raw["technology"]["effect-transmission"].icon, icon_size = data.raw["technology"]["effect-transmission"].icon_size, upgrade = "true", unit = { count = 400, ingredients = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"production-science-pack", 1}, {"utility-science-pack", 1}, }, time = 30, }, prerequisites = {"effect-transmission", "utility-science-pack"}, effects = { {type = "unlock-recipe", recipe = "beacon2-recipe"}, }, }, } end if settings.startup["wret-overload-enable-beaconmk3"].value == true then data:extend{ technology, --effect transmission 3 (beacon mk 3) { name = "effect-transmission-3", type = "technology", icon = data.raw["technology"]["effect-transmission"].icon, icon_size = data.raw["technology"]["effect-transmission"].icon_size, upgrade = "true", unit = { count = 1000, ingredients = { {"automation-science-pack", 1}, {"logistic-science-pack", 1}, {"chemical-science-pack", 1}, {"production-science-pack", 1}, {"utility-science-pack", 1}, {"space-science-pack", 1}, }, time = 30, }, prerequisites = {"effect-transmission-2", "space-science-pack", "electric-energy-distribution-2"}, effects = { {type = "unlock-recipe", recipe = "beacon3-recipe"} }, } } end
local hook local _E if (not IsAddOnLoaded("Bagnon")) then return end local function update(self) local slotFrame = _G[self:GetName()] local slotLink = self:GetItem() SyLevel:CallFilters("Bagnon", slotFrame, _E and slotLink) end local item = Bagnon.ItemSlot or Bagnon.Item local function doHook() if (not hook) then hook = function(...) if (_E) then return update(...) end end hooksecurefunc(item, "Update", update) end end local function enable(self) _E = true doHook() end local function disable(self) _E = nil end SyLevel:RegisterPipe("Bagnon", enable, disable, update, "Bagnon", nil)
function math.dotproduct(x1, y1, z1, x2, y2, z2) return x1*x2 + y1*y2 + z1*z2 end function math.crossproduct(x1, y1, z1, x2, y2, z2) return y1*z2 - y2*z1, z1*x2 - z2*x1, x1*y2 - x2*y1 end function math.length(x, y) return math.sqrt(x*x + y*y) end function math.distance(x1, y1, x2, y2) return math.length(x1 - x2, y1 - y2) end function math.angle(x1, y1, x2, y2) return math.acos( math.dotproduct(x1, y1, 0, x2, y2, 0) / (math.length(x1, y1) * math.length(x2, y2)) ) end function math.normal(x, y) local len = math.length(x, y) return x / len, y / len end function math.clamp(input, min, max) if (min > max) then local _ = min min = max max = _ end if (input < min) then return min end if (input > max) then return max end return input end function math.sign(n) if (n > 0) then return 1 end if (n < 0) then return -1 end return 0 end function math.approach(start, _end, inc) return math.clamp(start + inc, start, _end) end function math.approach2(start, _end, inc) local dir = math.sign(_end - start) return math.clamp(start + (dir * inc), start, _end) end function math.lerp(x1, x2, alpha) local dist = math.abs(x2 - x1) return math.approach2(x1, x2, alpha * dist) end function math.lerpVector(x1, y1, x2, y2, alpha) local dist = math.distance(x1, y1, x2, y2) return math.approach2(x1, x2, alpha * dist), math.approach2(y1, y2, alpha * dist) end function math.lerpAngle(start, _end, inc) local x, y, cross = math.crossproduct(math.cos(start), math.sin(start), 0, math.cos(_end), math.sin(_end), 0) local sign = math.sign(cross) local result = start + inc*sign local x, y, cross2 = math.crossproduct(math.cos(result), math.sin(result), 0, math.cos(_end), math.sin(_end), 0) local sign2 = math.sign(cross2) if sign == sign2 then return result else return _end end end function math.round(num) if (num - math.floor(num)) < 0.5 then return math.floor(num) else return math.ceil(num) end end ----------------------------------------------------------------------------------------------------------------------- -- tween.lua - v1.0.1 (2012-02) -- Enrique García Cota - enrique.garcia.cota [AT] gmail [DOT] com -- tweening functions for lua -- inspired by jquery's animate function ----------------------------------------------------------------------------------------------------------------------- -- bounce function math.outBounce(t, b, c, d) t = t / d if t < 1 / 2.75 then return c * (7.5625 * t * t) + b end if t < 2 / 2.75 then t = t - (1.5 / 2.75) return c * (7.5625 * t * t + 0.75) + b elseif t < 2.5 / 2.75 then t = t - (2.25 / 2.75) return c * (7.5625 * t * t + 0.9375) + b end t = t - (2.625 / 2.75) return c * (7.5625 * t * t + 0.984375) + b end
local lu = require("luaunit") local ubx = require("ubx") local utils = require("utils") local bd = require("blockdiagram") local time = require("time") local ffi = require("ffi") local LOGLEVEL = ffi.C.UBX_LOGLEVEL_DEBUG local CHECK_VERBOSE = false local ni TestSaturation = {} function TestSaturation:teardown() if ni then ubx.node_rm(ni) end ni = nil end function TestSaturation:TestLen1() local sys = bd.system { imports = { "stdtypes", "lfds_cyclic", "saturation_double" }, blocks = { { name = "satd1", type = "saturation_double" } }, configurations = { { name = "satd1", config = { lower_limits = -10, upper_limits = 3.3 } } } } -- testdata local in_data = { 1, 0, 2, 5, 10000, 3.2, -1, -1000, -9.9999, -10.1 } local exp_data = { 1, 0, 2, 3.3, 3.3, 3.2, -1, -10, -9.9999, -10 } assert(#in_data == #exp_data) local num_err = sys:validate(CHECK_VERBOSE) lu.assert_equals(num_err, 0) ni = sys:launch({nodename = "TestLen1", loglevel=LOGLEVEL }) lu.assert_not_nil(ni); local satd1 = ni:b("satd1") local pin = ubx.port_clone_conn(satd1, "in", 1, nil, 7, 0) local pout = ubx.port_clone_conn(satd1, "out", nil, 1, 7, 0) for i=1,#in_data do pin:write(in_data[i]) satd1:do_step() local len, val = pout:read() lu.assert_equals(tonumber(len), 1) lu.assert_equals(val:tolua(), exp_data[i]) end end function TestSaturation:TestLen5() local data_len = 5 local sys = bd.system { imports = { "stdtypes", "lfds_cyclic", "saturation_double" }, blocks = { { name = "satd1", type = "saturation_double" } }, configurations = { { name = "satd1", config = { data_len = data_len, lower_limits = { -1, -2, -3, -4, -5 }, upper_limits = { 1, 22, 333, 4444, 55555 } } } } } local in_data = { { 0, 0, 0, 0, 0 }, { 5, 5, 5, 5, 5 }, { 1, 400, 400, 400, 400 }, { 22, 333, 4444, 55555, 666666 }, { 55555, 4444, 333, 22, 1 }, { -1.1, -2.2, -3.3, -4.4, -5.5 }, { 0, -10, 0, -10, 0 }, { -666666, -666666, -666666, -666666, -6666660 }, } local exp_data = { { 0, 0, 0, 0, 0 }, { 1, 5, 5, 5, 5 }, { 1, 22, 333, 400, 400 }, { 1, 22, 333, 4444, 55555 }, { 1, 22, 333, 22, 1 }, { -1, -2, -3, -4, -5 }, { 0, -2, 0, -4, 0 }, { -1, -2, -3, -4, -5 } } assert(#in_data == #exp_data) for i=1,#in_data do assert(#in_data[i] == data_len); assert(#exp_data[i] == data_len); end local num_err = sys:validate(CHECK_VERBOSE) lu.assert_equals(num_err, 0) ni = sys:launch({nodename = "TestLen5", loglevel=LOGLEVEL }) lu.assert_not_nil(ni); local satd1 = ni:b("satd1") local pin = ubx.port_clone_conn(satd1, "in", 1, nil, 7, 0) local pout = ubx.port_clone_conn(satd1, "out", nil, 1, 7, 0) for i=1,#in_data do pin:write(in_data[i]) satd1:do_step() local len, val = pout:read() lu.assert_equals(tonumber(len), data_len) lu.assert_equals(val:tolua(), exp_data[i]) end end os.exit( lu.LuaUnit.run() )
local ffi = require "ffi" local M = {} -- Load the C library local include = function(tag) local f = io.open("include/" .. tag .. ".h") ffi.cdef(f:read("*a")) f:close() ffi.load("lib/lib" .. tag .. ".so", true) end include "geant4" -- Wrap the geant4 functions local Geant4 = ffi.metatype("struct geant4", { __new = function(ct, ...) local o = ffi.new(ct) ffi.C.geant4_initialise(o, ...) return o end, __gc = function(o) o.clear() end }) local g4 = {} function M.initialise(opts) local function args() local period = opts.period ~= nil and opts.period or 1 local secondaries = not opts.secondaries local cut = opts.cut ~= nil and opts.cut or 1. local mode = opts.mode ~= nil and opts.mode or ffi.C.GEANT4_MODE_G4TURTLE return opts.area, period, mode, secondaries, cut end g4 = Geant4(args()) end function M.run(view, particle, energy, azimuth, elevation) local pid = ({ Geantino = ffi.C.GEANT4_PARTICLE_GEANTINO, MuonMinus = ffi.C.GEANT4_PARTICLE_MUON_MINUS, MuonPlus = ffi.C.GEANT4_PARTICLE_MUON_PLUS })[particle] local depth = ffi.new "double[1]" local time = ffi.new "double[1]" local direction = ffi.new "double[3]" view:direction(azimuth, elevation, direction) local n = g4.run(pid, energy, view.position, direction, depth, time) return n, depth[0], time[0] end function M.configure(opts) local function args() local events = opts.events ~= nil and opts.events or -1 local verbosity = opts.verbosity ~= nil and opts.verbosity or -1 return events, verbosity end ffi.C.geant4_configure(g4, args()) end return M
object_tangible_wearables_armor_armor_imperial_guard_shadow_armor_imperial_guard_shadow_bicep_r = object_tangible_wearables_armor_armor_imperial_guard_shadow_shared_armor_imperial_guard_shadow_bicep_r:new { } ObjectTemplates:addTemplate(object_tangible_wearables_armor_armor_imperial_guard_shadow_armor_imperial_guard_shadow_bicep_r, "object/tangible/wearables/armor/armor_imperial_guard_shadow/armor_imperial_guard_shadow_bicep_r.iff")
--- @classmod core.physics.EmptyCollisionShape --- A collision shape without actual collision detection. -- -- Extends @{core.physics.CollisionShape}. local engine = require 'engine' local class = require 'middleclass' local Scheduler = require 'core/Scheduler' local CollisionShape = require 'core/physics/CollisionShape' local EmptyCollisionShape = class('core/physics/EmptyCollisionShape', CollisionShape) function EmptyCollisionShape:initialize() CollisionShape.initialize(self, Scheduler.awaitCall(engine.CreateEmptyCollisionShape)) end return EmptyCollisionShape
-- ... rust.lua
--记录整个游戏界面切换的布局, 用于新手引导和小红点. layout = {} layout.layer = {} layout.layer[enum.ui.layer.mainMenu] = { froms = {}, parent = enum.ui.scene.dock, links = { world = enum.ui.scene.world, battle = enum.ui.scene.battle, gm = enum.ui.layer.gm, -- btnName = scene or layer } } layout.layer[enum.ui.layer.gm] = { froms = {{enum.ui.layer.mainMenu, "gm"}}, parent = enum.ui.scene.popup, -- 这里不用 enum.ui.layer.consoleTab 做父节点, links = {} } -- 如何指定标签页, 界面跳转时指导一次, 还是两次? --在不打开界面的情况下, 知道父节点, 从哪个界面哪个按钮点开来 layerChart = {} layerChart[enum.ui.scene.login] = {} --没有引导返回登录的 layerChart[enum.ui.scene.dock] = {} layerChart[enum.ui.scene.popup] = {} layerChart[enum.ui.scene.battle] = {from=enum.ui.layer.mainMenu, btn="battle"} layerChart[enum.ui.scene.test] = {from=enum.ui.layer.mainMenu, btn="setting"} layerChart[enum.ui.layer.consoleTab] = {parent=enum.ui.scene.popup, from=enum.ui.layer.mainMenu, btn="console"} layerChart[enum.ui.layer.test] = {parent=enum.ui.scene.test} layerChart[enum.ui.layer.taskBrief] = {parent=enum.ui.scene.dock} layerChart[enum.ui.layer.mainMenu] = {parent=enum.ui.scene.dock} layerChart[enum.ui.layer.gm] = {parent=enum.ui.layer.consoleTab, from=enum.ui.layer.consoleTab, btn="gm"} layerChart[enum.ui.layer.protocol] = {parent=enum.ui.layer.consoleTab, from=enum.ui.layer.consoleTab, btn="protocol"} --可以一次计算依赖,存成tree数据结构.不必每次都去查找,空间换时间, 或者线下算好. -- 这两个查找函数废弃. 新手要重新设计, --父节点是谁 function layerChart.findParentPath(layerName) local t = {} local name = layerName while true do local data = layerChart[name] if data then table.insert(t, 1, name) if data.parent then name = data.parent else break end else error("not exist layer:"..name) break end end -- print("layerChart.findParentPath ", layerName) -- for i,layer in ipairs(t) do -- print(" ",i, layer) -- end return t end --打开你的是谁 --TODO. 可能有多个,上层需要结合实际处理. function layerChart.findFromPath(layerName) local t = {} local name = layerName while true do local data = layerChart[name] if data then table.insert(t, 1, name) if data.from then name = data.from elseif data.parent then name = data.parent else break end else error("not exist layer:"..name) break end end -- print("layerChart.findFromPath ", layerName) -- for i,layer in ipairs(t) do -- print(" ",i, layer) -- end return t end return layerChart
function main(splash) splash.images_enabled = false splash.response_body_enabled = true local url = splash.args.url assert(splash:go(url)) assert(splash:wait(5)) local detectFunction = [[ detect = function(){ var rs = []; softwareData.forEach(function(s) { var matchers = s.matchers; for (var i in matchers) { if (eval(matchers[i].check)){ var version = eval(matchers[i].version); if (version) { rs.push({'name': s.name, 'version': version}); } } } }); return rs; } ]] splash:runjs('softwareData = $js_data;') splash:runjs(detectFunction) local softwares = {} local scripts = {} local errors = {} local ok, res = pcall(splash.evaljs, self, 'detect()') if ok then softwares = res else errors['evaljs'] = res end local ok, res = pcall(splash.select_all, self, 'script') if ok then if res then for _, s in ipairs(res) do scripts[#scripts+1] = s.node.innerHTML end end else errors['select_all'] = res end return { har = splash:har(), softwares=softwares, scripts=scripts, errors=errors, } end
----------------------------------- -- Area: Periqia (Requiem) -- Mob: Draconic Draugar ----------------------------------- function onMobEngaged(mob, target) local instance = mob:getInstance() local mobID = mob:getID() SpawnMob(mobID +1, instance):updateEnmity(target) end function onMobDeath(mob, player, isKiller) end function onMobDespawn(mob) local instance = mob:getInstance() instance:setProgress(instance:getProgress() + 1) end
local i = require "luci.dispatcher" local e = require "nixio.fs" local e = require "luci.sys" local e = luci.model.uci.cursor() local o = "brook_server" m = Map(o, translate("Brook Server")) t = m:section(TypedSection, "global", translate("Global Settings")) t.anonymous = true t.addremove = false e = t:option(Flag, "enable", translate("Enable")) e.rmempty = false t:append(Template("brook_server/brook")) e = t:option(Value, "brook_path", translate("Brook Path")) e.description = translate("if you want to run from memory, change the path, such as /tmp/brook, Then save the application and update it manually.") e.default = "/usr/bin/brook" e.rmempty = false t = m:section(TypedSection, "user", translate("Users Manager")) t.anonymous = true t.addremove = true t.template = "cbi/tblsection" t.extedit = i.build_url("admin", "vpn", o, "config", "%s") function t.create(t, e) local e = TypedSection.create(t, e) luci.http.redirect(i.build_url("admin", "vpn", o, "config", e)) end function t.remove(t, a) t.map.proceed = true t.map:del(a) luci.http.redirect(i.build_url("admin", "vpn", o)) end e = t:option(Flag, "enable", translate("Enable")) e.width = "5%" e.rmempty = false e = t:option(DummyValue, "status", translate("Status")) e.template = "brook_server/users_status" e.value = translate("Collecting data...") e = t:option(DummyValue, "remarks", translate("Remarks")) e.width = "20%" e = t:option(DummyValue, "port", translate("Port")) e.width = "20%" e = t:option(DummyValue, "password", translate("Password")) e.width = "30%" e.cfgvalue = function(self, section) local e = m:get(section, "password") or "" local t = "" if type(e) == "table" then for a = 1, #e do t = t .. e[a] .. "," end t = string.sub(t, 0, #t - 1) else t = e end return t end m:append(Template("brook_server/log")) m:append(Template("brook_server/users_list_status")) return m
local Input = {} local keys = {} local prevKeys = {} function love.keypressed(key) keys[key] = true end function love.keyreleased(key) keys[key] = false end function Input.lateUpdate(dt) for key, value in pairs(keys) do prevKeys[key] = value end end function Input.isHeld(key) if type(key) == 'string' then return keys[val] else for _, val in ipairs(key) do if keys[val] then return true end end return false end end function Input.wasPressed(key) if type(key) == 'string' then return keys[key] and not prevKeys[key] else for _, val in ipairs(key) do if keys[val] and not prevKeys[val] then return true end end return false end end return Input
-- original by Doob -- fixed/modified by fingercomp port, radius, t = 31415, 2, 'timer' timer = math.random(3, 6) sounds = { 'entity.endermen.teleport', 'entity.lightning.thunder', 'entity.generic.explode', 'entity.pig.ambient', 'block.slime.step' } blocks = { 'opencomputers:microcontroller', 'opencomputers:robot' } function get(name) return component.proxy(component.list(name)()) end modem, tunnel, deb = get('modem'), get('tunnel'), get('debug') cmd = deb.runCommand function cmd(c) x,y,z=math.floor(deb.getX()),math.floor(deb.getY()),math.floor(deb.getZ()) tunnel.send(x,y,z,t,c) end function bang() x, y, z = math.floor(deb.getX()), math.floor(deb.getY()), math.floor(deb.getZ()) cmd(('particle heart %d %d %d 1 1 1 0.1'):format(x,y,z)) for _, i in pairs(sounds) do cmd(('playsound %s block @a %d %d %d 2 1'):format(i,x,y,z)) end for _, i in pairs(blocks) do cmd(('fill %d %d %d %d %d minecraft:air 0 replace %s'):format(x-radius,y-radius,z-radius,x+radius,y+radius,z+radius, i)) end end function signal(...) deb.changeBuffer(500) local s = {computer.pullSignal(...)} return table.unpack(s) end if timer then while computer.uptime() ~= timer do signal(1) end if math.random(1, 20) ~= 1 then bang() end else modem.open(port) while true do signal(1) end end
local ASSET = {} local dialogue_actors = {} local function NormalizeSoundPath(sound_path, gender) sound_path = string.Replace(sound_path, '%gender%', gender) return sound_path end local function _EmitSound(actor, sound) actor:GetNPC():EmitSound(sound, 70, 100, 1, CHAN_AUTO) end local function _PlayAnimation(dialogue) if #dialogue.animations ~= 0 then for _, value in ipairs(dialogue.animations) do if value.id == dialogue.replicId then local actor = dialogue.interlocutors[dialogue.speaking] if actor:IsAlive() then if value.time ~= nil then actor:PlayStaticSequence(value.sequence, true, value.time) else actor:PlayStaticSequence(value.sequence) end end break end end end end function ASSET:SetDialogue(actor1, actor2) for _, value in ipairs(dialogue_actors) do for _, interlocutor in ipairs(value.interlocutors) do if interlocutor == actor1 or interlocutor == actor2 then return end end end local npc1_model = actor1:GetNPC():GetModel() local npc2_model = actor2:GetNPC():GetModel() local dialogue = table.RandomBySeq(bgNPC.cfg.dialogues) local replic = dialogue.list[1] if dialogue.interlocutors == nil then return false end local type_1 = dialogue.interlocutors[1] local type_2 = dialogue.interlocutors[2] local gender_1 = 'unknown' local gender_2 = 'unknown' if actor1:GetType() ~= type_1 or actor2:GetType() ~= type_2 then return false end if dialogue.gender ~= nil then gender_1 = dialogue.gender[1] gender_2 = dialogue.gender[2] if gender_1 == 'female' and not tobool(string.find(npc1_model, 'female_*')) then return false elseif gender_1 == 'male' and tobool(string.find(npc1_model, 'female_*')) then return false elseif gender_1 == 'any' then if tobool(string.find(npc1_model, 'female_*')) then gender_1 = 'female' else gender_1 = 'male' end end if gender_2 == 'female' and not tobool(string.find(npc2_model, 'female_*')) then return false elseif gender_2 == 'male' and tobool(string.find(npc2_model, 'female_*')) then return false elseif gender_2 == 'any' then if tobool(string.find(npc2_model, 'female_*')) then gender_2 = 'female' else gender_2 = 'male' end end end local index = table.insert(dialogue_actors, { id = tostring(CurTime()) .. tostring(RealTime()) .. actor1:GetType() .. actor2:GetType(), interlocutors = { [1] = actor1, [2] = actor2, }, gender = { [1] = gender_1, [2] = gender_2, }, data = dialogue, list = dialogue.list, animations = dialogue.animations or {}, replic = replic, speaking = 1, replicId = 1, replicMax = table.Count(dialogue.list), soundId = 1, soundMax = table.Count(replic), switchTime = CurTime() + slib.SoundDuration('sound/' .. NormalizeSoundPath(replic[1], gender_1)) + 1, isIdle = false, }) _EmitSound(actor1, NormalizeSoundPath(replic[1], gender_1)) _PlayAnimation(dialogue_actors[index]) return true end function ASSET:UnsetDialogue(id) for i = #dialogue_actors, 1, -1 do local dialogue = dialogue_actors[i] if dialogue.id == id then table.remove(dialogue_actors, i) local actor1 = dialogue.interlocutors[1] local actor2 = dialogue.interlocutors[2] if dialogue.data.finalAction ~= nil then dialogue.data.finalAction(actor1, actor2) else actor1:RandomState() actor2:RandomState() end break end end end function ASSET:GetDialogue(actor) for index, value in ipairs(dialogue_actors) do for _, interlocutor in ipairs(value.interlocutors) do if interlocutor == actor then return dialogue_actors[index] end end end return nil end function ASSET:SwitchDialogue(actor) local dialogue = self:GetDialogue(actor) if dialogue == nil then return end if dialogue.interlocutors[1] == nil or not dialogue.interlocutors[1]:IsAlive() then self:UnsetDialogue(dialogue.id) return elseif dialogue.interlocutors[2] == nil or not dialogue.interlocutors[2]:IsAlive() then self:UnsetDialogue(dialogue.id) return end local gender = dialogue.gender[dialogue.speaking] if dialogue.switchTime < CurTime() then if dialogue.soundId + 1 > dialogue.soundMax then if dialogue.replicId + 1 > dialogue.replicMax then self:UnsetDialogue(dialogue.id) else local newReplicId = dialogue.replicId + 1 dialogue.replicId = newReplicId dialogue.replic = dialogue.list[newReplicId] dialogue.soundId = 1 dialogue.soundMax = table.Count(dialogue.replic) if dialogue.speaking == 1 then dialogue.speaking = 2 else dialogue.speaking = 1 end gender = dialogue.gender[dialogue.speaking] local sound_path = NormalizeSoundPath(dialogue.replic[1], gender) dialogue.switchTime = CurTime() + slib.SoundDuration('sound/' .. sound_path) + 0.5 local actor = dialogue.interlocutors[dialogue.speaking] _EmitSound(actor, sound_path) _PlayAnimation(dialogue) end else dialogue.soundId = dialogue.soundId + 1 local sound_path = NormalizeSoundPath(dialogue.replic[dialogue.soundId], gender) dialogue.switchTime = CurTime() + slib.SoundDuration('sound/' .. sound_path) + 0.5 local actor = dialogue.interlocutors[dialogue.speaking] _EmitSound(actor, sound_path) _PlayAnimation(dialogue) end end end function ASSET:ClearAll() table.Empty(dialogue_actors) end function ASSET:RemoveBadValues() for i = #dialogue_actors, 1, -1 do local value = dialogue_actors[i] local actor1 = value.interlocutors[1] local actor2 = value.interlocutors[2] if not actor1:HasState('dialogue') or not actor2:HasState('dialogue') then table.remove(dialogue_actors, i) end end end hook.Add("BGN_ActorLookAtObject", "BGN_Module_DialogueState", function(actor, ent) local dialogue = ASSET:GetDialogue(actor) if dialogue ~= nil and not dialogue.isIdle then local actor1 = dialogue.interlocutors[1] local actor2 = dialogue.interlocutors[2] local npc1 = actor1:GetNPC() local npc2 = actor2:GetNPC() if not IsValid(npc1) or not IsValid(npc2) then return end if ent == npc1 or ent == npc2 then if actor:GetNPC():GetPos():Distance(ent:GetPos()) <= 180 then dialogue.isIdle = true end if actor1:IsSequenceFinished() then npc1:ResetSequenceInfo() end if actor2:IsSequenceFinished() then npc2:ResetSequenceInfo() end end end end) list.Set('BGN_Modules', 'actors_dialogue', ASSET)
local server = require "http.server" local headers = require "http.headers" local json = require "rapidjson" local util = require "util" local parser = require "parser" function handle_request(sv, st) local rqh = st:get_headers() local rqm = rqh:get(':method') local path = rqh:get(':path') or '/' local rsh = headers.new() if rqm == 'HEAD' then rsh:append(':status','200') rsh:append('content-type','text/plain') st:write_headers(rsh, true) return end local parts = util.str_split(path, '/') if not parts or #parts < 2 then rsh:append(':status','404') rsh:append('content-type','text/plain') st:write_headers(rsh, false) st:write_chunk("Invalid URL "..path, true) return end local is_code = parts[1] == "code" local accountName = "" local characterName = "" if is_code then accountName = parts[2] characterName = parts[3] else accountName = parts[1] characterName = parts[2] end local ran, data, code = pcall(parser, accountName, characterName) if not ran then rsh:append(':status','500') rsh:append('content-type','text/plain') st:write_headers(rsh, false) st:write_chunk(data, true) return end rsh:append(':status','200') if is_code then rsh:append('content-type','text/plain') st:write_headers(rsh, false) st:write_chunk(code, true) else rsh:append('content-type','application/json') st:write_headers(rsh, false) st:write_chunk(json.encode(data, {sort_keys=true, empty_table_as_array=true}), true) end end local port = os.getenv("PORT") or 8000 local s = server.listen { host = '0.0.0.0', port = port, onstream = function (sv, st) ran, err = pcall(handle_request, sv, st) if not ran then print(err) end end } s:listen() print("Listening on port "..port) s:loop()
local point = {} function point.rotate(x, y, ox, oy, r) local angle = r * math.pi / 180 local sinAngle = math.sin(angle) local cosAngle = math.cos(angle) if ox == 0 and oy == 0 then local tempX = x * cosAngle - y * sinAngle y = y * cosAngle + x * sinAngle x = tempX else local tempX = x - ox local tempY = y - oy x = tempX * cosAngle - tempY * sinAngle + ox y = tempY * cosAngle + tempX * sinAngle + oy end return x, y end ------------------------------------- -- Apply a scissor to the current scissor (intersect the rects) ------------------------------------- function clipScissor(nx, ny, nw, nh) local ox, oy, ow, oh = love.graphics.getScissor() if ox then -- Intersect both rects nw = nx + nw nh = ny + nh nx, ny = math.max(nx, ox), math.max(ny, oy) nw = math.max(0, math.min(nw, ox + ow) - nx) nh = math.max(0, math.min(nh, oy + oh) - ny) end -- Set new scissor love.graphics.setScissor(nx, ny, nw, nh) -- Return old scissor return ox, oy, ow, oh end function csplit(str,sep) local ret={} local n=1 for w in str:gmatch("([^"..sep.."]*)") do ret[n] = ret[n] or w -- only set once (so the blank after a string is ignored) if w=="" then n = n + 1 end -- step forwards on a blank but not a string end return ret end return point
-- Simple command parser -- local command = {} local base = _G function command:new() local neu = {} setmetatable(neu, self) self.__index = self return neu end function command:parse(str) local inquote = false local incommand = true local s = str local command = '' local arg = '' local args = {} if string.sub(s, 1, 1) ~= '#' then error('command does not start with a #') end s = string.sub(s, 2) if not s or s == "" then error('no command given') end for c in string.gmatch(s, '.') do if string.match(c, '%s') then if incommand then incommand = false elseif not incommand then if not inquote then table.insert(args, arg) arg = '' else arg = arg .. c end end hadescape = false elseif c == '\\' then hadescape = true elseif c == '"' then if incommand then error('special characters not allowed in command') end if hadescape then arg = arg .. c else inquote = not inquote end hadescape = false elseif incommand then hadescape = false command = command .. c elseif not incommand then hadescape = false arg = arg .. c end end if arg ~= '' then table.insert(args, arg) end if not command or command == "" then error('no command given') end self.command = command self.args = args self.message = str end return command
local floor, ceil = math.floor, math.ceil local min, max = math.min, math.max local simple = require("layouts.simple") local compact = require("layouts.compact") local mpp_util = require("mpp_util") local mpp_revert = mpp_util.revert local pole_grid_mt = require("pole_grid_mt") ---@type SimpleLayout local layout = table.deepcopy(simple) layout.name = "logistics" layout.translation = {"mpp.settings_layout_choice_logistics"} layout.restrictions.robot_logistics = true ---@param self SimpleLayout ---@param state SimpleState function layout:placement_belts(state) local c = state.coords local m = state.miner local g = state.grid local DIR = state.direction_choice local surface = state.surface local attempt = state.best_attempt local underground_belt = game.entity_prototypes[state.belt_choice].related_underground_belt.name local power_poles = {} state.power_poles_all = power_poles ---@type table<number, MinerPlacement[]> local miner_lanes = {{}} local miner_lane_number = 0 -- highest index of a lane, because using # won't do the job if a lane is missing local miner_max_column = 0 for _, miner in ipairs(attempt.miners) do local index = miner.line miner_lane_number = max(miner_lane_number, index) if not miner_lanes[index] then miner_lanes[index] = {} end local line = miner_lanes[index] line[#line+1] = miner miner_max_column = max(miner_max_column, miner.column) end state.miner_lane_count = miner_lane_number state.miner_max_column = miner_max_column for _, lane in ipairs(miner_lanes) do table.sort(lane, function(a, b) return a.center.x < b.center.x end) end ---@param lane MinerPlacement[] local function get_lane_length(lane) if lane then return lane[#lane].center.x end return 0 end ---@param lane MinerPlacement[] local function get_lane_column(lane) if lane then return lane[#lane].column end return 0 end local belts = {} state.belts = belts for i = 1, miner_lane_number, 2 do local lane1 = miner_lanes[i] local lane2 = miner_lanes[i+1] local y = attempt.sy + (m.size + 1) * i local x0 = attempt.sx + 1 local column_count = max(get_lane_column(lane1), get_lane_column(lane2)) local indices = {} if lane1 then for _, v in ipairs(lane1) do indices[v.column] = v end end if lane2 then for _, v in ipairs(lane2) do indices[v.column] = v end end for j = 1, column_count do local x = x0 + m.near + m.size * (j-1) if indices[j] then g:get_tile(x, y).built_on = "belt" surface.create_entity{ raise_built=true, name="entity-ghost", player=state.player, force=state.player.force, position=mpp_revert(c.gx, c.gy, DIR, x, y, c.tw, c.th), inner_name=state.logistics_choice, } end end end state.delegate = "placement_poles" end return layout
local Plugin = SS.Plugins:New("Radar") // Chat command local Command = SS.Commands:New("Radar") function Command.Command(Player, Args) local TR = util.GetPlayerTrace(Player) local Trace = util.TraceLine(TR) if not (Trace.Entity) then SS.PlayerMessage(Player, "You must aim at a valid entity!", 1) return end local ID = table.concat(Args, " ") SS.PlayerMessage(Player, "Entity has been added to radar!", 0) Player:ConCommand('ss_radarentity "'..ID..'"\n') end Command:Create(Command.Command, {"basic"}, "Add an entity to your radar", "<Name>", 1, " ") // Advert SS.Adverts.Add("To see the radar type ss_showradar 1!") // Finish plugin Plugin:Create()
local colorscheme = 'tokyonight' local status_ok, _ = pcall(vim.cmd, 'colorscheme ' .. colorscheme) if not status_ok then vim.notify('colorscheme ' .. colorscheme .. ' 没有找到!') return end
if GetBot():IsInvulnerable() or not GetBot():IsHero() or not string.find(GetBot():GetUnitName(), "hero") or GetBot():IsIllusion() then return; end local ability_item_usage_generic = dofile( GetScriptDirectory().."/ability_item_usage_generic" ) local utils = require(GetScriptDirectory() .. "/util") local mutil = require(GetScriptDirectory() .. "/MyUtility") function AbilityLevelUpThink() ability_item_usage_generic.AbilityLevelUpThink(); end function BuybackUsageThink() ability_item_usage_generic.BuybackUsageThink(); end function CourierUsageThink() ability_item_usage_generic.CourierUsageThink(); end function ItemUsageThink() ability_item_usage_generic.ItemUsageThink() end local npcBot = GetBot(); local abilityQ = nil; local abilityE = nil; local abilityR = nil; local castQDesire = 0; local castEDesire = 0; local castRDesire = 0; function AbilityUsageThink() if mutil.CanNotUseAbility(npcBot) or npcBot:HasModifier('modifier_bounty_hunter_wind_walk') then return end if abilityQ == nil then abilityQ = npcBot:GetAbilityByName( "bounty_hunter_shuriken_toss" ) end if abilityE == nil then abilityE = npcBot:GetAbilityByName( "bounty_hunter_wind_walk" ) end if abilityR == nil then abilityR = npcBot:GetAbilityByName( "bounty_hunter_track" ) end castQDesire, castQTarget = ConsiderQ(); castEDesire = ConsiderE(); castRDesire, castRTarget = ConsiderR(); if ( castRDesire > 0 ) then npcBot:Action_UseAbilityOnEntity( abilityR, castRTarget ); return; end if ( castQDesire > 0 ) then npcBot:Action_UseAbilityOnEntity( abilityQ, castQTarget ); return; end if ( castEDesire > 0 ) then npcBot:Action_UseAbility( abilityE ); return; end end function ConsiderQ() -- Make sure it's castable if ( not abilityQ:IsFullyCastable() ) then return BOT_ACTION_DESIRE_NONE; end -- Get some of its values local nRadius = abilityQ:GetSpecialValueInt( "bounce_aoe" ); local nCastRange = abilityQ:GetCastRange( ); local nCastPoint = abilityQ:GetCastPoint( ); local nManaCost = abilityQ:GetManaCost( ); local nDamage = abilityQ:GetSpecialValueInt( 'bonus_damage' ); local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nRadius, true, BOT_MODE_NONE ); local tableNearbyCreeps = npcBot:GetNearbyLaneCreeps( nCastRange + 200, true ); --if we can kill any enemies for _,npcEnemy in pairs(tableNearbyEnemyHeroes) do if npcEnemy:IsChanneling() then return BOT_ACTION_DESIRE_HIGH, npcEnemy; end if mutil.CanCastOnNonMagicImmune(npcEnemy) and mutil.CanKillTarget(npcEnemy, nDamage, DAMAGE_TYPE_MAGICAL) then if mutil.IsInRange(npcEnemy, npcBot, nCastRange + 200) then return BOT_ACTION_DESIRE_HIGH, npcEnemy; elseif tableNearbyCreeps[1] ~= nil and mutil.StillHasModifier(npcEnemy, 'modifier_bounty_hunter_track') and mutil.IsInRange(npcEnemy, npcBot, nRadius - 200) then return BOT_ACTION_DESIRE_HIGH, tableNearbyCreeps[1] ; end end end if mutil.IsInTeamFight(npcBot, 1200) then local trackedEnemy = 0; for _,npcEnemy in pairs( tableNearbyEnemyHeroes ) do if ( mutil.StillHasModifier(npcEnemy, 'modifier_bounty_hunter_track') ) then trackedEnemy = trackedEnemy + 1; end end if trackedEnemy >= 2 then if tableNearbyCreeps[1] ~= nil then return BOT_ACTION_DESIRE_HIGH, tableNearbyCreeps[1]; elseif mutil.IsInRange(tableNearbyEnemyHeroes[1], npcBot, nCastRange + 200) then return BOT_ACTION_DESIRE_HIGH, tableNearbyEnemyHeroes[1]; end end end -- If we're going after someone if mutil.IsGoingOnSomeone(npcBot) then local npcTarget = npcBot:GetTarget(); if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) then if mutil.IsInRange(npcEnemy, npcBot, nCastRange + 200) then return BOT_ACTION_DESIRE_HIGH, npcEnemy; elseif tableNearbyCreeps[1] ~= nil and mutil.StillHasModifier(npcEnemy, 'modifier_bounty_hunter_track') and mutil.IsInRange(npcEnemy, npcBot, nRadius - 200) then return BOT_ACTION_DESIRE_HIGH, tableNearbyCreeps[1] ; end end end return BOT_ACTION_DESIRE_NONE, 0; end function ConsiderE() -- Make sure it's castable if ( not abilityE:IsFullyCastable() ) then return BOT_ACTION_DESIRE_NONE; end -- Get some of its values local nCastPoint = abilityQ:GetCastPoint( ); local nManaCost = abilityQ:GetManaCost( ); -- If we're seriously retreating, see if we can land a stun on someone who's damaged us recently if mutil.IsRetreating(npcBot) then local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( 1000, true, BOT_MODE_NONE ); if ( tableNearbyEnemyHeroes ~= nil and #tableNearbyEnemyHeroes >= 1 ) then return BOT_ACTION_DESIRE_MODERATE; end end -- If we're going after someone if mutil.IsGoingOnSomeone(npcBot) then local npcTarget = npcBot:GetTarget(); if mutil.IsValidTarget(npcTarget) and not mutil.IsInRange(npcTarget, npcBot, 300) and mutil.IsInRange(npcTarget, npcBot, 2000) then return BOT_ACTION_DESIRE_MODERATE; end end return BOT_ACTION_DESIRE_NONE; end function ConsiderR() -- Make sure it's castable if ( not abilityR:IsFullyCastable() ) then return BOT_ACTION_DESIRE_NONE; end -- Get some of its values local nCastRange = abilityR:GetCastRange( ); local nCastPoint = abilityR:GetCastPoint( ); local nManaCost = abilityR:GetManaCost( ); local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nCastRange + 200, true, BOT_MODE_NONE ); --if we can kill any enemies for _,npcEnemy in pairs(tableNearbyEnemyHeroes) do if mutil.CanCastOnNonMagicImmune(npcEnemy) and not mutil.StillHasModifier(npcEnemy, 'modifier_bounty_hunter_track') then return BOT_ACTION_DESIRE_HIGH, npcEnemy; end end return BOT_ACTION_DESIRE_NONE, 0; end
local KUI, E, L, V, P, G = unpack(select(2, ...)) local KUF = KUI:GetModule("KUIUnits") local UF = E:GetModule('UnitFrames'); local LSM = LibStub("LibSharedMedia-3.0"); UF.LSM = LSM local _G = _G local select = select -- Raid function KUF:ChangeRaidHealthBarTexture() local header = _G['ElvUF_Raid'] local bar = LSM:Fetch("statusbar", E.db.KlixUI.unitframes.textures.health) for i = 1, header:GetNumChildren() do local group = select(i, header:GetChildren()) for j = 1, group:GetNumChildren() do local unitbutton = select(j, group:GetChildren()) if unitbutton.Health then if not unitbutton.Health.isTransparent or (unitbutton.Health.isTransparent and E.db.KlixUI.unitframes.textures.ignoreTransparency) then unitbutton.Health:SetStatusBarTexture(bar) end end end end end hooksecurefunc(UF, 'Update_RaidFrames', KUF.ChangeRaidHealthBarTexture) -- Raid-40 function KUF:ChangeRaid40HealthBarTexture() local header = _G['ElvUF_Raid40'] local bar = LSM:Fetch("statusbar", E.db.KlixUI.unitframes.textures.health) for i = 1, header:GetNumChildren() do local group = select(i, header:GetChildren()) for j = 1, group:GetNumChildren() do local unitbutton = select(j, group:GetChildren()) if unitbutton.Health then if not unitbutton.Health.isTransparent or (unitbutton.Health.isTransparent and E.db.KlixUI.unitframes.textures.ignoreTransparency) then unitbutton.Health:SetStatusBarTexture(bar) end end end end end hooksecurefunc(UF, 'Update_Raid40Frames', KUF.ChangeRaid40HealthBarTexture) -- Party function KUF:ChangePartyHealthBarTexture() local header = _G['ElvUF_Party'] local bar = LSM:Fetch("statusbar", E.db.KlixUI.unitframes.textures.health) for i = 1, header:GetNumChildren() do local group = select(i, header:GetChildren()) for j = 1, group:GetNumChildren() do local unitbutton = select(j, group:GetChildren()) if unitbutton.Health then if not unitbutton.Health.isTransparent or (unitbutton.Health.isTransparent and E.db.KlixUI.unitframes.textures.ignoreTransparency) then unitbutton.Health:SetStatusBarTexture(bar) end end end end end hooksecurefunc(UF, 'Update_PartyFrames', KUF.ChangePartyHealthBarTexture) function KUF:ChangeHealthBarTexture() KUF:ChangeRaidHealthBarTexture() KUF:ChangeRaid40HealthBarTexture() KUF:ChangePartyHealthBarTexture() end hooksecurefunc(UF, 'Update_StatusBars', KUF.ChangeHealthBarTexture)
object_mobile_wod_reanimated_witch_04 = object_mobile_shared_wod_reanimated_witch_04:new { } ObjectTemplates:addTemplate(object_mobile_wod_reanimated_witch_04, "object/mobile/wod_reanimated_witch_04.iff")
----------------------------------------- -- ID: 4672 -- Scroll of Barthunder -- Teaches the white magic Barthunder ----------------------------------------- function onItemCheck(target) return target:canLearnSpell(64) end function onItemUse(target) target:addSpell(64) end
--conding:utf-8 package.path=package.path..";./luagy/?.lua" Class=require("grammar.class") require("print.printtable") require"lfs" -------------------------------- --Config: FOLDER_FILE_NAME="FOLDER.MD" local MDFile=Class(function(self) self.filecontant={} self.MainDesrc={} self:getContant(); self.dirDesrc={} self.fileDesrc={} self.dirs={} self.files={} self.dirsid={} self.filesid={} self.cur=3; end) function MDFile:getMainName() return self.filecontant[1] --??????????? end local sep = "/" local upper = ".." function newfn( self,fn,n ) local dirss=self.dirDesrc local filess=self.fileDesrc return function( k,v ) if(dirss[k])then if(not n) then fn(v.id,k,dirss[k]) end else if(filess[k]) then if(not n) then fn(v.id,k,filess[k]) end else fn(v.id,k,"[hasn't desrc]") end end end end function MDFile:ListMDFile() i=0 j=0; for file in lfs.dir('.') do if file ~= "." and file ~= ".." then local p = '.'..sep..file local attr = lfs.attributes (p) assert (type(attr) == "table") if attr.mode == "directory" then self.dirs[file]={id=i,name=file} ; self.dirsid[i]=file; i=i+1 else --is file self.files[file]={id=j,name=file} ; self.filesid[j]=file; j=j+1 end end end end function MDFile:List(n) pt(self.dirs,newfn(self,print,n)) pt(self.files,newfn(self,print,n)) end function MDFile:ToMDFile(filename ) filename=filename or FOLDER_FILE_NAME; local file=io.open(filename,"w") print(file) file:write(self:getMainName()) file:write("\n=====================\n>") file:write(table.concat(self.MainDesrc,"\n>")) file:write("\n目录说明\n----------------\n>Directories Description\n\n") for k,v in pairs(self.dirDesrc) do file:write("* `"..k.."` "..v.."\n") end file:write("\n\n") file:write("文件说明\n----------------\n>MDFiles Description Description\n\n") for k,v in pairs(self.fileDesrc) do file:write("* `"..k.."` "..v.."\n") end file:close() end REPL=require "repl.repl" file=MDFile(); print(file:getMainName()); file:parse(); file:ListMDFile() file:ToMDFile("test.md") config={ list={ long={"*print","+dev","?none"}, short={ p={"pages"}, r={} }, other={ "filename..." }, fn=function (t ) if(t.other[1]=="n") then file:List(true) else file:List() end end }, q={ fn=function ( ... ) os.exit(0) end }, e={ fn=function ( t ) if(t.other[1]) then ids=t.other[1] if(ids:sub(1,1)=='f') then filename=file.filesid[tonumber(ids:sub(2,-1))] if(not filename) then print("找不到对应的文件") else print("修改"..filename.."的描述") str=io.read("*l") file.fileDesrc[filename]=str file:ToMDFile("test.md") end else end end end } } r=REPL(config) r:run()
local ghost = {} local image = love.graphics.newImage function ghost.IdleLeftAnimation() local idleLeft = { image('entities/img/ghost/idleLeft1.png'), image('entities/img/ghost/idleLeft2.png'), image('entities/img/ghost/idleLeft3.png'), image('entities/img/ghost/idleLeft4.png'), image('entities/img/ghost/idleLeft5.png'), image('entities/img/ghost/idleLeft6.png') } return idleLeft end function ghost.IdleRightAnimation() local idleRight = { image('entities/img/ghost/idleRight1.png'), image('entities/img/ghost/idleRight2.png'), image('entities/img/ghost/idleRight3.png'), image('entities/img/ghost/idleRight4.png'), image('entities/img/ghost/idleRight5.png'), image('entities/img/ghost/idleRight6.png') } return idleRight end function ghost.WalkingLeftAnimation() local walkingLeft = { image('entities/img/ghost/walkingLeft1.png'), image('entities/img/ghost/walkingLeft2.png'), image('entities/img/ghost/walkingLeft3.png'), image('entities/img/ghost/walkingLeft4.png'), image('entities/img/ghost/walkingLeft5.png'), image('entities/img/ghost/walkingLeft6.png'), image('entities/img/ghost/walkingLeft7.png'), image('entities/img/ghost/walkingLeft8.png'), image('entities/img/ghost/walkingLeft9.png') } return walkingLeft end function ghost.WalkingRightAnimation() local walkingRight = { image('entities/img/ghost/walkingRight1.png'), image('entities/img/ghost/walkingRight2.png'), image('entities/img/ghost/walkingRight3.png'), image('entities/img/ghost/walkingRight4.png'), image('entities/img/ghost/walkingRight5.png'), image('entities/img/ghost/walkingRight6.png'), image('entities/img/ghost/walkingRight7.png'), image('entities/img/ghost/walkingRight8.png'), image('entities/img/ghost/walkingRight9.png') } return walkingRight end return ghost
if Config.Framework == "ESX" or Config.Framework == "NewESX" then -- ESX Compatibility code ESX = nil Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end end) ShowNotification = function(str) ESX.ShowNotification(str) end TriggerServerCallback = function(...) ESX.TriggerServerCallback(...) end elseif Config.Framework == "vRP" then -- vRP Compatibility code vRP = Proxy.getInterface("vRP") ShowNotification = function(str) vRP.notify({str}) end -- ESX.TriggerServerCallback (https://github.com/ESX-Org/es_extended/blob/ff9930068f83af6adf78275b2581a0e5ea54a3bf/client/functions.lua#L76) ServerCallbacks = {} CurrentRequestId = 0 TriggerServerCallback = function(name, cb, ...) ServerCallbacks[CurrentRequestId] = cb TriggerServerEvent("xnVending:triggerServerCallback", name, CurrentRequestId, ...) CurrentRequestId = (CurrentRequestId + 1) % 65535 end RegisterNetEvent('xnVending:serverCallback') AddEventHandler('xnVending:serverCallback', function(requestId, ...) if ServerCallbacks[requestId] then ServerCallbacks[requestId](...) ServerCallbacks[requestId] = nil end end) else -- Standalone ShowNotification = function(str) SetNotificationTextEntry("STRING") AddTextComponentString(str) DrawNotification(true, false) end -- ESX.TriggerServerCallback (https://github.com/ESX-Org/es_extended/blob/ff9930068f83af6adf78275b2581a0e5ea54a3bf/client/functions.lua#L76) ServerCallbacks = {} CurrentRequestId = 0 TriggerServerCallback = function(name, cb, ...) ServerCallbacks[CurrentRequestId] = cb TriggerServerEvent("xnVending:triggerServerCallback", name, CurrentRequestId, ...) CurrentRequestId = (CurrentRequestId + 1) % 65535 end RegisterNetEvent('xnVending:serverCallback') AddEventHandler('xnVending:serverCallback', function(requestId, ...) if ServerCallbacks[requestId] then ServerCallbacks[requestId](...) ServerCallbacks[requestId] = nil end end) end local animPlaying = false local usingMachine = false local VendingObject = nil local machineModel = nil Citizen.CreateThread(function() local waitTime = 500 while true do Citizen.Wait(waitTime) if nearVendingMachine() and not usingMachine and not IsPedInAnyVehicle(PlayerPedId(), 1) then waitTime = 1 local buttonsMessage = {} local machine = machineModel local machineInfo = Config.Machines[machineModel] local machineNames = machineInfo.name for i = 1, #machineNames do buttonsMessage[machineNames[i] .. " ($" .. machineInfo.price[i] .. ")"] = Config.PurchaseButtons[i] if IsControlJustPressed(1, Config.PurchaseButtons[i]) then TriggerServerCallback('esx_vending:checkMoneyandInvent', function(response) if response == "cash" then ShowNotification("~r~You don't have enough cash") elseif response == "inventory" then ShowNotification("You cannot carry any more ~y~" .. machineNames[i]) else usingMachine = true local ped = PlayerPedId() local position = GetOffsetFromEntityInWorldCoords(VendingObject, 0.0, -0.97, 0.05) TaskTurnPedToFaceEntity(ped, VendingObject, -1) ReqAnimDict(Config.DispenseDict[1]) RequestAmbientAudioBank("VENDING_MACHINE") HintAmbientAudioBank("VENDING_MACHINE", 0, -1) SetPedCurrentWeaponVisible(ped, false, true, 1, 0) ReqTheModel(machineInfo.prop[i]) SetPedResetFlag(ped, 322, true) if not IsEntityAtCoord(ped, position, 0.1, 0.1, 0.1, false, true, 0) then TaskGoStraightToCoord(ped, position, 1.0, 20000, GetEntityHeading(VendingObject), 0.1) while not IsEntityAtCoord(ped, position, 0.1, 0.1, 0.1, false, true, 0) do Citizen.Wait(2000) end end TaskTurnPedToFaceEntity(ped, VendingObject, -1) Citizen.Wait(1000) TaskPlayAnim(ped, Config.DispenseDict[1], Config.DispenseDict[2], 8.0, 5.0, -1, true, 1, 0, 0, 0) Citizen.Wait(2500) local canModel = CreateObjectNoOffset(machineInfo.prop[i], position, true, false, false) SetEntityAsMissionEntity(canModel, true, true) SetEntityProofs(canModel, false, true, false, false, false, false, 0, false) AttachEntityToEntity(canModel, ped, GetPedBoneIndex(ped, 28422), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1, 1, 0, 0, 2, 1) Citizen.Wait(1700) ReqAnimDict(Config.PocketAnims[1]) TaskPlayAnim(ped, Config.PocketAnims[1], Config.PocketAnims[2], 8.0, 5.0, -1, true, 1, 0, 0, 0) Citizen.Wait(1000) ClearPedTasks(ped) ReleaseAmbientAudioBank() RemoveAnimDict(Config.DispenseDict[1]) RemoveAnimDict(Config.PocketAnims[1]) if DoesEntityExist(canModel) then DetachEntity(canModel, true, true) DeleteEntity(canModel) end SetModelAsNoLongerNeeded(machineInfo.prop[i]) TriggerServerCallback('esx_vending:checkMoneyandInvent', function(response) end, machine, i, true) usingMachine = false end end, machine, i, false) end end local scaleForm = setupScaleform("instructional_buttons", buttonsMessage) DrawScaleformMovieFullscreen(scaleForm, 255, 255, 255, 255, 0) BlockWeaponWheelThisFrame() else waitTime = 500 end end end) function nearVendingMachine() local player = PlayerPedId() local playerLoc = GetEntityCoords(player, 0) for machine, _ in pairs(Config.Machines) do VendingObject = GetClosestObjectOfType(playerLoc, 0.6, machine, false) if DoesEntityExist(VendingObject) then machineModel = machine return true end end return false end function ReqTheModel(model) RequestModel(model) while not HasModelLoaded(model) do Citizen.Wait(0) end end function ReqAnimDict(animDict) RequestAnimDict(animDict) while not HasAnimDictLoaded(animDict) do Citizen.Wait(0) end end function ButtonMessage(text) BeginTextCommandScaleformString("STRING") AddTextComponentScaleform(text) EndTextCommandScaleformString() end function Button(ControlButton) PushScaleformMovieMethodParameterButtonName(ControlButton) end function setupScaleform(scaleform, buttonsMessages) local scaleform = RequestScaleformMovie(scaleform) while not HasScaleformMovieLoaded(scaleform) do Citizen.Wait(0) end PushScaleformMovieFunction(scaleform, "CLEAR_ALL") PopScaleformMovieFunctionVoid() PushScaleformMovieFunction(scaleform, "SET_CLEAR_SPACE") PushScaleformMovieFunctionParameterInt(200) PopScaleformMovieFunctionVoid() local buttonCount = 0 for machine, buttons in pairs(buttonsMessages) do PushScaleformMovieFunction(scaleform, "SET_DATA_SLOT") PushScaleformMovieFunctionParameterInt(buttonCount) Button(GetControlInstructionalButton(2, buttons, true)) ButtonMessage(machine) PopScaleformMovieFunctionVoid() buttonCount = buttonCount + 1 end PushScaleformMovieFunction(scaleform, "DRAW_INSTRUCTIONAL_BUTTONS") PopScaleformMovieFunctionVoid() PushScaleformMovieFunction(scaleform, "SET_BACKGROUND_COLOUR") PushScaleformMovieFunctionParameterInt(0) PushScaleformMovieFunctionParameterInt(0) PushScaleformMovieFunctionParameterInt(0) PushScaleformMovieFunctionParameterInt(70) PopScaleformMovieFunctionVoid() return scaleform end
local function t(str) return vim.api.nvim_replace_termcodes(str, true, true, true) end local function check_back_space() local col = vim.fn.col('.') - 1 return col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') ~= nil end -- Use (s-)tab to: --- move to prev/next item in completion menuone --- jump to prev/next snippet's placeholder _G.tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-n>" elseif require("luasnip").expand_or_jumpable() then return t "<cmd>lua require'luasnip'.jump(1)<Cr>" elseif check_back_space() then return t "<Tab>" else return vim.fn['compe#complete']() end end _G.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return t "<C-p>" elseif require("luasnip").jumpable(-1) then return t "<cmd>lua require'luasnip'.jump(-1)<CR>" else -- If <S-Tab> is not working in your terminal, change it to <C-h> return t "<S-Tab>" end end local function config() vim.o.completeopt = "menuone,noselect" vim.o.shortmess = vim.o.shortmess .. "c" local compe = require("compe") compe.setup({ source = { path = true, buffer = true, calc = true, nvim_lsp = true, nvim_lua = true, luasnip = true, } }) vim.api.nvim_set_keymap("i", "<C-Space>", "compe#complete()", {expr = true, silent = true}) vim.api.nvim_set_keymap("i", "<CR>", [[compe#confirm(luaeval("require('nvim-autopairs').autopairs_cr()"))]], {expr = true, silent = true}) vim.api.nvim_set_keymap("i", "<Tab>", "v:lua.tab_complete()", {expr = true}) vim.api.nvim_set_keymap("s", "<Tab>", "v:lua.tab_complete()", {expr = true}) vim.api.nvim_set_keymap("i", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true}) vim.api.nvim_set_keymap("s", "<S-Tab>", "v:lua.s_tab_complete()", {expr = true}) end return { "hrsh7th/nvim-compe", config = config, requires = {"L3MON4D3/LuaSnip"} }
local t = Def.ActorFrame{} t[#t+1] = LoadActor("_frame") return t
local MakePlayerCharacter = require "prefabs/player_common" local assets = { -- Asset( "SCRIPT", "scripts/prefabs/player_common.lua"), -- Asset( "SOUND", "sound/willow.fsb"), Asset( "ANIM", "anim/miotan.zip" ), Asset( "ANIM", "anim/ghost_miotan_build.zip" ), } local prefabs = {} local start_inv = {} for k, v in pairs(TUNING.GAMEMODE_STARTING_ITEMS) do start_inv[string.lower(k)] = v.MIOTAN end prefabs = FlattenTree({ prefabs, start_inv }, true) local function set_moisture(table) -- if table == nil then return end for _,v in pairs(table) do if (v.prefab == "nightmarefuel" or (v.components.equippable and v.components.equippable:IsEquipped())) and v.components.inventoryitem and v.components.inventoryitem:IsWet() then v.components.inventoryitemmoisture:SetMoisture(0) end end end local function dryequipment(inst) local inv = inst.components.inventory and inst.components.inventory.itemslots if inv then set_moisture(inv) end local eslots = inst.components.inventory and inst.components.inventory.equipslots if eslots then set_moisture(eslots) end local boat = inst.components.sailor and inst.components.sailor:GetBoat() if boat then local boatinv = boat.components.container and boat.components.container.boatequipslots local boatslots = boat.components.container and boat.components.container.slots if boatinv then set_moisture(boatinv) end if boatslots then set_moisture(boatslots) end end end local function CheckHasItem(inst,item) if item == nil then return end local inv = inst.components.inventory local inv_boat = inst.components.sailor and inst.components.sailor:GetBoat() and inst.components.sailor:GetBoat().components.container return (inv and inv:Has(item,1)) or (inv_boat and inv_boat:Has(item,1)) end local function ConsumeItem(inst,item) if item == nil then return end local inv = inst.components.inventory local inv_boat = inst.components.sailor and inst.components.sailor:GetBoat() and inst.components.sailor:GetBoat().components.container if inv and inv:Has(item,1) then inv:ConsumeByName(item,1) elseif inv_boat and inv_boat:Has(item,1) then inv_boat:ConsumeByName(item,1) end end local function autorefuel(inst) local is_fx_true = false local fueledtable = { "armorskeleton", -- 骨甲 "lantern", -- 提灯 "lighter", -- 薇洛的打火机 "minerhat", -- 头灯 "molehat", -- 鼹鼠帽 "nightstick", -- 晨星 "thurible", -- 香炉 "yellowamulet", -- 黄符 "purpleamulet", -- 紫符 "blueamulet", -- 冰符 "bottlelantern", -- 瓶灯 in Island Adventures "nightpack", -- 新版影背包 in Civi the MOgician of Light and Dark "darkamulet", -- 黑暗护符 in Civi "lightamulet", -- 光明护符 in Civi } local boat_fueledtable = { -- Island Adventures "boat_lantern", -- 船灯 "ironwind", -- 螺旋桨 } local lotustable = { -- Civi the MOgician of Light and Dark "blacklotus", -- 黑莲 -- "darklotus", -- 暗之莲 -- "lightlotus", -- 光之莲 } local eslots = inst.components.inventory and inst.components.inventory.equipslots or nil local boat = inst.components.sailor and inst.components.sailor:GetBoat() or nil -- IA local boat_container = boat and boat.components.container or nil if eslots then for _,v in pairs(eslots) do -- for k2, v2 in pairs(fueledtable) do if table.contains(fueledtable,v.prefab) then local target = v.components.fueled if target and target:GetPercent() + TUNING.LARGE_FUEL / target.maxfuel * target.bonusmult <= 1 and CheckHasItem(inst,"nightmarefuel") then is_fx_true = true target:DoDelta(TUNING.LARGE_FUEL * target.bonusmult) ConsumeItem(inst,"nightmarefuel") if target.ontakefuelfn then target.ontakefuelfn(v) end end end -- 黑莲, 暗之莲, 光之莲 -- if table.contains(lotustable,v.prefab) then local target = v.components.finiteuses if target and target:GetPercent() <= 0.75 and CheckHasItem(inst,"nightmarefuel") then is_fx_true = true target:SetPercent( math.min(1, (target:GetPercent() + 0.25))) ConsumeItem(inst,"nightmarefuel") if v.onrefuelfn then v.onrefuelfn(v,inst) end end end end end -- Compatible for Island Adventures if boat_container then local sailslots = boat_container.boatequipslots or nil if sailslots then for _,v in pairs(sailslots) do if table.contains(boat_fueledtable,v.prefab) then local target = v.components.fueled if target and target:GetPercent() + TUNING.LARGE_FUEL / target.maxfuel * target.bonusmult <= 1 and CheckHasItem(inst,"nightmarefuel") then is_fx_true = true target:DoDelta(TUNING.LARGE_FUEL * target.bonusmult) ConsumeItem(inst,"nightmarefuel") -- if _bf.ontakefuelfn then _bf.ontakefuelfn(v) end end end end end end if is_fx_true then SpawnPrefab("pandorachest_reset").entity:SetParent(inst.entity) end end local function onboost(inst) inst.components.locomotor.runspeed = TUNING.WILSON_RUN_SPEED * 1.25 inst.components.temperature.mintemp = 10 if inst.components.eater ~= nil then inst.components.eater:SetAbsorptionModifiers(0.6, 0.6, 0.6) end end local function onupdate(inst, dt) inst.boost_time = inst.boost_time - dt if inst.boost_time <= 0 then inst.boost_time = 0 if inst.boosted_task ~= nil then inst.boosted_task:Cancel() inst.boosted_task = nil end inst.components.locomotor.runspeed = TUNING.WILSON_RUN_SPEED inst.components.temperature.mintemp = -20 if inst.components.eater ~= nil then inst.components.eater:SetAbsorptionModifiers(1, 1, 1) end if inst._dry_task ~= nil then inst._dry_task:Cancel() inst._dry_task = nil end else --boosteffect(inst) autorefuel(inst) if inst._dry_task == nil then inst._dry_task = inst:DoPeriodicTask(0,function(inst) dryequipment(inst) end) end end end local function onlongupdate(inst, dt) inst.boost_time = math.max(0, inst.boost_time - dt) end local function startboost(inst, duration) inst.boost_time = duration if inst.boosted_task == nil then inst.boosted_task = inst:DoPeriodicTask(1, onupdate, nil, 1) inst:DoTaskInTime(0, function(inst) onupdate(inst, 0) end) -- Prevent autorefuel function consumes nightmarefuels before actually "eated" onboost(inst) end end local function onload(inst,data) if data ~= nil and data.boost_time ~= nil then startboost(inst,data.boost_time) end end local function onsave(inst,data) data.boost_time = inst.boost_time > 0 and inst.boost_time or nil end local function oneat(inst,food,eater) if food and food.components.edible and food.prefab == "nightmarefuel" then local player = food.components.inventoryitem and food.components.inventoryitem.owner or nil local fx = SpawnPrefab("statue_transition") if fx and player then fx.entity:SetParent(player.entity) fx.Transform:SetScale(0.4, 0.4, 0.4) end inst.SoundEmitter:PlaySound("dontstarve/common/nightmareAddFuel") startboost(inst, 180) end end local function onbecameghost(inst) if inst.boosted_task ~= nil then inst.boosted_task:Cancel() inst.boosted_task = nil inst.boost_time = 0 end end local common_postinit = function(inst) inst.soundsname = "willow" inst:AddTag("reader") inst:AddTag("nightmarer") -- Minimap icon inst.MiniMapEntity:SetIcon("miotan.tex") end -- This initializes for the host only local master_postinit = function(inst) inst.starting_inventory = start_inv[TheNet:GetServerGameMode()] or start_inv.default inst.boost_time = 0 inst.boosted_task = nil inst:AddComponent("reader") inst.components.health:SetMaxHealth(100) inst.components.hunger:SetMax(100) inst.components.sanity:SetMax(100) inst.components.sanity.dapperness = -1/18 inst.components.sanity.night_drain_mult = -TUNING.WENDY_SANITY_MULT inst.components.sanity.neg_aura_mult = TUNING.WENDY_SANITY_MULT if inst.components.eater ~= nil then inst.components.eater:SetCanEatNightmareFuel() inst.components.eater:SetOnEatFn(oneat) inst.components.eater.stale_hunger = -0.5 inst.components.eater.stale_health = 0 inst.components.eater.spoiled_hunger = -1 inst.components.eater.spoiled_health = -0.5 end inst:ListenForEvent("ms_becameghost", onbecameghost) inst.OnLongUpdate = onlongupdate inst.OnSave = onsave inst.OnLoad = onload end return MakePlayerCharacter("miotan", prefabs, assets, common_postinit, master_postinit), CreatePrefabSkin("miotan_none", { base_prefab = "miotan", type = "base", assets = assets, skins = { normal_skin = "miotan", ghost_skin = "ghost_miotan_build" }, bigportrait = { build = "bigportrait/miotan_none.xml", symbol = "miotan_none_oval.tex"}, skin_tags = { "MIOTAN", "BASE"}, build_name_override = "miotan", rarity = "Character", }), CreatePrefabSkin("miotan_classic", { base_prefab = "miotan", type = "base", assets = { Asset( "ANIM", "anim/miotan_classic.zip" ), Asset( "ANIM", "anim/ghost_miotan_classic_build.zip" ), Asset( "ATLAS", "bigportraits/miotan_classic.xml") }, skins = { normal_skin = "miotan_classic", ghost_skin = "ghost_miotan_classic_build" }, bigportrait = { build = "bigportrait/miotan_classic.xml", symbol = "miotan_classic_oval.tex"}, skin_tags = { "MIOTAN", "BASE"}, build_name_override = "miotan_classic", rarity = "Glassic", })
-------------------------------------------------------------------------------- --- Enhanced assertions -- @module lua-nucleo.assert -- This file is a part of lua-nucleo library -- @copyright lua-nucleo authors (see file `COPYRIGHT` for the license) -------------------------------------------------------------------------------- local error = error local lassert = function(level, cond, msg, ...) if cond then return cond, msg, ... end error(msg, level + 1) end return { lassert = lassert; }
return{ name = 'star', description = 'Star', type = 'material', info = 'a star', MAX_ITEMS = 10, }
local playsession = { {"mewmew", {2819}}, {"drbln", {141575}}, {"Krengrus", {195481}}, {"QuaxzRu", {150165}}, {"Ommuden", {105533}}, {"brftjx", {695}}, {"Merssedes", {92150}}, {"Schwert3000", {2454}}, {"seeyorise", {35675}}, {"Spocks", {14490}}, {"Sp00nkY", {221}}, {"SwampD0nkey", {2584}}, {"bigjoemonger", {34969}}, {"Chesmu", {10535}} } return playsession
local fail = false print("Test: sub sm pre...") local function state_a(arg) arg.val = arg.val + 1 return stater.NEXT end local function state_b(arg) arg.val = arg.val + 1000 return stater.NEXT end local function sm_pre_run(arg) return true end local function sm_pre_skip(arg) return false end local function sm_pre_skip2(arg) return false, 4 end local arg = { val=1 } local subm = stater({ { id=1, func=state_a } }) local subm2= stater({ { id=1, func=state_b } }) local sm = stater({ { id=1, subm=subm, pre=sm_pre_skip }, { id=2, subm=subm, pre=sm_pre_skip2 }, { id=3, subm=subm2 }, { id=4, subm=subm, pre=sm_pre_run } }) ret = sm:run(arg) if ret ~= stater.DONE then print(string.format("\tFail: ret = %d, expected %d", ret, stater.DONE)) fail = true end if arg.val ~= 2 then print(string.format("\tFail: val = %d, expected %d", arg.val, 2)) fail = true end if not fail then print("\tPass") end
fx_version 'adamant' game 'gta5' client_scripts { 'config.lua', 'client/main.lua' } server_scripts { 'config.lua', 'server/main.lua', 'server/vpn/antivpn.lua' -- 'server/mainEN' ( If you want to translate to English, delete (server/main.lua) and activate (server/mainEN ) }
print("Hello from lua! :p") print("LUA:", "attempting to load: test2") print("LUA:", util.execute("test2")) util.tableprint({ "Hello", "World", "Lua", "is", "cool", false, x1 = 5, x2 = { "z", { "lul" } }, x3 = { 5 } }) util.tableprint(game) util.tableprint(util) util.tableprint(instance) print("LUA:", "creating an empty instance!") local empty_instance = instance.new("empty") print(tostring(empty_instance)) util.tableprint(empty_instance) print(empty_instance.position) util.tableprint(empty_instance)
return function() require("nvim-treesitter.configs").setup({ ensure_installed = { "jsonc", "query", "toml", "svelte", "html", "go", "javascript", "lua", "python", "typescript", "c", "cpp", "css", "scss", "yaml", "zig", }, -- one of "all", "maintained" (parsers with maintainers), or a list of languages highlight = { enable = true, -- false will disable the whole extension additional_vim_regex_highlighting = false, }, context_commentstring = { enable = true, enable_autocmd = false, config = { -- Languages that have a single comment style typescript = "// %s", css = "/* %s */", scss = "/* %s */", html = "<!-- %s -->", svelte = "<!-- %s -->", vue = "<!-- %s -->", json = "", zig = "// %s", }, }, playground = { enable = false, disable = {}, updatetime = 25, -- Debounced time for highlighting nodes in the playground from source code persist_queries = false, -- Whether the query persists across vim sessions keybindings = { toggle_query_editor = "o", toggle_hl_groups = "i", toggle_injected_languages = "t", toggle_anonymous_nodes = "a", toggle_language_display = "I", focus_language = "f", unfocus_language = "F", update = "R", goto_node = "<cr>", show_help = "?", }, }, -- TODO seems to be broken indent = { enable = true, disable = { "yaml" } }, }) end
describe("comments", function() setup(function() TOML = require "toml" end) it("everywhere", function() local obj = TOML.parse[=[ # Top comment. # Top comment. # Top comment. # [no-extraneous-groups-please] [group] # Comment answer = 42 # Comment # no-extraneous-keys-please = 999 # Inbetween comment. more = [ # Comment # What about multiple # comments? # Can you handle it? # # Evil. # Evil. 42, 42, # Comments within arrays are fun. # What about multiple # comments? # Can you handle it? # # Evil. # Evil. # ] Did I fool you? ] # Hopefully not.]=] local sol = { group = { answer = 42, more = {42, 42}, } } assert.same(sol, obj) end) end)
NULL_SIGNAL = {signal = { type = "virtual", name = "signal-black" }, count = 0} HALT_SIGNAL = {signal = { type = "virtual", name = "signal-mc-halt"}, count = 1} RUN_SIGNAL = {signal = { type = "virtual", name = "signal-mc-run"}, count = 1} STEP_SIGNAL = {signal = { type = "virtual", name = "signal-mc-step"}, count = 1} SLEEP_SIGNAL = {signal = { type = "virtual", name = "signal-mc-sleep"}, count = 1} JUMP_SIGNAL = {signal = { type = "virtual", name = "signal-mc-jump"}, count = 1} OP_NOP = {type = 'nop'} MC_LINES = 32 -- {type = "instruction", name = ""} -- {type = "description", name = "", with_example = true} -- with_note = true local OLD_HELP_TEXT = [[ -- Registers (Read/Write): mem1 mem2 mem3 mem4 out -- Registers (Read Only): mem5/ipt : Instruction pointer index mem6/cnr : Number of signals on the red wire mem7/cng : Number of signals on the green wire mem8/clk : Clock (monotonic, always runnning) -- Modules: You can connect RAM Modules or other MicroControllers by placing them above or below this MicroController. External memory is mapped to: mem11-14 (North Port 1) mem21-24 (South Port 1) mem31-34 (North Port 2) mem41-44 (South Port 2) MicroControllers can only connect to North and South port 1. --- Wires: red1 red2 redN... green1 green2 greenN... --- Pointers: mem@N : Access memN where X is the value at memN red@N : Access redX where X is the value at memN green@N : Access greenX where X is the value at memN --- Glossary: Signal : A type and integer value. Value : The integer value part of a signal. Move : Copy a signal from one source to another. Set : Set the Value of a register. Register : A place that can store a signal. Clear : Reset a register back to Black 0 (the NULL signal). Find signal : Looks for a signal that has the same type as the type stored in a register. Label : A text identifier used for jumps. --- Key: W = Wire, I = Integer M = Memory, O = Output R = Register (Memory or Output) L = Label (:id) ------- OP CODES --------- OP A B : DESCRIPTION ------------:------------- MOV W/R R...: Move signal from [A] to register(s). SET M/I R : Set [B] signal count to [A]. SWP R R : Swap [A] with [B]. CLR R... : Clear register(s). Clears all if none specified. FIR R : Find signal R from the red wire and move to mem1. FIG R : Find signal R from the green wire and move to mem1. JMP M/I/L : Jump to line [A] or label. HLT : Halt the program. NOP : No Operation. --- Arithmetic Op Codes: All arithmetic ops ignore type, type in mem1 is preserved. ADD M/I M/I : Add [A] + [B], store result in mem1. SUB M/I M/I : Subtract [A] - [B], store result in mem1. MUL M/I M/I : Multiply [A] * [B], store result in mem1. DIV M/I M/I : Divide [A] / [B], store result in mem1. MOD M/I M/I : Modulo [A] % [B], store result in mem1. POW M/I M/I : Raise [A] to power of [B], store result in mem1. DIG M/I : Gets the [A]th digit from mem1, store result in mem1. DIS M/I M/I : Sets the [A]th digit from mem1 to the 1st digit from [B]. BND M/I M/I : Bitwise [A] AND [B] BOR M/I M/I : Bitwise [A] OR [B] BXR M/I M/I : Bitwise [A] XOR [B] BNO M/I : Bitwise NOT [A] BLS M/I M/I : Bitwise LEFT SHIFT [A] by [B] BRS M/I M/I : Bitwise RIGHT SHIFT [A] by [B] BLR M/I M/I : Bitwise LEFT ROTATE [A] by [B] BRR M/I M/I : Bitwise RIGHT ROTATE [A] by [B] --- Test Op Codes: Test Ops will skip the next line if the test is successful. TGT M/I M/I : Tests if [A] value greater than [B] value. TLT M/I M/I : Tests if [A] value less than [B] value. TEQ M/I M/I : Tests if [A] value equals [B] value. TNQ M/I M/I : Tests if [A] value does not equal [B] value. TTE M M : Tests if [A] type equals [B] type. TTN M M : Tests if [A] type does not equal [B] type. --- Blocking Op Codes: Blocking Ops will pause the program until the operation is complete. SLP M/I : Sleep for [A] ticks. BKR M/I : Block until there's [a]+ signals on the red wire. BKG M/I : Block until there's [a]+ signals on the green wire. SYN : Blocks until all other connected microcontrollers SYN. --- Interrupts: You can send interrupting signals to a microcontroller. There are: HLT (halt), RUN (run), STP (step), SLP (sleep) and JMP (jump). If a microcontroller receives any one of these signals it will execute them immediately. ------------------------------------------------------------------------- ------------------------------------------------------------------------- -- Example 1: # Outputs the first signal # from red multiplied by 2. mov red1 mem1 mul mem1 2 mov mem1 out jmp 2 -- Example 2: # accumulates first 4 # signals on the red wire. :SETUP clr set 11 mem2 set 1 mem3 :LOOP mov red@3 mem1 add mem1 mem@2 mov mem1 mem@2 :NEXT add mem2 1 tlt mem1 15 set 11 mem1 mov mem1 mem2 add mem3 1 tlt mem1 5 set 1 mem1 mov mem1 mem3 jmp :LOOP ]] local BIS_DESCRIPTION = [[ local BIS_DESCRIPTION = [[ <:I> specifies a parameter that takes a literal integer. <:R> specifies a parameter that takes a register address. <:W> specifies a parameter that takes a register address. <:L> specifies a parameter that takes a register address. ]] local EXAMPLE1 = ":LOOP\njmp :LOOP" local EXAMPLE2 = "fig mem21\nmul mem1 2\nmov mem1 out" local EXAMPLE3 = ":60 second clock.\nadd mem1 1\nmod mem1 60\njmp 1" local EXAMPLE4 = [[ mov red1 mem1 mul mem1 2 mov mem1 out ]] local EXAMPLE5 = [[ clr set 11 mem2 set 3 mem2 :loop mov red@3 mem1 add mem1 mem@2 mov mem1 mem@2 add mem2 1 tlt mem1 15 set 11 mem1 mov mem1 mem2 add mem3 1 tlt mem1 5 set 1 mem1 mov mem1 mem3 ]] DOCS = { { name = "overview", content = { {name = "registers"}, {name = "mapped-memory"} } }, { name = "glossary", content = { {name = "signal_glossary"}, {name = "type_glossary"}, {name = "value_glossary"}, {name = "move_glossary"}, {name = "set_glossary"}, {name = "register_glossary"}, {name = "clear_glossary"}, {name = "null_glossary"}, {name = "label_glossary"} } }, { name = "basic_instructions_set", content = { {example = BIS_DESCRIPTION}, {name = "description_BIS"}, {name = "comments_BIS", syntax = "#<comment>"}, {name = "labels_BIS", syntax = "#<label>", example = EXAMPLE1}, {name = "NOP_BIS", syntax = "nop"}, {name = "MOV_BIS", syntax = "mov <SRC:W/R> <DST:R>"}, {name = "SET_BIS", syntax = "set <SRC:I> <DST:R>"}, {name = "SWP_BIS", syntax = "swp <SRC:R> <DST:R>"}, {name = "CLR_BIS", syntax = "clr <DST:R>…"}, {name = "FIG_BIS", syntax = "fig <SRC:R>", example = EXAMPLE2}, {name = "FIR_BIS", syntax = "fir <SRC:R>"}, {name = "JMP_BIS", syntax = "jmp <SRC:I/R/L>", example = EXAMPLE1}, {name = "HLT_BIS", syntax = "hlt <SRC:R>"} } }, { name = "arithmetic_instructions", content = { {name = "ADD_AI", syntax = "add <SRC:I/R> <DST:I/R>"}, {name = "SUB_AI", syntax = "sub <SRC:I/R> <DST:I/R>"}, {name = "MUL_AI", syntax = "mul <SRC:I/R> <DST:I/R>"}, {name = "DIV_AI", syntax = "div <SRC:I/R> <DST:I/R>"}, {name = "MOD_AI", syntax = "mod <SRC:I/R> <DST:I/R>", example = EXAMPLE3}, {name = "POW_AI", syntax = "pow <SRC:I/R> <DST:I/R>"}, {name = "DIG_AI", syntax = "swp <SRC:I/R>"}, {name = "DIS_AI", syntax = "dis <SRC:I/R> <DST:I/R>"}, {name = "BND_AI", syntax = "bnd <SRC:I/R> <DST:I/R"}, {name = "BOR_AI", syntax = "bor <SRC:I/R> <DST:I/R>"}, {name = "BXR_AI", syntax = "bxr <SRC:I/R> <DST:I/R>"}, {name = "BND2_AI", syntax = "bnd <SRC:I/R>"}, {name = "BLS_AI", syntax = "bls <SRC:I/R> <DST:I/R>"}, {name = "BRS_AI", syntax = "brs <SRC:I/R> <DST:I/R>"}, {name = "BLR_AI", syntax = "blr <SRC:I/R> <DST:I/R>"}, {name = "BRR_AI", syntax = "brr <SRC:I/R> <DST:I/R>"} } }, { name = "test_instructions", content = { {name = "TGT_TI", syntax = "tgt <SRC:I/R> <DST:I/R>"}, {name = "TLT_TI", syntax = "tlt <SRC:I/R> <DST:I/R>"}, {name = "TEQ_TI", syntax = "teq <SRC:I/R> <DST:I/R>"}, {name = "TTE_TI", syntax = "tte <SRC:R> <DST:R>"}, {name = "TTN_TI", syntax = "ttn <SRC:R> <DST:R>"} } }, { name = "blocking_instructions", content = { {name = "SLP_BI", syntax = "slp <SRC:I/R>"}, {name = "BKR_BI", syntax = "bkr <SRC:I/R>"}, {name = "BKG_BI", syntax = "bkg <SRC:I/R>"}, {name = "SYN_BI", syntax = "SYN"} } }, { name = "interrupt_signals", content = { {name = "HLT_IS"}, {name = "RUN_IS"}, {name = "STP_IS"}, {name = "SLP_IS"}, {name = "JMP_IS"} } }, { name = "pointers", content = { {name = "MEM_pointer"}, {name = "RED_pointer"}, {name = "GREEN_pointer"} } }, { name = "example_programs", content = { {name = "MULTIPLY_INPUT_EP", example = EXAMPLE4}, {name = "ACCUMULATE_INPUT_EP", example = EXAMPLE5}, } }, { name = "old-help-text", content = { {example = OLD_HELP_TEXT} } } }
--- Module which provides transport level interface for emulate connection with HMI for SDL -- -- *Dependencies:* `json`, `qt`, `network` -- -- *Globals:* `atf_logger`, `qt`, `network` -- @module websocket_connection -- @copyright [Ford Motor Company](https://smartdevicelink.com/partners/ford/) and [SmartDeviceLink Consortium](https://smartdevicelink.com/consortium/) -- @license <https://github.com/smartdevicelink/sdl_core/blob/master/LICENSE> local json = require("json") local WS = { mt = { __index = {} } } --- Type which provides transport level interface for emulate connection with HMI for SDL -- @type WebSocketConnection --- Construct instance of WebSocketConnection type -- @tparam string url URL for websocket -- @tparam number port Port for Websocket -- @treturn WebSocketConnection Constructed instance function WS.Connection(params) local res = { url = params.url, port = params.port } res.socket = network.WebSocket() setmetatable(res, WS.mt) res.qtproxy = qt.dynamic() return res end --- Connect with SDL function WS.mt.__index:Connect() self.socket:open(self.url, self.port, config.connectionTimeout) end --- Check 'self' argument local function checkSelfArg(s) if type(s) ~= "table" or getmetatable(s) ~= WS.mt then error("Invalid argument 'self': must be connection (use ':', not '.')") end end --- Send message from HMI to SDL -- @tparam string text Message function WS.mt.__index:Send(data) local text if type(data) == "table" then text = json.encode(data) else text = data end atf_logger.LOG("HMItoSDL", text) self.socket:write(text) end --- Set handler for OnInputData -- @tparam function func Handler function function WS.mt.__index:OnInputData(func) local d = qt.dynamic() local this = self function d:textMessageReceived(text) atf_logger.LOG("SDLtoHMI", text) local data = json.decode(text) --print("ws input:", text) func(this, data) end qt.connect(self.socket, "textMessageReceived(QString)", d, "textMessageReceived(QString)") end --- Set handler for OnDataSent -- @tparam function func Handler function function WS.mt.__index:OnDataSent(func) local d = qt.dynamic() local this = self function d:bytesWritten(num) func(this, num) end qt.connect(self.socket, "bytesWritten(qint64)", d, "bytesWritten(qint64)") end --- Set handler for OnConnected -- @tparam function func Handler function function WS.mt.__index:OnConnected(func) if self.qtproxy.connected then error("Websocket connection: connected signal is handled already") end local this = self self.qtproxy.connected = function() func(this) end qt.connect(self.socket, "connected()", self.qtproxy, "connected()") end --- Set handler for OnDisconnected -- @tparam function func Handler function function WS.mt.__index:OnDisconnected(func) if self.qtproxy.disconnected then error("Websocket connection: disconnected signal is handled already") end local this = self self.qtproxy.disconnected = function() func(this) end qt.connect(self.socket, "disconnected()", self.qtproxy, "disconnected()") end --- Close connection function WS.mt.__index:Close() checkSelfArg(self) self.socket:close(); end return WS
LoseFrame = {} LoseFrame.__index = LoseFrame local ViewWidth = 1024 local ViewHeight = 576 local FrameCooldown = 1.0 function LoseFrame:New() local self = {} self.screenSpace = Graphics.ScreenSpace() self.timer = 0.0 setmetatable(self, LoseFrame) return self end function LoseFrame:Process(event) if event.type == Event.KeyDown then if self.timer > FrameCooldown then -- Change state to menu frame. Main.loseFrame = nil Main.stateMachine:Change(Main.menuFrame) end return true end return false end function LoseFrame:Update(timeDelta) -- Update the frame transition cooldown. self.timer = self.timer + timeDelta end function LoseFrame:Draw() -- Setup screen space. local windowWidth = Console.GetInteger("r_width") local windowHeight = Console.GetInteger("r_height") self.screenSpace:SetSourceSize(windowWidth, windowHeight) self.screenSpace:SetTargetSize(ViewWidth, ViewHeight) -- Clear the screen buffer. CoreRenderer:SetClearColor(Vec4(1.0, 1.0, 1.0, 1.0)) CoreRenderer:SetClearDepth(1.0) CoreRenderer:Clear(bit.bor(ClearFlags.Color, ClearFlags.Depth)) -- Draw the game over text. do local info = Graphics.TextDrawInfo() info.font = Graphics.GetDefaultFont() info.size = 128 info.align = TextDrawAlign.Centered info.bodyColor = Vec4(1.0, 1.0, 1.0, 1.0) info.outlineColor = Vec4(0.0, 0.0, 0.0, 1.0) info.outlineRange = Vec2(0.45, 0.55) info.position = Vec2(ViewWidth * 0.5, ViewHeight * 0.7) TextRenderer:Draw(info, "Game Over", self.screenSpace:GetTransform()) end do local info = Graphics.TextDrawInfo() info.font = Graphics.GetDefaultFont() info.size = 48 info.align = TextDrawAlign.Centered info.bodyColor = Vec4(0.0, 0.0, 0.0, 1.0) info.position = Vec2(ViewWidth * 0.5, ViewHeight * 0.5) TextRenderer:Draw(info, "Press any key to continue...", self.screenSpace:GetTransform()) end end setmetatable(LoseFrame, { __call = LoseFrame.New })
require "defines" require "GUI" taxiStations = {"#callFARL", "#callSupply"} function createMainUI(player) if player.gui.top.trainTaxi then player.gui.top.trainTaxi.destroy() end GUI.add(player.gui.top, {type="frame", name="trainTaxi", direction="vertical", style="outer_frame_style"}) end function onTrainStopOpened(player) --player.print("Opened") local ui = GUI.add(player.gui.top.trainTaxi, {type="frame", name="ui", style="trainTaxi_frame"}) for i,s in pairs(taxiStations) do GUI.addButton(ui, {name="setName"..i, caption=s}, GUI.rename) end end function onTrainStopClosed(player) --player.print("Closed") player.gui.top.trainTaxi.ui.destroy() end function ontick(event) if event.tick%10==8 then for pi, player in ipairs(game.players) do if not player.gui.top.trainTaxi then createMainUI(player) end if player.opened ~= nil and player.opened.valid then if player.opened.type == "train-stop" then if player.gui.top.trainTaxi.ui == nil then onTrainStopOpened(player) end end elseif player.opened == nil then local gui=player.gui.top.trainTaxi.ui if gui then onTrainStopClosed(player) end end end end end function onguiclick(event) local index = event.playerindex or event.name local player = game.players[index] if player.gui.top.trainTaxi ~= nil and player.gui.top.trainTaxi.ui ~= nil then GUI.onGuiClick(event, player) end end function ontrainchangedstate(event) local train = event.train local schedule = train.schedule if train.state == defines.trainstate["waitstation"] then for _,station in pairs(taxiStations) do if schedule.records[schedule.current].station == station then train.manualmode = true end end end end game.onevent(defines.events.ontick, ontick) game.onevent(defines.events.onguiclick, onguiclick) game.onevent(defines.events.ontrainchangedstate, ontrainchangedstate)
hp = 1000 attack = 245 defense = 200 speed = 30 mdefense = 240 luck = 40 float = 0 strength = ELEMENT_NONE weakness = ELEMENT_NONE function initId(id) myId = id end function start() end function get_action(step) if (getRandomNumber(2) == 0) then return COMBAT_CASTING, "Vampire", 1, getRandomPlayer() else return COMBAT_ATTACKING, 1, getRandomPlayer() end end function die() end
M={} function oa_key(k) return string.format(" key code %d \n", k) end function oa_command(cmd) return string.format(" keystroke \"%s\"\nkeystroke return\ndelay .1 \n", cmd) end function commands_to_oa(commands) local o = "" for k,t in pairs(commands) do o = o .. oa_command(t) end return o end function M.load_and_run(dest) local commands = { "load " .. dest } local preamble = "osascript -e 'tell application \"PICO-8\" to activate' -e 'tell application \"System Events\" \n delay .1\n" local postamble = " key code 15 using control down \n end tell'" local whole = preamble .. commands_to_oa(commands) .. postamble os.execute(whole) end return M
--- Provide gzip utility functions. -- @module jls.util.zip.gzip local logger = require('jls.lang.logger') local StringBuffer = require('jls.lang.StringBuffer') local Deflater = require('jls.util.zip.Deflater') local Inflater = require('jls.util.zip.Inflater') local StreamHandler = require('jls.io.streams.StreamHandler') local Crc32 = require('jls.util.md.Crc32') -- see https://tools.ietf.org/html/rfc1952 local gzip = {} local FLAGS = { TEXT = 1, HCRC = 2, EXTRA = 4, NAME = 8, COMMENT = 16 } function gzip.formatHeader(header) local compressionMethod = 8 local flags = 0 local mtime = 0 local extraFlags = 0 local os = 3 -- Unix local name, comment, extra if header then if type(header.modificationTime) == 'number' then mtime = header.modificationTime end if type(header.os) == 'number' then os = header.os end if type(header.extra) == 'string' then extra = header.extra flags = flags | FLAGS.EXTRA end if type(header.name) == 'string' then name = header.name flags = flags | FLAGS.NAME end if type(header.comment) == 'string' then comment = header.comment flags = flags | FLAGS.COMMENT end end local buffer = StringBuffer:new() buffer:append(string.pack('<BBBBI4BB', 0x1f, 0x8b, compressionMethod, flags, mtime, extraFlags, os)) if extra then buffer:append(string.pack('<I2', #extra)) buffer:append(extra) end if name then buffer:append(name) buffer:append('\0') end if comment then buffer:append(comment) buffer:append('\0') end return buffer:toString() end function gzip.parseHeader(data) local size = #data if size < 10 then return end local id1, id2, compressionMethod, flags, mtime, extraFlags, os = string.unpack('<BBBBI4BB', data) if id1 ~= 0x1f or id2 ~= 0x8b then return nil, nil, 'Invalid magic identification bytes' end local name, comment, extra local offset = 11 if flags & FLAGS.EXTRA ~= 0 then if size < 12 then return end local extraSize = string.unpack('<I2', data, 11) offset = 13 + extraSize if size < offset then return end extra = string.sub(data, 13, offset) end if flags & FLAGS.NAME ~= 0 then local index = string.find(data, '\0', offset, true) if not index then return end name = string.sub(data, offset, index - 1) offset = index + 1 end if flags & FLAGS.COMMENT ~= 0 then local index = string.find(data, '\0', offset, true) if not index then return end comment = string.sub(data, offset, index - 1) offset = index + 1 end return { modificationTime = mtime, os = os, name = name, comment = comment, extra = extra, }, offset - 1 end --[[-- Returns a @{jls.io.streams.StreamHandler} that will compress into the specified stream handler. See @{jls.util.zip.Deflater} @param sh the stream handler to call with the deflated data @tparam[opt] table header the gzip header table @tparam[opt] number compressionLevel the compression level @return the @{jls.io.streams.StreamHandler} @usage local gzip = require('jls.util.zip.gzip') local FileStreamHandler = require('jls.io.streams.FileStreamHandler') local sh = gzip.compressStream(FileStreamHandler:new('test.txt.gz')) FileStreamHandler.readAllSync('test.txt', sh) ]] function gzip.compressStream(sh, header, compressionLevel) local cb = StreamHandler.ensureCallback(sh) cb(nil, gzip.formatHeader(header)) local size = 0 local crc = Crc32:new() local deflater = Deflater:new(compressionLevel, -15) return StreamHandler:new(function(err, data) if err then return cb(err) end if data then crc:update(data) size = size + #data cb(nil, deflater:deflate(data)) else cb(nil, deflater:finish()..string.pack('<I4I4', crc:final(), size)) cb(nil, nil) end end) end --[[-- Returns a @{jls.io.streams.StreamHandler} that will decompress into the specified stream handler. See @{jls.util.zip.Inflater} @param sh the stream handler to call with the inflated data @tparam[opt] function onHeader a function that will be called with the header table @return the @{jls.io.streams.StreamHandler} @usage local gzip = require('jls.util.zip.gzip') local FileStreamHandler = require('jls.io.streams.FileStreamHandler') local sh = gzip.decompressStream(FileStreamHandler:new('test.txt')) FileStreamHandler.readAllSync('test.txt.gz', sh) ]] function gzip.decompressStream(sh, onHeader) if logger:isLoggable(logger.FINER) then logger:finer('decompressStream()') end local cb = StreamHandler.ensureCallback(sh) local header, inflated local buffer = '' local size = 0 local crc = Crc32:new() local inflater = Inflater:new(-15) return StreamHandler:new(function(err, data) if err then return cb(err) end if header then if buffer then local footer if data then if #data < 8 then -- do not consume the buffer if data is less than footer buffer = buffer..data return end else local bufferSize = #buffer footer = string.sub(buffer, bufferSize - 7) buffer = string.sub(buffer, 1, bufferSize - 8) if logger:isLoggable(logger.FINER) then logger:finer('footer'..require('jls.util.hex').encode(footer)) end end inflated = inflater:inflate(buffer) crc:update(inflated) size = size + #inflated cb(nil, inflated) if data then buffer = data else local crcFooter, sizeFooter = string.unpack('<I4I4', footer) if logger:isLoggable(logger.FINER) then logger:finer('decompressStream() CRC '..tostring(crc:final())..'/'..tostring(crcFooter)..', size '..tostring(size)..' expected '..tostring(sizeFooter)) end if crcFooter ~= crc:final() then cb('Bad CRC (found '..tostring(crc:final())..' expected '..tostring(crcFooter)..')') elseif sizeFooter ~= size then cb('Bad size (found '..tostring(size)..' expected '..tostring(sizeFooter)..')') else cb() end if logger:isLoggable(logger.FINER) then logger:finer('decompressStream() completed') end end end else local err, headerSize buffer = buffer..data header, headerSize, err = gzip.parseHeader(buffer) if err then return cb(err) end if header then if type(onHeader) == 'function' then onHeader(header) end buffer = string.sub(buffer, headerSize + 1) else return end end end) end function gzip.compressStreamRaw(stream, compressionLevel) return Deflater.deflateStream(stream, compressionLevel) end function gzip.decompressStreamRaw(stream) return Inflater.inflateStream(stream) -- auto detect end return gzip
-- items: 1673 function event_trade(e) local item_lib = require("items"); if e.other:GetFactionLevel(e.other:CharacterID(), e.self:GetID(), e.other:GetRace(), e.other:GetClass(), e.other:GetDeity(), 404, e.self) == 1 then if(item_lib.check_turn_in(e.trade, {item1 = 1673})) then e.self:Emote("looks down at the tear in his hand and says 'A minion of my god came to me one night. I knew it was of Cazic-Thule as I was frozen in terror. My mind screamed for me to flee but my body would not respond. The being took my daughter and vanished to only he knew where. When I regained control of my body and thoughts, I felt nothing but betrayal. I don't care anymore about anything. If you want repentance then slay me, " .. e.other:GetName() .."."); eq.depop() e.other:Ding(); e.other:Faction(404,100); -- true spirit eq.spawn2(90183,0,0,e.self:GetX(),e.self:GetY(),e.self:GetZ(),e.self:GetHeading()); -- NPC: #Lord_Rak`Ashiir_ end else e.self:Say("Go away! We don't have time for the likes of you."); end item_lib.return_items(e.self, e.other, e.trade) end
--[[ © 2020 TERRANOVA do not share, re-distribute or modify without permission of its author. --]] ITEM.name = "Coffee Pot"; ITEM.model = "models/props_office/coffe_pot.mdl"; ITEM.width = 2; ITEM.height = 2; ITEM.description = "A large coffee pot with a glass carafe."; ITEM.capacity = 1650
local colorscheme = "tokyonight" -- tokyonight -- OceanicNext -- gruvbox -- zephyr -- nord -- onedark -- nightfox local status_ok, _ = pcall(vim.cmd, "colorscheme " .. colorscheme) if not status_ok then vim.notify("colorscheme: " .. colorscheme .. " 没有找到!") return end
ITEM.name = "Eye" ITEM.model ="models/nasca/etherealsrp_artifacts/eye.mdl" ITEM.description = "This artifact looks like an eye." ITEM.longdesc = "This artifact, which resembles the human eye, considerably increases metabolism of the body, helping wounds heal quicker. Experienced stalkers say that Eye also brings luck. Irrespective of the validity of that statement, its positive effects are indeed quite potent. First of all, it reduces temperature of user's body and cools all objects in its vicinity. Secondly, it provides substantial protection against all types of acids by gradually increasing their pH to the level of water (pH of 7). Thirdly, this artifact soothes the pain and is extremely useful when treating wounds. These beneficial qualities, however, come at a price. This artifact is extremely dangerous when exposed to chemical anomalies as it amplifies their toxicity and increases their potency. It is hence highly recommended to keep the artifact in your backpack, never on the body, when exploring toxic areas unless you have a death wish. The artifact is also known colloquially as 'copper eye' as it conducts electricity and amplifies its dangerous effects in the same way as copper does. Very rare artifact." ITEM.width = 1 ITEM.height = 1 ITEM.price = 30000 ITEM.flag = "A" ITEM.value = ITEM.price*0.5
a = {} a.b = {} a.b.c = function() print "hello" end a.b.c() ax = {} ax.by = {} ax.by.cz = function() print "hello" end ax.by.cz()
require('playback') ui = { play = function() playingBack = not playingBack if (ACTION_INDEX-1)/#ACTIONS == 1 then resetEverything() end end, step = function() playingBack = false delay_timer = -1 end, reset = function() resetEverything() end, back = function() playingBack = false local index = ACTION_INDEX-2 if index < 0 then index = 0 end resetEverything() for i=1,index do executeAction(ACTIONS[i],true) end end, debug = function() debugModeWrapper.state = not debugModeWrapper.state end, faster = function() DELAY_TIMER_SET = DELAY_TIMER_SET - .05 if DELAY_TIMER_SET < .05 then DELAY_TIMER_SET = .05 end end, slower = function() DELAY_TIMER_SET = DELAY_TIMER_SET + .05 if DELAY_TIMER_SET > 1 then DELAY_TIMER_SET = 1 end end } keybind = {} keybind['space'] = ui.play keybind['w'] = ui.play keybind['e'] = ui.step keybind['q'] = ui.back keybind['r'] = ui.reset keybind['d'] = ui.debug keybind['right'] = ui.step keybind['left'] = ui.back keybind['a'] = ui.slower keybind['d'] = ui.faster -- Built in function that's called every keypress function love.keypressed(key, scancode, isrepeat) if keybind[scancode] then keybind[scancode]() end end
-- Module: copax.lock -- Version: 0.1 -- Author: Bruno Silvestre local copas = require("copas") ------------------------------------------------------------------------------- local function acquire(l) while l.locked and ( (not l.reentrant) or (l.current ~= coroutine.running()) ) do table.insert(l.queue, (coroutine.running())) copas.sleep(-1) end l.locked = true l.current = coroutine.running() end local function release(l) if l.locked then l.current = nil l.locked = false local co = table.remove(l.queue, 1) if co then copas.wakeup(co) end end end local meta = { __index = { acquire = acquire, release = release, } } ------------------------------------------------------------------------------- local Module = {} function Module.create(init, reentrant) local l = { locked = init, reentrant = reentrant, current = nil, queue = {}, } return setmetatable(l, meta) end return Module
return PlaceObj("ModDef", { "title", "WasteRock Prod Info", "version", 3, "version_major", 0, "version_minor", 3, "saved", 0, "image", "Preview.png", "id", "ChoGGi_WasterockProdInfo", "steam_id", "1816128962", "pops_any_uuid", "10811f3f-2a27-4ecb-a34a-17eef76d7385", "author", "ChoGGi", "lua_revision", 249143, "code", { "Code/Script.lua", }, "TagInterface", true, "description", [[Adds Production counts for WasteRock to resource producers, and Consumption added to WasteRock consumers (daily estimate). Requested by sbp_reborn_again.]], })
C_LevelSquish = {} ---@param level number ---@param maxFollowerLevel number ---@return number squishedLevel ---[Documentation](https://wow.gamepedia.com/API_C_LevelSquish.ConvertFollowerLevel) function C_LevelSquish.ConvertFollowerLevel(level, maxFollowerLevel) end ---@param level number ---@return number squishedLevel ---[Documentation](https://wow.gamepedia.com/API_C_LevelSquish.ConvertPlayerLevel) function C_LevelSquish.ConvertPlayerLevel(level) end
--!A cross-toolchain build utility based on Lua -- -- 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. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file check.lua -- -- imports import("core.base.option") import("core.project.config") import("detect.sdks.find_ndk") import("detect.sdks.find_android_sdk") -- check the ndk toolchain function _check_ndk(toolchain) local ndk for _, package in ipairs(toolchain:packages()) do local installdir = package:installdir() if installdir and os.isdir(installdir) then ndk = find_ndk(installdir, {force = true, verbose = option.get("verbose"), plat = toolchain:plat(), arch = toolchain:arch(), sdkver = toolchain:config("sdkver")}) if ndk then break end end end if not ndk then ndk = find_ndk(toolchain:config("ndk") or config.get("ndk"), {force = true, verbose = true, plat = toolchain:plat(), arch = toolchain:arch(), sdkver = toolchain:config("sdkver")}) end if ndk then toolchain:config_set("ndk", ndk.sdkdir) toolchain:config_set("bindir", ndk.bindir) toolchain:config_set("cross", ndk.cross) toolchain:config_set("llvm_toolchain", ndk.llvm_toolchain) toolchain:config_set("gcc_toolchain", ndk.gcc_toolchain) toolchain:config_set("ndkver", ndk.ndkver) toolchain:config_set("ndk_sdkver", ndk.sdkver) toolchain:config_set("ndk_toolchains_ver", ndk.toolchains_ver) toolchain:config_set("ndk_sysroot", ndk.sysroot) toolchain:configs_save() return true else --[[TODO we need also add this tips when use remote ndk toolchain -- failed cprint("${bright color.error}please run:") cprint(" - xmake config --ndk=xxx") cprint("or - xmake global --ndk=xxx") raise()]] end end -- check the android sdk function _check_android_sdk(toolchain) local sdk = find_android_sdk(toolchain:config("android_sdk") or config.get("android_sdk"), {force = true, verbose = toolchain:is_global()}) if sdk then toolchain:config_set("android_sdk", sdk.sdkdir) toolchain:config_set("build_toolver", sdk.build_toolver) toolchain:configs_save() end end -- main entry function main(toolchain) _check_android_sdk(toolchain) return _check_ndk(toolchain) end
local protobuf = require "gw.codec.protobuf" local codec = {} --- 新建codec实例 -- @param[type=table] conf 配置 -- @usage -- -- protobuf -- local codecobj = codec.new({ -- type = "protobuf", -- pbfile = "proto/protobuf/all.bytes", -- idfile = "proto/protobuf/message_define.bytes", -- }) function codec.new(conf) local self = {} if conf.type == "protobuf" then self.proto = protobuf.new(conf) else assert(false, conf.type) end return setmetatable(self, {__index = codec}) end --- 重新加载协议 function codec:reload() self.proto:reload() end --- 打包消息 -- @param[type=table] msg 消息 -- @return[type=string] 打出的二进制数据 -- @usage -- local bin = codecobj:pack_message({ -- ud = ud, -- 自定义数据 -- cmd = cmd, -- 协议名 -- args = args, -- 协议参数 -- }) function codec:pack_message(msg) return self.proto:pack_message(msg) end --- 解包消息 -- @param[type=string] msg 消息二进制数据 -- @return[type=table] 解出的消息 function codec:unpack_message(msg) return self.proto:unpack_message(msg) end return codec
AddCSLuaFile() ENT.Base = "gballoon_tower_base" ENT.Type = "anim" ENT.PrintName = "Orb of Cold" ENT.Category = "#rotgb.category.tower" ENT.Author = "Piengineer12" ENT.Contact = "http://steamcommunity.com/id/Piengineer12/" ENT.Purpose = "#rotgb.tower.gballoon_tower_05.purpose" ENT.Instructions = "" ENT.Spawnable = false ENT.AdminOnly = false ENT.RenderGroup = RENDERGROUP_BOTH ENT.Model = Model("models/hunter/misc/cone1x05.mdl") ENT.FireRate = 0.4 ENT.Cost = 450 ENT.DetectionRadius = 256 ENT.AbilityCooldown = 30 ENT.FireWhenNoEnemies = true ENT.UseLOS = true ENT.LOSOffset = Vector(0,0,40) ENT.AttackDamage = 0 ENT.rotgb_ShardDamage = 10 --ENT.rotgb_FreezeFireRate = 1 ENT.rotgb_FreezeTime = 1 ENT.rotgb_SpeedPercent = 1 ENT.rotgb_FireRateMul = 1 ENT.UpgradeReference = { { Names = {"Snappy Freezing","Thorough Freezing","Snappier Freezing","Breakneck Freezing","Snappiest Freezing","Fiery Freezing"}, Descs = { "Pops one layer when freezing gBalloons.", "gBalloons move 50% slower after frozen, for 3 seconds.", "Considerably increases freezing damage.", "Considerably increases freezing rate and tremendously increases freezing damage.", "Colossally increases freezing damage! Frozen gBalloons also lose all damage type immunities while frozen (if they can be frozen).", "Freezing gBalloons now sets them on fire, dealing 500 layers of damage over 5 seconds! gBalloons that are immune to freezing can be affected by this upgrade." }, Prices = {500,2750,3500,35000,375000,1e6}, Funcs = { function(self) self.AttackDamage = self.AttackDamage + 10 end, function(self) self.rotgb_SpeedPercent = self.rotgb_SpeedPercent * 0.5 end, function(self) self.AttackDamage = self.AttackDamage + 10 end, function(self) self.FireRate = self.FireRate * 2 self.AttackDamage = self.AttackDamage + 40 end, function(self) self.AttackDamage = self.AttackDamage + 240 self.rotgb_PowerFreeze = true end, function(self) self.rotgb_FireLight = true end } }, { Names = {"Greater Influence","Better Coolant","Below Zero","Winds of Antarctica","Ice Sign: Absolute Zero","The World of White Wonderland"}, Descs = { "Slightly increases freezing range.", "Slightly increases freezing duration.", "Freezing now causes ALL layers to be frozen. Enables the tower to freeze Blue gBlimps and lower non-white gBalloons.", "Red gBlimps and lower within radius move 50% slower, even if hidden.", "Once every 30 seconds, shooting at this tower causes ALL gBalloons to move 75% slower for 15 seconds. This ability does not affect newly spawned gBalloons.", "Considerably increases freezing range and all gBalloons move 75% slower regardless of range. Once every 30 seconds, shooting at this tower freezes all Green gBlimps and lower regardless of immunities in addition to slowing them down for 15 seconds." }, Prices = {200,950,7500,100000,200000,25e6}, Funcs = { function(self) self.DetectionRadius = self.DetectionRadius * 1.5 end, function(self) self.rotgb_FreezeTime = self.rotgb_FreezeTime * 1.5 --self.rotgb_FreezeBoost = true end, function(self) self.rotgb_Intense = true end, function(self) self.rotgb_SpeedSlowdown = true end, function(self) --self.rotgb_Viral = true self.HasAbility = true end, function(self) self.DetectionRadius = self.DetectionRadius * 2 self.rotgb_Wonderland = true end, } }, { Names = {"Agitated Core","Quick Refresher","Angered Core","Cold Play","Icicle Storm","Blizzard and Hail"}, Descs = { "The Orb of Cold now fires ice shards which pop one layer per shot.", "Slightly increases shard fire rate and freezing rate.", "Tremendously increases shard fire rate and damage.", "Colossally increases shard damage and shards gain infinite range. Will still freeze gBalloons only in its original radius.", "Increases shard fire rate by 1% per RgBE of every gBalloon within range.", "Every time a shard hits a gBalloon, shard damage is increased by 1/10th of a layer. All bonus damage is lost when no gBalloons can be attacked with shards." }, Prices = {250,1750,2750,30000,275000,2.5e6}, Funcs = { function(self) self.FireRate = self.FireRate * 5 self.rotgb_FireRateMul = self.rotgb_FireRateMul * 5 self.UserTargeting = true end, function(self) self.FireRate = self.FireRate * 1.5 end, function(self) self.FireRate = self.FireRate * 3 self.rotgb_FireRateMul = self.rotgb_FireRateMul * 3 self.rotgb_ShardDamage = self.rotgb_ShardDamage + 20 end, function(self) self.rotgb_ShardDamage = self.rotgb_ShardDamage + 120 self.InfiniteRange = true end, function(self) self.rotgb_FireRateBoost = true end, function(self) self.rotgb_DamageBoost = true end } } } ENT.UpgradeLimits = {6,2,0} function ENT:ROTGB_ApplyPerks() self.rotgb_SpeedPercent = self.rotgb_SpeedPercent * (1+hook.Run("GetSkillAmount", "orbOfColdSpeedPercent")/100) end function ENT:DoFreeze(ent) if self:ValidTarget(ent) then if self.rotgb_FireLight then ent:RotgB_Ignite(1000, self:GetTowerOwner(), self, 5) end if not ent:GetBalloonProperty("BalloonBlimp") or self.rotgb_Intense and ent:GetRgBE()<=ent:GetRgBEByType("gballoon_blimp_blue") then if self.rotgb_Intense then ent:Freeze2(self.rotgb_FreezeTime) else ent:Freeze(self.rotgb_FreezeTime) end if self.rotgb_SpeedPercent ~= 1 then ent:Slowdown("ROTGB_ICE_TOWER",self.rotgb_SpeedPercent,3+self.rotgb_FreezeTime) end if self.rotgb_PowerFreeze then ent:InflictRotgBStatusEffect("unimmune",1) end else ent:ShowResistEffect(1) end end end function ENT:FireFunction(gBalloons) self.rotgb_Freezer = (self.rotgb_Freezer or 0) + --[[self.rotgb_FreezeFireRate]]1/self.rotgb_FireRateMul if self.rotgb_Freezer >= 1 then self.FireWhenNoEnemies = false end if self.rotgb_Freezer >= 1 and next(gBalloons) then self.rotgb_Freezer = self.rotgb_Freezer - 1 self.FireWhenNoEnemies = true local drrt = self.DetectionRadius*self.DetectionRadius if self.AttackDamage > 0 then for k,v in pairs(ents.FindInSphere(self:GetShootPos(),self.DetectionRadius)) do if self:ValidTargetIgnoreRange(v) and v:GetPos():DistToSqr(self:GetShootPos())<=drrt then if not v:GetBalloonProperty("BalloonBlimp") or self.rotgb_Intense and v:GetRgBE()<=v:GetRgBEByType("gballoon_blimp_blue") then v:TakeDamage(self.AttackDamage,self:GetTowerOwner(),self) else v:ShowResistEffect(1) end end end end timer.Simple(0,function() for k,v in pairs(ents.FindInSphere(self:GetShootPos(),self.DetectionRadius)) do self:DoFreeze(v) end end) self:SetNWFloat("LastFireTime",CurTime()) end if self.UserTargeting and IsValid(gBalloons[1]) then local startPos = self:GetShootPos() local uDir = gBalloons[1]:LocalToWorld(gBalloons[1]:OBBCenter())-startPos local bullet = { Attacker = self:GetTowerOwner(), Callback = function(attacker,tracer,dmginfo) dmginfo:SetDamageType(DMG_SNIPER) end, Damage = self.rotgb_ShardDamage, Distance = self.DetectionRadius*1.5, HullSize = 1, AmmoType = "", TracerName = "GlassImpact", Dir = uDir, Src = startPos } self:FireBullets(bullet) if self.rotgb_DamageBoost then self.rotgb_ShardDamage = self.rotgb_ShardDamage + 1 self.rotgb_ExtraDamage = (self.rotgb_ExtraDamage or 0) + 1 end self:SetNWFloat("LastFireTime",CurTime()) elseif self.rotgb_DamageBoost then self.rotgb_ShardDamage = self.rotgb_ShardDamage - (self.rotgb_ExtraDamage or 0) self.rotgb_ExtraDamage = 0 end if self.rotgb_FireRateBoost then local increment = 0 for k,v in pairs(gBalloons) do increment = v:GetRgBE() end self.FireRate = self.FireRate / self.rotgb_FireRateMul self.rotgb_FireRateMul = 8 * (1 + increment * 0.01) self.FireRate = self.FireRate * self.rotgb_FireRateMul end end function ENT:ROTGB_Think() --[[if self.rotgb_Viral then for k,v in pairs(ents.FindInSphere(self:GetShootPos(),self.DetectionRadius)) do if self:ValidTargetIgnoreRange(v) and ((v.FreezeUntil or 0)>CurTime() or (v.FreezeUntil2 or 0)>CurTime()) then for k2,v2 in pairs(ents.FindInSphere(v:GetPos(),self:BoundingRadius()*2)) do self:DoFreeze(v2) end end end end]] if (self.NextLocalThink or 0) < CurTime() then self.NextLocalThink = CurTime() + 0.1 if self.rotgb_SpeedSlowdown then if self.rotgb_Wonderland then for index,ent in pairs(ROTGB_GetBalloons()) do ent:Slowdown("ROTGB_ICE_TOWER_ARCTIC",0.25,999999) end else for k,v in pairs(ents.FindInSphere(self:GetShootPos(),self.DetectionRadius)) do if v:GetClass()=="gballoon_base" and v:GetRgBE() <= v:GetRgBEByType("gballoon_blimp_red") then v:Slowdown("ROTGB_ICE_TOWER_ARCTIC",0.5,0.25) end end end end end end function ENT:ROTGB_Draw() local curTime = CurTime() local pi = math.pi self.DispVec = self.DispVec or Vector() self.DispVec.z = math.sin(curTime%2*pi)*6 local elapsedseconds = curTime-self:GetNWFloat("LastFireTime") local dispvec = self.LOSOffset + self.DispVec local sat = math.min(math.EaseInOut(math.abs(curTime*pi/2%2-1),0.5,0.5)/2+0.5,elapsedseconds*pi) self:DrawModel() render.SetColorMaterial() render.DrawSphere(self:LocalToWorld(dispvec),6,24,13,HSVToColor(180,sat,1)) end function ENT:TriggerAbility() local entities = ROTGB_GetBalloons() if not next(entities) then return true end for index,ent in pairs(entities) do ent:Slowdown("ROTGB_ICE_TOWER_ABILITY",0.25,15) if self.rotgb_Wonderland then if self.rotgb_FireLight then ent:RotgB_Ignite(1000, self:GetTowerOwner(), self, 5) end if not ent:GetBalloonProperty("BalloonBlimp") or ent:GetRgBE()<=ent:GetRgBEByType("gballoon_blimp_green") then if self.rotgb_Intense then ent:Freeze2(15) else ent:Freeze(15) end if self.rotgb_SpeedPercent ~= 1 then ent:Slowdown("ROTGB_ICE_TOWER",self.rotgb_SpeedPercent,18) end if self.rotgb_PowerFreeze then ent:InflictRotgBStatusEffect("unimmune",1) end else ent:ShowResistEffect(1) end end end end
--Device IDs GCHROMA_DEVICE_ALL = 0 GCHROMA_DEVICE_KEYBOARD = 1 GCHROMA_DEVICE_MOUSEPAD = 2 GCHROMA_DEVICE_MOUSE = 3 GCHROMA_DEVICE_HEADSET = 4 GCHROMA_DEVICE_KEYPAD = 5 GCHROMA_DEVICE_LINK = 6 --Mouse lights GCHROMA_MOUSE_SCROLLWHEEL = 0x0203 GCHROMA_MOUSE_LOGO = 0x0703 GCHROMA_MOUSE_BACKLIGHT = 0x0403 GCHROMA_MOUSE_LEFT_SIDE1 = 0x0100 GCHROMA_MOUSE_LEFT_SIDE2 = 0x0200 GCHROMA_MOUSE_LEFT_SIDE3 = 0x0300 GCHROMA_MOUSE_LEFT_SIDE4 = 0x0400 GCHROMA_MOUSE_LEFT_SIDE5 = 0x0500 GCHROMA_MOUSE_LEFT_SIDE6 = 0x0600 GCHROMA_MOUSE_LEFT_SIDE7 = 0x0700 GCHROMA_MOUSE_BOTTOM1 = 0x0801 GCHROMA_MOUSE_BOTTOM2 = 0x0802 GCHROMA_MOUSE_BOTTOM3 = 0x0803 GCHROMA_MOUSE_BOTTOM4 = 0x0804 GCHROMA_MOUSE_BOTTOM5 = 0x0805 GCHROMA_MOUSE_RIGHT_SIDE1 = 0x0106 GCHROMA_MOUSE_RIGHT_SIDE2 = 0x0206 GCHROMA_MOUSE_RIGHT_SIDE3 = 0x0306 GCHROMA_MOUSE_RIGHT_SIDE4 = 0x0406 GCHROMA_MOUSE_RIGHT_SIDE5 = 0x0506 GCHROMA_MOUSE_RIGHT_SIDE6 = 0x0606 GCHROMA_MOUSE_RIGHT_SIDE7 = 0x0706 --Keyboard lights GCHROMA_KEY_ESCAPE = 0x0001 GCHROMA_KEY_F1 = 0x0003 GCHROMA_KEY_F2 = 0x0004 GCHROMA_KEY_F3 = 0x0005 GCHROMA_KEY_F4 = 0x0006 GCHROMA_KEY_F5 = 0x0007 GCHROMA_KEY_F6 = 0x0008 GCHROMA_KEY_F7 = 0x0009 GCHROMA_KEY_F8 = 0x000A GCHROMA_KEY_F9 = 0x000B GCHROMA_KEY_F10 = 0x000C GCHROMA_KEY_F11 = 0x000D GCHROMA_KEY_F12 = 0x000E GCHROMA_KEY_1 = 0x0102 GCHROMA_KEY_2 = 0x0103 GCHROMA_KEY_3 = 0x0104 GCHROMA_KEY_4 = 0x0105 GCHROMA_KEY_5 = 0x0106 GCHROMA_KEY_6 = 0x0107 GCHROMA_KEY_7 = 0x0108 GCHROMA_KEY_8 = 0x0109 GCHROMA_KEY_9 = 0x010A GCHROMA_KEY_0 = 0x010B GCHROMA_KEY_A = 0x0302 GCHROMA_KEY_B = 0x0407 GCHROMA_KEY_C = 0x0405 GCHROMA_KEY_D = 0x0304 GCHROMA_KEY_E = 0x0204 GCHROMA_KEY_F = 0x0305 GCHROMA_KEY_G = 0x0306 GCHROMA_KEY_H = 0x0307 GCHROMA_KEY_I = 0x0209 GCHROMA_KEY_J = 0x0308 GCHROMA_KEY_K = 0x0309 GCHROMA_KEY_L = 0x030A GCHROMA_KEY_M = 0x0409 GCHROMA_KEY_N = 0x0408 GCHROMA_KEY_O = 0x020A GCHROMA_KEY_P = 0x020B GCHROMA_KEY_Q = 0x0202 GCHROMA_KEY_R = 0x0205 GCHROMA_KEY_S = 0x0303 GCHROMA_KEY_T = 0x0206 GCHROMA_KEY_U = 0x0208 GCHROMA_KEY_V = 0x0406 GCHROMA_KEY_W = 0x0203 GCHROMA_KEY_X = 0x0404 GCHROMA_KEY_Y = 0x0207 GCHROMA_KEY_Z = 0x0403 GCHROMA_KEY_NUMLOCK = 0x0112 GCHROMA_KEY_KP_INS = 0x0513 GCHROMA_KEY_KP_END = 0x0412 GCHROMA_KEY_KP_DOWNARROW = 0x0413 GCHROMA_KEY_KP_PGDN = 0x0414 GCHROMA_KEY_KP_LEFTARROW = 0x0312 GCHROMA_KEY_KP_5 = 0x0313 GCHROMA_KEY_KP_RIGHTARROW = 0x0314 GCHROMA_KEY_KP_HOME = 0x0212 GCHROMA_KEY_KP_UPARROW = 0x0213 GCHROMA_KEY_KP_PGUP = 0x0214 GCHROMA_KEY_KP_SLASH = 0x0113 GCHROMA_KEY_KP_MULTIPLY = 0x0114 GCHROMA_KEY_KP_MINUS = 0x0115 GCHROMA_KEY_KP_PLUS = 0x0215 GCHROMA_KEY_KP_ENTER = 0x0415 GCHROMA_KEY_KP_DEL = 0x0514 GCHROMA_KEY_PRINTSCREEN = 0x000F GCHROMA_KEY_SCROLLLOCK = 0x0010 GCHROMA_KEY_PAUSE = 0x0011 GCHROMA_KEY_INS = 0x010F GCHROMA_KEY_HOME = 0x0110 GCHROMA_KEY_PGUP = 0x0111 GCHROMA_KEY_DELETE = 0x020f GCHROMA_KEY_END = 0x0210 GCHROMA_KEY_PGDN = 0x0211 GCHROMA_KEY_UPARROW = 0x0410 GCHROMA_KEY_LEFTARROW = 0x050F GCHROMA_KEY_DOWNARROW = 0x0510 GCHROMA_KEY_RIGHTARROW = 0x0511 GCHROMA_KEY_TAB = 0x0201 GCHROMA_KEY_CAPSLOCK = 0x0301 GCHROMA_KEY_BACKSPACE = 0x010E GCHROMA_KEY_ENTER = 0x030E GCHROMA_KEY_CTRL = 0x0501 GCHROMA_KEY_LWIN = 0x0502 GCHROMA_KEY_ALT = 0x0503 GCHROMA_KEY_SPACE = 0x0507 GCHROMA_KEY_RALT = 0x050B GCHROMA_KEY_FN = 0x050C GCHROMA_KEY_RMENU = 0x050D GCHROMA_KEY_RCTRL = 0x050E GCHROMA_KEY_SHIFT = 0x0401 GCHROMA_KEY_RSHIFT = 0x040E GCHROMA_KEY_MACRO1 = 0x0100 GCHROMA_KEY_MACRO2 = 0x0200 GCHROMA_KEY_MACRO3 = 0x0300 GCHROMA_KEY_MACRO4 = 0x0400 GCHROMA_KEY_MACRO5 = 0x0500 GCHROMA_KEY_OEM_1 = 0x0101 GCHROMA_KEY_OEM_2 = 0x010C GCHROMA_KEY_OEM_3 = 0x010D GCHROMA_KEY_OEM_4 = 0x020C GCHROMA_KEY_OEM_5 = 0x020D GCHROMA_KEY_OEM_6 = 0x020E GCHROMA_KEY_OEM_7 = 0x030B GCHROMA_KEY_OEM_8 = 0x030C GCHROMA_KEY_OEM_9 = 0x040A GCHROMA_KEY_OEM_10 = 0x040B GCHROMA_KEY_OEM_11 = 0x040C GCHROMA_KEY_EUR_1 = 0x030D GCHROMA_KEY_EUR_2 = 0x0402 GCHROMA_KEY_JPN_1 = 0x0015 GCHROMA_KEY_JPN_2 = 0x040D GCHROMA_KEY_JPN_3 = 0x0504 GCHROMA_KEY_JPN_4 = 0x0509 GCHROMA_KEY_JPN_5 = 0x050A GCHROMA_KEY_KOR_1 = 0x0015 GCHROMA_KEY_KOR_2 = 0x030D GCHROMA_KEY_KOR_3 = 0x0402 GCHROMA_KEY_KOR_4 = 0x040D GCHROMA_KEY_KOR_5 = 0x0504 GCHROMA_KEY_KOR_6 = 0x0509 GCHROMA_KEY_KOR_7 = 0x050A GCHROMA_KEY_INVALID = 0xFFFF --Colors GCHROMA_COLOR_BLACK = Vector( 0, 0, 0 ) GCHROMA_COLOR_WHITE = Vector( 255, 255, 255 ) GCHROMA_COLOR_RED = Vector( 255, 0, 0 ) GCHROMA_COLOR_GREEN = Vector( 0, 255, 0 ) GCHROMA_COLOR_BLUE = Vector( 0, 0, 255 ) GCHROMA_COLOR_MAGENTA = Vector( 255, 0, 255 ) GCHROMA_COLOR_YELLOW = Vector( 255, 255, 0 ) GCHROMA_COLOR_CYAN = Vector( 0, 255, 255 ) --Function types GCHROMA_FUNC_DEVICECOLOR = 1 GCHROMA_FUNC_DEVICECOLOREX = 2 GCHROMA_FUNC_RESETCOLOR = 3
project "EngineManaged.Tests" kind "SharedLib" language "C#" location "." files { "EngineManaged.Tests.lua", "**.cs", } links { "System", "EngineManaged", path.join(depsdir,"NUnit","nunit.framework"), path.join(depsdir,"NSubstitute","NSubstitute") }
local cjson = require("cjson") local dbrun = require("db"):set_conf(nil) local function refresh() local endpoints = ngx.shared.endpoints local res = dbrun("SELECT * FROM endpoint") for _, ep in ipairs(res) do endpoints:set(ep.endpoint, cjson.encode(ep), 60 * 60) end ngx.say('{"msg": "refreshed"}') end local function handle() local endpoints = ngx.shared.endpoints local endpoint_str = endpoints:get(ngx.var.endpoint) if not endpoint_str then ngx.exit(ngx.HTTP_NOT_FOUND) end local endpoint = cjson.decode(endpoint_str) local resource = '/' .. ngx.var.resource ngx.req.set_uri(resource, false) ngx.req.set_header('host', endpoint.hostname) ngx.var.resip = endpoint.ip end return { refresh = refresh, handle = handle, }