content
stringlengths
5
1.05M
--[[ Layout (96 KB) -------------- 0x0000 Meta Data (736 Bytes) 0x02E0 SpriteMap (12 KB) 0x32E0 Flags Data (288 Bytes) 0x3400 MapData (18 KB) 0x7C00 Sound Tracks (13 KB) 0xB000 Compressed Lua Code (20 KB) 0x10000 Persistant Data (2 KB) 0x10800 GPIO (128 Bytes) 0x10880 Reserved (768 Bytes) 0x10B80 Draw State (64 Bytes) 0x10BC0 Reserved (64 Bytes) 0x10C00 Free Space (1 KB) 0x11000 Reserved (4 KB) 0x12000 Label Image (12 KBytes) 0x15000 VRAM (12 KBytes) 0x18000 End of memory (Out of range) Meta Data (1 KB) ---------------- 0x0000 Data Length (6 Bytes) 0x0006 LIKO-12 Header (7 Bytes) 0x000D Color Palette (64 Bytes) 0x004D Disk Version (1 Byte) 0x004E Disk Meta (1 Byte) 0x004F Screen Width (2 Bytes) 0x0051 Screen Hight (2 Bytes) 0x0053 Reserved (1 Byte) 0x0054 SpriteMap Address (4 Bytes) 0x0058 MapData Address (4 Bytes) 0x005C Instruments Data Address (4 Bytes) 0x0060 Tracks Data Address (4 Bytes) 0x0064 Tracks Orders Address (4 Bytes) 0x0068 Compressed Lua Code Address (4 Bytes) 0x006C Author Name (16 Bytes) 0x007C Game Name (16 Bytes) 0x008C SpriteSheet Width (2 Bytes) 0x008E SpriteSheet Height (2 Bytes) 0x0090 Map Width (1 Byte) 0x0091 Map height (1 Byte) 0x0093 Reserved (594 Bytes) Disk META: -------------- 1. Auto event loop. 2. Activate controllers. 3. Keyboad Only. 4. Mobile Friendly. 5. Static Resolution. 6. Compatibilty Mode. 7. Write Protection. 8. Licensed Under CC0. ]] --luacheck: ignore 421 422 return function(config) local ramsize = 0 --The current size of the ram local ram = {} --The RAM table (Only affected by the default handler) local handlers = {} --The active ram handlers system local layout = config.layout or {{88*1024}} --Defaults to a 88KB RAM. local devkit = {} --The devkit of the RAM --function to convert a number into a hex string. local function tohex(a) return string.format("0x%X",a or 0) end function devkit.addHandler(startAddress, endAddress, handler) if type(startAddress) ~= "number" then return error("Start address must be a number, provided: "..type(startAddress)) end if type(endAddress) ~= "number" then return error("End address must be a number, provided: "..type(endAddress)) end if type(handler) ~= "function" then return error("Handler must be a function, provided: "..type(handler)) end table.insert(handlers,{startAddr = startAddress, endAddr = endAddress, handler = handler}) end --A binary handler. function devkit.defaultHandler(mode,startAddress,...) local args = {...} if mode == "poke" then local address, value = unpack(args) ram[address] = value elseif mode == "poke4" then local address4, value = unpack(args) local address = math.floor(address4 / 2) local byte = ram[address] if address4 % 2 == 0 then --left nibble byte = bit.band(byte,0x0F) value = bit.rshift(value,4) byte = bit.bor(byte,value) else --right nibble byte = bit.band(byte,0xF0) byte = bit.bor(byte,value) end ram[address] = byte elseif mode == "peek" then local address = args[1] return ram[address] elseif mode == "peek4" then local address4 = args[1] local address = math.floor(address4 / 2) local byte = ram[address] if address4 % 2 == 0 then --left nibble byte = bit.lshift(byte,4) else --right nibble byte = bit.band(byte,0x0F) end return byte elseif mode == "memcpy" then local from, to, len = unpack(args) for i=0,len-1 do ram[to+i] = ram[from+i] end elseif mode == "memset" then local address, value = unpack(args) local len = value:len() for i=0,len-1 do ram[address+i] = string.byte(value,i+1) end elseif mode == "memget" then local address, len = unpack(args) local subtable,nextid = {}, 1 for i=address,address+len-1 do subtable[nextid] = ram[i] nextid = nextid + 1 end if len > 255 then for i=1,nextid-1 do subtable[i] = string.char(subtable[i]) end return table.concat(subtable) else return string.char(unpack(subtable)) end end end --Build the layout. for k, section in ipairs(layout) do local size = section[1] local handler = section[2] or devkit.defaultHandler local startAddress = ramsize ramsize = ramsize + size local endAddress = ramsize-1 print("Layout ["..k.."]: "..tohex(startAddress).." -> ".. tohex(endAddress)) devkit.addHandler(startAddress,endAddress,handler) --Extend the ram table for i=#ram, #ram+size do ram[i] = 0 end end ram[#ram] = nil --Remove the last address. local lastaddr = string.format("0x%X",ramsize-1) --The last accessible ram address. local lastaddr4 = string.format("0x%X",(ramsize-1)*2) --The last accessible ram address for peek4 and poke4. local function Verify(value,name,etype,allowNil) if type(value) ~= etype then if allowNil then error(name.." should be a "..etype.." or a nil, provided: "..type(value),3) else error(name.." should be a "..etype..", provided: "..type(value),3) end end if etype == "number" then return math.floor(value) end end local api, yapi = {}, {} --API Start function api.poke4(address,value) address = Verify(address,"Address","number") value = Verify(value,"Value","number") if address < 0 or address > (ramsize-1)*2 then return error("Address out of range ("..tohex(address*2).."), must be in range [0x0,"..lastaddr4.."]") end if value < 0 or value > 15 then return error("Value out of range ("..value..") must be in range [0,15]") end for k,h in ipairs(handlers) do if address <= h.endAddr*2+1 then h.handler("poke4",h.startAddr*2,address,value) return end end end function api.poke(address,value) address = Verify(address,"Address","number") value = Verify(value,"Value","number") if address < 0 or address > ramsize-1 then return error("Address out of range ("..tohex(address).."), must be in range [0x0,"..lastaddr.."]") end if value < 0 or value > 255 then return error("Value out of range ("..value..") must be in range [0,255]") end for k,h in ipairs(handlers) do if address <= h.endAddr then h.handler("poke",h.startAddr,address,value) return end end end function api.peek4(address) address = Verify(address,"Address","number") if address < 0 or address > (ramsize-1)*2 then return error("Address out of range ("..tohex(address*2).."), must be in range [0x0,"..lastaddr4.."]") end for k,h in ipairs(handlers) do if address <= h.endAddr*2+1 then local v = h.handler("peek4",h.startAddr*2,address) return v --It ran successfully end end return 0 --No handler is found end function api.peek(address) address = Verify(address,"Address","number") if address < 0 or address > ramsize-1 then return error("Address out of range ("..tohex(address).."), must be in range [0x0,"..lastaddr.."]") end for k,h in ipairs(handlers) do if address <= h.endAddr then local v = h.handler("peek",h.startAddr,address) return v --It ran successfully end end return 0 --No handler is found end function api.memget(address,length) address = Verify(address,"Address","number") length = Verify(length,"Length","number") if address < 0 or address > ramsize-1 then return error("Address out of range ("..tohex(address).."), must be in range [0x0,"..lastaddr.."]") end if length <= 0 then return error("Length must be bigger than 0") end if address+length > ramsize then return error("Length out of range ("..length..")") end local endAddress = address+length-1 local str = "" for k,h in ipairs(handlers) do if endAddress >= h.startAddr then if address <= h.endAddr then local sa, ea = address, endAddress if sa < h.startAddr then sa = h.startAddr end if ea > h.endAddr then ea = h.endAddr end local data = h.handler("memget",h.startAddr,sa,ea-sa+1) str = str .. data end end end return str end function api.memset(address,data) address = Verify(address,"Address","number") Verify(data,"Data","string") if address < 0 or address > ramsize-1 then return error("Address out of range ("..tohex(address).."), must be in range [0x0,"..lastaddr.."]") end local length = data:len() if length == 0 then return error("Cannot set empty string") end if address+length > ramsize then return error("Data too long to fit in the memory ("..length.." character)") end local endAddress = address+length-1 for k,h in ipairs(handlers) do if endAddress >= h.startAddr then if address <= h.endAddr then local sa, ea = address, endAddress if sa < h.startAddr then sa = h.startAddr end if ea > h.endAddr then ea = h.endAddr end local d = data:sub(sa-address+1,ea-address+1) h.handler("memset",h.startAddr,sa,d) end end end end function api.memcpy(from_address,to_address,length) from_address = Verify(from_address,"Source Address","number") to_address = Verify(to_address,"Destination Address","number") length = Verify(length,"Length","number") if from_address < 0 or from_address > ramsize-1 then return error("Source Address out of range ("..tohex(from_address).."), must be in range [0x0,"..tohex(ramsize-2).."]") end if to_address < 0 or to_address > ramsize then return error("Destination Address out of range ("..tohex(to_address).."), must be in range [0x0,"..lastaddr.."]") end if length <= 0 then return error("Length should be bigger than 0") end if from_address+length > ramsize then return error("Length out of range ("..length..")") end if to_address+length > ramsize then length = ramsize-to_address end local from_end = from_address+length-1 local to_end = to_address+length-1 for k1,h1 in ipairs(handlers) do if from_end >= h1.startAddr and from_address <= h1.endAddr then local sa1, ea1 = from_address, from_end if sa1 < h1.startAddr then sa1 = h1.startAddr end if ea1 > h1.endAddr then ea1 = h1.endAddr end local to_address = to_address + (sa1 - from_address) local to_end = to_end + (ea1 - from_end) for k2,h2 in ipairs(handlers) do if to_end >= h2.startAddr and to_address <= h2.endAddr then local sa2, ea2 = to_address, to_end if sa2 < h2.startAddr then sa2 = h2.startAddr end if ea2 > h2.endAddr then ea2 = h2.endAddr end local sa1 = sa1 + (sa2 - to_address) --local ea1 = sa1 + (ea2 - to_end) if h1.handler == h2.handler then --Direct Copy h1.handler("memcpy",h1.startAddr,sa1,sa2,ea2-sa2+1) else --InDirect Copy local d = h1.handler("memget",h1.startAddr,sa1,ea2-sa2+1) h2.handler("memset",h2.startAddr,sa2,d) end end end end end end devkit.ramsize = ramsize devkit.ram = ram devkit.tohex = tohex devkit.layout = layout devkit.handlers = handlers devkit.api = api return api, yapi, devkit end
local Object = require 'lib.classic.classic' local Utils = require 'mixins.utils' local Physics = Object:extend() function Physics:new(parent, world, x, y, w, h, acceleration, damping) self.parent = parent self.world = world self.x, self.y = x, y self.w, self.h = w, h self.world:add(self.parent, self.x, self.y, self.w, self.h) self.acceleration = acceleration self.damping = damping self.position = Vector(self.x, self.y) self.velocity = Vector(0, 0) self.teleportX, self.teleportY = nil, nil self.gravity = 2600 end function Physics:applyAcceleration(dt) self.velocity = Vector(self.velocity.x + self.acceleration * dt, self.velocity.y + self.acceleration * dt) end function Physics:applyVelocityDirection(dt, direction) if direction == 'up' then self.velocity.y = self.velocity.y - self.acceleration * dt elseif direction == 'down' then self.velocity.y = self.velocity.y + self.acceleration * dt elseif direction == 'left' then self.velocity.x = self.velocity.x - self.acceleration * dt elseif direction == 'right' then self.velocity.x = self.velocity.x + self.acceleration * dt end end function Physics:applyDamping(dt) self.velocity = self.velocity / (1 + self.damping * 1.3 * dt) end function Physics:applyVelocity(dt) self.position = self.position + self.velocity * dt end function Physics:applyGravity(dt) self.velocity.y = self.velocity.y + self.gravity * dt if self.velocity.y > self.gravity then -- Prevents warp speed falls! self.velocity.y = self.gravity end end function Physics:applyDirection(dt, goal) local goalDirection = (goal.body.position - self.position):normalized() -- Tweak the magnitude (and thus overall velocity) of the goalDirection here self.velocity = self.velocity + (goalDirection * 10) end -- Requires a callback function from the parent entity function Physics:moveInWorld(dt, callback) local world = self.world -- The goal_x and y is the position that the Player intends to travel towards based on keydowns local goal = self.position + self.velocity * dt -- Move the object in the Bump world and handle collisions. Refer to parent entity to see filter definition. local actualX, actualY, collisions, collisionLength = world:move(self.parent, goal.x, goal.y, self.parent.filter) -- If a collision is detected, call back to the injected function to resolve for i = 1, collisionLength do local col = collisions[i] callback(self, col) end self.position = Vector(actualX, actualY) end function Physics:applyTeleportation(position) -- local world = self.world local teleportDestination = position print("Begin teleportation of " .. tostring(self.parent.name) .. " to " .. tostring(teleportDestination.x) .. " " .. tostring(teleportDestination.y)) local actualX, actualY, collisions, collisionLength = world:check(self.parent, teleportDestination.x, teleportDestination.y) print("Actual xy destination " .. tostring(actualX) .. " " .. tostring(actualY)) world:update(self.parent, actualX, actualY) print("World updated with new player location") self.position.x, self.position.y = actualX, actualY print("Teleported position " .. tostring(self.position.x) .. " " .. tostring(self.position.y)) end function Physics:jump(jumpVelocity, jumpTerm) if self.inAir == false and self.velocity.y > 0 then self.grounded = false self.inAir = true self.velocity.y = self.velocity.y - jumpVelocity end end function Physics:releaseJump() self.inAir = false if self.parent.body.velocity.y < 0 then self.parent.body.velocity.y = 0 end end function Physics:getX() return self.position.x end function Physics:getY() return self.position.y end function Physics:getW() return self.w end function Physics:getH() return self.h end return Physics
local ok, wk = pcall(require, 'which-key') if not ok then return end local M = {} local config = { opts = { mode = 'n', prefix = '<leader>', buffer = nil, silent = true, noremap = true, nowait = true, }, vopts = { mode = 'v', prefix = '<leader>', buffer = nil, silent = true, noremap = true, nowait = true, }, mappings = { ['/'] = { [[<cmd>lua require('Comment.api').toggle_current_linewise()<CR>]], 'Comment', }, w = { '<cmd>w!<CR>', 'Save', }, q = { '<cmd>q!<CR>', 'Quit', }, e = { '<cmd>NvimTreeToggle<CR>', 'Explorer', }, h = { name = 'help', f = { '<cmd>Telescope help_tags<CR>', 'Find Help' }, c = { '<cmd>Telescope commands<CR>', 'Commands', }, }, b = { name = 'buffer', f = { '<cmd>Telescope buffers<CR>', 'Find Buffer', }, h = { '<cmd>BufferLineCloseLeft<CR>', 'Close to the Left', }, j = { '<cmd>BufferLineCyclePrev<CR>', 'Go to Previous', }, k = { '<cmd>BufferLineCycleNext<CR>', 'Go to Next', }, l = { '<cmd>BufferLineCloseRight<CR>', 'Close to the Right', }, q = { '<cmd>BufferLinePickClose<CR>', 'Pick Close', }, }, p = { name = 'packer', s = { '<cmd>PackerSync<CR>', 'Sync', }, S = { '<cmd>PackerStatus<CR>', 'Status', }, i = { '<cmd>PackerInstall<CR>', 'Install', }, u = { '<cmd>PackerUpdate<CR>', 'Update', }, }, f = { name = 'file', f = { '<cmd>Telescope find_files<CR>', 'Find File', }, r = { '<cmd>Telescope oldfiles<CR>', 'Open Recent' }, g = { '<cmd>Telescope live_grep<CR>', 'Grep', }, }, l = { name = 'lsp', a = { '<cmd>lua vim.lsp.buf.code_action()<CR>', 'Code Action', }, f = { '<cmd>lua vim.lsp.buf.formatting()<CR>', 'Format', }, i = { '<cmd>LspInfo<CR>', 'Info', }, r = { '<cmd>lua vim.lsp.buf.rename()<CR>', 'Rename', }, j = { '<cmd>lua vim.diagnostic.goto_next()<CR>', 'Go to Next', }, k = { '<cmd>lua vim.diagnostic.goto_prev()<CR>', 'Go to Previous', }, h = { '<cmd>lua vim.lsp.buf.hover()<CR>', 'Hover', }, p = { name = 'peek', d = { '<cmd>lua vim.lsp.buf.definition()<CR>', 'Definition', }, t = { '<cmd>lua vim.lsp.buf.type_definition()<CR>', 'Type Definition', }, i = { '<cmd>lua vim.lsp.buf.implementation()<CR>', 'Implementation', }, s = { '<cmd>lua vim.lsp.buf.signature_help()<CR>', 'Signature', }, }, }, }, vmappings = { ['/'] = { [[<esc><cmd>lua require('Comment.api').toggle_linewise_op(vim.fn.visualmode())<CR>]], 'Comment', }, }, } M.setup = function() wk.setup({}) wk.register(config.mappings, config.opts) wk.register(config.vmappings, config.vopts) end return M
coa2_relay_captain = Creature:new { randomNameType = NAME_GENERIC, socialGroup = "imperial", faction = "imperial", level = 29, chanceHit = 0.38, damageMin = 280, damageMax = 290, baseXp = 3005, baseHAM = 8300, baseHAMmax = 10100, armor = 0, resists = {25,25,25,25,25,25,25,25,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + KILLER, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = {"object/mobile/dressed_imperial_captain_m.iff"}, lootGroups = { { groups = { {group = "junk", chance = 4000000}, {group = "weapons_all", chance = 500000}, {group = "armor_all", chance = 2500000}, {group = "wearables_all", chance = 3000000} } } }, weapons = {"imperial_weapons_heavy"}, conversationTemplate = "", reactionStf = "@npc_reaction/military", attacks = merge(riflemanmaster,carbineermaster,marksmanmaster,brawlermaster) } CreatureTemplates:addCreatureTemplate(coa2_relay_captain, "coa2_relay_captain")
require("toggleterm").setup { size = 10, -- size can be a number or function which is passed the current terminal open_mapping = [[<c-\>]], hide_numbers = true, -- hide the number column in toggleterm buffers shade_filetypes = {}, shade_terminals = true, shading_factor = '1', -- the degree by which to darken to terminal colour, default: 1 for dark backgrounds, 3 for light start_in_insert = true, insert_mappings = true, -- whether or not the open mapping applies in insert mode persist_size = true, direction = 'horizontal', close_on_exit = true, -- close the terminal window when the process exits shell = vim.o.shell, -- change the default shell }
RegisterNetEvent("_teleport:setCoords") AddEventHandler("_teleport:setCoords", function(coords) local ped = PlayerPedId() SetPedCoordsKeepVehicle(ped, coords.x, coords.y, coords.z) end)
require "ClassBase" local ads_plugin = nil local function onAdsResult( code, msg ) print("on ads result listener.") print("code:"..code..",msg:"..msg) if code == AdsResultCode.kAdsReceived then --do elseif code == AdsResultCode.kAdsShown then --do elseif code == AdsResultCode.kAdsDismissed then --do elseif code == AdsResultCode.kPointsSpendSucceed then --do elseif code == AdsResultCode.kPointsSpendFailed then --do elseif code == AdsResultCode.kNetworkError then --do elseif code == AdsResultCode.kUnknownError then --do elseif code == AdsResultCode.kOfferWallOnPointsChanged then --do end end Ads = class() function Ads:ctor() ads_plugin = AgentManager:getInstance():getAdsPlugin() if ads_plugin ~= nil then ads_plugin:setAdsListener(onAdsResult) end end function Ads:showAds(adType) if ads_plugin ~= nil then if ads_plugin:isAdTypeSupported(adType) then ads_plugin:showAds(adType) end end end function Ads:hideAds(adType) if ads_plugin ~= nil then if ads_plugin:isAdTypeSupported(adType) then ads_plugin:hideAds(adType) end end end function Ads:preloadAds(adType) if ads_plugin ~= nil then if ads_plugin:isAdTypeSupported(adType) then ads_plugin:preloadAds(adType) end end end function Ads:queryPoints() if ads_plugin ~= nil then local points = ads_plugin:queryPoints() print("points:"..points) end end function Ads:spendPoints(points) if ads_plugin ~= nil then ads_plugin:spendPoints(points) end end
------------------------------------------------- -- World View ------------------------------------------------- include( "FLuaVector" ); local g_pathFromSelectedUnitToMouse = nil; local turn1Color = Vector4( 0, 1, 0, 0.25 ); local turn2Color = Vector4( 1, 1, 0, 0.25 ); local turn3PlusColor = Vector4( 0.25, 0, 1, 0.25 ); local maxRangeColor = Vector4( 1, 1, 1, 0.25 ); local rButtonDown = false; local bEatNextUp = false; local pathBorderStyle = "MovementRangeBorder"; local attackPathBorderStyle = "AMRBorder"; -- attack move function UpdatePathFromSelectedUnitToMouse() local interfaceMode = UI.GetInterfaceMode(); --Events.ClearHexHighlightStyle(pathBorderStyle); --if (interfaceMode == InterfaceModeTypes.INTERFACEMODE_SELECTION and rButtonDown) or (interfaceMode == InterfaceModeTypes.INTERFACEMODE_MOVE_TO) then --for i, pathNode in ipairs(g_pathFromSelectedUnitToMouse) do --local hexID = ToHexFromGrid( Vector2( pathNode.x, pathNode.y) ); --if pathNode.turn == 1 then --Events.SerialEventHexHighlight( hexID, true, turn1Color, pathBorderStyle ); --elseif pathNode.turn == 2 then --Events.SerialEventHexHighlight( hexID, true, turn2Color, pathBorderStyle ); --else --Events.SerialEventHexHighlight( hexID, true, turn3PlusColor, pathBorderStyle ); --end --end -- this doesnt work because the size of the array is irrelevant --if ( #g_pathFromSelectedUnitToMouse > 0 ) then --Events.DisplayMovementIndicator( true ); --else --Events.DisplayMovementIndicator( false ); --end --end if (interfaceMode == InterfaceModeTypes.INTERFACEMODE_SELECTION and rButtonDown) or (interfaceMode == InterfaceModeTypes.INTERFACEMODE_MOVE_TO) then Events.DisplayMovementIndicator( true ); else Events.DisplayMovementIndicator( false ); end end function ShowMovementRangeIndicator() local unit = UI.GetHeadSelectedUnit(); if not unit then return; end local iPlayerID = Game.GetActivePlayer(); Events.ShowMovementRange( iPlayerID, unit:GetID() ); end -- Add any interface modes that need special processing to this table -- (look at InGame.lua for a bigger example) local InterfaceModeMessageHandler = { [InterfaceModeTypes.INTERFACEMODE_DEBUG] = {}, [InterfaceModeTypes.INTERFACEMODE_SELECTION] = {}, [InterfaceModeTypes.INTERFACEMODE_PING] = {}, [InterfaceModeTypes.INTERFACEMODE_MOVE_TO] = {}, [InterfaceModeTypes.INTERFACEMODE_MOVE_TO_TYPE] = {}, [InterfaceModeTypes.INTERFACEMODE_MOVE_TO_ALL] = {}, [InterfaceModeTypes.INTERFACEMODE_ROUTE_TO] = {}, [InterfaceModeTypes.INTERFACEMODE_AIRLIFT] = {}, [InterfaceModeTypes.INTERFACEMODE_NUKE] = {}, [InterfaceModeTypes.INTERFACEMODE_PARADROP] = {}, [InterfaceModeTypes.INTERFACEMODE_ATTACK] = {}, [InterfaceModeTypes.INTERFACEMODE_RANGE_ATTACK] = {}, [InterfaceModeTypes.INTERFACEMODE_CITY_RANGE_ATTACK] = {}, [InterfaceModeTypes.INTERFACEMODE_AIRSTRIKE] = {}, [InterfaceModeTypes.INTERFACEMODE_AIR_SWEEP] = {}, [InterfaceModeTypes.INTERFACEMODE_REBASE] = {}, [InterfaceModeTypes.INTERFACEMODE_EMBARK] = {}, [InterfaceModeTypes.INTERFACEMODE_DISEMBARK] = {}, [InterfaceModeTypes.INTERFACEMODE_PLACE_UNIT] = {}, [InterfaceModeTypes.INTERFACEMODE_GIFT_UNIT] = {} } local DefaultMessageHandler = {}; rotatingDirection = 0 DefaultMessageHandler[KeyEvents.KeyDown] = function( wParam, lParam ) local bShift = UIManager:GetShift() -- check for shift key, if it's enabled rotate instead of move if ( wParam == Keys.A or wParam == Keys.VK_LEFT ) and bShift and rotatingDirection ~= 1 then if rotatingDirection == -1 then Events.CameraStopRotatingCW() end Events.CameraStartRotatingCCW() rotatingDirection = 1 elseif ( wParam == Keys.D or wParam == Keys.VK_RIGHT ) and bShift and rotatingDirection ~= -1 then if rotatingDirection == 1 then Events.CameraStopRotatingCCW() end Events.CameraStartRotatingCW() rotatingDirection = -1 elseif( wParam == Keys.A or wParam == Keys.VK_LEFT ) and not bShift then -- stop rotating if rotatingDirection == 1 then Events.CameraStopRotatingCCW() rotatingDirection = 0 else Events.SerialEventCameraStopMovingRight(); Events.SerialEventCameraStartMovingLeft(); end return true; elseif ( wParam == Keys.D or wParam == Keys.VK_RIGHT ) and not bShift then -- stop rotating if rotatingDirection == -1 then Events.CameraStopRotatingCW() rotatingDirection = 0 else Events.SerialEventCameraStopMovingLeft(); Events.SerialEventCameraStartMovingRight(); end return true; elseif ( wParam == Keys.W or wParam == Keys.VK_UP ) then Events.SerialEventCameraStopMovingBack(); Events.SerialEventCameraStartMovingForward(); return true; elseif ( wParam == Keys.S or wParam == Keys.VK_DOWN ) then Events.SerialEventCameraStopMovingForward(); Events.SerialEventCameraStartMovingBack(); return true; elseif ( wParam == Keys.VK_NEXT or wParam == Keys.VK_OEM_MINUS ) then Events.SerialEventCameraOut( Vector2(0,0) ); return true; elseif ( wParam == Keys.VK_PRIOR or wParam == Keys.VK_OEM_PLUS ) then Events.SerialEventCameraIn( Vector2(0,0) ); return true; elseif ( wParam == Keys.VK_ESCAPE and InStrategicView() ) then ToggleStrategicView(); return true; --end --alpaca elseif (wParam == Keys.VK_MULTIPLY) then Events.CameraStopRotatingCCW() Events.CameraStartRotatingCW() rotatingDirection = -1 return true; elseif (wParam == Keys.VK_DIVIDE) then Events.CameraStopRotatingCW() Events.CameraStartRotatingCCW() rotatingDirection = 1 rotateKeyIsDown = true return true; end --/alpaca end DefaultMessageHandler[KeyEvents.KeyUp] = function( wParam, lParam ) if ( wParam == Keys.A or wParam == Keys.VK_LEFT ) then if rotatingDirection == 1 then Events.CameraStopRotatingCCW() rotatingDirection = 0 else Events.SerialEventCameraStopMovingLeft(); end return true; elseif ( wParam == Keys.D or wParam == Keys.VK_RIGHT ) then if rotatingDirection == -1 then Events.CameraStopRotatingCW() rotatingDirection = 0 else Events.SerialEventCameraStopMovingRight(); end return true; elseif ( wParam == Keys.W or wParam == Keys.VK_UP ) then Events.SerialEventCameraStopMovingForward(); return true; elseif ( wParam == Keys.S or wParam == Keys.VK_DOWN ) then Events.SerialEventCameraStopMovingBack(); return true; --end --alpaca elseif (wParam == Keys.VK_MULTIPLY) or (wParam == Keys.VK_DIVIDE) then Events.CameraStopRotatingCW() Events.CameraStopRotatingCCW() rotateKeyIsDown = false return true end --/alpaca return false; end -- Emergency key up handler function KeyUpHandler( wParam ) if ( wParam == Keys.A or wParam == Keys.VK_LEFT ) then Events.SerialEventCameraStopMovingLeft(); elseif ( wParam == Keys.D or wParam == Keys.VK_RIGHT ) then Events.SerialEventCameraStopMovingRight(); elseif ( wParam == Keys.W or wParam == Keys.VK_UP ) then Events.SerialEventCameraStopMovingForward(); elseif ( wParam == Keys.S or wParam == Keys.VK_DOWN ) then Events.SerialEventCameraStopMovingBack(); end end Events.KeyUpEvent.Add( KeyUpHandler ); -- INTERFACEMODE_DEBUG g_UnitPlopper = { UnitType = -1, Embarked = false, Plop = function(plot) if (g_PlopperSettings.Player ~= -1 and g_UnitPlopper.UnitType ~= -1) then local player = Players[g_PlopperSettings.Player]; if (player ~= nil) then local unit; print(g_UnitPlopper.UnitNameOffset); print(player.InitUnitWithNameOffset); if(g_UnitPlopper.UnitNameOffset ~= nil and player.InitUnitWithNameOffset ~= nil) then unit = player:InitUnitWithNameOffset(g_UnitPlopper.UnitType, g_UnitPlopper.UnitNameOffset, plot:GetX(), plot:GetY()); else unit = player:InitUnit(g_UnitPlopper.UnitType, plot:GetX(), plot:GetY()); end if (g_UnitPlopper.Embarked) then unit:Embark(); end end end end, Deplop = function(plot) local unitCount = plot:GetNumUnits(); for i = 0, unitCount - 1 do local unit = plot:GetUnit(i); if unit ~= nil then unit:Kill(true, -1); end end end } g_ResourcePlopper = { ResourceType = -1, ResourceAmount = 1, Plop = function(plot) if (g_ResourcePlopper.ResourceType ~= -1) then plot:SetResourceType(g_ResourcePlopper.ResourceType, g_ResourcePlopper.ResourceAmount); end end, Deplop = function(plot) plot:SetResourceType(-1); end } g_ImprovementPlopper = { ImprovementType = -1, Pillaged = false, HalfBuilt = false, Plop = function(plot) if (g_ImprovementPlopper.ImprovementType ~= -1) then plot:SetImprovementType(g_ImprovementPlopper.ImprovementType); if (g_ImprovementPlopper.Pillaged) then plot:SetImprovementPillaged(true); end end end, Deplop = function(plot) plot:SetImprovementType(-1); end } g_CityPlopper = { Plop = function(plot) if (g_PlopperSettings.Player ~= -1) then local player = Players[g_PlopperSettings.Player]; if (player ~= nil) then player:InitCity(plot:GetX(), plot:GetY()); end end end, Deplop = function(plot) local city = plot:GetPlotCity(); if (city ~= nil) then city:Kill(); end end } g_PlopperSettings = { Player = -1, Plopper = g_UnitPlopper, EnabledWhenInTab = false } InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_DEBUG][MouseEvents.LButtonUp] = function( wParam, lParam ) local plot = Map.GetPlot( UI.GetMouseOverHex() ); local plotX = plot:GetX(); local plotY = plot:GetY(); local pActivePlayer = Players[Game.GetActivePlayer()]; local debugItem1 = UI.GetInterfaceModeDebugItemID1(); -- City if (UI.debugItem1 == 0) then pActivePlayer:InitCity(plotX, plotY); -- Unit elseif (debugItem1 == 1) then local iUnitID = UI.GetInterfaceModeDebugItemID2(); pActivePlayer:InitUnit(iUnitID, plotX, plotY); -- Improvement elseif (debugItem1 == 2) then local iImprovementID = UI.GetInterfaceModeDebugItemID2(); plot:SetImprovementType(iImprovementID); -- Route elseif (debugItem1 == 3) then local iRouteID = UI.GetInterfaceModeDebugItemID2(); plot:SetRouteType(iRouteID); -- Feature elseif (debugItem1 == 4) then local iFeatureID = UI.GetInterfaceModeDebugItemID2(); plot:SetFeatureType(iFeatureID); -- Resource elseif (debugItem1 == 5) then local iResourceID = UI.GetInterfaceModeDebugItemID2(); plot:SetResourceType(iResourceID, 5); -- Plopper elseif (debugItem1 == 6 and type(g_PlopperSettings) == "table" and type(g_PlopperSettings.Plopper) == "table" and type(g_PlopperSettings.Plopper.Plop) == "function") then g_PlopperSettings.Plopper.Plop(plot); return true; -- Do not allow the interface mode to be set back to INTERFACEMODE_SELECTION end UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; end ---------------------------------- -- RIGHT MOUSE BUTTON ---------------------------------- InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_DEBUG][MouseEvents.RButtonDown] = function( wParam, lParam ) local plot = Map.GetPlot( UI.GetMouseOverHex() ); local plotX = plot:GetX(); local plotY = plot:GetY(); local debugItem1 = UI.GetInterfaceModeDebugItemID1(); -- Plopper if (debugItem1 == 6 and type(g_PlopperSettings) == "table" and type(g_PlopperSettings.Plopper) == "table" and type(g_PlopperSettings.Plopper.Deplop) == "function") then g_PlopperSettings.Plopper.Deplop(plot); end return true; end InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_DEBUG][MouseEvents.RButtonUp] = function( wParam, lParam ) -- Trap RButtonUp return true; end InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_RANGE_ATTACK][KeyEvents.KeyDown] = function( wParam, lParam ) if ( wParam == Keys.VK_ESCAPE ) then UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; elseif (wParam == Keys.VK_NUMPAD1 or wParam == Keys.VK_NUMPAD3 or wParam == Keys.VK_NUMPAD4 or wParam == Keys.VK_NUMPAD6 or wParam == Keys.VK_NUMPAD7 or wParam == Keys.VK_NUMPAD8 ) then UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return DefaultMessageHandler[KeyEvents.KeyDown]( wParam, lParam ); else return DefaultMessageHandler[KeyEvents.KeyDown]( wParam, lParam ); end end InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_CITY_RANGE_ATTACK][KeyEvents.KeyDown] = function( wParam, lParam ) if ( wParam == Keys.VK_ESCAPE ) then UI.ClearSelectedCities(); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; elseif (wParam == Keys.VK_NUMPAD1 or wParam == Keys.VK_NUMPAD3 or wParam == Keys.VK_NUMPAD4 or wParam == Keys.VK_NUMPAD6 or wParam == Keys.VK_NUMPAD7 or wParam == Keys.VK_NUMPAD8 ) then UI.ClearSelectedCities(); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return DefaultMessageHandler[KeyEvents.KeyDown]( wParam, lParam ); else return DefaultMessageHandler[KeyEvents.KeyDown]( wParam, lParam ); end end -- this is a default handler for all Interface Modes that correspond to a mission function missionTypeLButtonUpHandler( wParam, lParam ) local plot = Map.GetPlot( UI.GetMouseOverHex() ); if plot then local plotX = plot:GetX(); local plotY = plot:GetY(); local bShift = UIManager:GetShift(); local interfaceMode = UI.GetInterfaceMode(); local eInterfaceModeMission = GameInfoTypes[GameInfo.InterfaceModes[interfaceMode].Mission]; if eInterfaceModeMission ~= MissionTypes.NO_MISSION then if UI.CanDoInterfaceMode(interfaceMode) then Game.SelectionListGameNetMessage(GameMessageTypes.GAMEMESSAGE_PUSH_MISSION, eInterfaceModeMission, plotX, plotY, 0, false, bShift); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; end end end UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; end InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO_TYPE][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO_ALL][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_ROUTE_TO][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIRLIFT][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_NUKE][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_PARADROP][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIRSTRIKE][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIR_SWEEP][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_REBASE][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; if (UI.IsTouchScreenEnabled()) then InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO_TYPE][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO_ALL][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_ROUTE_TO][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIRLIFT][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_NUKE][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_PARADROP][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIRSTRIKE][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIR_SWEEP][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_REBASE][MouseEvents.PointerUp] = missionTypeLButtonUpHandler; end function AirStrike( wParam, lParam ) local plot = Map.GetPlot( UI.GetMouseOverHex() ); local plotX = plot:GetX(); local plotY = plot:GetY(); local pHeadSelectedUnit = UI.GetHeadSelectedUnit(); local bShift = UIManager:GetShift(); local interfaceMode = InterfaceModeTypes.INTERFACEMODE_RANGE_ATTACK; -- Don't let the user do a ranged attack on a plot that contains some fighting. if plot:IsFighting() then return true; end -- should handle the case of units bombarding tiles when they are already at war if pHeadSelectedUnit and pHeadSelectedUnit:CanRangeStrikeAt(plotX, plotY, true, true) then local interfaceMode = UI.GetInterfaceMode(); local eInterfaceModeMission = GameInfoTypes[GameInfo.InterfaceModes[interfaceMode].Mission]; Game.SelectionListGameNetMessage(GameMessageTypes.GAMEMESSAGE_PUSH_MISSION, eInterfaceModeMission, plotX, plotY, 0, false, bShift); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; -- Unit Range Strike - special case for declaring war with range strike elseif pHeadSelectedUnit and pHeadSelectedUnit:CanRangeStrikeAt(plotX, plotY, false, true) then -- Is there someone here that we COULD bombard, perhaps? local eRivalTeam = pHeadSelectedUnit:GetDeclareWarRangeStrike(plot); if (eRivalTeam ~= -1) then UIManager:SetUICursor(0); local popupInfo = { Type = ButtonPopupTypes.BUTTONPOPUP_DECLAREWARRANGESTRIKE, Data1 = eRivalTeam, Data2 = plotX, Data3 = plotY }; Events.SerialEventGameMessagePopup(popupInfo); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; end end return true; end InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIRSTRIKE][MouseEvents.LButtonUp] = AirStrike; if (UI.IsTouchScreenEnabled()) then InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIRSTRIKE][MouseEvents.PointerUp] = AirStrike; end function RangeAttack( wParam, lParam ) local plot = Map.GetPlot( UI.GetMouseOverHex() ); local plotX = plot:GetX(); local plotY = plot:GetY(); local pHeadSelectedUnit = UI.GetHeadSelectedUnit(); local bShift = UIManager:GetShift(); local interfaceMode = InterfaceModeTypes.INTERFACEMODE_RANGE_ATTACK; -- Don't let the user do a ranged attack on a plot that contains some fighting. if plot:IsFighting() then return true; end -- should handle the case of units bombarding tiles when they are already at war if pHeadSelectedUnit and pHeadSelectedUnit:CanRangeStrikeAt(plotX, plotY, true, true) then Game.SelectionListGameNetMessage(GameMessageTypes.GAMEMESSAGE_PUSH_MISSION, MissionTypes.MISSION_RANGE_ATTACK, plotX, plotY, 0, false, bShift); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; -- Unit Range Strike - special case for declaring war with range strike elseif pHeadSelectedUnit and pHeadSelectedUnit:CanRangeStrikeAt(plotX, plotY, false, true) then -- Is there someone here that we COULD bombard, perhaps? local eRivalTeam = pHeadSelectedUnit:GetDeclareWarRangeStrike(plot); if (eRivalTeam ~= -1) then UIManager:SetUICursor(0); local popupInfo = { Type = ButtonPopupTypes.BUTTONPOPUP_DECLAREWARRANGESTRIKE, Data1 = eRivalTeam, Data2 = plotX, Data3 = plotY }; Events.SerialEventGameMessagePopup(popupInfo); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; end end return true; end InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_RANGE_ATTACK][MouseEvents.LButtonUp] = RangeAttack; if (UI.IsTouchScreenEnabled()) then InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_RANGE_ATTACK][MouseEvents.PointerUp] = RangeAttack; end function CityBombard( wParam, lParam ) local plot = Map.GetPlot( UI.GetMouseOverHex() ); local plotX = plot:GetX(); local plotY = plot:GetY(); local pHeadSelectedCity = UI.GetHeadSelectedCity(); local bShift = UIManager:GetShift(); local interfaceMode = InterfaceModeTypes.INTERFACEMODE_CITY_RANGE_ATTACK; -- Don't let the user do a ranged attack on a plot that contains some fighting. if plot:IsFighting() then UI.ClearSelectedCities(); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; end if pHeadSelectedCity and pHeadSelectedCity:CanRangeStrike() then if pHeadSelectedCity:CanRangeStrikeAt(plotX,plotY, true, true) then Game.SelectedCitiesGameNetMessage(GameMessageTypes.GAMEMESSAGE_DO_TASK, TaskTypes.TASK_RANGED_ATTACK, plotX, plotY); local activePlayerID = Game.GetActivePlayer(); Events.SpecificCityInfoDirty( activePlayerID, pHeadSelectedCity:GetID(), CityUpdateTypes.CITY_UPDATE_TYPE_BANNER); end UI.ClearSelectedCities(); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; end return true; end InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_CITY_RANGE_ATTACK][MouseEvents.LButtonUp] = CityBombard; if (UI.IsTouchScreenEnabled()) then InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_CITY_RANGE_ATTACK][MouseEvents.PointerUp] = CityBombard; end -- If the user presses the right mouse button when in city range attack mode, make sure and clear the -- mode and also clear the selection. InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_CITY_RANGE_ATTACK][MouseEvents.RButtonUp] = function ( wParam, lParam ) UI.ClearSelectedCities(); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return true; end function EmbarkInputHandler( wParam, lParam ) local plot = Map.GetPlot( UI.GetMouseOverHex() ); local plotX = plot:GetX(); local plotY = plot:GetY(); local pHeadSelectedUnit = UI.GetHeadSelectedUnit(); local bShift = UIManager:GetShift(); if pHeadSelectedUnit then if (pHeadSelectedUnit:CanEmbarkOnto(pHeadSelectedUnit:GetPlot(), plot)) then Game.SelectionListGameNetMessage(GameMessageTypes.GAMEMESSAGE_PUSH_MISSION, MissionTypes.MISSION_EMBARK, plotX, plotY, 0, false, bShift); end end UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); end -- Have either right or left click trigger this InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_EMBARK][MouseEvents.LButtonUp] = EmbarkInputHandler; if (UI.IsTouchScreenEnabled()) then InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_EMBARK][MouseEvents.PointerUp] = EmbarkInputHandler; else InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_EMBARK][MouseEvents.RButtonUp] = EmbarkInputHandler; end function DisembarkInputHandler( wParam, lParam ) local plot = Map.GetPlot( UI.GetMouseOverHex() ); local plotX = plot:GetX(); local plotY = plot:GetY(); local pHeadSelectedUnit = UI.GetHeadSelectedUnit(); local bShift = UIManager:GetShift(); if pHeadSelectedUnit then if (pHeadSelectedUnit:CanDisembarkOnto(plot)) then Game.SelectionListGameNetMessage(GameMessageTypes.GAMEMESSAGE_PUSH_MISSION, MissionTypes.MISSION_DISEMBARK, plotX, plotY, 0, false, bShift); end end UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); end -- Have either right or left click trigger this InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_DISEMBARK][MouseEvents.LButtonUp] = DisembarkInputHandler; if (UI.IsTouchScreenEnabled()) then InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_DISEMBARK][MouseEvents.PointerUp] = DisembarkInputHandler; else InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_DISEMBARK][MouseEvents.RButtonUp] = DisembarkInputHandler; end -- this is a default handler for all Interface Modes that correspond to a mission --function missionTypeLButtonUpHandler( wParam, lParam ) --UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); --return true; --end --InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; --InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO_TYPE][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; --InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO_ALL][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; --InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_ROUTE_TO][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; --InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIRLIFT][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; --InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_NUKE][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; --InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_PARADROP][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; ----InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIRSTRIKE][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; --InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_AIR_SWEEP][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; --InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_REBASE][MouseEvents.LButtonUp] = missionTypeLButtonUpHandler; -- InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_SELECTION][MouseEvents.RButtonDown] = function( wParam, lParam ) ShowMovementRangeIndicator(); UI.SendPathfinderUpdate(); UpdatePathFromSelectedUnitToMouse(); end if (UI.IsTouchScreenEnabled()) then InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_SELECTION][MouseEvents.LButtonDoubleClick] = function( wParam, lParam ) if( UI.GetHeadSelectedUnit() ~= NULL ) then UI.SetInterfaceMode( InterfaceModeTypes.INTERFACEMODE_MOVE_TO ); bEatNextUp = true; end end end function ClearAllHighlights() --Events.ClearHexHighlights(); other systems might be using these! Events.ClearHexHighlightStyle(""); Events.ClearHexHighlightStyle(pathBorderStyle); Events.ClearHexHighlightStyle(attackPathBorderStyle); Events.ClearHexHighlightStyle(genericUnitHexBorder); Events.ClearHexHighlightStyle("FireRangeBorder"); Events.ClearHexHighlightStyle("GroupBorder"); Events.ClearHexHighlightStyle("ValidFireTargetBorder"); end function MovementRButtonUp( wParam, lParam ) if( bEatNextUp == true ) then bEatNextUp = false; return; end if (UI.IsTouchScreenEnabled()) then UI.SetInterfaceMode( InterfaceModeTypes.INTERFACEMODE_SELECTION ); end local bShift = UIManager:GetShift(); local bAlt = UIManager:GetAlt(); local bCtrl = UIManager:GetControl(); local plot = Map.GetPlot( UI.GetMouseOverHex() ); if not plot then return true; end local plotX = plot:GetX(); local plotY = plot:GetY(); local pHeadSelectedUnit = UI.GetHeadSelectedUnit(); UpdatePathFromSelectedUnitToMouse(); if pHeadSelectedUnit then if (UI.IsCameraMoving() and not Game.GetAllowRClickMovementWhileScrolling()) then print("Blocked by moving camera"); --Events.ClearHexHighlights(); ClearAllHighlights(); return; end Game.SetEverRightClickMoved(true); local bBombardEnemy = false; -- Is there someone here that we COULD bombard perhaps? local eRivalTeam = pHeadSelectedUnit:GetDeclareWarRangeStrike(plot); if (eRivalTeam ~= -1) then UIManager:SetUICursor(0); local popupInfo = { Type = ButtonPopupTypes.BUTTONPOPUP_DECLAREWARRANGESTRIKE, Data1 = eRivalTeam, Data2 = plotX, Data3 = plotY }; Events.SerialEventGameMessagePopup(popupInfo); return true; end -- Visible enemy... bombardment? if (plot:IsVisibleEnemyUnit(pHeadSelectedUnit:GetOwner()) or plot:IsEnemyCity(pHeadSelectedUnit)) then local bNoncombatAllowed = false; if plot:IsFighting() then return true; -- Already some combat going on in there, just exit end if pHeadSelectedUnit:CanRangeStrikeAt(plotX, plotY, true, bNoncombatAllowed) then local iMission; if (pHeadSelectedUnit:GetDomainType() == DomainTypes.DOMAIN_AIR) then iMission = MissionTypes.MISSION_MOVE_TO; -- Air strikes are moves... yep else iMission = MissionTypes.MISSION_RANGE_ATTACK; end Game.SelectionListGameNetMessage(GameMessageTypes.GAMEMESSAGE_PUSH_MISSION, iMission, plotX, plotY, 0, false, bShift); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); --Events.ClearHexHighlights(); ClearAllHighlights(); return true; end end -- No visible enemy to bombard, just move --print("bBombardEnemy check"); if bBombardEnemy == false then if bShift == false and pHeadSelectedUnit:AtPlot(plot) then --print("Game.SelectionListGameNetMessage(GameMessageTypes.GAMEMESSAGE_DO_COMMAND, CommandTypes.COMMAND_CANCEL_ALL);"); Game.SelectionListGameNetMessage(GameMessageTypes.GAMEMESSAGE_DO_COMMAND, CommandTypes.COMMAND_CANCEL_ALL); else--if plot == UI.GetGotoPlot() then --print("Game.SelectionListMove(plot, bAlt, bShift, bCtrl);"); Game.SelectionListMove(plot, bAlt, bShift, bCtrl); --UI.SetGotoPlot(nil); end --Events.ClearHexHighlights(); ClearAllHighlights(); return true; end end end if (UI.IsTouchScreenEnabled()) then InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO][MouseEvents.PointerUp] = MovementRButtonUp; else InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_SELECTION][MouseEvents.RButtonUp] = MovementRButtonUp; InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_MOVE_TO][MouseEvents.RButtonUp] = MovementRButtonUp; end function EjectHandler( wParam, lParam ) local plot = Map.GetPlot( UI.GetMouseOverHex() ); local plotX = plot:GetX(); local plotY = plot:GetY(); --print("INTERFACEMODE_PLACE_UNIT"); local unit = UI.GetPlaceUnit(); UI.ClearPlaceUnit(); local returnValue = false; if (unit ~= nil) then local city = unitPlot:GetPlotCity(); if (city ~= nil) then if UI.CanPlaceUnitAt(unit, plot) then --Network.SendCityEjectGarrisonChoice(city:GetID(), plotX, plotY); returnValue = true; end end end UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); return returnValue; end InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_PLACE_UNIT][MouseEvents.LButtonUp] = EjectHandler; if (UI.IsTouchScreenEnabled()) then InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_PLACE_UNIT][MouseEvents.PointerUp] = EjectHandler; else InterfaceModeMessageHandler[InterfaceModeTypes.INTERFACEMODE_PLACE_UNIT][MouseEvents.RButtonUp] = EjectHandler; end DefaultMessageHandler[MouseEvents.RButtonUp] = function( wParam, lParam ) UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); end ---------------------------------------------------------------- -- Input handling ---------------------------------------------------------------- function InputHandler( uiMsg, wParam, lParam ) if uiMsg == MouseEvents.RButtonDown then rButtonDown = true; elseif uiMsg == MouseEvents.RButtonUp then rButtonDown = false; end if( UI.IsTouchScreenEnabled() and uiMsg == MouseEvents.PointerDown ) then if( UIManager:GetNumPointers() > 1 ) then print( "Faking rbuttonup" ); uiMsg = MouseEvents.RButtonUp; end end local interfaceMode = UI.GetInterfaceMode(); local currentInterfaceModeHandler = InterfaceModeMessageHandler[interfaceMode]; if currentInterfaceModeHandler and currentInterfaceModeHandler[uiMsg] then return currentInterfaceModeHandler[uiMsg]( wParam, lParam ); elseif DefaultMessageHandler[uiMsg] then return DefaultMessageHandler[uiMsg]( wParam, lParam ); end return false; end ContextPtr:SetInputHandler( InputHandler ); ---------------------------------------------------------------- -- Deal with a new path from the path finder -- this is a place holder implementation to give an example of how to handle it ---------------------------------------------------------------- function OnUIPathFinderUpdate( thePath ) --g_pathFromSelectedUnitToMouse = thePath; UpdatePathFromSelectedUnitToMouse(); end Events.UIPathFinderUpdate.Add( OnUIPathFinderUpdate ); function OnMouseMoveHex( hexX, hexY ) --local pPlot = Map.GetPlot( hexX, hexY); local interfaceMode = UI.GetInterfaceMode(); if (interfaceMode == InterfaceModeTypes.INTERFACEMODE_SELECTION and rButtonDown) or (interfaceMode == InterfaceModeTypes.INTERFACEMODE_MOVE_TO) then UI.SendPathfinderUpdate(); end end Events.SerialEventMouseOverHex.Add( OnMouseMoveHex ); function OnClearUnitMoveHexRange() Events.ClearHexHighlightStyle(pathBorderStyle); Events.ClearHexHighlightStyle(attackPathBorderStyle); end Events.ClearUnitMoveHexRange.Add( OnClearUnitMoveHexRange ); function OnStartUnitMoveHexRange() Events.ClearHexHighlightStyle(pathBorderStyle); Events.ClearHexHighlightStyle(attackPathBorderStyle); end Events.StartUnitMoveHexRange.Add( OnStartUnitMoveHexRange ); function OnAddUnitMoveHexRangeHex(i, j, k, attackMove, unitID) if attackMove then Events.SerialEventHexHighlight( Vector2( i, j ), true, turn1Color, attackPathBorderStyle ); else Events.SerialEventHexHighlight( Vector2( i, j ), true, turn1Color, pathBorderStyle ); end end Events.AddUnitMoveHexRangeHex.Add( OnAddUnitMoveHexRangeHex ); --Events.EndUnitMoveHexRange.Add( OnEndUnitMoveHexRange ); local g_PerPlayerStrategicViewSettings = {} ---------------------------------------------------------------- -- 'Active' (local human) player has changed ---------------------------------------------------------------- function OnActivePlayerChanged(iActivePlayer, iPrevActivePlayer) if (iPrevActivePlayer ~= -1) then g_PerPlayerStrategicViewSettings[ iPrevActivePlayer + 1 ] = InStrategicView(); end if (iActivePlayer ~= -1 ) then if (g_PerPlayerStrategicViewSettings[ iActivePlayer + 1] and not InStrategicView()) then ToggleStrategicView(); else if (not g_PerPlayerStrategicViewSettings[ iActivePlayer + 1] and InStrategicView()) then ToggleStrategicView(); end end end end Events.GameplaySetActivePlayer.Add(OnActivePlayerChanged); ------------------------------------------------- function OnMultiplayerGameAbandoned(eReason) local popupInfo = { Type = ButtonPopupTypes.BUTTONPOPUP_KICKED, Data1 = eReason }; Events.SerialEventGameMessagePopup(popupInfo); UI.SetInterfaceMode(InterfaceModeTypes.INTERFACEMODE_SELECTION); end Events.MultiplayerGameAbandoned.Add( OnMultiplayerGameAbandoned ); ------------------------------------------------- function OnMultiplayerGameLastPlayer() UI.AddPopup( { Type = ButtonPopupTypes.BUTTONPOPUP_TEXT, Data1 = 800, Option1 = true, Text = "TXT_KEY_MP_LAST_PLAYER" } ); end Events.MultiplayerGameLastPlayer.Add( OnMultiplayerGameLastPlayer );
--- Acts as a command processor for specialization commands, delegating -- to the specialization commands. -- @classmod SpecializationCommand -- region imports local class = require('classes/class') local prototype = require('prototypes/prototype') local specialization_pool = require('classes/specializations/specialization_pool') local adventurers = require('functional/game_context/adventurers') local word_wrap = require('functional/word_wrap') local arg_parser = require('functional/arg_parser') require('prototypes/command') -- endregion local SpecializationCommand = {} function SpecializationCommand.priority() return 'explicit' end local function is_command_or_alias(comm, first_arg) local stripped_of_slash = first_arg:sub(2) if comm:get_command() == stripped_of_slash then return true end local aliases = comm:get_aliases() for _,alias in ipairs(aliases) do if alias == stripped_of_slash then return true end end return false end local function print_help(comm) local str = comm:get_command() str = str:sub(1, 1):upper() .. str:sub(2) print('\27[K\r' .. str) word_wrap.print_wrapped(comm:get_long_description(), 2) end local function handle_command(comm, game_ctx, local_ctx, args) local succ, events = comm:parse(game_ctx, local_ctx, args) if not succ then print_help(comm) local_ctx.dirty = true return true, {} end return succ, events end local function print_specialization_info(game_ctx, local_ctx, text, args, spec) print('\27[K\r' .. text) print(' Usage: /specialization [--lore] [--specialization name] [--ability name]') local lore = false for k,v in ipairs(args) do if k ~= 1 then if v == '--lore' then lore = true else -- assume it's asking about a passive local tmp = v:sub(3):lower() for _, pass in ipairs(spec:get_specialization_passives()) do if pass:get_name():lower() == tmp then print('\27[2mPassive\27[0m: ' .. pass:get_name()) word_wrap.print_wrapped(pass:get_long_description(), 2) return end end -- perhaps an ability? for _, comm in ipairs(spec:get_specialization_commands()) do if comm:get_command():lower() == tmp then print('/' .. comm:get_command()) word_wrap.print_wrapped(comm:get_long_description(), 2) return end end -- okay maybe it's asking about another specialization? if specialization_pool.specs_by_name[tmp] then local new_spec = specialization_pool.specs_by_name[tmp] -- strip this argument out local new_args = {} for k2,v2 in ipairs(args) do if k ~= k2 then table.insert(new_args, v2) end end return print_specialization_info(game_ctx, local_ctx, new_args, new_spec) end print('\27[41mUnknown parameter\27[49m: ' .. v) end end end local nm = spec:get_name() print(nm:sub(1, 1):upper() .. nm:sub(2)) if lore then word_wrap.print_wrapped(spec:get_long_description(), 2) return end print(' ' .. spec:get_short_description()) for _,comm in ipairs(spec:get_specialization_commands()) do print(' /' .. comm:get_command() .. ' - ' .. comm:get_short_description()) end for _,pass in ipairs(spec:get_specialization_passives()) do print(' \27[2mPassive\27[0m: ' .. pass:get_name() .. ' - ' .. pass:get_short_description()) end end function SpecializationCommand:parse(game_ctx, local_ctx, text) if game_ctx.in_setup_phase == nil or game_ctx.in_setup_phase then return false, nil end if text:sub(1, 1) ~= '/' then return false, nil end local my_advn = adventurers.get_local_adventurer(game_ctx, local_ctx) if not my_advn then return false, nil end local spec_name = my_advn.specialization if not spec_name then return false, nil end local parsed = arg_parser.parse_allow_quotes(text) local spec = specialization_pool:get_by_name(spec_name) local commands = spec:get_specialization_commands() if parsed[1] == '/specialization' then print_specialization_info(game_ctx, local_ctx, text, parsed, spec) return true, {} end for _, comm in ipairs(commands) do if is_command_or_alias(comm, parsed[1]) then return handle_command(comm, game_ctx, local_ctx, parsed) end end return false, nil end prototype.support(SpecializationCommand, 'command') return class.create('SpecializationCommand', SpecializationCommand)
TOOL.Category = "Wire Extras/GUI Panels" TOOL.Name = "Set Draw Params" TOOL.Command = nil TOOL.ConfigName = "" TOOL.ClientConVar["drawx"] = "" TOOL.ClientConVar["drawy"] = "" TOOL.ClientConVar["draww"] = "" TOOL.ClientConVar["drawh"] = "" TOOL.ClientConVar["drawres"] = "" if CLIENT then language.Add( "Tool_drawchanger_name", "Developer Tool" ) language.Add( "Tool_drawchanger_desc", "change draw params" ) language.Add( "Tool_drawchanger_0", "Primary: set draw params, Sec: " ) language.Add("Tool_drawchanger_drawvariable", "Variable:") language.Add("Tool_drawchanger_drawvalue", "Value:") language.Add("Tool_drawchanger_drawx", "X:") language.Add("Tool_drawchanger_drawy", "Y:") language.Add("Tool_drawchanger_draww", "W:") language.Add("Tool_drawchanger_drawh", "H:") language.Add("Tool_drawchanger_drawres", "Res:") function umGetNewSet() local ent = net.ReadEntity() ent.drawParams.x = net.ReadFloat() ent.drawParams.y = net.ReadFloat() ent.drawParams.w = net.ReadFloat() ent.drawParams.h = net.ReadFloat() ent.drawParams.Res = net.ReadFloat() gpCalcDrawCoefs(ent) end net.Receive("umsgDrawChangerCfg", umGetNewSet) end if SERVER then util.AddNetworkString("umsgDrawChangerCfg") function TOOL:sendSetVal(ent, x, y, w, h, res) Msg ("um send function\n") //local allPlayers = RecipientFilter() //allPlayers:AddAllPlayers() net.Start("umsgDrawChangerCfg") net.WriteEntity(ent) net.WriteFloat(x) net.WriteFloat(y) net.WriteFloat(w) net.WriteFloat(h) net.WriteFloat(res) net.Broadcast() --do we need to send entity with all user messages (so we know which pannel we are talking about?) end end function TOOL:LeftClick( trace ) if trace.Entity && trace.Entity:IsPlayer() then return false end if CLIENT then return true end local x = tonumber(self:GetClientInfo("drawx")) local y = self:GetClientInfo("drawy") local w = self:GetClientInfo("draww") local h = self:GetClientInfo("drawh") local res = self:GetClientInfo("drawres") self:sendSetVal(trace.Entity, x, y, w, h, res) return true end function TOOL:RightClick( trace ) if trace.Entity && trace.Entity:IsPlayer() then return false end if CLIENT then return true end return true end function TOOL:Think() end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool_wire_modular_panel_name", Description = "#Tool_wire_modular_panel_desc" }) panel:AddControl("TextBox", {Label = "#Tool_drawchanger_drawx", MaxLength = tostring(50), Command = "drawchanger_drawx"}) panel:AddControl("TextBox", {Label = "#Tool_drawchanger_drawy", MaxLength = tostring(50), Command = "drawchanger_drawy"}) panel:AddControl("TextBox", {Label = "#Tool_drawchanger_draww", MaxLength = tostring(50), Command = "drawchanger_draww"}) panel:AddControl("TextBox", {Label = "#Tool_drawchanger_drawh", MaxLength = tostring(50), Command = "drawchanger_drawh"}) panel:AddControl("TextBox", {Label = "#Tool_drawchanger_drawres", MaxLength = tostring(50), Command = "drawchanger_drawres"}) end
AddCSLuaFile() DEFINE_BASECLASS( "weapon_csbasegun" ) CSParseWeaponInfo( SWEP , [[WeaponData { "MaxPlayerSpeed" "220" "WeaponType" "Shotgun" "FullAuto" 1 "WeaponPrice" "1700" "WeaponArmorRatio" "1.0" "CrosshairMinDistance" "8" "CrosshairDeltaDistance" "6" "Team" "ANY" "BuiltRightHanded" "0" "PlayerAnimationExtension" "m3s90" "MuzzleFlashScale" "1.3" "CanEquipWithShield" "0" // Weapon characteristics: "Penetration" "1" "Damage" "26" "Range" "3000" "RangeModifier" "0.70" "Bullets" "9" "CycleTime" "0.88" // New accuracy model parameters "Spread" 0.04000 "InaccuracyCrouch" 0.00750 "InaccuracyStand" 0.01000 "InaccuracyJump" 0.42000 "InaccuracyLand" 0.08400 "InaccuracyLadder" 0.07875 "InaccuracyFire" 0.04164 "InaccuracyMove" 0.04320 "RecoveryTimeCrouch" 0.29605 "RecoveryTimeStand" 0.41447 // Weapon data is loaded by both the Game and Client DLLs. "printname" "#Cstrike_WPNHUD_m3" "viewmodel" "models/weapons/v_shot_m3super90.mdl" "playermodel" "models/weapons/w_shot_m3super90.mdl" "anim_prefix" "anim" "bucket" "0" "bucket_position" "0" "clip_size" "8" "primary_ammo" "BULLET_PLAYER_BUCKSHOT" "secondary_ammo" "None" "weight" "20" "item_flags" "0" // Sounds for the weapon. There is a max of 16 sounds per category (i.e. max 16 "single_shot" sounds) SoundData { //"reload" "Default.Reload" //"empty" "Default.ClipEmpty_Rifle" "single_shot" "Weapon_M3.Single" special3 Default.Zoom } // Weapon Sprite data is loaded by the Client DLL. TextureData { "weapon" { "font" "CSweaponsSmall" "character" "K" } "weapon_s" { "font" "CSweapons" "character" "K" } "ammo" { "font" "CSTypeDeath" "character" "J" } "crosshair" { "file" "sprites/crosshairs" "x" "0" "y" "48" "width" "24" "height" "24" } "autoaim" { "file" "sprites/crosshairs" "x" "0" "y" "48" "width" "24" "height" "24" } } ModelBounds { Viewmodel { Mins "-13 -3 -13" Maxs "26 10 -3" } World { Mins "-9 -8 -5" Maxs "28 9 9" } } }]] ) SWEP.Spawnable = true SWEP.Slot = 0 SWEP.SlotPos = 0 function SWEP:Initialize() BaseClass.Initialize( self ) self:SetHoldType( "shotgun" ) self:SetWeaponID( CS_WEAPON_M3 ) end function SWEP:PrimaryAttack() if self:GetNextPrimaryAttack() > CurTime() then return end local owner = self:GetOwner() if owner:WaterLevel()==3 then self:PlayEmptySound() self:SetNextPrimaryAttack( CurTime() + 0.2 ) return false end -- Out of ammo? if self:Clip1() <= 0 then self:PlayEmptySound() self:SetNextPrimaryAttack( CurTime() + 0.2 ) return false end local ply = self:GetOwner() local pCSInfo = self:GetWeaponInfo() local iDamage = pCSInfo.Damage local flRangeModifier = pCSInfo.RangeModifier local soundType = "single_shot" self:SendWeaponAnim( self:TranslateViewModelActivity( ACT_VM_PRIMARYATTACK ) ) self:SetClip1( self:Clip1() -1 ) -- player "shoot" animation ply:DoAttackEvent() ply:FireBullets { Attacker = ply, AmmoType = self.Primary.Ammo, Distance = pCSInfo.Range, Tracer = 1, Damage = iDamage, Src = ply:GetShootPos(), Dir = dir, Spread = vector_origin, Callback = function( hitent , trace , dmginfo ) --TODO: penetration --unfortunately this can't be done with a static function or we'd need to set global variables for range and shit if flRangeModifier then --Jvs: the damage modifier valve actually uses local flCurrentDistance = trace.Fraction * pCSInfo.Range dmginfo:SetDamage( dmginfo:GetDamage() * math.pow( flRangeModifier, ( flCurrentDistance / 500 ) ) ) end end } self:DoFireEffects() local cycletime = .875 self:SetNextPrimaryAttack( CurTime() + cycletime ) self:SetNextSecondaryAttack( CurTime() + cycletime ) if self:Clip1() ~= 0 then self:SetNextIdle( CurTime() + 2.5 ) else self:SetNextIdle( CurTime() + cycletime ) end self:SetLastFire( CurTime() ) local angle = self:GetOwner():GetViewPunchAngles() -- Update punch angles. if not self:GetOwner():OnGround() then angle.x = angle.x - util.SharedRandom( "M3PunchAngleGround" , 4, 6 ) else angle.x = angle.x - util.SharedRandom( "M3PunchAngle" , 8, 11 ) end self:GetOwner():SetViewPunchAngles( angle ) return true end SWEP.AdminOnly = true
local Observer = require('stdlib.utils.observer') local UnitTracker = require('stdlib.triggers.UnitTracker') ---DamageDetection --- Listen to any damage event that happens on the map. --- Example: --- ---DamageDetection:add(function() --- print("Damage Event with dmg: " .. Event:getEventDamage()) ---end) --- ---@class DamageDetection local DamageDetection = Observer:new() function DamageDetection:init() self.SWAP_TIMEOUT = 600 self.current = Trigger:create() ---@type Trigger self.toDestroy = nil ---@type function[] self.callback = {} UnitTracker:enter(function() self:push(UnitTracker:getUnit()) end) local timer = Timer:create() timer:start(self.SWAP_TIMEOUT, function() self:swap() end) end ---@param u Unit function DamageDetection:push(u) self.current:registerUnitEvent(u, UnitEvent.Damaged) end --- Cleanup function DamageDetection:swap() local e = self.current:isEnabled() self.current:disable() if self.toDestroy then self.toDestroy:destroy() end self.toDestroy = self.current self.current = Trigger:create() if not e then self.current:disable() end for _, p in ipairs(Player:all()) do p:getUnits(function(u) self:push(u) return false end) end for _, c in ipairs(self.callback) do self.current:addCondition(c) end end ---@param c function function DamageDetection:add(c) self.current:addCondition(c) table.insert(self.callback, c) end function DamageDetection:disable() self.current:disable() end function DamageDetection:enable() self.current:enable() end DamageDetection:init() return DamageDetection
local Block = Object:extend() function Block:new(x, y) self.x = x self.y = y end function Block:update(dt) end function Block:draw() love.graphics.rectangle('fill', self.x, self.y, block_size, block_size) end return Block
-- Localize globals local math, setmetatable, table = math, setmetatable, table -- Set environment local _ENV = {} setfenv(1, _ENV) local metatable = {__index = _ENV} function less_than(a, b) return a < b end --> empty min heap function new(less_than) return setmetatable({less_than = less_than}, metatable) end function push(self, value) table.insert(self, value) local function heapify(index) if index == 1 then return end local parent = math.floor(index / 2) if self.less_than(self[index], self[parent]) then self[parent], self[index] = self[index], self[parent] heapify(parent) end end heapify(#self) end function pop(self) local value = self[1] local last = #self if last == 1 then self[1] = nil return value end self[1], self[last] = self[last], nil last = last - 1 local function heapify(index) local left_child = index * 2 if left_child > last then return end local smallest_child = left_child + 1 if smallest_child > last or self.less_than(self[left_child], self[smallest_child]) then smallest_child = left_child end if self.less_than(self[smallest_child], self[index]) then self[index], self[smallest_child] = self[smallest_child], self[index] heapify(smallest_child) end end heapify(1) return value end -- Export environment return _ENV
-- $Id: icon_generator.lua 4354 2009-04-11 14:32:28Z licho $ ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- -- Icon Generator Config File -- --// Info if (info) then local ratios = {["1to1"]=(1/1)} --{["16to10"]=(10/16), ["1to1"]=(1/1), ["5to4"]=(4/5)} --, ["4to3"]=(3/4)} local resolutions = {{128,128}} --{{128,128},{64,64}} local schemes = {""} return schemes,resolutions,ratios end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --// filename ext imageExt = ".png" --// render into a fbo in 4x size renderScale = 4 --// faction colors (check (and needs) LuaRules/factions.lua) factionTeams = { arm = 0, --// arm core = 1, --// core tll = 2, --// tll unknown = 3, --// unknown } factionColors = { arm = {0, 0, 1}, --// arm core = {1, 0, 0}, --// core tll = {1,1,0}, --// chicken unknown = {0, 1, 0}, --// unknown } ----------------------------------------------------------------------- ----------------------------------------------------------------------- --// render options textured textured = (scheme~="bw") lightAmbient = {1,1,1} lightDiffuse = {0,0,0} lightPos = {-0.3,0.5,0.6} --// Ambient Occlusion & Outline settings aoPower = ((scheme=="bw") and 1.5) or 1 aoContrast = ((scheme=="bw") and 2.5) or 1 aoTolerance = 0 olContrast = ((scheme=="bw") and 5) or 10 olTolerance = 0 --// halo (white) halo = false --(scheme~="bw") ----------------------------------------------------------------------- ----------------------------------------------------------------------- --// backgrounds background = true local function Greater30(a) return a>30; end local function GreaterEq15(a) return a>=15; end local function GreaterZero(a) return a>0; end local function GreaterEqZero(a) return a>=0; end local function GreaterFour(a) return a>4; end local function LessEqZero(a) return a<=0; end local function IsCoreOrChicken(a) if a then return a.chicken else return false end end backgrounds = { --//subs {check={waterline=GreaterEq15,minWaterDepth=GreaterZero}, texture="LuaRules/Images/IconGenBkgs/water.png"}, {check={floatOnWater=false,minWaterDepth=GreaterFour}, texture="LuaRules/Images/IconGenBkgs/water.png"}, --//sea {check={floatOnWater=true,minWaterDepth=GreaterZero}, texture="LuaRules/Images/IconGenBkgs/water.png"}, {check={canFly=true}, texture="LuaRules/Images/IconGenBkgs/sky.png"}, } ----------------------------------------------------------------------- ----------------------------------------------------------------------- --// default settings for rendering --//zoom := used to make all model icons same in size (DON'T USE, it is just for auto-configuration!) --//offset := used to center the model in the fbo (not in the final icon!) (DON'T USE, it is just for auto-configuration!) --//rot := facing direction --//angle := topdown angle of the camera (0 degree = frontal, 90 degree = topdown) --//clamp := clip everything beneath it (hide underground stuff) --//scale := render the model x times as large and then scale down, to replaces missing AA support of FBOs (and fix rendering of very tine structures like antennas etc.)) --//unfold := unit needs cob to unfolds --//move := send moving cob events (works only with unfold) --//attack := send attack cob events (works only with unfold) --//shotangle := vertical aiming, useful for arties etc. (works only with unfold+attack) --//wait := wait that time in gameframes before taking the screenshot (default 300) (works only with unfold) --//border := free space around the final icon (in percent/100) --//empty := empty model (used for fake units in CA) --//attempts := number of tries to scale the model to fit in the icon defaults = {unfold=true, attack=true, border=0.05, angle=30, rot="right", clamp=-10000, scale=2, empty=false, attempts=10, wait=300, zoom=1.0, offset={0,0,0},}; ----------------------------------------------------------------------- ----------------------------------------------------------------------- unitConfigs = { -- [UnitDefNames.eartytank.id] = { wait = 30 }, } for i=1,#UnitDefs do if (UnitDefs[i].canFly) then if (unitConfigs[i]) then if (unitConfigs[i].unfold ~= false) then unitConfigs[i].unfold = true unitConfigs[i].move = true end else unitConfigs[i] = {unfold = true, move = true} end elseif (UnitDefs[i].canKamikaze) then if (unitConfigs[i]) then if (not unitConfigs[i].border) then unitConfigs[i].border = 0.156 end else unitConfigs[i] = {border = 0.156} end end end
return function(data) return { type = "SetUnknownComponents", data = data, } end
-- TODO Tangentspace Normal Mapping if (true) then return NOTREADY() end -- <Resources> -- models/senior.f3d -- materials/senior.tga.mtl -- shaders/normalmap_full.shd -- gpuprogs/tangentnormalmap.cg
-- "Madness" camVar = 1; cameraZoom = 0.7 hudZoom = 1.0 camHudAngle = 0.0 cameraAngle = 0.0 function update(elapsed) camShenigans() if leftVar > 0 then leftVar = leftVar - (leftVar / 10) end if downVar > 0 then downVar = downVar - (downVar / 10) end if upVar > 0 then upVar = upVar - (upVar / 10) end if rightVar > 0 then rightVar = rightVar - (rightVar / 10) end local currentBeat = (songPos / 1000) * (bpm/60) for i=0,7 do local receptor = _G['receptor_'..i] local hahaLeft = 0.7 local hahaDown = 0.7 local hahaUp = 0.7 local hahaRight = 0.7 if i == 0 or i == 4 then hahaLeft = 2.1 elseif i == 1 or i == 5 then hahaDown = 2.1 elseif i == 2 or i == 6 then hahaUp = 2.1 elseif i == 3 or i == 7 then hahaRight = 2.1 end receptor.x = receptor.defaultX + (-24 * leftVar * hahaLeft) + (24 * rightVar * hahaRight) receptor.y = receptor.defaultY + (24 * downVar * hahaDown) + (-24 * upVar * hahaUp) end end leftVar = 0.0 downVar = 0.0 upVar = 0.0 rightVar = 0.0 function playerTwoSing(note, songPos) if note == 0 then leftVar = leftVar + 2.5 elseif note == 1 then downVar = downVar + 2.5 elseif note == 2 then upVar = upVar + 2.5 elseif note == 3 then rightVar = rightVar + 2.5 end if Game.health > 0.1 then Game.health = Game.health - (.035 * Game.health) end end function playerOneSing(note, songPos) if note == 0 then leftVar = leftVar + 1.0 elseif note == 1 then downVar = downVar + 1.0 elseif note == 2 then upVar = upVar + 1.0 elseif note == 3 then rightVar = rightVar + 1.0 end end function beatHit(beat) if (beat > 32 and beat < 256) then if math.fmod(beat, 4) == 0 then cameraZoom = 0.78 camHudAngle = 4 * camVar else cameraZoom = 0.765 camHudAngle = 2 * camVar end elseif (beat > 256 and beat < 384) then cameraZoom = 0.76 camHudAngle = 1 * camVar elseif (beat > 384 and beat < 448) then if math.fmod(beat, 4) == 0 then cameraZoom = 0.8 camHudAngle = 4 * camVar else cameraZoom = 0.775 camHudAngle = 2 * camVar end elseif (beat > 448 and beat < 512) then if math.fmod(beat, 4) == 0 then cameraZoom = 0.78 camHudAngle = 4 * camVar else cameraZoom = 0.765 camHudAngle = 2 * camVar end end --cam zooms during the slower duet section are less intense (1st elseif) --cam zooms during the repeated of the chorus are significantly worse (2nd elseif) camVar = camVar * -1 -- on the beats of the "HEY!"s, cheer if beat == 203 or beat == 235 or beat == 395 or beat == 411 then dad:playAnim('cheer', 'true') gf:playAnim('cheer', 'true') elseif beat == 219 or beat == 251 or beat == 427 or beat == 443 then gf:playAnim('cheer', 'true') end end function camShenigans() local defaultCam = 0.7 local funnyVar = math.abs(camHudAngle / 15) cameraAngle = camHudAngle * -0.8 hudZoom = cameraZoom + 0.3 if camHudAngle > 0 then camHudAngle = camHudAngle - (funnyVar) elseif camHudAngle < 0 then camHudAngle = camHudAngle + (funnyVar) end if cameraZoom > defaultCam then cameraZoom = cameraZoom - 0.005 elseif cameraZoom < defaultCam then cameraZoom = defaultCam end end
--mobs_fallout v0.0.3 --maikerumine --made for Extreme Survival game --dofile(minetest.get_modpath("mobs_fallout").."/api.lua") --REFERENCE --function (mod_name_here):spawn_specific(name, nodes, neighbors, min_light, max_light, interval, chance, active_object_count, min_height, max_height) --dofile(minetest.get_modpath("crossfiremob").."/api.lua") mobs.npc_drops = { "default:pick_steel", "mobs_fallout:meat", "default:sword_steel", "default:shovel_steel", "farming:bread", "default:wood" }--Added 20151121 mobs:register_spawn("mobs_fallout:Mr_Black", {"default:dirt_with_grass","default:desert_sand","default:sand","default:stonebrick","default:cobble", "default:dry_dirt", "default:snow"}, 14, -1, 8000, 1, 30) mobs:register_spawn("mobs_fallout:Mr_White", {"default:dirt_with_grass", "ethereal:green_dirt","default:grass","default:stonebrick","default:cobble", "default:dry_dirt", "default:snow"}, 14, -1, 8000, 1, 30) mobs:register_spawn("mobs_fallout:Mr_Pink", {"default:dirt_with_grass","default:desert_sand","default:sand","default:stonebrick","default:cobble", "default:dry_dirt", "default:snow"}, 14, -1, 8000, 1, 30) mobs:register_mob("mobs_fallout:Mr_White", { type = "npc", group_attack = true, pathfinding = true, hp_min = 35, hp_max = 65, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"white.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 3, damage = 2, sounds = { war_cry = "mobs_die_yell", death = "mobs_death1", attack = "shooter_rifle", shoot_attack = "shooter_rifle", }, drops = { {name = "default:apple", chance = 1, min = 0, max = 2,}, {name = "default:sword_steel", chance = 2, min = 0, max = 1,}, }, armor = 75, drawtype = "front", water_damage = 70, lava_damage = 50, light_damage = 0, --[[ --Maikerumine added hackish follow code on_rightclick = function (self, clicker) mobs:face_pos(self,clicker:getpos()) mobs:team_player(self,clicker:getpos()) if self.state ~= "path" and self.state ~= "following" then local_chat(clicker:getpos(),"Mr. White: Let's go kick some Mob butt!",3) if not self.tamed then self.tamed = true self.follow = true end end end,]] on_rightclick = function(self, clicker) local item = clicker:get_wielded_item() local_chat(clicker:getpos(),"Mr. White: Let's go kick some Mob butt!",3) if item:get_name() == "mobs_fallout:meat" or item:get_name() == "farming:bread" then local hp = self.object:get_hp() if hp + 4 > self.hp_max then return end if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end self.object:set_hp(hp+4) -- right clicking with gold lump drops random item from mobs.npc_drops elseif item:get_name() == "default:gold_lump" then if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end local pos = self.object:getpos() pos.y = pos.y + 0.5 minetest.add_item(pos, {name = mobs.npc_drops[math.random(1,#mobs.npc_drops)]}) else if self.owner == "" then self.owner = clicker:get_player_name() else local formspec = "size[8,4]" formspec = formspec .. "textlist[2.85,0;2.1,0.5;dialog;What can I do for you?]" formspec = formspec .. "button_exit[1,1;2,2;gfollow;follow]" formspec = formspec .. "button_exit[5,1;2,2;gstand;stand]" formspec = formspec .. "button_exit[0,2;4,4;gfandp;follow and protect]" formspec = formspec .. "button_exit[4,2;4,4;gsandp;stand and protect]" --formspec = formspec .. "button_exit[1,2;2,2;ggohome; go home]" --formspec = formspec .. "button_exit[5,2;2,2;gsethome; sethome]" minetest.show_formspec(clicker:get_player_name(), "order", formspec) minetest.register_on_player_receive_fields(function(clicker, formname, fields) if fields.gfollow then self.order = "follow" self.attacks_monsters = false end if fields.gstand then self.order = "stand" self.attacks_monsters = false end if fields.gfandp then self.order = "follow" self.attacks_monsters = true end if fields.gsandp then self.order = "stand" self.attacks_monsters = true end if fields.gsethome then self.floats = self.object:getpos() end if fields.ggohome then if self.floats then self.order = "stand" self.object:setpos(self.floats) end end end) end end end, --attack_type = "dogfight", attack_type = "dogshoot", dogshoot_switch = 1, dogshoot_count_max = 10, arrow = "mobs_fallout:bullet", shoot_interval = 2.5, animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, attacks_monsters = true, peaceful = true, group_attack = true, step = 1, }) mobs:register_mob("mobs_fallout:Mr_Black", { type = "monster", group_attack = true, pathfinding = true, hp_min = 35, hp_max = 65, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"black.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 3, damage = 2, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_rifle", shoot_attack = "shooter_rifle", }, drops = { {name = "default:apple", chance = 1, min = 1, max = 2,}, {name = "default:sword_steel", chance = 2, min = 0, max = 1,}, }, armor = 75, drawtype = "front", water_damage = 70, lava_damage = 50, light_damage = 0, --attack_type = "dogfight", attack_type = "dogshoot", dogshoot_switch = 1, dogshoot_count_max = 10, arrow = "mobs_fallout:bullet", shoot_interval = 2.5, --[[ on_rightclick = function (self, clicker) mobs:face_pos(self,clicker:getpos()) mobs:team_player(self,clicker:getpos()) if self.state ~= "path" and self.state ~= "following" then local_chat(clicker:getpos(),"Mr. Black: Grrrrrrrrrrrr!",3) if not self.tamed then self.tamed = true self.follow = true end end end,]] on_rightclick = function(self, clicker) local item = clicker:get_wielded_item() local_chat(clicker:getpos(),"Mr. Black: Grrrrrrrrrrrr!",3) if item:get_name() == "mobs_fallout:meat" or item:get_name() == "farming:bread" then local hp = self.object:get_hp() if hp + 4 > self.hp_max then return end if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end self.object:set_hp(hp+4) -- right clicking with gold lump drops random item from mobs.npc_drops elseif item:get_name() == "default:gold_lump" then if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end local pos = self.object:getpos() pos.y = pos.y + 0.5 minetest.add_item(pos, {name = mobs.npc_drops[math.random(1,#mobs.npc_drops)]}) else if self.owner == "" then self.owner = clicker:get_player_name() else local formspec = "size[8,4]" formspec = formspec .. "textlist[2.85,0;2.1,0.5;dialog;What can I do for you?]" formspec = formspec .. "button_exit[1,1;2,2;gfollow;follow]" formspec = formspec .. "button_exit[5,1;2,2;gstand;stand]" formspec = formspec .. "button_exit[0,2;4,4;gfandp;follow and protect]" formspec = formspec .. "button_exit[4,2;4,4;gsandp;stand and protect]" --formspec = formspec .. "button_exit[1,2;2,2;ggohome; go home]" --formspec = formspec .. "button_exit[5,2;2,2;gsethome; sethome]" minetest.show_formspec(clicker:get_player_name(), "order", formspec) minetest.register_on_player_receive_fields(function(clicker, formname, fields) if fields.gfollow then self.order = "follow" self.attacks_monsters = false end if fields.gstand then self.order = "stand" self.attacks_monsters = false end if fields.gfandp then self.order = "follow" self.attacks_monsters = true end if fields.gsandp then self.order = "stand" self.attacks_monsters = true end if fields.gsethome then self.floats = self.object:getpos() end if fields.ggohome then if self.floats then self.order = "stand" self.object:setpos(self.floats) end end end) end end end, animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, attacks_monsters = true, peaceful = true, group_attack = true, step = 1, }) mobs:register_mob("mobs_fallout:Mr_Pink", { type = "npc", group_attack = true, pathfinding = true, hp_min = 35, hp_max = 65, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"pink.png", "3d_armor_trans.png", minetest.registered_items["shooter:rifle"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 3, damage = 2, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_rifle", shoot_attack = "shooter_rifle", }, drops = { {name = "default:apple", chance = 1, min = 1, max = 2,}, {name = "default:sword_steel", chance = 2, min = 0, max = 1,}, }, armor = 75, drawtype = "front", water_damage = 70, lava_damage = 50, light_damage = 0, --attack_type = "dogfight", attack_type = "dogshoot", dogshoot_switch = 1, dogshoot_count_max = 10, arrow = "mobs_fallout:bullet", shoot_interval = 0.5, shoot_offset = 1, --[[ --MAIKERUMINE CRAP CODE on_rightclick = function (self, clicker) mobs:face_pos(self,clicker:getpos()) mobs:team_player(self,clicker:getpos()) if self.state ~= "path" and self.state ~= "following" then local_chat(clicker:getpos(),"Mr. Black: Grrrrrrrrrrrr!",3) if not self.tamed then self.tamed = true self.follow = true end end end,]] --TENPLUS1 and CProgrammerRU AWESOME CODES. -- right clicking with cooked meat will give npc more health on_rightclick = function(self, clicker) local item = clicker:get_wielded_item() local_chat(clicker:getpos(),"Mr. Pink: My name is Norman, how may I assist?",3) if item:get_name() == "mobs_fallout:meat" or item:get_name() == "farming:bread" then local hp = self.object:get_hp() if hp + 4 > self.hp_max then return end if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end self.object:set_hp(hp+4) -- right clicking with gold lump drops random item from mobs.npc_drops elseif item:get_name() == "default:gold_lump" then if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end local pos = self.object:getpos() pos.y = pos.y + 0.5 minetest.add_item(pos, {name = mobs.npc_drops[math.random(1,#mobs.npc_drops)]}) else if self.owner == "" then self.owner = clicker:get_player_name() else local formspec = "size[8,4]" formspec = formspec .. "textlist[2.85,0;2.1,0.5;dialog;What can I do for you?]" formspec = formspec .. "button_exit[1,1;2,2;gfollow;follow]" formspec = formspec .. "button_exit[5,1;2,2;gstand;stand]" formspec = formspec .. "button_exit[0,2;4,4;gfandp;follow and protect]" formspec = formspec .. "button_exit[4,2;4,4;gsandp;stand and protect]" --formspec = formspec .. "button_exit[1,2;2,2;ggohome; go home]" --formspec = formspec .. "button_exit[5,2;2,2;gsethome; sethome]" minetest.show_formspec(clicker:get_player_name(), "order", formspec) minetest.register_on_player_receive_fields(function(clicker, formname, fields) if fields.gfollow then self.order = "follow" self.attacks_monsters = false end if fields.gstand then self.order = "stand" self.attacks_monsters = false end if fields.gfandp then self.order = "follow" self.attacks_monsters = true end if fields.gsandp then self.order = "stand" self.attacks_monsters = true end if fields.gsethome then self.floats = self.object:getpos() end if fields.ggohome then if self.floats then self.order = "stand" self.object:setpos(self.floats) end end end) end end end, animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, attacks_monsters = true, peaceful = true, group_attack = true, step = 1, }) -- fireball (weapon) mobs:register_arrow("mobs_fallout:bullet", { visual = "sprite", visual_size = {x = 0.1, y = 0.11}, textures = {"shooter_bullet.png"}, velocity = 6, -- tail = 1, -- tail_texture = "mobs_fireball.png", -- tail_size = 10, -- direct hit, no fire... just plenty of pain hit_player = function(self, player) player:punch(self.object, 1.0, { full_punch_interval = 1.0, damage_groups = {fleshy = 8}, }, nil) end, hit_mob = function(self, player) player:punch(self.object, 1.0, { full_punch_interval = 1.0, damage_groups = {fleshy = 8}, }, nil) end, -- node hit, bursts into flame hit_node = function(self, pos, node) --mobs:explosion(pos, 1, 1, 0) end }) if minetest.setting_get("log_mods") then minetest.log("action", "crossfiremob loaded") end
slot2 = "LoadCcsCachedBean" LoadCcsCachedBean = class(slot1) LoadCcsCachedBean.ctor = function (slot0) slot4 = AbstractBean ClassUtil.extends(slot2, slot0) slot4 = TickBase ClassUtil.extends(slot2, slot0) slot0._ccsConfigs = {} slot0._tempCaches = {} slot0._curCcsIndex = 1 slot0._curCcsNum = 0 end LoadCcsCachedBean.tick = function (slot0) if not slot0._ccsConfigs[slot0._curCcsIndex] then slot4 = slot0._tempCaches for slot5, slot6 in ipairs(slot3) do slot10 = slot6 ccsPoolMgr.put(slot8, ccsPoolMgr) end slot0._tempCaches = {} else slot5 = slot1.totalNum - slot0._curCcsNum slot5 = "正在缓存:" .. slot1.url .. ",数量:" .. math.min(slot3, slot1.numPerFrame) print(slot1.numPerFrame) for slot6 = 1, math.min(slot3, slot1.numPerFrame), 1 do slot12 = slot1.isNodeOrLayout slot14 = tickMgr slot11 = "耗时:" .. tickMgr.getTimer(slot13) - tickMgr.getTimer(slot8) .. ", url:" .. slot1.url print(ccsPoolMgr) slot12 = ccsPoolMgr.get(tickMgr, ccsPoolMgr, slot1.url) table.insert(ccsPoolMgr, slot0._tempCaches) end slot0._curCcsNum = slot0._curCcsNum + slot2 if slot1.totalNum <= slot0._curCcsNum then slot0._curCcsIndex = slot0._curCcsIndex + 1 slot0._curCcsNum = 0 end end end LoadCcsCachedBean.destroy = function (slot0) slot3 = slot0 TickBase.destroy(slot2) slot3 = slot0 AbstractBean.destroy(slot2) end LoadCcsCachedBean.start = function (slot0) slot4 = 60 slot0.startTick(slot2, slot0) slot3 = slot0 slot0.tick(slot2) end return
--------------------------------------------- -- Familiar -- pet powers increase. --------------------------------------------- require("scripts/globals/msg") --------------------------------------------- function onMobSkillCheck(target, mob, skill) return 0 end function onMobWeaponSkill(target, mob, skill) mob:familiar() skill:setMsg(tpz.msg.basic.FAMILIAR_MOB) return 0 end
--[[ misc - nitro na klawisz @author Jakub 'XJMLN' Starzak <jack@pszmta.pl @package PSZMTA.psz-misc @copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl> Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie. ]]-- addEventHandler( "onClientResourceStart", getResourceRootElement(), function( ) bindKey( "vehicle_fire", "both", toggleNOS ); bindKey( "vehicle_secondary_fire", "both", toggleNOS ); end ) function toggleNOS( key, state ) local veh = getPedOccupiedVehicle(localPlayer); if veh and getPedOccupiedVehicleSeat(localPlayer)==0 then if state == "up" then removeVehicleUpgrade( veh, 1010 ); setControlState( "vehicle_fire", false ); else addVehicleUpgrade( veh, 1010 ); end end end
local ffi=require'ffi' ffi.cdef[[ typedef void *webview_t; // Creates a new webview instance. If debug is non-zero - developer tools will // be enabled (if the platform supports them). Window parameter can be a // pointer to the native window handle. If it's non-null - then child WebView // is embedded into the given parent window. Otherwise a new window is created. // Depending on the platform, a GtkWindow, NSWindow or HWND pointer can be // passed here. webview_t webview_create(int debug, void *window); // Destroys a webview and closes the native window. void webview_destroy(webview_t w); // Runs the main loop until it's terminated. After this function exits - you // must destroy the webview. void webview_run(webview_t w); // Stops the main loop. It is safe to call this function from another other // background thread. void webview_terminate(webview_t w); // Posts a function to be executed on the main thread. You normally do not need // to call this function, unless you want to tweak the native window. void webview_dispatch(webview_t w, void (*fn)(webview_t w, void *arg), void *arg); // Returns a native window handle pointer. When using GTK backend the pointer // is GtkWindow pointer, when using Cocoa backend the pointer is NSWindow // pointer, when using Win32 backend the pointer is HWND pointer. void *webview_get_window(webview_t w); // Updates the title of the native window. Must be called from the UI thread. void webview_set_title(webview_t w, const char *title); // Window size hints enum { HINT_NONE, // Width and height are default size HINT_MIN, // Width and height are minimum bounds HINT_MAX, // Width and height are maximum bounds HINT_FIXED // Window size can not be changed by a user }; // Updates native window size. See WEBVIEW_HINT constants. void webview_set_size(webview_t w, int width, int height, int hints); // Navigates webview to the given URL. URL may be a data URI, i.e. // "data:text/text,<html>...</html>". It is often ok not to url-encode it // properly, webview will re-encode it for you. void webview_navigate(webview_t w, const char *url); // Injects JavaScript code at the initialization of the new page. Every time // the webview will open a the new page - this initialization code will be // executed. It is guaranteed that code is executed before window.onload. void webview_init(webview_t w, const char *js); // Evaluates arbitrary JavaScript code. Evaluation happens asynchronously, also // the result of the expression is ignored. Use RPC bindings if you want to // receive notifications about the results of the evaluation. void webview_eval(webview_t w, const char *js); // Binds a native C callback so that it will appear under the given name as a // global JavaScript function. Internally it uses webview_init(). Callback // receives a request string and a user-provided argument pointer. Request // string is a JSON array of all the arguments passed to the JavaScript // function. void webview_bind(webview_t w, const char *name, void (*fn)(const char *seq, const char *req, void *arg), void *arg); // Allows to return a value from the native binding. Original request pointer // must be provided to help internal RPC engine match requests with responses. // If status is zero - result is expected to be a valid JSON result value. // If status is not zero - result is an error JSON object. void webview_return(webview_t w, const char *seq, int status, const char *result) ; ]] -- for windows, run: checknetisolation LoopbackExempt -a -n=Microsoft.Win32WebViewHost_cw5n1h2txyewy local api=ffi.load('./lib/libwebview.dylib') local _mt={} function _mt:__index(key) local r=rawget(self,key) if r~=nil then return r end if key=='reply' then key='return' end local meth='webview_'..key local f=api[meth] if f then return function(self,...) assert(self.view,'webview is nil') return f(self.view,...) end end end function _mt:__gc() if self.view then api.webview_destroy(self.view) self.view=nil end end local function create(dbg,window) local obj={view=api.webview_create(dbg or 0,window)} return setmetatable(obj,_mt) end if not ... then local cjson=require'cjson' local win=create() win:set_title('test win') win:set_size(640,480,0) win:bind('test',function(seq,req,arg) local sreq=ffi.string(req) print('got req:',sreq,'\nseq:',ffi.string(seq)) local jsn_req=cjson.decode(sreq); local ret=jsn_req[1]+jsn_req[2] win:reply(seq,0,cjson.encode(ret)) end,nil) win:bind('closewin',function(seq,req,arg) win:terminate() end,nil) -- win:init('') win:navigate([[data:text/html, <!doctype html> <html> <body> <div><h1>TEST</h1></div> <b>result:</b><i id='result'></i> <div id='navigator'></div> <div><button onclick='closewin()'>Shut me down</button></div> </body> <script> window.onload = function() { test(1, 2).then(function(res) { console.log('add res', res); document.getElementById('result').innerText=res document.getElementById('navigator').innerText = `hello, ${navigator.userAgent}`; }); }; </script> </html> ]]) win:run() else return create end
BattleScene.text("* Susie cooked up a cure!") BattleScene.text("* What, you want me to cook\nsomething?", "face_2", "susie") BattleScene.text("* Susie put a hot dog in the\nmicrowave!") local susie = BattleScene.getCharacter("susie") local target = BattleScene.getTarget() target:explode(0, 0, true) target:hurt(target.health * 0.75, susie) BattleScene.text("* She forgot to poke holes in it!\nThe hot dog exploded!") -- Note: the following isn't part of the original act, it's here for testing battle cutscenes! BattleScene.enemyText(target, "Dumbass") BattleScene.text("* I, uh, meant to do that.", "face_3", "susie")
local ultimateHealthPot = 8473 local greatHealthPot = 7591 local greatManaPot = 7590 local greatSpiritPot = 8472 local strongHealthPot = 7588 local strongManaPot = 7589 local healthPot = 7618 local manaPot = 7620 local smallHealthPot = 8704 local antidotePot = 8474 local greatEmptyPot = 7635 local strongEmptyPot = 7634 local emptyPot = 7636 local antidote = Combat() antidote:setParameter(COMBAT_PARAM_TYPE, COMBAT_HEALING) antidote:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE) antidote:setParameter(COMBAT_PARAM_TARGETCASTERORTOPMOST, true) antidote:setParameter(COMBAT_PARAM_AGGRESSIVE, false) antidote:setParameter(COMBAT_PARAM_DISPEL, CONDITION_POISON) local exhaust = Condition(CONDITION_EXHAUST_HEAL) exhaust:setParameter(CONDITION_PARAM_TICKS, (configManager.getNumber(configKeys.EX_ACTIONS_DELAY_INTERVAL) - 100)) -- 1000 - 100 due to exact condition timing. -100 doesn't hurt us, and players don't have reminding ~50ms exhaustion. function onUse(player, item, fromPosition, target, toPosition, isHotkey) if target == nil or not target:isPlayer() then return true end if player:getCondition(CONDITION_EXHAUST_HEAL) then player:sendTextMessage(MESSAGE_STATUS_SMALL, Game.getReturnMessage(RETURNVALUE_YOUAREEXHAUSTED)) return true end local itemId = item:getId() if itemId == antidotePot then if not antidote:execute(target, numberToVariant(target:getId())) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(emptyPot, 1) elseif itemId == smallHealthPot then if not doTargetCombatHealth(0, target, COMBAT_HEALING, 60, 90, CONST_ME_MAGIC_BLUE) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(emptyPot, 1) elseif itemId == healthPot then if not doTargetCombatHealth(0, target, COMBAT_HEALING, 125, 175, CONST_ME_MAGIC_BLUE) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(emptyPot, 1) elseif itemId == manaPot then if not doTargetCombatMana(0, target, 75, 125, CONST_ME_MAGIC_BLUE) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(emptyPot, 1) elseif itemId == strongHealthPot then if (not isInArray({3, 4, 7, 8}, target:getVocation():getId()) or target:getLevel() < 50) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then player:say("This potion can only be consumed by paladins and knights of level 50 or higher.", TALKTYPE_MONSTER_SAY) return true end if not doTargetCombatHealth(0, target, COMBAT_HEALING, 250, 350, CONST_ME_MAGIC_BLUE) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(strongEmptyPot, 1) elseif itemId == strongManaPot then if (not isInArray({1, 2, 3, 5, 6, 7}, target:getVocation():getId()) or target:getLevel() < 50) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then player:say("This potion can only be consumed by sorcerers, druids and paladins of level 50 or higher.", TALKTYPE_MONSTER_SAY) return true end if not doTargetCombatMana(0, target, 115, 185, CONST_ME_MAGIC_BLUE) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(strongEmptyPot, 1) elseif itemId == greatSpiritPot then if (not isInArray({3, 7}, target:getVocation():getId()) or target:getLevel() < 80) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then player:say("This potion can only be consumed by paladins of level 80 or higher.", TALKTYPE_MONSTER_SAY) return true end if not doTargetCombatHealth(0, target, COMBAT_HEALING, 250, 350, CONST_ME_MAGIC_BLUE) or not doTargetCombatMana(0, target, 100, 200, CONST_ME_MAGIC_BLUE) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(greatEmptyPot, 1) elseif itemId == greatHealthPot then if (not isInArray({4, 8}, target:getVocation():getId()) or target:getLevel() < 80) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then player:say("This potion can only be consumed by knights of level 80 or higher.", TALKTYPE_MONSTER_SAY) return true end if not doTargetCombatHealth(0, target, COMBAT_HEALING, 425, 575, CONST_ME_MAGIC_BLUE) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(greatEmptyPot, 1) elseif itemId == greatManaPot then if (not isInArray({1,2,5,6}, target:getVocation():getId()) or target:getLevel() < 80) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then player:say("This potion can only be consumed by sorcerers and druids of level 80 or higher.", TALKTYPE_MONSTER_SAY) return true end if not doTargetCombatMana(0, target, 150, 250, CONST_ME_MAGIC_BLUE) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(greatEmptyPot, 1) elseif itemId == ultimateHealthPot then if (not isInArray({4, 8}, target:getVocation():getId()) or target:getLevel() < 130) and not getPlayerFlagValue(player, PlayerFlag_IgnoreSpellCheck) then player:say("This potion can only be consumed by knights of level 130 or higher.", TALKTYPE_MONSTER_SAY) return true end if not doTargetCombatHealth(0, target, COMBAT_HEALING, 650, 850, CONST_ME_MAGIC_BLUE) then return false end player:addCondition(exhaust) target:say("Aaaah...", TALKTYPE_MONSTER_SAY) item:remove(1) player:addItem(greatEmptyPot, 1) end return true end
local rules = require "scripts.rules" local animations = require "character.animations" local Character = require "character.character" local Skeleton = Character:new() function Skeleton:new(o, control) o = o or Character:new(o, control) setmetatable(o, self) self.__index = self return o end function Skeleton:create() Character.create(self) self:set_skin("skeleton") local stats = self.data.stats stats.name = "Skeleton" rules.set_ability_scores_map(stats, { str = 15, dex = 10, con = 13, int = 3, wis = 3, cha = 3, }) stats.armor = { code = self.name .. "_armor", name = "skeleton_bones", type = "armor" } end return Skeleton
-- local U = require('utils') -- local err = U.get_hl_color('ErrorMsg', 'fg') -- local warn = U.get_hl_color('WarningMsg', 'fg') require('lualine').setup({ options = { theme = 'horizon' } })
-- richtext library --[[ This version is modified by UmmUmmDe to fix some bugs that were affecting the Pokemon Engine. ]] --[[ Copyright (c) 2010 Robin Wellner Copyright (c) 2014 Florian Fischer (class changes, initial color, ...) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ]] -- issues/bugs: -- * still under-tested -- * word wrapping might not be optimal -- * words keep their final space in wrapping, which may cause words to be wrapped too soon local rich = {} rich.__index = rich function rich:new(t, stdcolor) -- syntax: rt = rich.new{text, width, resource1 = ..., ...} local obj = setmetatable({parsedtext = {}, resources = {}}, rich) obj.width = t[2] obj.hardwrap = false obj:extract(t) obj:parse(t) -- set text standard color if stdcolor and type(stdcolor) =='table' then love.graphics.setColor( unpack(stdcolor) ) end if love.graphics.isSupported and love.graphics.isSupported('canvas') then obj:render() obj:render(true) end return obj end function rich:draw(x, y) local firstR, firstG, firstB, firstA = love.graphics.getColor() --love.graphics.setColor(255, 255, 255, 255) --Note from UUD: No longer sets color. local prevMode = love.graphics.getBlendMode() if self.framebuffer then love.graphics.setBlendMode("premultiplied") love.graphics.draw(self.framebuffer, x, y) love.graphics.setBlendMode(prevMode) else love.graphics.push() love.graphics.translate(x, y) self:render() love.graphics.pop() end love.graphics.setColor(firstR, firstG, firstB, firstA) end function rich:extract(t) if t[3] and type(t[3]) == 'table' then for key,value in pairs(t[3]) do local meta = type(value) == 'table' and value or {value} self.resources[key] = self:initmeta(meta) -- sets default values, does a PO2 fix... end else for key,value in pairs(t) do if type(key) == 'string' then local meta = type(value) == 'table' and value or {value} self.resources[key] = self:initmeta(meta) -- sets default values, does a PO2 fix... end end end end local function parsefragment(parsedtext, textfragment) -- break up fragments with newlines local n = textfragment:find('\n', 1, true) while n do table.insert(parsedtext, textfragment:sub(1, n-1)) table.insert(parsedtext, {type='nl'}) textfragment = textfragment:sub(n + 1) n = textfragment:find('\n', 1, true) end table.insert(parsedtext, textfragment) end function rich:parse(t) local text = t[1] if string.len(text) > 0 then -- look for {tags} or [tags] for textfragment, foundtag in text:gmatch'([^{]*){(.-)}' do parsefragment(self.parsedtext, textfragment) table.insert(self.parsedtext, self.resources[foundtag] or foundtag) end local match = text:match('[^}]+$') if match then parsefragment(self.parsedtext, text:match('[^}]+$')) end end end -- [[ since 0.8.0, no autopadding needed any more local log2 = 1/math.log(2) local function nextpo2(n) return math.pow(2, math.ceil(math.log(n)*log2)) end local metainit = {} function metainit.Image(res, meta) meta.type = 'img' local w, h = res:getWidth(), res:getHeight() --[[ since 0.8.0, no autopadding needed any more if not rich.nopo2 then local neww = nextpo2(w) local newh = nextpo2(h) if neww ~= w or newh ~= h then local padded = love.image.newImageData(wp, hp) padded:paste(love.image.newImageData(res), 0, 0) meta[1] = love.graphics.newImage(padded) end end ]] meta.width = meta.width or w meta.height = meta.height or h end function metainit.Font(res, meta) meta.type = 'font' end function metainit.number(res, meta) meta.type = 'color' end function rich:initmeta(meta) local res = meta[1] local type = (type(res) == 'userdata') and res:type() or type(res) if metainit[type] then metainit[type](res, meta) else error("Unsupported type") end return meta end local function wrapText(parsedtext, fragment, lines, maxheight, x, width, i, fnt, hardwrap) if not hardwrap or (hardwrap and x > 0) then -- find first space, split again later if necessary local n = fragment:find(' ', 1, true) local lastn = n while n do local newx = x + fnt:getWidth(fragment:sub(1, n-1)) if newx > width then break end lastn = n n = fragment:find(' ', n + 1, true) end n = lastn or (#fragment + 1) -- wrapping parsedtext[i] = fragment:sub(1, n-1) table.insert(parsedtext, i+1, fragment:sub((fragment:find('[^ ]', n) or (n+1)) - 1)) lines[#lines].height = maxheight maxheight = 0 x = 0 table.insert(lines, {}) end return maxheight, 0 end local function renderText(parsedtext, fragment, lines, maxheight, x, width, i, hardwrap) local fnt = love.graphics.getFont() or love.graphics.newFont(12) if x + fnt:getWidth(fragment) > width then -- oh oh! split the text maxheight, x = wrapText(parsedtext, fragment, lines, maxheight, x, width, i, fnt, hardwrap) end -- hardwrap long words if hardwrap and x + fnt:getWidth(parsedtext[i]) > width then local n = #parsedtext[i] while x + fnt:getWidth(parsedtext[i]:sub(1, n)) > width do n = n - 1 end local p1, p2 = parsedtext[i]:sub(1, n - 1), parsedtext[i]:sub(n) parsedtext[i] = p1 if not parsedtext[i + 1] then parsedtext[i + 1] = p2 elseif type(parsedtext[i + 1]) == 'string' then parsedtext[i + 1] = p2 .. parsedtext[i + 1] elseif type(parsedtext[i + 1]) == 'table' then table.insert(parsedtext, i + 2, p2) table.insert(parsedtext, i + 3, {type='nl'}) end lines[#lines].height = maxheight maxheight = 0 x = 0 table.insert(lines, {}) end local h = math.floor(fnt:getHeight(parsedtext[i]) * fnt:getLineHeight()) maxheight = math.max(maxheight, h) return maxheight, x + fnt:getWidth(parsedtext[i]), {parsedtext[i], x = x > 0 and x or 0, type = 'string', height = h, width = fnt:getWidth(parsedtext[i])} end local function renderImage(fragment, lines, maxheight, x, width) local newx = x + fragment.width if newx > width and x > 0 then -- wrapping lines[#lines].height = maxheight maxheight = 0 x = 0 table.insert(lines, {}) end maxheight = math.max(maxheight, fragment.height) return maxheight, newx, {fragment, x = x, type = 'img'} end local function doRender(parsedtext, width, hardwrap) local x = 0 local lines = {{}} local maxheight = 0 for i, fragment in ipairs(parsedtext) do -- prepare rendering if type(fragment) == 'string' then maxheight, x, fragment = renderText(parsedtext, fragment, lines, maxheight, x, width, i, hardwrap) elseif fragment.type == 'img' then maxheight, x, fragment = renderImage(fragment, lines, maxheight, x, width) elseif fragment.type == 'font' then love.graphics.setFont(fragment[1]) elseif fragment.type == 'nl' then -- move onto next line, reset x and maxheight lines[#lines].height = maxheight maxheight = 0 x = 0 table.insert(lines, {}) -- don't want nl inserted into line fragment = '' end table.insert(lines[#lines], fragment) end --~ for i,f in ipairs(parsedtext) do --~ print(f) --~ end lines[#lines].height = maxheight return lines end local function doDraw(lines) local y = 0 local colorr,colorg,colorb,colora = love.graphics.getColor() for i, line in ipairs(lines) do -- do the actual rendering y = y + line.height for j, fragment in ipairs(line) do if fragment.type == 'string' then -- remove leading spaces, but only at the begin of a new line -- Note: the check for fragment 2 (j==2) is to avoid a sub for leading line space if j==2 and string.sub(fragment[1], 1, 1) == ' ' then fragment[1] = string.sub(fragment[1], 2) end love.graphics.print(fragment[1], fragment.x, y - fragment.height) if rich.debug then love.graphics.rectangle('line', fragment.x, y - fragment.height, fragment.width, fragment.height) end elseif fragment.type == 'img' then love.graphics.setColor(255,255,255) love.graphics.draw(fragment[1][1], fragment.x, y - fragment[1].height) if rich.debug then love.graphics.rectangle('line', fragment.x, y - fragment[1].height, fragment[1].width, fragment[1].height) end love.graphics.setColor(colorr,colorg,colorb,colora) elseif fragment.type == 'font' then love.graphics.setFont(fragment[1]) elseif fragment.type == 'color' then love.graphics.setColor(unpack(fragment)) colorr,colorg,colorb,colora = love.graphics.getColor() end end end end function rich:calcHeight(lines) local h = 0 for _, line in ipairs(lines) do h = h + line.height end return h end function rich:render(usefb) local renderWidth = self.width or math.huge -- if not given, use no wrapping local firstFont = love.graphics.getFont() or love.graphics.newFont(12) local firstR, firstG, firstB, firstA = love.graphics.getColor() local lines = doRender(self.parsedtext, renderWidth, self.hardwrap) -- dirty hack, add half height of last line to bottom of height to ensure tails of y's and g's, etc fit in properly. self.height = self:calcHeight(lines) + math.floor((lines[#lines].height / 2) + 0.5) local fbWidth = math.max(nextpo2(math.max(love.graphics.getWidth(), self.width or 0)), nextpo2(math.max(love.graphics.getHeight(), self.height))) local fbHeight = fbWidth love.graphics.setFont(firstFont) if usefb then self.framebuffer = love.graphics.newCanvas(fbWidth, fbHeight) self.framebuffer:setFilter( 'nearest', 'nearest' ) self.framebuffer:renderTo(function () doDraw(lines) end) else self.height = doDraw(lines) end love.graphics.setFont(firstFont) love.graphics.setColor(firstR, firstG, firstB, firstA) end return rich
-- Moonstone Web Development Framework,A Framework To Develop Websites And Webpages Using Lua Programming Language -- Copyright (c)2019-Present Rabia Alhaffar,All Rights Reserved!!! -- You Can Also Use C/C++/HTML/CSS/Javascript/PHP/VBScript/JScript/C#/Lua/Visual Basic .NET/ASP Code Within The Main Lua Code,But With Some Differences!!! page_to_open = "" notonsameline = true autolaunchsite = false local moonstone = { str = function(x) return "\""..x.."\"" end, start = function() print("Enter Directory Of Compiled Code File(Type Extension):") page_directory = io.read() page_to_open = io.open(page_directory,'w') end, finish = function() page_to_open:close() if autolaunchsite then os.execute("start "..page_directory) end end, html = { start = function() page_to_open:write("<!DOCTYPE html>\n") page_to_open:write("<html>\n") end, finish = function() page_to_open:write("</html>\n") end, head = { start = function() page_to_open:write("<head>\n") end, finish = function() page_to_open:write("</head>\n") end }, center = { start = function() page_to_open:write("<center>\n") end, finish = function() page_to_open:write("</center>\n") end }, code = { start = function() page_to_open:write("<code>\n") end, finish = function() page_to_open:write("</code>\n") end }, body = { start = function() page_to_open:write("<body>\n") end, finish = function() page_to_open:write("</body>\n") end }, ol = { start = function() page_to_open:write("<ol>\n") end, finish = function() page_to_open:write("</ol>\n") end }, ul = { start = function() page_to_open:write("<ul>\n") end, finish = function() page_to_open:write("</ul>\n") end }, title = function(t) page_to_open:write("<title>"..t.."</title>\n") end, p = function(text) page_to_open:write("<p>"..text.."</p>") checkline() end, b = function(text) page_to_open:write("<b>"..text.."</b>") checkline() end, i = function(text) page_to_open:write("<i>"..text.."</i>") checkline() end, s = function(text) page_to_open:write("<s>"..text.."</s>") checkline() end, strong = function(text) page_to_open:write("<strong>"..text.."</strong>") checkline() end, em = function(text) page_to_open:write("<em>"..text.."</em>") checkline() end, h1 = function(text) page_to_open:write("<h1>"..text.."</h1>") checkline() end, h2 = function(text) page_to_open:write("<h2>"..text.."</h2>") checkline() end, h3 = function(text) page_to_open:write("<h3>"..text.."</h3>") checkline() end, h4 = function(text) page_to_open:write("<h4>"..text.."</h4>") checkline() end, h5 = function(text) page_to_open:write("<h5>"..text.."</h5>") checkline() end, h6 = function(text) page_to_open:write("<h6>"..text.."</h6>") checkline() end, var = function(text) page_to_open:write("<var>"..text.."</var>") checkline() end, kbd = function(text) page_to_open:write("<kbd>"..text.."</kbd>") checkline() end, samp = function(text) page_to_open:write("<samp>"..text.."</samp>") checkline() end, q = function(text) page_to_open:write("<q>"..text.."</q>") checkline() end, ins = function(text) page_to_open:write("<ins>"..text.."</ins>") checkline() end, del = function(text) page_to_open:write("<del>"..text.."</del>") checkline() end, small = function(text) page_to_open:write("<small>"..text.."</small>") checkline() end, u = function(text) page_to_open:write("<u>"..text.."</u>") checkline() end, comment = function(text) page_to_open:write("<!-- "..text.." -->\n") end, pre = function(text) page_to_open:write("<pre>"..text.."</pre>") checkline() end, watermark = function() page_to_open:write("<b>Generated And Powered By <a href=".."\"".."https://lua.org".."\""..">".._VERSION.."</a>,And <a href=".."\"".."https://github.com/Rabios/Moonstone".."\""..">Moonstone</a> Framework</b>\n") end, noscript = function(text) page_to_open:write("<noscript>"..text.."</noscript>") checkline() end, br = function() page_to_open:write("<br>") checkline() end, wbr = function() page_to_open:write("<wbr>") checkline() end, a = function(href,text) page_to_open:write("<a href=".."\""..href.."\""..">"..text.."</a>") checkline() end, attr = function(name,value) page_to_open:write(name.."=".."\""..value.."\"".."\n") end, img = function(src) page_to_open:write("<img src=".."\""..src.."\""..">") checkline() end, canvas = function(id,height,width) page_to_open:write("<canvas id=".."\""..id.."\"".." height=".."\""..height.."\"".." width=".."\""..width.."\"".."></canvas>") checkline() end, progress = function(value,max) page_to_open:write("<progress value=".."\""..value.."\"".." max=".."\""..max.."\"".."></progress>\n") checkline() end, li = function(text) page_to_open:write("<li>"..text.."</li>") checkline() end, article = { start = function() page_to_open:write("<article>\n") end, finish = function() page_to_open:write("</article>\n") end }, bdi = function(text) page_to_open:write("<bdi>"..text.."</bdi>") checkline() end, dl = { start = function() page_to_open:write("<dl>\n") checkline() end, finish = function() page_to_open:write("</dl>\n") checkline() end }, dt = function(text) page_to_open:write("<dt>"..text.."</dt>") checkline() end, dd = function(text) page_to_open:write("<dd>"..text.."</dd>") checkline() end, embed = function(src) page_to_open:write("<embed src=".."\""..src.."\""..">") checkline() end, data = function(text,value) page_to_open:write("<data value=".."\""..value.."\""..">"..text.."</data>") checkline() end, button = function(id,text) page_to_open:write("<button id=".."\""..id.."\""..">"..text.."</button>") checkline() end, ruby = { start = function() page_to_open:write("<ruby>\n") end, finish = function() page_to_open:write("</ruby>\n") end }, rp = function(text) page_to_open:write("<rp>"..text.."</rp>") checkline() end, rt = function(text) page_to_open:write("<rt>"..text.."</rt>") checkline() end, sup = function(text) page_to_open:write("<sup>"..text.."<sup>") checkline() end, cite = function(text) page_to_open:write("<cite>"..text.."</cite>") checkline() end, hr = function() page_to_open:write("<hr>") checkline() end, details = { start = function(summary) page_to_open:write("<details>\n") page_to_open:write("<summary>"..summary.."</summary>\n") end, finish = function() page_to_open:write("</details>\n") end, }, summary = function(text) page_to_open:write("<summary>"..text.."</summary>") checkline() end, textarea = { start = function(text) page_to_open:write("<textarea>\n") page_to_open:write(text.."\n") end, finish = function() page_to_open:write("</textarea>\n") end }, div = { start = function(id) page_to_open:write("<div id=".."\""..id.."\""..">\n") end, finish = function() page_to_open:write("</div>\n") end }, nav = { start = function() page_to_open:write("<nav>\n") end, finish = function() page_to_open:write("</nav>\n") end }, select = { start = function() page_to_open:write("<select>\n") end, finish = function() page_to_open:write("</select>\n") end }, option = function(text) page_to_open:write("<option>"..text.."</option>") checkline() end, input = function(t) page_to_open:write("<input type=".."\""..t.."\""..">") checkline() end, audio = { start = function() page_to_open:write("<audio controls>\n") end, finish = function() page_to_open:write("</audio>\n") end }, video = { start = function(height,width) page_to_open:write("<video height=".."\""..height.."\"".." width=".."\""..width.."\"".." controls>\n") end, finish = function() page_to_open:write("</video>\n") end }, footer = { start = function() page_to_open:write("<footer>\n") end, finish = function() page_to_open:write("</footer>\n") end }, figure = { start = function() page_to_open:write("<figure>\n") end, finish = function() page_to_open:write("</figure>\n") end }, mark = function(text) page_to_open:write("<mark>"..text.."</mark>") checkline() end, main = { start = function() page_to_open:write("<main>\n") end, finish = function() page_to_open:write("</main>\n") end }, section = { start = function() page_to_open:write("<section>\n") end, finish = function() page_to_open:write("</section>\n") end }, table = { start = function() page_to_open:write("<table>\n") end, finish = function() page_to_open:write("</table>\n") end }, tr = { start = function() page_to_open:write("<tr>\n") end, finish = function() page_to_open:write("</tr>\n") end }, th = function(text) page_to_open:write("<th>"..text.."</th>") checkline() end, td = function(text) page_to_open:write("<td>"..text.."</td>") checkline() end }, js = { start = function() page_to_open:write("<script>\n") end, finish = function() page_to_open:write("</script>\n") end, comment = function(comment) page_to_open:write("//"..comment.."\n") end, multiline_comment = { start = function() page_to_open:write("/*\n") end, finish = function() page_to_open:write("*/\n") end }, console = { log = function(msg) page_to_open:write("console.log("..msg..");\n") end }, window = { alert = function(msg) page_to_open:write("window.alert("..msg..");\n") end, open = function(link) page_to_open:write("window.open(".."\""..link.."\""..");\n") end }, document = { reload = function() page_to_open:write("document.reload();\n") end, write = function(msg) page_to_open:write("document.write("..msg..");\n") end, writeln = function(msg) page_to_open:write("document.writeln("..msg..");\n") end } }, md = { h1 = function(text) page_to_open:write("# "..text.."\n") end, h2 = function(text) page_to_open:write("## "..text.."\n") end, h3 = function(text) page_to_open:write("### "..text.."\n") end, h4 = function(text) page_to_open:write("#### "..text.."\n") end, h5 = function(text) page_to_open:write("##### "..text.."\n") end, h6 = function(text) page_to_open:write("###### "..text.."\n") end, underline = function() page_to_open:write("------------------------------------------\n") end, p = function(text) page_to_open:write(text.."\n") end, a = function(text,href) page_to_open:write("["..text.."]("..tostring(href)..")\n") end, checkbox = function(text,checked) if checked then page_to_open:write("- [x] "..text.."\n") end if not checked then page_to_open:write("- [ ] "..text.."\n") end end, point = function(text) page_to_open:write("- "..text.."\n") end, note = function(text) page_to_open:write("\n> "..text.."\n") end, step = function(number,text) page_to_open:write(tostring(number)..". "..text.."\n") end, emoji = function(name) page_to_open:write(":"..name.."\n") end, watermark = function() page_to_open:write("\n> Generated And Powered By [".._VERSION.."](https://lua.org),And [Moonstone](https://github.com/Rabios/Moonstone) Framework\n") end, comment = function(comment) page_to_open:write("\n[comment]: # ("..tostring(comment)..")\n") end, b = function(text) page_to_open:write("**"..text.."**\n") end, i = function(text) page_to_open:write("*"..text.."*\n") end, del = function(text) page_to_open:write("~~"..text.."~~\n") end , code = { start = function(language) page_to_open:write("```"..tostring(language).."\n") end, finish = function() page_to_open:write("```\n") end, snippet = function(code) page_to_open:write("`"..code.."`\n") end } }, css = { start = function() page_to_open:write("<style>\n") end, finish = function() page_to_open:write("</style>\n") end, style = { class = function(class,style) page_to_open:write("."..class.." { "..style.." }\n") end, tag = function(tags,style) page_to_open:write(tags.." { "..style.." }\n") end, id = function(id,style) page_to_open:write("#"..id.." { "..style.." }\n") end } }, php = { start = function() page_to_open:write("<?php\n") end, finish = function() page_to_open:write("?>\n") end, echo = function(msg) page_to_open:write("echo "..msg..";\n") end }, csharp = { start = function() page_to_open:write("@{\n") end, finish = function() page_to_open:write("}\n") end }, vb = { start = function() page_to_open:write("@Code\n") end, finish = function() page_to_open:write("End Code\n") end }, vbscript = { start = function() page_to_open:write("<%@ Language=".."\"".."VBScript".."\"".."\n") end, finish = function() page_to_open:write("%>\n") end }, jscript = { start = function() page_to_open:write("<%@ Language=".."\"".."JScript".."\"".."\n") end, finish = function() page_to_open:write("%>\n") end }, endline = function() page_to_open:write("\n") end, script = function(code) page_to_open:write(code.."\n") end, writeline = function(mode) notonsameline = mode end, src = function(t,src) if t == "script" then page_to_open:write("<script src=".."\""..src.."\"".."></script>") checkline() end if t == "style" then page_to_open:write("<style src=".."\""..src.."\"".."></style>") checkline() end if t == "iframe" then page_to_open:write("<iframe src=".."\""..src.."\"".."></iframe>") checkline() end if t == "source" then page_to_open:write("<source src=".."\""..src.."\""..">\n") end end, } function p(text) return "<p>"..text.."</p>" end function b(text) return "<b>"..text.."</b>" end function i(text) return "<i>"..text.."</i>" end function u(text) return "<u>"..text.."</u>" end function small(text) return "<small>"..text.."</small>" end function samp(text) return "<samp>"..text.."</samp>" end function kbd(text) return "<kbd>"..text.."</kbd>" end function ins(text) return "<ins>"..text.."</ins>" end function q(text) return "<q>"..text.."</q>" end function del(text) return "<del>"..text.."</del>" end function mark(text) return "<mark>"..text.."</mark>" end function var(text) return "<var>"..text.."</var>" end function pre(text) return "<pre>"..text.."</pre>" end function strong(text) return "<strong>"..text.."</strong>" end function em(text) return "<em>"..text.."</em>" end function h1(text) return "<h1>"..text.."</h1>" end function h2(text) return "<h2>"..text.."</h2>" end function h3(text) return "<h3>"..text.."</h3>" end function h4(text) return "<h4>"..text.."</h4>" end function h5(text) return "<h5>"..text.."</h5>" end function h6(text) return "<h6>"..text.."</h6>" end function rp(text) return "<rp>"..text.."</rp>" end function rt(text) return "<rt>"..text.."</rt>" end function sup(text) return "<sup>"..text.."</sup>" end function cite(text) return "<cite>"..text.."</cite>" end function option(text) return "<option>"..text.."</option>" end function summary(text) return "<summary>"..text.."</summary>" end function dd(text) return "<dd>"..text.."</dd>" end function dt(text) return "<dt>"..text.."</dt>" end function bdi(text) return "<bdi>"..text.."</bdi>" end function li(text) return "<li>"..text.."</li>" end function th(text) return "<th>"..text.."</th>" end function td(text) return "<td>"..text.."</td>" end function noscript(text) return "<noscript>"..text.."</noscript>" end function a(href,text) return "<a href=".."\""..href.."\""..">"..text.."</a>" end function br() return "<br>" end function wbr() return "<wbr>" end function img(src) return "<img src=".."\""..src.."\""..">" end function attr(name,value) return tostring(name).."=".."\""..value.."\"".."\n" end function checkline() if notonsameline then page_to_open:write("\n") end end function mdbold(text) return "**"..text.."**" end function mditalic() return "*"..text.."*" end function mddel() return "~~"..text.."~~" end function str(x) return "\""..x.."\"" end return moonstone
local path, Delta = ... local Thread = Delta.lib.Thread local Switch = {} local Services = {} local Processes = {} Services.DHCP = Thread.new(Delta.dofile(path.."Switch.lua", Delta)) function Switch.run() Thread.run(Services) end return Switch
-- 001 local style = utaha.styleCollection -- Global Font Styles style :addFont("font.normal", "res/fonts/wqy-zenhei.ttf", 18) :addFont("font.small", "res/fonts/wqy-zenhei.ttf", 12) :addFont("font.big", "res/fonts/wqy-zenhei.ttf", 20) -- Flat Menu Styles :setFont("FlatMenu.font", "font.normal") :setColor("FlatMenu.bg.color", 0x00000080) :setColor("FlatMenu.hot.color", 0x007bffff) :setColor("FlatMenu.font.color", 0xffffffff) :setColor("FlatMenu.border.color", 0xffffffff) :setInt("FlatMenu.padding.size", 4) -- Flat Menu Group Styles :setFont("FlatMenuGroup.font", "font.normal") :setColor("FlatMenuGroup.bg.color", 0x000000ff) :setColor("FlatMenuGroup.hot.color", 0x007bffff) :setColor("FlatMenuGroup.font.color", 0xffffffff) :setColor("FlatMenuGroup.border.color", 0xffffffff) :setInt("FlatMenuGroup.padding.h.size", 10) :setInt("FlatMenuGroup.padding.v.size", 2) -- Flat Button Styles :setFont("FlatButton.font", "font.normal") :setSize("FlatButton.defaultSize", 40, 22) :setColor("FlatButton.bg.color", 0x007bffff) :setColor("FlatButton.hot.color", 0x108bffff) :setColor("FlatButton.font.color", 0xffffffff) :setColor("FlatButton.pressed.color", 0x007bffff) -- Flat Input Box Styles :setFont("FlatInputBox.font", "font.normal") :setSize("FlatInputBox.defaultSize", 40, 22) :setInt("FlatInputBox.defaultMaxInput", 32) :setColor("FlatInputBox.bg.color", 0x000000ff) :setColor("FlatInputBox.font.color", 0x00ff00ff) :setColor("FlatInputBox.border.color", 0xffffffff) :setInt("FlatInputBox.padding.size", 4) -- Flat Check Box Styles :setFont("FlatCheckBox.font", "font.normal") :setColor("FlatCheckBox.font.color", 0xffffffff) :setColor("FlatCheckBox.box.color", 0x007bffff) :setInt("FlatCheckBox.padding.h.size", 10) :setInt("FlatCheckBox.padding.v.size", 2) -- Flat Status Bar Styles :setFont("FlatStatusBar.font", "font.normal") :setColor("FlatStatusBar.font.color", 0xffffffff) :setColor("FlatStatusBar.bg.color", 0x000000ff) :setColor("FlatCheckBox.border.color", 0xffffffff) :setInt("FlatStatusBar.padding.size", 10) -- Pic Grid Selector Styles :setColor("PicGridSelector.grid.color", 0x00ff00ff) :setColor("PicGridSelector.selected.color", 0x80ff008f)
local M = {} -- perform a correct deep merge of several maps function M.tbl_merge(self, ...) return vim.tbl_deep_extend("force", ...) end -- this function sets a global key mapping function M.keymap(self, mode, lhs, rhs, options) return vim.api.nvim_set_keymap( mode, lhs, rhs, self:tbl_merge({silent=true}, options or {}) ) end -- this function sets a global key mapping with noremap=true function M.keynmap(self, mode, lhs, rhs, options) return self:keymap(mode, lhs, rhs, {noremap=true}) end -- this function sets a global key mapping with expr=true function M.keyemap(self, mode, lhs, rhs, options) return self:keymap(mode, lhs, rhs, {expr=true}) end -- returns another function that sets a key mapping to a buffer function M.get_buf_keymap(self, bufnr, defaults) defaults = self:tbl_merge({silent=true}, defaults or {}) return function(mode, lhs, rhs, options) return vim.api.nvim_buf_set_keymap( bufnr, mode, lhs, rhs, self:tbl_merge(defaults or {}, options or {}) ) end end -- returns another function that sets an option to a buffer function M.get_buf_set_option(self, bufnr) return function(key, value) vim.api.nvim_buf_set_option(bufnr, key, value) end end -- returns internal representation of terminal code or keycodes. -- please see :h nvim_replace_termcodes() for details. function M.termcode(self, code) return vim.api.nvim_replace_termcodes(code, true, true, true) end -- sets a consistent indentation settings function M.set_indent(self, tbl, options) if type(options) == "number" then options = {tabstop=options} end options.tabstop = options.tabstop or 4 tbl.tabstop = options.tabstop tbl.softtabstop = options.softtabstop or options.tabstop tbl.shiftwidth = options.shiftwidth or options.tabstop end return M
do local function getTermLength() if sys.uname() == 'windows' then return 80 end local tputf = io.popen('tput cols', 'r') local w = tonumber(tputf:read('*a')) local rc = {tputf:close()} if rc[3] == 0 then return w else return 80 end end local barDone = true local previous = -1 local tm = '' local timer local times local indices local termLength = math.min(getTermLength(), 120) function progress(current, goal, cost) -- defaults: local barLength = termLength - 64 local smoothing = 100 local maxfps = 10 -- Compute percentage local percent = math.floor(((current) * barLength) / goal) -- start new bar if (barDone and ((previous == -1) or (percent < previous))) then barDone = false previous = -1 tm = '' timer = torch.Timer() times = {timer:time().real} indices = {current} else io.write('\r') end --if (percent ~= previous and not barDone) then if (not barDone) then previous = percent -- print bar io.write(' [') for i=1,barLength do if (i < percent) then io.write('=') elseif (i == percent) then io.write('>') else io.write('.') end end io.write('] ') for i=1,termLength-barLength-4 do io.write(' ') end for i=1,termLength-barLength-4 do io.write('\b') end -- time stats local elapsed = timer:time().real local step = (elapsed-times[1]) / (current-indices[1]) if current==indices[1] then step = 0 end local remaining = math.max(0,(goal - current)*step) table.insert(indices, current) table.insert(times, elapsed) if #indices > smoothing then indices = table.splice(indices) times = table.splice(times) end -- Print remaining time when running or total time when done. if (percent < barLength) then tm = ' ETA: ' .. formatTime(remaining) else tm = ' Tot: ' .. formatTime(elapsed) end tm = tm .. ' | Step: ' .. formatTime(step) io.write(tm) io.write(' | Cost: ' .. cost) -- go back to center of bar, and print progress for i=1,5+#tm+barLength/2 do io.write('\b') end io.write(' ', current, '/', goal, ' ') -- reset for next bar if (percent == barLength) then barDone = true io.write('\n') end -- flush io.write('\r') io.flush() end end end function formatTime(seconds) -- decompose: local floor = math.floor local days = floor(seconds / 3600/24) seconds = seconds - days*3600*24 local hours = floor(seconds / 3600) seconds = seconds - hours*3600 local minutes = floor(seconds / 60) seconds = seconds - minutes*60 local secondsf = floor(seconds) seconds = seconds - secondsf local millis = floor(seconds*1000) -- string local f = '' local i = 1 if days > 0 then f = f .. days .. 'D' i=i+1 end if hours > 0 and i <= 2 then f = f .. hours .. 'h' i=i+1 end if minutes > 0 and i <= 2 then f = f .. minutes .. 'm' i=i+1 end if secondsf > 0 and i <= 2 then f = f .. secondsf .. 's' i=i+1 end if millis > 0 and i <= 2 then f = f .. millis .. 'ms' i=i+1 end if f == '' then f = '0ms' end -- return formatted time return f end
-- -- Author: Reyn -- Date: 2016-06-18 15:41:04 -- require('init') local q1 = Queue(10) console_colorful("=======enqueue=======") console_colorful("sapce = " .. q1:space()) print(q1:enqueue('a')) q1.serial() print(q1:enqueue('b')) q1.serial() print(q1:enqueue('c')) q1.serial() print(q1:enqueue('d')) q1.serial() print(q1:enqueue('e')) q1.serial() print(q1:enqueue('f')) q1.serial() print(q1:enqueue('g')) q1.serial() print(q1:enqueue('h')) q1.serial() print(q1:enqueue('i')) q1.serial() print(q1:enqueue('j')) q1.serial() print(q1:enqueue('k')) q1.serial() print(q1:enqueue('l')) q1.serial() print(q1:enqueue('m')) q1.serial() print(q1:enqueue('n')) q1.serial() print(q1:enqueue('o')) q1.serial() q1:setSpace(15) console_colorful("sapce = " .. q1:space()) print(q1:enqueue('p')) q1.serial() print(q1:enqueue('q')) q1.serial() print(q1:enqueue('r')) q1.serial() console_colorful("=======dequeue=======") console_colorful("len = " .. q1:len()) console_colorful("space = " .. q1:space()) print(q1:dequeue()) q1.serial() print(q1:dequeue()) q1.serial() print(q1:dequeue()) q1.serial() print(q1:dequeue()) q1.serial() print(q1:dequeue()) q1.serial() print(q1:dequeue()) q1.serial() console_colorful("len = " .. q1:len()) console_colorful("sapce = " .. q1:space())
-------------------------------- -- @module Controller -- @parent_module cc -------------------------------- -- Activate receives key event from external key. e.g. back,menu.<br> -- Controller receives only standard key which contained within enum Key by default.<br> -- warning The API only work on the android platform for support diversified game controller.<br> -- param externalKeyCode External key code.<br> -- param receive True if external key event on this controller should be receive, false otherwise. -- @function [parent=#Controller] receiveExternalKeyEvent -- @param self -- @param #int externalKeyCode -- @param #bool receive -- @return Controller#Controller self (return value: cc.Controller) -------------------------------- -- Gets the name of this Controller object. -- @function [parent=#Controller] getDeviceName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- Indicates whether the Controller is connected. -- @function [parent=#Controller] isConnected -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Gets the Controller id. -- @function [parent=#Controller] getDeviceId -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Changes the tag that is used to identify the controller easily.<br> -- param tag A integer that identifies the controller. -- @function [parent=#Controller] setTag -- @param self -- @param #int tag -- @return Controller#Controller self (return value: cc.Controller) -------------------------------- -- Returns a tag that is used to identify the controller easily.<br> -- return An integer that identifies the controller. -- @function [parent=#Controller] getTag -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Start discovering new controllers.<br> -- warning The API has an empty implementation on Android. -- @function [parent=#Controller] startDiscoveryController -- @param self -- @return Controller#Controller self (return value: cc.Controller) -------------------------------- -- Stop the discovery process.<br> -- warning The API has an empty implementation on Android. -- @function [parent=#Controller] stopDiscoveryController -- @param self -- @return Controller#Controller self (return value: cc.Controller) -------------------------------- -- Gets a Controller object with device ID.<br> -- param deviceId A unique identifier to find the controller.<br> -- return A Controller object. -- @function [parent=#Controller] getControllerByDeviceId -- @param self -- @param #int deviceId -- @return Controller#Controller ret (return value: cc.Controller) -------------------------------- -- Gets a Controller object with tag.<br> -- param tag An identifier to find the controller.<br> -- return A Controller object. -- @function [parent=#Controller] getControllerByTag -- @param self -- @param #int tag -- @return Controller#Controller ret (return value: cc.Controller) return nil
env = {} f = load("return x", nil, nil, env) env.x = tonumber(io.read()) -- user enters 2 a = f() env.x = tonumber(io.read()) -- user enters 3 b = f() print(a + b) --> outputs 5
local function make_char_bool(str) local booltab = {} for ix=1,#str do booltab[str:sub(ix,ix)] = true end return booltab end local l = ljcurses local a = l.attributes local b = l.boxes local k = l.keys local state_signs = { SKP='-', ADD='+', OPT='o', REC=' ' } local excluded_char = make_char_bool '[]<>/? ' local escapemap = { a='M-a', o='M-o', r='M-r', R='M-R', s='M-s', C='M-C', M='M-M', l='M-l', L='M-L', x='M-x', n='M-n', N='M-N', ['\14']='M-^N', d='M-d', ['\12']='M-^L', u='M-u' } local constrain_state_commands={ ['M-a']='ADD', ['M-o']='OPT', ['M-r']='REC', ['M-s']='SKP', ['M-R']='REQ', ['M-C']='CHG', ['M-M']='MIS' } local constraint_special_flags = {} local constraint_special_flag_names = { 'CHG', 'REQ', 'MIS' } do local power=1 for _, name in ipairs(constraint_special_flag_names) do constraint_special_flags[name] = power power = 2 * power end end local scroll_keys={ KEY_HOME=true, KEY_END=true, KEY_UP=true, KEY_DOWN=true, KEY_NPAGE=true, KEY_PPAGE=true } local function assert(bool, ...) if not bool then l.endwin() end return _G.assert(bool, ...) end function trim_editor_cache(tagset) tagset.manifest = nil tagset.package_cache = nil tagset.packages_loaded = {} end function clone_editor_cache(new_tagset, old_tagset) new_tagset.installation = old_tagset.installation end function edit_tagset(tagset, installation) assert(tagset.type == 'tagset', 'Self is not a tagset') assert(not installation or installation.type == 'installation', 'Argument is not an installation') if installation == false then tagset.installation = nil elseif installation then tagset.installation = installation else installation = tagset.installation end local categories_sorted = tagset.categories_sorted local category_index = tagset.category_index or {} if not tagset.categories_sorted then categories_sorted = {} for k in pairs(tagset.categories) do table.insert(categories_sorted, k) end table.sort(categories_sorted) tagset.categories_sorted = categories_sorted for ix, category in ipairs(categories_sorted) do category_index[category] = ix end tagset.category_index = category_index end local package_cursors = {} local current_category local package_cursor local last_package = tagset.last_package if last_package then current_category = category_index[last_package.category] package_cursor = last_package.category_index else last_package = tagset.categories[categories_sorted[1]][1] current_category = 1 package_cursor = 1 end local skip_set = tagset.skip_set if skip_set and skip_set[categories_sorted[current_category]] then current_category = nil for i,catname in ipairs(categories_sorted) do if not skip_set[catname] then current_category = i break end end if not current_category then print 'All categories inhibited. Goodbye!' return end last_package = tagset.categories[categories_sorted[current_category]][1] package_cursor = 1 end local package_list = tagset.categories[categories_sorted[current_category]] if not tagset.maxtaglen then local maxtaglen = 0 for tag,_ in pairs(tagset.tags) do if #tag > maxtaglen then maxtaglen = #tag end end tagset.maxtaglen = maxtaglen end local maxtaglen = tagset.maxtaglen local tagformat = '%-'..maxtaglen..'s' local colors = {} local viewport_top local current_constraint local constraint_flags = {} local constraint_flags_set = 0 local constraint_bits = 0 local only_required = false local package_window local reportview_lines local reportview_color local reportview_head local descr_window local special_window local rows, cols, subwin_lines, half_subwin local installed = installation and installation.tags or {} local pattern_trap local function activate_reportview() reportview_lines = { '' } reportview_color = colors.report reportview_head = 1 end local function redraw_reportview() if not reportview_window then reportview_window = l.newwin(subwin_lines, cols-2, 3, 1) l.bkgd(reportview_window, reportview_color) end l.move(reportview_window, 0, 0) l.clrtobot(reportview_window) local cursor = reportview_head for line = 0, subwin_lines-1 do if not reportview_lines[cursor] then break end l.move(reportview_window, line, 1) l.addnstr(reportview_window, reportview_lines[cursor], cols-4) cursor = cursor+1 end l.noutrefresh(reportview_window) end local function deactivate_reportview() reportview_lines = nil end local function add_to_reportview(text) if not reportview_window then redraw_reportview() end if text then reportview_lines[#reportview_lines] = reportview_lines[#reportview_lines]..text else table.insert(reportview_lines, '') end local minhead = #reportview_lines - subwin_lines + 1 if reportview_head >= minhead then local where = #reportview_lines - reportview_head l.move(reportview_window, where, 1) l.clrtoeol(reportview_window) l.addnstr(reportview_window, reportview_lines[#reportview_lines], cols-4) l.noutrefresh(reportview_window) elseif minhead == reportview_head + 1 then reportview_head = minhead l.move(reportview_window, 0, 0) l.insdelln(reportview_window, -1) l.move(reportview_window, subwin_lines-1, 0) l.addnstr(reportview_window, reportview_lines[#reportview_lines], cols-4) l.noutrefresh(reportview_window) else reportview_head = minhead l.move(reportview_window, 0, 0) l.clrtobot(reportview_window) redraw_reportview() end end local get_constraint_flag_string do local constraint_flag_string = '' local last_flag_count = 0 local last_constraint_bits = 0 get_constraint_flag_string = function () if last_flag_count ~= constraint_flags_set or last_constraint_bits ~= constraint_bits then if constraint_flags_set > 0 or constraint_bits > 0 then local newcfs = ' [' for _,flag in ipairs { 'ADD', 'OPT', 'REC', 'SKP' } do if constraint_flags[flag] then newcfs = newcfs.. ({ADD='a',OPT='o',REC='r',SKP='s'})[flag] end end for _, bitname in ipairs(constraint_special_flag_names) do if not constraint_special_flags[bitname] then l.endwin() print(bitname) os.exit(0) end if bit.band(constraint_bits, constraint_special_flags[bitname]) ~= 0 then newcfs = newcfs..bitname:sub(1,1) end end constraint_flag_string = newcfs..']' else constraint_flag_string = '' end last_flag_count = constraint_flags_set last_constraint_bits = constraint_bits end return constraint_flag_string end end local function show_constraint() if current_constraint then local constraint = (#current_constraint > 0 and current_constraint or '* EMPTY *').. get_constraint_flag_string() l.move(subwin_lines+4, cols - #constraint-2) local color if #package_list == 0 then color = colors.nomatch else color = colors.highlight end l.attron(color) l.addstr(constraint) l.attroff(color) l.attron(colors.main) end end local function draw_package_line(tuple, line, selected) local outstr = tagformat:format(tuple.tag) local outmax=cols-4 l.move(package_window, line, 0) l.clrtoeol(package_window) l.attron(package_window, colors[tuple.state]) l.addstr(package_window, state_signs[tuple.state]) l.attroff(package_window, colors[tuple.state]) if tuple.state == tuple.old_state then l.addstr(package_window, ' ') else l.attron(package_window, colors[tuple.old_state]) l.addch(package_window, b.diamond) l.attroff(package_window, colors[tuple.old_state]) end if installation and not installed[tuple.tag] then outstr = outstr:sub(1,#outstr-1) outmax = outmax - 1 l.attron(package_window, colors.missing) l.addstr(package_window, '*') l.attroff(package_window, colors.missing) end if tuple.shortdescr then outstr = outstr..' - '..tuple.shortdescr end if selected then l.attron(package_window, colors.highlight) l.addnstr(package_window, outstr, outmax) l.attroff(package_window, colors.highlight) else if tuple.required and tuple.state ~= 'ADD' then l.attron(package_window, colors.required) l.addnstr(package_window, outstr, outmax) l.attroff(package_window, colors.required) else l.addnstr(package_window, outstr, outmax) end end end local function draw_package_top_win(tuple) local outstr local outmax=cols-4 l.move(1, 11) local descrs=tagset.category_description[tuple.category] l.addnstr(tuple.category .. (descrs and (' - '..descrs.short) or ''), cols - 10) l.clrtoeol() l.move(1, cols-1) l.addch(b.vline) l.move(1, cols-12) l.addnstr(' '..package_cursor..'/'..#package_list, 13) l.move(subwin_lines+4, 2) local pkgdescr if tuple.version then pkgdescr = string.format('%s-%s-%s-%s state: %s', tuple.tag, tuple.version, tuple.arch, tuple.build, tuple.state) else pkgdescr = string.format('%s state: %s', tuple.tag, tuple.state) end if tuple.state ~= tuple.old_state then pkgdescr = pkgdescr..' was: '..tuple.old_state end if tuple.required and tuple.state ~= 'ADD' then l.attron(colors.required) l.addnstr(pkgdescr, outmax) l.attroff(colors.required) else l.addnstr(pkgdescr, outmax) end l.clrtoeol() l.move(subwin_lines+4, cols-1) l.addch(b.vline) if installation then l.move(subwin_lines+5,2) l.clrtoeol() local installed = installed[tuple.tag] if installed then local instdescr = string.format('Installed %s-%s-%s-%s', installed.tag, installed.version, installed.arch, installed.build) if tuple.version ~= installed.version or tuple.arch ~= installed.arch or tuple.build ~= installed.build then l.addnstr(instdescr, outmax) else l.attron(colors.same_version) l.addnstr(instdescr, outmax) l.attroff(colors.same_version) end else l.attron(colors.missing) l.addnstr('* NOT INSTALLED *', outmax) l.attroff(colors.missing) end l.move(subwin_lines+5,cols-1) l.addch(b.vline) end end local function draw_package(tuple, line, selected) draw_package_line(tuple, line, selected) if selected then draw_package_top_win(tuple) end end local function redraw_package_list() if not package_window then package_window = l.newwin(subwin_lines, cols-2, 3, 1) l.bkgd(package_window, colors.main) end viewport_top = package_cursor - half_subwin if viewport_top < 1 then viewport_top = 1 end local top = viewport_top for i=0,subwin_lines-1 do local selected = top+i local tuple=package_list[selected] if not tuple then break end draw_package(tuple, i, package_cursor == selected) end if #package_list == 0 then local msg = "* NO PACKAGES *" l.move(package_window, half_subwin, cols/2 - #msg/2) l.addstr(package_window, msg) end show_constraint() l.noutrefresh(package_window) end local function show_description(description) local descr_lines = description and description() activate_reportview() if descr_lines then for i, line in ipairs(descr_lines) do if i > 1 then add_to_reportview() end add_to_reportview(line) end else add_to_reportview('Sorry! I can\'t find this description.') end end local function repaint() _,_,rows,cols = l.getdims() subwin_lines = rows - (installation and 7 or 6) half_subwin = math.floor(subwin_lines/2) l.move(0,0) l.clrtobot() l.box(b.vline,b.hline) l.move(2,0) l.addch(b.ltee) l.hline(b.hline, cols-2) l.move(2,cols-1) l.addch(b.rtee) l.move(1,1) l.addstr('Category:') l.move(subwin_lines + 3, 0) l.addch(b.ltee) l.hline(b.hline, cols-2) l.move(subwin_lines + 3, cols-1) l.addch(b.rtee) l.noutrefresh() redraw_package_list() if reportview_lines then if #package_list then draw_package_top_win(package_list[package_cursor]) end if reportview_window then l.delwin(reportview_window) reportview_window = nil end redraw_reportview() else if package_window then l.delwin(package_window) package_window = nil end redraw_package_list() end end -- Constraint stuff local function clear_constraint() if current_constraint then current_constraint = nil constraint_flags = {} constraint_flags_set = 0 constraint_bits = 0 -- Cached status string may be invalid, so refresh it. get_constraint_flag_string() if #package_list > 0 then last_package = package_list[package_cursor] else assert(last_package, "last_package not assigned") end current_category = category_index[last_package.category] package_cursor = last_package.category_index package_list = tagset.categories[last_package.category] end end local function match_constraint(tuple, constraint) if skip_set and skip_set[tuple.category] then return end if bit.band(constraint_bits, constraint_special_flags.REQ) ~= 0 and not tuple.required then return end if bit.band(constraint_bits, constraint_special_flags.CHG) ~= 0 and tuple.state == tuple.old_state then return end if bit.band(constraint_bits, constraint_special_flags.MIS) ~= 0 and installation and installation.tags[tuple.tag] then return end if constraint_flags_set > 0 and not constraint_flags[tuple.state] then return end -- Case insensitive match with bad pattern trap do pattern_trap = true local success = tuple.tag:lower():find(constraint:lower()) pattern_trap = nil return success end end local function constrain(constraint, old_constraint) assert(last_package, "last_package not assigned") if not old_constraint then package_cursors[current_category] = package_cursor end if #package_list > 0 then last_package = package_list[package_cursor] end current_constraint = constraint local new_cursor = 1 package_list = {} local success,msg = pcall(function () local insert_number=1 for _, category in ipairs(categories_sorted) do local cat = tagset.categories[category] for _, tuple in ipairs(cat) do if match_constraint(tuple,constraint) then table.insert(package_list, tuple) if tuple == last_package then new_cursor = insert_number end insert_number = insert_number+1 end end end end) if not success then assert(pattern_trap, 'pcall failed\n'..msg) end if #package_list > 0 then new_package = package_list[new_cursor] if new_package.category ~= last_package.category then current_category = category_index[new_package.category] end package_cursor = new_cursor end end local function toggle_constrain_by_state(flag) if constraint_special_flags[flag] then constraint_bits = bit.bxor(constraint_bits, constraint_special_flags[flag]) else local old_flag = constraint_flags[flag] if old_flag then constraint_flags[flag] = false constraint_flags_set = constraint_flags_set - 1 else constraint_flags[flag] = true constraint_flags_set = constraint_flags_set + 1 end end constrain(current_constraint or '', current_constraint) end local function find_new_category(start, finish) local function select_category(new_category) local save_package = last_package if #package_list > 0 then save_package = package_list[package_cursor] end if new_category ~= current_category then package_cursors[current_category] = save_package.category_index package_cursor = package_cursors[new_category] or 1 package_list = tagset.categories[categories_sorted[new_category]] current_category = new_category end repaint() end if not categories_sorted[start] then return end if not skip_set then select_category(start) else local bump = start < finish and 1 or -1 for new_category=start,finish,bump do if not skip_set[categories_sorted[new_category]] then select_category(new_category) break end end end end local function change_state(tuple, new_state, line) if #package_list < 1 then return end if not new_state then new_state = tuple.state == 'ADD' and 'SKP' or 'ADD' end if new_state ~= tuple.state then tuple.state = new_state tagset.dirty = true draw_package(tuple, line, true) l.noutrefresh(package_window) show_constraint() end end local function confirm(prompt, pattern, default) local char, key, _ repeat local row, col = add_to_reportview(prompt) l.doupdate() while true do key = l.getch() if key >= 0 then break end util.usleep(1000) end if key == k.resize or key == k.ctrl_c then add_to_reportview() return default or '' end char = key >= 0 and key < 128 and string.char(key) or '' if key > 32 and key < 127 and #prompt < cols-3 then add_to_reportview(char) end add_to_reportview() until not pattern or char:match(pattern) l.doupdate() return char == '\n' and default or char end local function load_package(overwrite) local function print(...) local lineout = '' for i=1,select('#', ...) do if i > 1 then lineout = lineout..(' '):sub(1 + #lineout % 8) end lineout = lineout..tostring(select(i, ...)) end add_to_reportview(lineout) add_to_reportview() end if #package_list > 0 then activate_reportview() repaint() local conflicts local now = util.realtime() local tuple = package_list[package_cursor] local file = string.format('%s/%s-%s-%s-%s', tuple.category, tuple.tag, tuple.version, tuple.arch, tuple.build) if tuple.arch == 'noarch' then add_to_reportview('Skipping NOARCH package '..file) l.doupdate() else local filepath=tagset.directory..'/'..file if not tagset.package_cache or overwrite then add_to_reportview('Loading package '..file) add_to_reportview() l.doupdate() tagset.packages_loaded = { [tuple] = true } tagset.package_cache = read_archive(filepath, print, confirm) else add_to_reportview('Loading additional package '..file) add_to_reportview() l.doupdate() tagset.packages_loaded[tuple] = true conflicts = tagset.package_cache:extend(filepath, print, confirm) end end if conflicts then add_to_reportview '' add_to_reportview 'Hit any non-scroll key to continue' else local elapsed = util.realtime() - now if elapsed < 1 then util.usleep(1000000 * (1 - elapsed)) end deactivate_reportview() repaint() end end end local function report_sorted_keys(tbl, extractor, printer, singular, plural, rest) if not extractor then extractor = function (x) return x end end if not printer then printer = add_to_reportview end activate_reportview() local sorted = {} for key in pairs(tbl) do table.insert(sorted, extractor(key)) end table.sort(sorted) add_to_reportview(''..#sorted..' ') add_to_reportview(#sorted == 1 and singular or plural) add_to_reportview(rest ) add_to_reportview() for _,item in ipairs(sorted) do add_to_reportview() add_to_reportview(' ') printer(item) end repaint() end local function find_next_or_prev_opt_or_rec(finish,direction) for cursor=package_cursor+direction,finish,direction do if package_list[cursor].state ~= 'ADD' and package_list[cursor].state ~= 'SKP' then if cursor < viewport_top or cursor >= viewport_top + subwin_lines then package_cursor=cursor repaint() else draw_package(package_list[package_cursor], package_cursor-viewport_top, false) draw_package(package_list[cursor], cursor-viewport_top, true) package_cursor = cursor show_constraint() l.noutrefresh(package_window) end return end end end local function command_loop() repaint() -- If a timeout isn't given at first, then SIGINT isn't -- handled correctly. l.timeout(100000) while true do ::continue:: l.doupdate() local key, suffix while true do key, suffix = l.getch() if key >= 0 then break end util.usleep(1000) end if key == k.resize then -- 1/5 sec l.timeout(200) repeat key = l.getch() until key ~= k.resize l.timeout(0) -- We need to recompute these. repaint() if key == -1 then goto continue end end -- Regardless if ctrl/c is SIGINT, it quits the editor. if key == k.ctrl_c then break end local char = key < 128 and string.char(key) or l.keyname(key) if key == k.escape and escapemap[suffix] then key = -1 char = escapemap[suffix] end if key == k.ctrl_l then repaint() goto continue end if not scroll_keys[char] and reportview_lines then deactivate_reportview() repaint() goto continue end if char == 'M-u' then tagset.show_uncompressed_size = not tagset.show_uncompressed_size tagset:reset_descriptions() -- Navigation elseif char == 'KEY_RIGHT' then clear_constraint() find_new_category(current_category+1, #categories_sorted) elseif char == 'KEY_LEFT' then clear_constraint() find_new_category(current_category-1, 1) elseif char == '<' then clear_constraint() find_new_category(1,#categories_sorted) elseif char == '>' then clear_constraint() find_new_category(#categories_sorted, 1) elseif char == 'KEY_HOME' then if reportview_lines then reportview_head = 1 else package_cursor = 1 end repaint() elseif char == 'KEY_END' then if not reportview_lines then package_cursor = #package_list elseif #reportview_lines >= subwin_lines then reportview_head = #reportview_lines - subwin_lines + 1 end repaint() elseif char == 'KEY_DOWN' then if reportview_lines then if reportview_head <= #reportview_lines - subwin_lines then l.move(reportview_window, 0, 0) l.insdelln(reportview_window, -1) l.move(reportview_window, subwin_lines - 1, 1) reportview_head = reportview_head + 1 l.addnstr(reportview_window, reportview_lines[reportview_head+subwin_lines-1], cols-4) l.noutrefresh(reportview_window) end elseif package_cursor < #package_list then package_cursor = package_cursor+1 if package_cursor == viewport_top + subwin_lines then repaint() else draw_package(package_list[package_cursor-1], package_cursor-viewport_top-1, false) draw_package(package_list[package_cursor], package_cursor-viewport_top, true) show_constraint() l.noutrefresh(package_window) end end elseif char == 'KEY_UP' then if reportview_lines then if reportview_head > 1 then l.move(reportview_window, 0, 1) l.insdelln(reportview_window, 1) reportview_head = reportview_head - 1 l.addnstr(reportview_window, reportview_lines[reportview_head], cols-4) l.noutrefresh(reportview_window) end elseif #package_list > 0 and package_cursor > 1 then package_cursor = package_cursor - 1 if package_cursor < viewport_top then repaint() else draw_package(package_list[package_cursor+1], package_cursor-viewport_top+1, false) draw_package(package_list[package_cursor], package_cursor-viewport_top, true) show_constraint() l.noutrefresh(package_window) end end elseif key == k.ctrl_i then find_next_or_prev_opt_or_rec(#package_list, 1) elseif char == 'KEY_BTAB' then find_next_or_prev_opt_or_rec(1, -1) elseif char == 'KEY_NPAGE' then if reportview_lines then local maxhead = #reportview_lines - subwin_lines + 1 if maxhead < 1 then maxhead = 1 end reportview_head = reportview_head + half_subwin if reportview_head > maxhead then reportview_head = maxhead end redraw_reportview() elseif #package_list > 0 and package_cursor < #package_list then package_cursor = package_cursor + half_subwin if package_cursor > #package_list then package_cursor = #package_list end repaint() end elseif char == 'KEY_PPAGE' then if reportview_lines then reportview_head = reportview_head - half_subwin if reportview_head < 1 then reportview_head = 1 end redraw_reportview() elseif package_cursor > 1 then package_cursor = package_cursor - half_subwin if package_cursor < 1 then package_cursor = 1 end repaint() end -- Show description elseif key == k.ctrl_d then if #package_list > 0 then show_description(package_list[package_cursor].description) repaint() end elseif char == 'M-d' then -- Does the installation description ever change between releases? if #package_list > 0 and installation then local entry = installation.tags[package_list[package_cursor].tag] if entry then show_description(entry.description) repaint() end end -- Constraint elseif key == k.escape and not suffix then clear_constraint() repaint() elseif constrain_state_commands[char] then toggle_constrain_by_state(constrain_state_commands[char], has_constraint) repaint() elseif key == k.ctrl_u then if current_constraint then constrain('', current_constraint) repaint() end elseif key >= 32 and key < 127 and not excluded_char[char] then local new_constraint = current_constraint if not current_constraint then only_required = false constraint_flags_set = 0 constraint_flags = {} new_constraint = '' constraint_state = { } end if #new_constraint < 16 then constrain(new_constraint..char, current_constraint) repaint() end elseif char == 'KEY_BACKSPACE' or key == k.delete then if current_constraint then constrain(current_constraint:sub(1, -2), current_constraint) repaint() end -- Help elseif char == '?' or char == 'KEY_F(15)' then activate_reportview() for i, line in ipairs { 'Key command help','', 'TO BE DONE' } do if i > 1 then add_to_reportview() end add_to_reportview(line) end -- Change package state elseif key == k.ctrl_a or char == 'KEY_IC' then change_state(package_list[package_cursor], 'ADD', package_cursor-viewport_top) elseif key == k.ctrl_s or char == 'KEY_DC' then change_state(package_list[package_cursor], 'SKP', package_cursor-viewport_top) elseif key == k.ctrl_o then change_state(package_list[package_cursor], 'OPT', package_cursor-viewport_top) elseif key == k.ctrl_r then change_state(package_list[package_cursor], 'REC', package_cursor-viewport_top) elseif key == k.ctrl_x then change_state(package_list[package_cursor], package_list[package_cursor].old_state, package_cursor-viewport_top) elseif char == ' ' then change_state(package_list[package_cursor], nil, package_cursor-viewport_top) -- Archive loading and library resolution elseif char == 'M-l' then load_package() elseif char == 'M-L' then load_package(true) elseif char == 'M-^L' then if tagset.package_cache then report_sorted_keys(tagset.packages_loaded, function (p) return p.tag end, nil, 'package', 'package', ' loaded:') end elseif char == 'M-x' then tagset.package_cache = nil tagset.packages_loaded = nil elseif char == 'M-n' then local cache = tagset.package_cache if cache then report_sorted_keys(cache.needed, nil, nil, 'library', 'libraries', ' needed') end elseif char == 'M-^N' or char == 'M-N' then local cache = tagset.package_cache local function needers(tag) add_to_reportview(tag) add_to_reportview() local sorted={} for key in pairs(cache.needed[tag] or {}) do table.insert(sorted, key.path) end table.sort(sorted) for _,val in ipairs(sorted) do add_to_reportview ' ' add_to_reportview(val) add_to_reportview() end repaint() end if cache then activate_reportview() report_sorted_keys(cache.needed, nil, char == 'M-^N' and needers, 'library', 'libraries', ' needed') if tagset.directory then add_to_reportview() add_to_reportview() if not tagset.manifest then if confirm('Read manifest for suggestions? (Y/n): ', '[YyNn\n\4]', 'y') == 'y' then add_to_reportview 'Reading manifest...' l.doupdate() tagset.manifest = read_manifest(tagset.directory) add_to_reportview 'Done!' add_to_reportview() add_to_reportview() else add_to_reportview 'Skipping suggestions' l.doupdate() util.usleep(1000000) deactivate_reportview() repaint() end end if tagset.manifest then add_to_reportview 'Suggestions:' add_to_reportview() add_to_reportview() local format = ' %-24s %-24s %-24s' add_to_reportview('CATEGORY / PACKAGE [-- STATE]') add_to_reportview() add_to_reportview(format:format('SONAME','GUESS','STEM')) add_to_reportview() add_to_reportview(' '..('-'):rep(54)) add_to_reportview() local suggestions = tagset.manifest:get_suggestions(cache) for _, suggestion in ipairs(suggestions) do local tuple = tagset.tags[suggestion[1]] if char == 'M-^N' or tuple.state ~= 'ADD' then add_to_reportview() add_to_reportview(tuple.category..' / '.. suggestion[1]) if tuple.state ~= 'ADD' then add_to_reportview(' -- '..tuple.state) end add_to_reportview() for _, lib in ipairs(suggestion[2]) do local outstr = format:format(lib[1],lib[2],lib[3]) add_to_reportview(outstr) add_to_reportview() end end end end end end end end end l.init_curses() l.start_color() l.curs_set(0) l.init_pair(1, a.white, a.blue) l.init_pair(2, a.cyan, a.blue) l.init_pair(3, a.green, a.blue) l.init_pair(4, a.red, a.blue) l.init_pair(5, a.yellow, a.blue) l.init_pair(6, a.yellow, a.black) l.init_pair(7, a.green, a.black) colors.highlight = bit.bor(l.color_pair(2), a.bold) colors.report = bit.bor(l.color_pair(6), a.bold) colors.ADD = bit.bor(l.color_pair(3), a.bold) colors.SKP = bit.bor(l.color_pair(4), a.bold) colors.OPT = bit.bor(l.color_pair(5), a.bold) colors.REC = 0 colors.pattern = colors.highlight colors.nomatch = colors.SKP colors.required = colors.SKP colors.same_version = colors.ADD colors.missing = colors.SKP colors.main = bit.bor(l.color_pair(1), a.bold) l.bkgd(colors.main) l.attron(colors.main) l.refresh() local result={pcall(command_loop)} l.endwin() clear_constraint() if not result[1] and not result[2]:match ': interrupted!$' then print(result[2]) end if not current_constraint then last_package = package_list[package_cursor] end tagset.last_package = last_package if tagset.package_cache then tagset.package_cache:cleanup() end print 'Editor finished' end
-- Media is a common area for providing sources of media, like fonts, textures, -- colors, and so forth. It's similar to LibSharedMedia and other mods, though -- it does not pretend to be the sole provider of media. It also doesn't require -- you to learn a custom API for accessing tabular data. For these reasons, I -- prefer ours over object-based or global registry-based solutions. -- -- However, like I said, other providers are happily welcome in this mod, and we -- steal their data freely. Here's how you use Media: -- -- local t=UIParent:CreateTexture(); -- t:SetTexture(unpack(Media.colors.red)); -- -- That's it. We support any capitalization (similar to our mod's Chat table), so -- you don't need to remember this piece of information, nor do you need to check -- before using other tables. -- -- If you're writing a provider, try to be as forgiving as possible. Have a sensible -- or obvious default value, and anticipate and correct common user errors, such as -- misspellings or locale-dependent spellings. Media is intended to be extremely -- easy to use. -- -- You register your provider by setting it for the correct media name. For example, -- if I want to support LibSharedMedia, this is how I would do it: -- -- Media.color(function(name) -- if not LibStub then -- return; -- end; -- local sharedMedia = LibStub("LibSharedMedia-3.0"); -- if not sharedMedia then -- return; -- end; -- return sharedMedia:Fetch("color", name); -- end); -- -- As you can see, most of our code is ensuring we actually have SharedMedia. Once this -- is executed, we'll have full access to any color in SharedMedia. Note that for this -- particular example, we provide this code for you. Use it through: -- -- Media.color(Curry(Media.SharedMedia, "color")); -- -- I'm not sure whether older registries should have higher priority or not. I think -- the code prefers this, but it's not set in stone just yet. If you need to register -- a provider out of order, do so by accessing Media's registry directly, like so: -- -- table.insert(Media.registry.color, 1, yourProvider); -- -- As always, please access this internal with care. local registry={}; Media = setmetatable({ registry=registry, SharedMedia=function(mediaType, mediaName) if not LibStub then return; end; local sharedMedia = LibStub("LibSharedMedia-3.0"); if not sharedMedia then return; end; return sharedMedia:Fetch("color", name); end }, { __newindex=function(self,k,v) error("Media is not directly settable: use Media['"..k.."'](v) instead"); end; __index=function(self,mediaType) if type(mediaType) == "string" then mediaType=mediaType:lower(); end; if not registry[mediaType] then local providers = {}; rawset(self,mediaType, setmetatable({}, { __call=function(self, provider) assert(provider, "provider must not be nil"); if not registry[mediaType] then registry[mediaType] = {}; end; table.insert(providers, provider); return provider; end, __index=function(self, k) if type(k) == "string" then k=k:lower(); end; local reg=registry[mediaType]; if reg==nil then return nil; end; for i=1, #providers do local provider=providers[i]; local v; if type(provider) == "function" then v=provider(k); elseif type(provider) == "table" then v=provider[k]; end; if v ~= nil then return v; end; end; if k ~= "default" then return self.default end; end })); end; return self[mediaType]; end }); rawset(Media, "SetAlias", function(root, ...) for i=1,select("#", ...) do rawset(Media, select(i, ...), Media[root]); end; end);
-- Submodule for sending messages to remote processes. module('concurrent._distributed._message', package.seeall) require 'mime' -- The existing version of this function for message sending is renamed. _send = concurrent._message.send -- Sends a message to local or remote processes. If the process is local the -- old renamed version of this function is used, otherwise the message is send -- through the network. The message is serialized and the magic cookie is also -- attached before sent. Returns true for success and false otherwise. function send(dest, mesg) if type(dest) ~= 'table' then return _send(concurrent.whereis(dest), mesg) end local pid, node = unpack(dest) local socket = concurrent._distributed._network.connect(node) if not socket then return false end local data if concurrent.getcookie() then data = concurrent.getcookie() .. ' ' .. tostring(pid) .. ' ' .. serialize(mesg) .. '\r\n' else data = tostring(pid) .. ' ' .. serialize(mesg) .. '\r\n' end local total = #data repeat local n, errmsg, _ = socket:send(data, total - #data + 1) if not n and errmsg == 'closed' then concurrent._distributed._network.disconnect(node) return false end total = total - n until total == 0 if concurrent.getoption('debug') then print('-> ' .. string.sub(data, 1, #data - 2)) end return true end -- Serializes an object that can be any of: nil, boolean, number, string, table, -- function. Returns the serialized object. function serialize(obj) local t = type(obj) if t == 'nil' or t == 'boolean' or t == 'number' then return tostring(obj) elseif t == 'string' then return string.format("%q", obj) elseif t == 'function' then return 'loadstring((mime.unb64([[' .. (mime.b64(string.dump(obj))) .. ']])))' elseif t == 'table' then local t = '{' for k, v in pairs(obj) do if type(k) == 'number' or type(k) == 'boolean' then t = t .. ' [' .. tostring(k) .. '] = ' .. serialize(v) .. ',' else t = t .. ' ["' .. tostring(k) .. '"] = ' .. serialize(v) .. ',' end end t = t .. ' }' return t else error('cannot serialize a ' .. t) end end concurrent.send = send
local entityMeta = FindMetaTable("Entity") local playerMeta = FindMetaTable("Player") ix.net = ix.net or {} ix.net.globals = ix.net.globals or {} -- Check if there is an attempt to send a function. Can't send those. local function CheckBadType(name, object) local objectType = type(object) if (objectType == "function") then ErrorNoHalt("Net var '"..name.."' contains a bad object type!") return true elseif (objectType == "table") then for k, v in pairs(object) do -- Check both the key and the value for tables, and has recursion. if (CheckBadType(name, k) or CheckBadType(name, v)) then return true end end end end function SetNetVar(key, value, receiver) -- luacheck: globals SetNetVar if (CheckBadType(key, value)) then return end if (GetNetVar(key) == value) then return end ix.net.globals[key] = value netstream.Start(receiver, "gVar", key, value) end function playerMeta:SyncVars() for entity, data in pairs(ix.net) do if (entity == "globals") then for k, v in pairs(data) do netstream.Start(self, "gVar", k, v) end elseif (IsValid(entity)) then for k, v in pairs(data) do netstream.Start(self, "nVar", entity:EntIndex(), k, v) end end end end function entityMeta:SendNetVar(key, receiver) netstream.Start(receiver, "nVar", self:EntIndex(), key, ix.net[self] and ix.net[self][key]) end function entityMeta:ClearNetVars(receiver) ix.net[self] = nil netstream.Start(receiver, "nDel", self:EntIndex()) end function entityMeta:SetNetVar(key, value, receiver) if (CheckBadType(key, value)) then return end ix.net[self] = ix.net[self] or {} if (ix.net[self][key] != value) then ix.net[self][key] = value end self:SendNetVar(key, receiver) end function entityMeta:GetNetVar(key, default) if (ix.net[self] and ix.net[self][key] != nil) then return ix.net[self][key] end return default end function playerMeta:SetLocalVar(key, value) if (CheckBadType(key, value)) then return end ix.net[self] = ix.net[self] or {} ix.net[self][key] = value netstream.Start(self, "nLcl", key, value) end playerMeta.GetLocalVar = entityMeta.GetNetVar function GetNetVar(key, default) -- luacheck: globals GetNetVar local value = ix.net.globals[key] return value != nil and value or default end hook.Add("EntityRemoved", "nCleanUp", function(entity) entity:ClearNetVars() end) hook.Add("PlayerInitialSpawn", "nSync", function(client) client:SyncVars() end)
local K, C, L, _ = unpack(select(2, ...)) if C["skins"].skada ~= true then return end -- Skada skin local frame = CreateFrame("Frame") frame:RegisterEvent("PLAYER_LOGIN") frame:SetScript("OnEvent", function(self, event) if not IsAddOnLoaded("Skada") then return end local barmod = Skada.displays["bar"] -- Used to strip unecessary options from the in-game config local function StripOptions(options) options.baroptions.args.barspacing = nil options.titleoptions.args.texture = nil options.titleoptions.args.bordertexture = nil options.titleoptions.args.thickness = nil options.titleoptions.args.margin = nil options.titleoptions.args.color = nil options.windowoptions = nil options.baroptions.args.barfont = nil options.baroptions.args.reversegrowth = nil options.titleoptions.args.font = nil end barmod.AddDisplayOptions_ = barmod.AddDisplayOptions barmod.AddDisplayOptions = function(self, win, options) self:AddDisplayOptions_(win, options) StripOptions(options) end for k, options in pairs(Skada.options.args.windows.args) do if options.type == "group" then StripOptions(options.args) end end -- Override settings from in-game GUI barmod.ApplySettings_ = barmod.ApplySettings barmod.ApplySettings = function(self, win) barmod.ApplySettings_(self, win) local skada = win.bargroup local titlefont = CreateFont("TitleFont"..win.db.name) titlefont:SetFont(C["font"].basic_font, C["font"].basic_font_size - 1, C["font"].basic_font_style) titlefont:SetShadowColor(0, 0) if win.db.enabletitle then skada.button:SetNormalFontObject(titlefont) skada.button:SetBackdrop(nil) skada.button:GetFontString():SetPoint("TOPLEFT", skada.button, "TOPLEFT", 1, -1) skada.button:SetHeight(19) if not skada.button.backdrop then K.CreateBackdrop(skada.button) skada.button.backdrop:SetPoint("TOPLEFT", win.bargroup.button, "TOPLEFT", -2, 2) skada.button.backdrop:SetPoint("BOTTOMRIGHT", win.bargroup.button, "BOTTOMRIGHT", 2, 0) end skada.button.bg = skada.button:CreateTexture(nil, "BACKGROUND") skada.button.bg:SetTexture(C["media"].texture) skada.button.bg:SetVertexColor(unpack(C["media"].border_color)) skada.button.bg:SetPoint("TOPLEFT", win.bargroup.button, "TOPLEFT", 0, 0) skada.button.bg:SetPoint("BOTTOMRIGHT", win.bargroup.button, "BOTTOMRIGHT", 0, 2) end skada:SetTexture(C["media"].texture) skada:SetSpacing(7) skada:SetBackdrop(nil) end hooksecurefunc(Skada, "UpdateDisplay", function(self) for _, win in ipairs(self:GetWindows()) do for i, v in pairs(win.bargroup:GetBars()) do if not v.BarStyled then if not v.backdrop then K.CreateBackdrop(v) end v:SetHeight(14) v.label:ClearAllPoints() v.label.ClearAllPoints = K.Dummy v.label:SetPoint("LEFT", v, "LEFT", 2, 0) v.label.SetPoint = K.Dummy v.label:SetFont(C["font"].basic_font, C["font"].basic_font_size, C["font"].basic_font_style) v.label.SetFont = K.Dummy v.label:SetShadowOffset(0, 0) v.label.SetShadowOffset = K.Dummy v.timerLabel:ClearAllPoints() v.timerLabel.ClearAllPoints = K.Dummy v.timerLabel:SetPoint("RIGHT", v, "RIGHT", 0, 0) v.timerLabel.SetPoint = K.Dummy v.timerLabel:SetFont(C["font"].basic_font, C["font"].basic_font_size, C["font"].basic_font_style) v.timerLabel.SetFont = K.Dummy v.timerLabel:SetShadowOffset(0, 0) v.timerLabel.SetShadowOffset = K.Dummy v.BarStyled = true end if v.icon and v.icon:IsShown() then v.backdrop:SetPoint("TOPLEFT", -14, 2) v.backdrop:SetPoint("BOTTOMRIGHT", 2, -2) else v.backdrop:SetPoint("TOPLEFT", -2, 2) v.backdrop:SetPoint("BOTTOMRIGHT", 2, -2) end end end end) -- Update pre-existing displays for _, window in ipairs(Skada:GetWindows()) do window:UpdateDisplay() end end)
VFS.Include(SPRINGMON_DIR .. "utils/shared.lua", nil, VFS.ZIP) local absPathToVfsPath = {} -- vfsFilePath -> { context1 = true, context2 = true... } -- where context is one of: "widget", "gadget_synced", "gadget_unsynced") local fileContextMap = {} -- We won't update listeners until at least WAIT_TIME has passed after the last change -- This can help prevent disasterous race conditions like reading a file that is being flushed to disk local WAIT_TIME = 0.3 local fileChangedBuffer = {} local lastChange = nil -- TODO: belongs to a lib, like Path.Recurse or Path.Walk local function Recurse(path, f, opts) opts = opts or {} for _, file in pairs(VFS.DirList(path), "*", opts.mode) do f(file) end for _, dir in pairs(VFS.SubDirs(path, "*", opts.mode)) do if opts.apply_folders then f(dir) end Recurse(dir, f, opts) end end local function Track(paths) for _, path in ipairs(paths) do -- path = path:lower() Spring.Log(LOG_SECTION, LOG.NOTICE, 'Watching: ' .. tostring(path)) WG.Connector.Send("WatchFile", { path = path }) end end -- unless anyFile is specified, only Lua files will be tracked local function TrackVFSDir(vfsDir, anyFile) -- track only the relevant Lua context dirs, e.g. "LuaUI" or "LuaRules" local paths = {} Recurse(vfsDir, function(vfsFilePath) vfsFilePath = vfsFilePath:lower() local absPath = VFS.GetFileAbsolutePath(vfsFilePath) if absPath == nil then return end local archiveName = VFS.GetArchiveContainingFile(vfsFilePath) if archiveName == (Game.gameName .. " " .. Game.gameVersion) then if not anyFile and vfsFilePath:sub(-4) == '.lua' then table.insert(paths, absPath) absPathToVfsPath[absPath] = vfsFilePath end end end, { mode = VFS.ZIP } ) Track(paths) end function widget:Update() if lastChange == nil then return end if os.clock() - lastChange > WAIT_TIME then FlushChanges() end end -- TODO: Maybe we should send a list of paths instead -- This could allow listeners to optimize reload -- (e.g. only reload once per a list of files) function FlushChanges() -- Cleanup early in case an error happens (prevents error spam) local buffer = fileChangedBuffer lastChange = nil fileChangedBuffer = {} local pathsMap = {} for _, cmd in pairs(buffer) do local path = cmd.path if not pathsMap[path] then pathsMap[path] = true OnFileChanged(path) end end end function widget:Initialize() if not WG.Connector or not WG.Connector.enabled then Spring.Log(LOG_SECTION, LOG.NOTICE, "Disabling springmon as the connector is also disabled.") widgetHandler:RemoveWidget(self) return end local addonPathToName = LoadAddonList() for vfsFilePath, _ in pairs(addonPathToName) do fileContextMap[vfsFilePath] = { widget = true } end ------------------------------------------------------- -- Notice: widget is loaded as handler = true, -- So we need to pass the widget as a first argument -- Careful with changing this code or the widget loader ------------------------------------------------------- widgetHandler:RegisterGlobal(widget, COMM_EVENTS.REGISTER_GADGET, function(vfsFilePath) local luaContexts = fileContextMap[vfsFilePath] if not luaContexts then luaContexts = {} fileContextMap[vfsFilePath] = luaContexts end luaContexts["gadget"] = true end) WG.Connector.Register("FileChanged", function(cmd) lastChange = os.clock() table.insert(fileChangedBuffer, cmd) end) Spring.Log(LOG_SECTION, LOG.NOTICE, "Watching files for changes...") TrackVFSDir("LuaUI") TrackVFSDir("LuaRules") Spring.SendLuaRulesMsg(COMM_EVENTS.SYNC_GADGETS) end local Springmon = { trackers = {}, -- VFS -> tracker name mapping custom_trackers = {}, -- TrackVFSDir = TrackVFSDir } function OnFileChanged(filePath) local tracker_name = Springmon.custom_trackers[filePath] if tracker_name ~= nil then local tracker = Springmon.trackers[custom_tracker] tracker.callback(filePath) return end for _, tracker in pairs(Springmon.trackers) do if tracker.canTrack ~= nil and tracker.canTrack(filePath) then tracker.callback(filePath) return end end local vfsPath = absPathToVfsPath[filePath] if not vfsPath then Spring.Log(LOG_SECTION, LOG.WARNING, "Cannot resolve VFS path for tracked file " .. tostring(filePath)) return end local luaContexts = fileContextMap[vfsPath] if luaContexts == nil then Spring.Log(LOG_SECTION, LOG.WARNING, "Cannot reload " .. tostring(vfsPath) .. " : no detected Lua context. Reload manually.") return end for luaContext, _ in pairs(luaContexts) do if luaContext == "widget" then ReloadFile(vfsPath) else Spring.SendLuaRulesMsg(COMM_EVENTS.FILE_CHANGED .. vfsPath) end end end function Springmon.AddTracker(name, absPaths, callback, canTrack) if type(absPaths) == "string" then absPaths = {absPaths} end Springmon.trackers[name] = { absPaths = absPaths, callback = callback, canTrack = canTrack } Track(absPaths) for _, absPath in ipairs(absPaths) do Springmon.custom_trackers[absPath] = name end end function Springmon.RemoveTracker(name) local tracker = Springmon.trackers[name] if not tracker then Spring.Log(LOG_SECTION, LOG.WARNING, "Trying to remove tracker that doesn't exist: " .. tostring(name)) return end for _, absPath in ipairs(tracker.absPaths) do Springmon.custom_trackers[absPath] = nil end end WG.Springmon = Springmon
-------------------------------------------------------------------------- -- Crytek Source File. -- Copyright (C), Crytek Studios, 2001-2006. -------------------------------------------------------------------------- -- $Id$ -- $DateTime$ -- Description: Shooting target. -- -------------------------------------------------------------------------- -- History: -- - 8/2006 : Created by Sascha Gundlach -- -------------------------------------------------------------------------- ShootingTarget = { Client = {}, Server = {}, Properties= { fileModel = "objects/library/architecture/aircraftcarrier/props/misc/target.cgf", bTurningMode = 1, fIntervallMin = 3, fIntervallMax = 5, fLightUpTime = 2, fTurnSpeed = 0.5, soclasses_SmartObjectClass = "ShootingTarget", }, Editor= { Icon="Item.bmp", ShowBounds = 1, }, States = {"Activated","Deactivated","Turning","Init"}, } ACTIVATION_TIMER=0; TURN_TIMER=1; function ShootingTarget:OnReset() local props=self.Properties; if(not EmptyString(props.fileModel))then self:LoadObject(0,props.fileModel); end; EntityCommon.PhysicalizeRigid(self,0,self.physics,0); self.side=0; self.ended=0; self:GetAngles(self.initialrot); CopyVector(self.turnrot,self.initialrot); self.turnrot.x=self.turnrot.x+(math.pi/2); self:Activate(1); self:GotoState("Deactivated"); end; function ShootingTarget:OnSave(tbl) tbl.side=self.side; tbl.ended=self.ended; end; function ShootingTarget:OnLoad(tbl) self.side=tbl.side self.ended=tbl.ended; end; function ShootingTarget:OnPropertyChange() self:OnReset(); end; function ShootingTarget.Server:OnInit() self.physics = { bRigidBody=0, bRigidBodyActive = 0, Density = -1, Mass = -1, }; self.tmp={x=0,y=0,z=0}; self.turnrot={x=0,y=0,z=0}; self.initialrot={x=0,y=0,z=0}; self.inc=0; self.init=1; self:OnReset(); end; function ShootingTarget.Server:OnHit(hit) if(self:GetState()~="Activated")then return;end; local vTmp=g_Vectors.temp; SubVectors(vTmp,self:GetPos(),hit.pos); local dist=LengthVector(vTmp); dist=((1-(dist*2))+0.08)*10; if(dist>9.4)then dist=10; else dec=string.find(dist,".",1,1) dist=tonumber(string.sub(dist,1,dec-1)) end; if(self.Properties.bTurningMode==1)then local shooter=0; if(hit.shooter and hit.shooter==g_localActor)then shooter=1; else shooter=2; end; if(self.side==1)then self:GotoState("Init"); self:ActivateOutput("Hit",dist); else self:ActivateOutput("Hit",-1); end; else --Normal mode just outputs hit end; end; ----------------------------------------------------------------------------------- function ShootingTarget:Event_Activated() self:GotoState("Init"); BroadcastEvent(self, "Activated") end; function ShootingTarget:Event_Deactivated() self.ended=1; self:GotoState("Deactivated"); BroadcastEvent(self, "Deactivated") end; ----------------------------------------------------------------------------------- ShootingTarget.Server.Deactivated= { OnBeginState = function(self) if(self.init==0)then local props=self.Properties; self:KillTimer(ACTIVATION_TIMER); self:KillTimer(TURN_TIMER); AI.SetSmartObjectState(self.id,"Neutral"); if(props.fIntervallMin>props.fIntervallMax)then props.fIntervallMin=props.fIntervallMax;end; self:SetTimer(ACTIVATION_TIMER,20); else self.init=0; end; end, OnTimer = function(self,timerId,msec) if(timerId==ACTIVATION_TIMER)then self:GetAngles(self.tmp); self.inc=self.inc+self.Properties.fTurnSpeed; self.tmp.x=self.tmp.x+self.Properties.fTurnSpeed; self:SetAngles(self.tmp); if(self.inc<math.pi)then self:SetTimer(ACTIVATION_TIMER,20); else self:SetAngles(self.initialrot); end; end; end, }; ShootingTarget.Server.Activated= { OnBeginState = function(self) self.ended=0; if(self.Properties.bTurningMode==1)then AI.SetSmartObjectState(self.id,"Neutral"); local props=self.Properties; if(props.fIntervallMin>props.fIntervallMax)then props.fIntervallMin=props.fIntervallMax;end; self:SetTimer(ACTIVATION_TIMER,1000*random(props.fIntervallMin,props.fIntervallMax)); end; end, OnTimer = function(self,timerId,msec) if(self.ended==1)then self:GotoState("Deactivated"); return; end; if(timerId==ACTIVATION_TIMER)then self:GetAngles(self.tmp); self.inc=self.inc+self.Properties.fTurnSpeed; self.tmp.x=self.tmp.x-self.Properties.fTurnSpeed; self:SetAngles(self.tmp); if(self.inc<math.pi)then self:SetTimer(ACTIVATION_TIMER,20); else self:SetAngles(self.initialrot); AI.SetSmartObjectState(self.id,"Colored"); self.side=1; self:SetTimer(TURN_TIMER,1000*self.Properties.fLightUpTime); end; elseif(timerId==TURN_TIMER)then AI.SetSmartObjectState(self.id,"Neutral"); self:GotoState("Init"); end; end, }; ShootingTarget.Server.Init= { OnBeginState = function(self) self:KillTimer(ACTIVATION_TIMER); self:KillTimer(TURN_TIMER); self.inc=0; self.side=0; self:SetTimer(ACTIVATION_TIMER,25); end, OnTimer = function(self,timerId,msec) if(timerId==ACTIVATION_TIMER)then self:GetAngles(self.tmp); self.inc=self.inc+self.Properties.fTurnSpeed; self.tmp.x=self.tmp.x+self.Properties.fTurnSpeed; self:SetAngles(self.tmp); if(self.inc<math.pi/2)then self:SetTimer(ACTIVATION_TIMER,25); else self:SetAngles(self.turnrot); self:GotoState("Activated"); end; end; end, }; ----------------------------------------------------------------------------------- ShootingTarget.FlowEvents = { Inputs = { Deactivated = { ShootingTarget.Event_Deactivated, "bool" }, Activated = { ShootingTarget.Event_Activated, "bool" }, }, Outputs = { Deactivated = "bool", Activated = "bool", Hit = "int", PlayerOne = "int", PlayerTwo = "int", }, }
---------------------------------------- -- -- Copyright (c) 2015, 128 Technology, Inc. -- -- author: Hadriel Kaplan <hadriel@128technology.com> -- -- This code is licensed under the MIT license. -- -- Version: 1.0 -- ------------------------------------------ -- prevent wireshark loading this file as a plugin if not _G['protbuf_dissector'] then return end local Settings = require "settings" local dprint = Settings.dprint local dprint2 = Settings.dprint2 local dassert = Settings.dassert local derror = Settings.derror local Base = require "generic.base" ---------------------------------------- -- Fixed64Decoder class, for "fixed64" fields -- local Fixed64Decoder = {} local Fixed64Decoder_mt = { __index = Fixed64Decoder } setmetatable( Fixed64Decoder, { __index = Base } ) -- make it inherit from Base function Fixed64Decoder.new(pfield) local new_class = Base.new("FIXED32", pfield) setmetatable( new_class, Fixed64Decoder_mt ) return new_class end function Fixed64Decoder:decode(decoder, tag) dprint2("Fixed64Decoder:decode() called") return decoder:addFieldStruct(self.pfield, "<E", 8) end return Fixed64Decoder
local enabled = false local Log = {} function Log.setEnabled(bool) enabled = bool end function Log.info(message) if enabled then print("Sentry Info: "..message) end end function Log.warn(message) if enabled then warn("Sentry Warn: "..message) end end function Log.error(message) if enabled then coroutine.wrap(function() error("Sentry Error: "..message, 2) end)() end end return Log
local widget, version = "Font", 2 local LBO = LibStub("LibLimeOption-1.0") if not LBO:NewWidget(widget, version) then return end local SM = LibStub("LibSharedMedia-3.0", true) local _G = _G local type = _G.type local CreateFrame = _G.CreateFrame local menu = LibLimeOption10FontMenu or nil local file, size, attribute, shadow, fixSize local function getfuncvalue(func, ...) if type(func) == "function" then return func(...) else return func end end local function hide(self) if menu then if not self or menu.parent == self or menu.parent == self:GetParent() then menu:SetMenu(nil) return true end end return nil end local function getFontFile(file) if file and SM.MediaTable.font[file] then return file else return SM.DefaultMedia.font end end local function update(self) if self and self.GetValue then file, size, attribute, shadow, fixSize = self:GetValue() file = getFontFile(file) self.text:SetFont(SM:Fetch("font", file), 12, attribute or "") if shadow then self.text:SetShadowColor(0, 0, 0) self.text:SetShadowOffset(1, -1) else self.text:SetShadowOffset(0, 0) end if getfuncvalue(fixSize) then self.text:SetFormattedText(file) else self.text:SetFormattedText("%s, %d", file, size or 12) end end end local function createFontFrame() if not menu then menu = LBO:CreateDropDownMenu(widget, "DIALOG") menu:SetWidth(150) menu:SetHeight(230) menu.attributeList = { "None", "OUTLINE", "THICKOUTLINE" } menu.info = {} local function hidden(key) if menu:IsVisible() and menu.parent and type(menu.parent.set) == "function" then if key == "size" then if getfuncvalue(menu.info.fixSize) then menu.fontAttribute:ClearAllPoints() menu.fontAttribute:SetPoint("TOP", menu.fontFile, "BOTTOM", 0, -5) menu:SetHeight(181) return true else menu.fontAttribute:ClearAllPoints() menu.fontAttribute:SetPoint("TOP", menu.fontSize, "BOTTOM", 0, -5) menu:SetHeight(230) return nil end else return nil end end return true end local function set(v, key) if key == "file" or key == "size" or key == "shadow" then menu.info[key] = v elseif key == "attribute" then menu.info[key] = v or nil else return end menu.parent.set( menu.info.file, menu.info.size, menu.info.attribute, menu.info.shadow, menu.parent.arg1, menu.parent.arg2, menu.parent.arg3 ) update(menu.parent) end menu.fontFile = LBO:CreateWidget("Media", menu, "font", "Font.", hidden, nil, nil, function() return menu.info.file, "font" end, set, "file") menu.fontFile:SetWidth(120) menu.fontFile:SetPoint("TOP", 0, -15) menu.fontSize = LBO:CreateWidget("Slider", menu, "size", "Font size.", hidden, nil, nil, function() return menu.info.size, 7, 34, 1, "pt" end, set, "size") menu.fontSize:SetWidth(120) menu.fontSize:SetPoint("TOP", menu.fontFile, "BOTTOM", 0, -5) menu.fontAttribute = LBO:CreateWidget("DropDown", menu, "attribute", "Font attribute.", hidden, nil, nil, function() return menu.info.attribute, menu.attributeList end, set, "attribute") menu.fontAttribute:SetWidth(120) menu.fontAttribute:SetPoint("TOP", menu.fontSize, "BOTTOM", 0, -5) menu.fontShadow = LBO:CreateWidget("CheckBox", menu, "shadow", "Font shadow", hidden, nil, nil, function() return menu.info.shadow end, set, "shadow") menu.fontShadow:SetWidth(120) menu.fontShadow:SetPoint("TOP", menu.fontAttribute, "BOTTOM", 0, 0) menu.fontOkay = LBO:CreateWidget("Button", menu, OKAY, nil, hidden, nil, nil, function() menu:SetMenu(nil) LBO:Refresh() end ) menu.fontOkay:SetPoint("BOTTOMLEFT", 10, 0) menu.fontOkay:SetPoint("BOTTOMRIGHT", menu, "BOTTOM", 0.5, 0) menu.fontCancel = LBO:CreateWidget("Button", menu, CANCEL, nil, hidden, nil, nil, function() if menu.info.file ~= menu.info.prev_file or menu.info.size ~= menu.info.prev_size or menu.info.attribute ~= menu.info.prev_attribute or menu.info.prev_shadow ~= menu.info.shadow then menu.parent.set( menu.info.prev_file, menu.info.prev_size, menu.info.prev_attribute, menu.info.prev_shadow, menu.parent.arg1, menu.parent.arg2, menu.parent.arg3 ) LBO:Refresh() end menu:SetMenu(nil) end) menu.fontCancel:SetPoint("BOTTOMLEFT", menu, "BOTTOM", -0.5, 0) menu.fontCancel:SetPoint("BOTTOMRIGHT", -10, 0) end end local function click(self) if hide(self) then return nil else createFontFrame() file, size, menu.info.attribute, shadow, menu.info.fixSize = self:GetValue() menu:SetMenu(self) menu.info.file = getFontFile(file) menu.info.size = size or 12 menu.info.shadow = shadow and true or nil menu.info.prev_file = menu.info.file menu.info.prev_size = menu.info.size menu.info.prev_attribute = menu.info.attribute menu.info.prev_shadow = menu.info.shadow menu:Show() return true end end LBO:RegisterWidget(widget, version, function(self, name) LBO:CreateDropDown(self, true, click) self.Setup = update end)
_G.NPCCache = {} _G.BlockCache = {} _G.EffectCache = {} _G.BGOCache = {} _G.PlayerCache = {} _G.SectionCache = {} _G.NPC_MAX_ID = 1000 _G.BLOCK_MAX_ID = 1000 _G.EFFECT_MAX_ID = 1000 _G.BGO_MAX_ID = 1000 _G.PLAYER_MAX_CHARACTERS = 7 _G.SECTION_MAX_ID = 200 _G.NPC_MAX_AMOUNT = 8000 _G.BLOCK_MAX_AMOUNT = 50000 _G.EFFECT_MAX_AMOUNT = 2000 _G.BGO_MAX_AMOUNT = 8000 _G.PLAYER_MAX_AMOUNT = 200 _G.NPC = require 'engine/npc_t'
Lasergun = Class { __includes=LineTower, init = function(self, gridOrigin, worldOrigin, orientation) self.towerType = "LASERGUN" LineTower.init(self, animationController:createInstance(self.towerType), gridOrigin, worldOrigin, constants.STRUCTURE.LASERGUN.WIDTH, constants.STRUCTURE.LASERGUN.HEIGHT, constants.STRUCTURE.LASERGUN.COST, constants.STRUCTURE.LASERGUN.ATTACK_DAMAGE, constants.STRUCTURE.LASERGUN.ATTACK_INTERVAL, constants.STRUCTURE.LASERGUN.LINE_LENGTH, constants.STRUCTURE.LASERGUN.LINE_WIDTH, orientation ) end; update = function(self, dt) MeleeTower.update(self, dt) end; addMutation = function(self, mutation) assert(mutation and mutation.id) MeleeTower.addMutation(self, mutation, animationController:createInstance(self.towerType..'-'..mutation.id)) end; fireLaser = function(self) -- create an Impact audioController:playAny("LASERGUN_SHOOT") local x, y, width, height = LineTower.calculateHitbox(self) local stats = {BASE_DAMAGE = self.attackDamage} local dimensions = {width = width, height = height} if self.mutation then local mutationStats = Util.t.copy(self.mutation.stats) mutationStats.BASE_DAMAGE = self.attackDamage if self.mutation.id == "FIRE" then return LaserFireImpact(Vector(x, y), mutationStats, dimensions) elseif self.mutation.id == "ELECTRIC" then return LaserElectricImpact(Vector(x, y), mutationStats, dimensions) elseif self.mutation.id == "ICE" then return LaserIceImpact(Vector(x, y), mutationStats, dimensions) end else return LaserImpact(Vector(x, y), stats, dimensions) end end; }
local utils = require 'utils' local unitindex = require 'units/unitindex' UnitsLayer = {} function UnitsLayer:initLayer(game, spawnlayer) self.game = game self.spawnlayer = spawnlayer self.objects = self.objects or {} self.draw = UnitsLayer.draw self.update = UnitsLayer.update self.mousemoved = UnitsLayer.mousemoved for k, o in pairs(spawnlayer.objects) do if o.type == "spawn" then local count = o.properties.count or 1 for i = 1, count do self.objects[#self.objects+1] = GenericUnit(game.world, {x=o.x, y=o.y}, o.name, o.properties.unit, o.properties.behaviour) end end end local player = Player(world, spawnlayer.spawn) self.objects[#self.objects+1] = player self.area = spawnlayer.spawn self.player = player if not map.properties.safe then for k,v in pairs(self.game.state.units) do self.objects[#self.objects+1] = GenericUnit(self.game.world, spawnlayer.spawn, 'player', v) end end end -- Draw units layer function UnitsLayer:draw() for k,v in pairs(self.objects) do if v:isAlive() == false then v:draw() end end for k,v in utils.spairs(self.objects, function(o,a,b) return o[b].body.body:getY() > o[a].body.body:getY() end) do if v:isAlive() == true then v:draw() end end end -- Update units layer function UnitsLayer:update(dt) local w = love.keyboard.isDown( 'w' ) local a = love.keyboard.isDown( 'a' ) local s = love.keyboard.isDown( 's' ) local d = love.keyboard.isDown( 'd' ) local moveX = 0 local moveY = 0 if d then moveX = 1 end if a then moveX = moveX - 1 end if s then moveY = 1 end if w then moveY = moveY - 1 end if a or s or d or w then self.player.behaviour:setMovement(math.atan2(moveY, moveX)) else self.player.behaviour:setMovement(nil) end for k,v in pairs(self.objects) do if v:getFraction() == 'player' then if self.cursor then if self.cursor.button == 1 then v:setTarget({self.cursor.wx, self.cursor.wy}) else local distx = self.player.body.body:getX() - v.body.body:getX() local disty = self.player.body.body:getY() - v.body.body:getY() local dist = math.sqrt(distx*distx + disty*disty) if dist > 128 then v:setTarget({self.player.body.body:getX(), self.player.body.body:getY()}) else v:setTarget(nil) end end end end v:update(dt, self) end local lastarea = self.area local currentarea for k,area in pairs(self.spawnlayer.objects) do if utils.inarea({x=self.player.body.body:getX(), y=self.player.body.body:getY()}, area) then currentarea = area end end self.area = currentarea if currentarea and currentarea ~= lastarea and currentarea.type == "exit" and currentarea.properties.map then self.game:leave() self.game:enter(currentarea.properties.map, currentarea.properties.exit) end end function UnitsLayer:mousemoved(x, y, dx, dy, istouch , button) local wx, wy = love.graphics.inverseTransformPoint( x, y ) self.cursor = {x=x, y=y, wx=wx, wy=wy, button=button} end
--- Wheels function init() local mode = 1 local lastClock = 0 local dt = 0.5 local mdt = function() return dt / mode end local makeArray = function(count, f) local array = {} for i = 1, count do array[i] = f(i) end return array end local reduceArray = function(a, f) local result for i = 1, #a do result = f(result, a[i]) end return result end local makeTable = function(count) return makeArray(count, function(i) return 0 end) end local makeLoop = function(t) return loop(makeArray( #t, function(i) return to( function() return t[i] end, mdt, 'now' ) end )) end local randomTable = makeTable(8) local printArray = function(a) local merged = reduceArray( a, function(r, v) if r == nil then return v else return r .. ', ' .. v end end ) print('[' .. (merged or '') .. ']') end local updateTables = function() local steps = math.floor(2 ^ (mode - 1)) local values = makeArray(steps, function() return math.random() * 5.0 end) printArray(randomTable) local randomLength = #randomTable for i = 1, randomLength do local idx = math.floor((i - 1) / (randomLength / steps)) + 1 randomTable[i] = values[idx] end printArray(randomTable) end local clock = function() print('clock') local c = time() dt = (c - lastClock) / 1000 lastClock = c local v = input[2].volts or 0 local x = (v + 5) / 2.5 + 1 local newMode = math.floor(math.min(math.max(x, 1), 4)) if mode ~= newMode then mode = newMode print(mode) end updateTables() output[1]('restart') output[2]('restart') -- output[3]('restart') -- output[4]('restart') print(dt) end input[1]{ mode = 'change' , direction = 'rising', change = clock } input[2].mode = 'none' output[1](lfo(mdt, 5, 'linear')) output[2](makeLoop(randomTable)) -- output[3](makeLoop(tables[3])) -- output[4](makeLoop(tables[4])) end
local bin = require "plc52.bin" local Reader = require("lightning-dissector.utils").Reader local OrderedDict = require("lightning-dissector.utils").OrderedDict local f = require("lightning-dissector.constants").fields.payload.deserialized function deserialize(payload) local reader = Reader:new(payload) local packed_channel_id = reader:read(32) local packed_signature = reader:read(64) local packed_num_htlcs = reader:read(2) local num_htlcs = string.unpack(">I2", packed_num_htlcs) local signatures = {} for i = 1, num_htlcs do local packed_signature = reader:read(64) table.insert(signatures, OrderedDict:new( f.htlc_signature.raw, bin.stohex(packed_signature), f.htlc_signature.der, bin.stohex(convert_signature_der(packed_signature)) )) end return OrderedDict:new( f.channel_id, bin.stohex(packed_channel_id), "signature", OrderedDict:new( f.signature.raw, bin.stohex(packed_signature), f.signature.der, bin.stohex(convert_signature_der(packed_signature)) ), "num_htlcs", OrderedDict:new( f.num_htlcs.raw, bin.stohex(packed_num_htlcs), f.num_htlcs.deserialized, num_htlcs ), "htlc_siganture", signatures ) end return { number = 132, name = "commitment_signed", deserialize = deserialize }
function fib(N) local array = {1,1} while #array < N do array[#array + 1] = array[#array - 1] + array[#array] end return array end print(table.concat(fib(100), ","))
object_static_item_item_component_power_pack = object_static_item_shared_item_component_power_pack:new { } ObjectTemplates:addTemplate(object_static_item_item_component_power_pack, "object/static/item/item_component_power_pack.iff")
local i = get() if i == "one" then if check1() then do1() end elseif i == "two" then if check2() then do2() else -- do nothing end else return end
return { { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 700 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 810 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 920 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 1030 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 1140 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 1250 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 1360 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 1470 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 1580 } } } }, { effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 1700 } } } }, desc_get = "当鱼雷命中敌人时,有4%概率触发集火信号,持续8秒,将导致该敌舰受到鱼雷的伤害提高20%(不可叠加)", name = "集火信号-鱼雷", init_effect = "", time = 0, color = "red", picture = "", desc = "当鱼雷命中敌人时,有4%概率触发集火信号,持续8秒,将导致该敌舰受到鱼雷的伤害提高20%(40%)(不可叠加)", stack = 1, id = 2121, icon = 2120, last_effect = "", effect_list = { { type = "BattleBuffCastSkill", trigger = { "onStartGame" }, arg_list = { skill_id = 2121 } }, { type = "BattleBuffAddBuff", trigger = { "onBulletHit" }, arg_list = { buff_id = 2120, weaponType = 16, rant = 700 } } } }
Network:Subscribe( 'DamageActor', function( WNO, sender ) if sender == nil or not IsValid( sender ) then return end if not WNO or not IsValid( WNO ) then return end local actor = AM.actors_id[WNO:GetId()] if not actor then return end local weapon = sender:GetEquippedWeapon() if not weapon then return end local weapon_info = WI:GetWeaponInfo( weapon.id ) if not weapon_info then return end if actor.Damage then actor:Damage( sender, weapon_info ) end end )
--[[--------------------------------------------- AdvLib (C) Mijyuoon 2014-2020 Contains various helper functions -----------------------------------------------]] adv = { -- Constants here HttpCache = {}, Markup = {}, } ----- Config section ---------------------------- local Use_MoonScript = true local Use_PrintTable = false ------------------------------------------------- local MODLOAD = {} adv._MODLOAD = MODLOAD function loadmodule(name) if MODLOAD[name] then return MODLOAD[name] end local kname = name:gsub("%.", "/") .. ".lua" local is_sv = file.Exists(kname, "LUA") local is_cl = file.Exists(kname, "LCL") if not (is_sv or is_cl) then error(adv.StrFormat{"cannot find module \"$1\"", name}) end local func = CompileFile(kname, name) if func then MODLOAD[name] = func() or true return MODLOAD[name] end end if pcall(require, "lpeg") then function lpeg.L(v) return #v end else loadmodule("moonscript.lulpeg"):register(_G) end lpeg.re = loadmodule("moonscript.lpeg_re") local trmv = table.remove function adv.StrFormat(text, subst) if subst == nil then subst = text text = trmv(text, 1) end text = text:gsub("$([%w_]+)", function(s) local ns = tonumber(s) or s local subs = subst[ns] if subs == nil then return end return tostring(subs) end) return text end function adv.StrSet(text, pos, rep) pos = (pos < 0) and #text+pos+1 or pos if pos > #text or pos < 1 then return text end return text:sub(1, pos-1) .. rep .. text:sub(pos+1, -1) end function adv.StrSplit(str, sep) sep = lpeg.re.compile(sep) local elem = lpeg.C((1 - sep)^0) local gs = lpeg.Ct(elem * (sep * elem)^0) return gs:match(str) end adv.StrPatt = lpeg.re.compile adv.StrFind = lpeg.re.find adv.StrMatch = lpeg.re.match adv.StrSubst = lpeg.re.gsub function adv.TblMap(tbl, func) for ki, vi in pairs(tbl) do tbl[ki] = func(vi) end return tbl end function adv.TblMapN(tbl, func) local res = {} for ki, vi in pairs(tbl) do res[ki] = func(vi) end return res end function adv.TblFold(tbl, acc, func) local init = nil if func == nil then func = acc acc = tbl[1] init = acc end for _, vi in next, tbl, init do acc = func(acc, vi) end return acc end function adv.TblFilt(tbl, func) for ki, vi in pairs(tbl) do if not func(vi) then tbl[ki] = nil end end return tbl end function adv.TblFiltN(tbl, func) local res = {} for ki, vi in pairs(tbl) do if func(vi) then res[ki] = vi end end return res end function adv.TblSlice(tbl, from, to, step) local res = {} from = from or 1 to = to or #tbl step = step or 1 for i = from, to, step do res[#res+1] = tbl[i] end return res end function adv.TblAny(tbl, func) for ki, vi in pairs(tbl) do if func(vi) then return true end end return false end function adv.TblAll(tbl, func) for ki, vi in pairs(tbl) do if not func(vi) then return false end end return true end function adv.TblKeys(tbl) local res = {} for k in pairs(tbl) do res[#res+1] = k end return res end for _, kn in pairs{"K", "V", "KV"} do adv["TblWeak" .. kn] = function() return setmetatable({}, { __mode = kn:lower() }) end end local function prefix(str) local stri = tostring(str) return (stri:gsub("^[a-z]+: ", "")) end local function do_printr(arg, spaces, passed) local ty = type(arg) if ty == "table" then passed[arg] = true Msg(adv.StrFormat{"(table) $v {\n", v = prefix(arg)}) for k ,v in pairs(arg) do if not passed[v] then Msg(adv.StrFormat{" $s($t) $k => ", s = spaces, t = type(k), k = k}) do_printr(rawget(arg, k), spaces.." ", passed) else Msg(adv.StrFormat{" $s($t) $k => [RECURSIVE TABLE: $v]\n", s = spaces, t = type(k), k = k, v = prefix(v)}) end end Msg(spaces .. "}\n") elseif ty == "function" then Msg(adv.StrFormat{"($t) $v\n", t = ty, v = prefix(arg)}) elseif ty == "string" then Msg(adv.StrFormat{"($t) '$v'\n", t = ty, v = arg}) elseif ty == "nil" then Msg(adv.StrFormat{"($t)\n", t = ty}) else Msg(adv.StrFormat{"($t) $v\n", t = ty, v = arg}) end end function adv.TblPrint(...) local arg = {...} for i = 1, #arg do do_printr(arg[i], "", {}) end end if CLIENT then function adv.DataMat(mat, opts) return Material(adv.StrFormat{"../data/$1\n.png", mat}, opts) end function adv.DataSnd(snd, opts, func) sound.PlayFile(adv.StrFormat{"../data/$1\n.mp3", snd}, opts, func) end end local http_cache = {} file.CreateDir("httpcache/") function adv.HttpCache.Del(url) if not http_cache[url] then return false end url = url:gsub("^%w://", "") file.Delete(http_cache[url]) if file.Exists(http_cache[url], "DATA") then return false end http_cache[url] = nil return true end function adv.HttpCache.Wipe(filt) for key, fn in pairs(http_cache) do if not filt or key:match(filt) then adv.HttpCache.Del(key) end end local rest = file.Find("httpcache/*.txt", "DATA") for _, fn in ipairs(rest) do if not filt or fn:match(filt) then file.Delete(fn) end end end function adv.HttpCache.Get(url, rd) local url2 = http_cache[url:gsub("^%w://", "")] if not url2 then return false end if not rd then return url2 end return url2, file.Read(url2, "DATA") end function adv.HttpCache.New(url, succ, fail) local url2 = url:gsub("^%w://", "") local rand = url2:match("/([^/]+)$"):gsub("[^%w_%-]", "") rand = adv.StrFormat{"httpcache/$1.txt", rand} if http_cache[url2] then succ(http_cache[url2]) return true elseif file.Exists(rand, "DATA") then http_cache[url2] = rand succ(http_cache[url2]) return true end http.Fetch(url, function(data, ...) file.Write(rand, data) http_cache[url2] = rand if succ then succ(rand, data, ...) end end, fail) return false end do ---- Markup parser -------------------------------- local esc = { ['<'] = "&lt;", ['>'] = "&gt;", ['&'] = "&amp;", ['"'] = "&quot;", } local repl; repl = { __Stk = {}; StkPush = function(val) table.insert(repl.__Stk, val) end; StkPop = function() return table.remove(repl.__Stk) end; ReInit = function() table.Empty(repl.__Stk) end; PtEsc = function(value) return value[1] end; PtCmd = function(iden, ...) if iden == "{\\}" then local val = repl.StkPop() return "</"..(val or "")..">" end local tags = adv.Markup.Tags if not tags[iden] then return "" end local html = tags[iden](...) local tag = html:match"^<([a-z%-]+)" if tag then repl.StkPush(tag) end return html end; PtRaw = function(value) return (value:gsub('[<>&"]', esc)) end; } local lP,lR,lS = lpeg.P, lpeg.R, lpeg.S local lC,lCs,lCt = lpeg.C, lpeg.Cs, lpeg.Ct local besc = lP"{{" / repl.PtEsc local sesc = lP"\"\"" / repl.PtEsc local iden = lC( (lR("az","AZ","09") + lS"#-")^1 ) local var1 = iden + "\"" * lCs(( (1 - lP"\"")^1 + sesc )^0) * "\"" local varn = var1 * (";" * var1)^0 local cmd = lCs(lP"{\\" * ( iden * ("=" * varn)^-1 )^-1 * "}" / repl.PtCmd) local grammar = lCt(( besc + cmd + ((1 - lP"{")^1 / repl.PtRaw) )^0) adv.Markup.Tags = { c = function(arg1) if not arg1 then return "" end return adv.StrFormat{'<span style="color:$1">', arg1} end; n = function(arg1) local temp = tonumber(arg1) if not temp then return "" end return adv.StrFormat{'<span style="font-size:$1">', temp} end; f = function(...) local args = {...} if #args < 1 then return "" end adv.TblMap(args, function(v) local fn = v:gsub("\"", "") if not fn:match(" ") then return fn end return adv.StrFormat{"&quot;$1$quot;", fn} end) local temp = table.concat(args, ", ") return adv.StrFormat{'<span style="font-family:$1">', temp} end; b = function() return "<b>" end; i = function() return "<i>" end; u = function() return "<u>" end; s = function() return "<s>" end; } function adv.Markup.Parse(text) repl.ReInit() local vals = grammar:match(text) for i = 1, #repl.__Stk do vals[#vals+1] = "</"..repl.StkPop()..">" end local result = table.concat(vals) return (result:gsub("\r?\n", "<br>\n")) end end -------------------------------------------------- do ---- SQL query builder ---------------------------- local lP,lR,lS = lpeg.P, lpeg.R, lpeg.S local lC,lCs,lCt = lpeg.C, lpeg.Cs, lpeg.Ct local str = lC(lP"'" * (lP"''" + (1 - lP"'"))^0 * "'") local mark = lCt(lC"?" * lC(lR("AZ", "az", "09", "__")^1)^-1) local grammar = lCt(( str + mark + lC((1 - lS"'?")^1) )^0) local sq_meta = {} sq_meta.__index = sq_meta function sq_meta:BindParam(key, value) local ty, _value = type(value), nil if ty == "boolean" then _value = value and 1 or 0 elseif ty == "string" then _value = SQLStr(value) elseif ty == "number" then _value = value end if not _value then error("unsupported type") end self.params[key] = _value end function sq_meta:BindTable(tbl) for key, val in pairs(tbl) do self:BindParam(key, val) end end function sq_meta:Execute() local pd = self.params local qd = self.builder local count = 1 for i = 1, #qd do local value = qd[i] if istable(value) then local nk = value[2] nk = tonumber(nk) or nk if not nk then nk = count count = nk + 1 end if not pd[nk] then error("Unbound parameter: "..nk) end qd[i] = pd[nk] end end local query = table.concat(qd) local ret = sql.Query(query) if ret == false then return false, sql.LastError() end return ret end function adv.SqlNew(query) query = grammar:match(query) local parv = adv.TblWeakKV() return setmetatable({ params = parv, builder = query, }, sq_meta) end end -------------------------------------------------- if Use_PrintTable then PrintTable = adv.TblPrint end if Use_MoonScript then if SERVER then AddCSLuaFile("moonscript/base.lua") AddCSLuaFile("moonscript/compile.lua") AddCSLuaFile("moonscript/data.lua") AddCSLuaFile("moonscript/dump.lua") AddCSLuaFile("moonscript/errors.lua") AddCSLuaFile("moonscript/line_tables.lua") AddCSLuaFile("moonscript/lpeg_re.lua") AddCSLuaFile("moonscript/lulpeg.lua") AddCSLuaFile("moonscript/parse.lua") AddCSLuaFile("moonscript/transform.lua") AddCSLuaFile("moonscript/types.lua") AddCSLuaFile("moonscript/util.lua") AddCSLuaFile("moonscript/compile/statement.lua") AddCSLuaFile("moonscript/compile/value.lua") AddCSLuaFile("moonscript/transform/names.lua") AddCSLuaFile("moonscript/transform/destructure.lua") end moonscript = loadmodule "moonscript.base" end
--[[ MIT LICENSE Copyright (c) 2013 Enrique García Cota + Eike Decker + Jeffrey Friedl Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -- loading this file (takes a while but grants a boost of factor 13) -- local storing of global functions (minor speedup) local floor, modf = math.floor,math.modf local char,format,rep = string.char,string.format,string.rep -- merge 4 bytes to an 32 bit word local function bytes_to_w32(a,b,c,d) return a*0x1000000+b*0x10000+c*0x100+d end -- shift the bits of a 32 bit word. Don't use negative values for "bits" local function w32_rot(bits,a) local b2 = 2^(32-bits) local a,b = modf(a/b2) return a+b*b2*(2^(bits)) end local band, bor, bxor, bnot = bit32.band, bit32.bor, bit32.bxor, bit32.bnot --- adding 2 32bit numbers, cutting off the remainder on 33th bit local function w32_add(a,b) return (a+b) % 4294967296 end --- adding n 32bit numbers, cutting off the remainder (again) local function w32_add_n(a,...) for i=1,select('#',...) do a = (a+select(i,...)) % 4294967296 end return a end -- converting the number to a hexadecimal string local function w32_to_hexstring(w) return format("%08x",w) end -- calculating the SHA1 for some text local function sha1(msg) local H0,H1,H2,H3,H4 = 0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0 local msg_len_in_bits = #msg * 8 local first_append = char(0x80) -- append a '1' bit plus seven '0' bits local non_zero_message_bytes = #msg +1 +8 -- the +1 is the appended bit 1, the +8 are for the final appended length local current_mod = non_zero_message_bytes % 64 local second_append = current_mod>0 and rep(char(0), 64 - current_mod) or "" -- now to append the length as a 64-bit number. local B1, R1 = modf(msg_len_in_bits / 0x01000000) local B2, R2 = modf( 0x01000000 * R1 / 0x00010000) local B3, R3 = modf( 0x00010000 * R2 / 0x00000100) local B4 = 0x00000100 * R3 local L64 = char( 0) .. char( 0) .. char( 0) .. char( 0) -- high 32 bits .. char(B1) .. char(B2) .. char(B3) .. char(B4) -- low 32 bits msg = msg .. first_append .. second_append .. L64 assert(#msg % 64 == 0) local chunks = #msg / 64 local W = { } local start, A, B, C, D, E, f, K, TEMP local chunk = 0 while chunk < chunks do -- -- break chunk up into W[0] through W[15] -- start,chunk = chunk * 64 + 1,chunk + 1 for t = 0, 15 do W[t] = bytes_to_w32(msg:byte(start, start + 3)) start = start + 4 end -- -- build W[16] through W[79] -- for t = 16, 79 do -- For t = 16 to 79 let Wt = S1(Wt-3 XOR Wt-8 XOR Wt-14 XOR Wt-16). W[t] = w32_rot(1, bxor(W[t-3], W[t-8], W[t-14], W[t-16])) -- TODO: bxor many end A,B,C,D,E = H0,H1,H2,H3,H4 for t = 0, 79 do if t <= 19 then -- (B AND C) OR ((NOT B) AND D) f = bor(band(B, C), band(bnot(B), D)) K = 0x5A827999 elseif t <= 39 then -- B XOR C XOR D f = bxor(B, C, D) -- TODO: bxor many K = 0x6ED9EBA1 elseif t <= 59 then -- (B AND C) OR (B AND D) OR (C AND D) f = bor(band(B, C), band(B, D), band(C, D)) -- TODO: bor many K = 0x8F1BBCDC else -- B XOR C XOR D f = bxor(B, C, D) -- TODO: bxor many K = 0xCA62C1D6 end -- TEMP = S5(A) + ft(B,C,D) + E + Wt + Kt; A,B,C,D,E = w32_add_n(w32_rot(5, A), f, E, W[t], K), A, w32_rot(30, B), C, D end -- Let H0 = H0 + A, H1 = H1 + B, H2 = H2 + C, H3 = H3 + D, H4 = H4 + E. H0,H1,H2,H3,H4 = w32_add(H0, A),w32_add(H1, B),w32_add(H2, C),w32_add(H3, D),w32_add(H4, E) end local f = w32_to_hexstring return f(H0) .. f(H1) .. f(H2) .. f(H3) .. f(H4) end return sha1
-- TimeComplexity O(n*m) where n is the number of cached queries and m is the average number of ids in each document. -- SpaceComplexity O(1) local invalidateKey = KEYS[1] local queryKey = KEYS[2] local objectKey = KEYS[3] local commonIndexKey = KEYS[4] local now = ARGV[1] local oid = ARGV[2] local ojson = ARGV[3] if invalidateKey ~= "" then if redis.call("SET", invalidateKey, 1, "NX", "EX", 600) == nil then return 0 end end local clearBefore = now - 600 redis.call('ZREMRANGEBYSCORE', queryKey, 0, clearBefore) local queries = redis.call("ZRANGE", queryKey, 0, -1) local value local key for i=1,#queries do key = queryKey .. ":" .. queries[i] value = redis.call("GET", key) if value ~= nil and value ~= false and string.find(value, oid) then redis.call("DEL", key) redis.call("ZREM", queryKey, queries[i]) end end if ojson == "" then redis.call("DEL", objectKey .. ":" .. oid) redis.call("ZREM", objectKey, oid) else redis.call("SET", objectKey .. ":" .. oid, ojson, "EX", 600) redis.call("ZADD", objectKey, now, oid) end if commonIndexKey ~= nil then redis.call('ZREMRANGEBYSCORE', commonIndexKey, 0, clearBefore) local queries = redis.call("ZRANGE", commonIndexKey, 0, -1) local value local key for i=1,#queries do key = objectKey .. ":" .. queries[i] value = redis.call("GET", key) if val ~= nil and string.find(value, oid) then redis.call("DEL", key) redis.call("ZREM", queryKey, queries[i]) end end end return 1
-- -- Lua global definition file. -- -- @filename LGlobal.lua -- The declared global name. local DeclaredNames = {} -- The internal global variable table check method. local function __inner_declare(Name, InitValue) if not rawget(_G, Name) then rawset(_G, Name, InitValue or false) else error("You have already declared global : " .. Name, 2) end DeclaredNames[Name] = true return _G[Name] end -- The internal global variable table index method. local function __inner_declare_index(t, k) if not DeclaredNames[k] then error("Attempt to access an undeclared global variable : " .. k, 2) end return nil end local ignore_global = {protobuf=true} -- The internal global variable table newindex method. local function __inner_declare_newindex(t, k, v) if (not DeclaredNames[k]) and (ignore_global[k] == nil) then error("Attempt to write an undeclared global variable : " .. k, 2) else rawset(t, k, v) end end -- The global variable declare function. local function __Declare(Name, InitValue) local ok, res = pcall(__inner_declare, Name, InitValue) if not ok then print(debug.traceback(res, 2)) return nil else return res end end -- Check if a global variable is declared. local function __IsDeclared(Name) if DeclaredNames[Name] or rawget(_G, Name) then return true else return false end end -- Set "Declare" into global. if (not __IsDeclared("LDeclare")) or (not LDeclare) then __Declare("LDeclare", __Declare) end -- Set "IsDeclared" into global. if (not __IsDeclared("LIsDeclared")) or (not LIsDeclared) then __Declare("LIsDeclared", __IsDeclared) end -- Set limit to define global variables. setmetatable(_G, { __index = function (t, k) local ok, res = pcall(__inner_declare_index, t, k) if not ok then print(debug.traceback(res, 2)) end return nil end, __newindex = function (t, k, v) local ok, res = pcall(__inner_declare_newindex, t, k, v) if not ok then print(debug.traceback(res, 2)) end end }) -- Return this. return __Declare
local ThemeColor = LoadModule('Theme.Colors.lua') local function CallSongFunc(func) local song = GAMESTATE:GetCurrentSong() if song then return song[func](song) end return '' end return Def.ActorFrame { InitCommand = function(self) self :xy(SCREEN_CENTER_X, SCREEN_CENTER_Y + 120) end, OnCommand = function(self) -- discord support UwU -y0sefu local player = GAMESTATE:GetMasterPlayerNumber() GAMESTATE:UpdateDiscordProfile(GAMESTATE:GetPlayerDisplayName(player)) if GAMESTATE:IsCourseMode() then GAMESTATE:UpdateDiscordScreenInfo("Selecting Course","",1) else local StageIndex = GAMESTATE:GetCurrentStageIndex() GAMESTATE:UpdateDiscordScreenInfo("Selecting a Song (Stage ".. StageIndex + 1 .. ") ","",1) end end, Def.Quad { InitCommand = function(self) self :SetSize(SCREEN_WIDTH * 1.5, 428) :diffuse(ThemeColor.Black) :skewx(-0.5) :fadetop(0.01) :fadebottom(0.01) :diffusealpha(0.75) :fadeleft(0.1) :cropleft(1) end, OnCommand = function(self) self :easeoutexpo(0.25) :fadeleft(0) :cropleft(0) end, OffCommand = function(self) self :sleep(0.25) :easeoutexpo(0.25) :fadeleft(0.1) :cropleft(1) end, }, Def.Quad { InitCommand = function(self) self :SetSize(SCREEN_WIDTH * 1.5, 420) :diffuse(ThemeColor.Primary) :skewx(-0.5) :diffusealpha(0.25) :fadeleft(0.1) :cropleft(1) end, OnCommand = function(self) self :easeoutexpo(0.25) :fadeleft(0) :cropleft(0) end, OffCommand = function(self) self :sleep(0.25) :easeinexpo(0.25) :fadeleft(0.1) :cropleft(1) end, }, Def.ActorFrame { InitCommand = function(self) self :x(-SCREEN_CENTER_X) end, Def.Quad { InitCommand = function(self) self :skewx(-0.5) :SetSize(SCREEN_WIDTH * 0.5 + 24, 320) :diffuse(ThemeColor.Elements) :shadowlength(2, 2) :diffusealpha(0.5) :faderight(0.1) :cropright(1) end, OnCommand = function(self) self :sleep(0.25) :easeoutexpo(0.25) :faderight(0) :cropright(0) end, OffCommand = function(self) self :easeinexpo(0.25) :faderight(0.1) :cropright(1) end, }, -- Song Info Def.ActorFrame { Name = 'BannerFrame', InitCommand = function(self) self :xy(48, -SCREEN_CENTER_Y + 104) :diffusealpha(0) :addx(-24) :addy(12) end, OnCommand = function(self) -- You may now admire your glorious artwork, Chegg. You better use my theme now. ~Sudo local InputHandler = function(event) if event.button ~= 'Up' and event.button ~= 'Down' then return end local children = { self:GetChild('BannerFade'), self:GetChild('BPM'), self:GetChild('Length'), self:GetChild('SongInfo'), self:GetChild('Jacket'), } if event.button == 'Down' then if event.type == 'InputEventType_FirstPress' then for _, v in ipairs(children) do v:stoptweening():sleep(0.5):linear(0.1):diffusealpha(0) end elseif event.type == 'InputEventType_Release' then for i, v in ipairs(children) do if v:GetName() == 'BannerFade' then if GAMESTATE:GetCurrentSong() then v:stoptweening():linear(0.1):diffusealpha(0.75) else v:stoptweening():linear(0.1):diffusealpha(0.5) end else v:stoptweening():linear(0.1):diffusealpha(1) end end end elseif event.button == 'Up' then if event.type == 'InputEventType_FirstPress' then for _, v in ipairs(children) do if v:GetName() ~= 'Jacket' then v:stoptweening():sleep(0.5):linear(0.1):diffusealpha(0) end end self:GetChild('Jacket'):stoptweening():sleep(0.5):easeoutexpo(0.2):zoom(128 / 48) elseif event.type == 'InputEventType_Release' then for _, v in ipairs(children) do if v:GetName() == 'BannerFade' then if GAMESTATE:GetCurrentSong() then v:stoptweening():linear(0.1):diffusealpha(0.75) else v:stoptweening():linear(0.1):diffusealpha(0.5) end elseif v:GetName() ~= 'Jacket' then v:stoptweening():linear(0.1):diffusealpha(1) end end self:GetChild('Jacket'):stoptweening():easeoutexpo(0.2):zoom(1) end end return InputHander end SCREENMAN:GetTopScreen():AddInputCallback(InputHandler) self :sleep(0.25) :easeoutexpo(0.5) :addx(24) :diffusealpha(1) end, OffCommand = function(self) --SCREENMAN:GetTopScreen():RemoveInputCallback(InputHandler) self :sleep(0.25) :easeinexpo(0.5) :addx(-24) :diffusealpha(0) end, Def.Banner { Name = 'Banner', InitCommand = function(self) self :xy(208 - 16, -220 + 84 + 68) :scaletoclipped(418, 164) :addy(6) end, OnCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() local wheel = SCREENMAN:GetTopScreen():GetMusicWheel() if song then if song:HasBanner() then self:LoadFromSong(song) else self:LoadFromSongGroup(song:GetGroupName()) end elseif course then if course:HasBanner() then self:LoadFromCourse(course) end elseif FILEMAN:DoesFileExist(SOMGMAN:GetSongGroupBannerPath(wheel:GetSelectedSection())) then self:LoadFromSongGroup(wheel:GetSelectedSection()) else self:LoadFromCachedBanner(THEME:GetPathG('Common', 'fallback banner')) end end, CurrentSongChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() local wheel = SCREENMAN:GetTopScreen():GetMusicWheel() print(wheel:GetSelectedSection()) if song then if song:HasBanner() then self:LoadFromSong(song) else self:LoadFromSongGroup(song:GetGroupName()) end elseif course then if course:HasBanner() then self:LoadFromCourse(course) end elseif wheel:GetSelectedSection() then self:LoadFromSongGroup(wheel:GetSelectedSection()) else self:LoadFromCachedBanner(THEME:GetPathG('Common', 'fallback banner')) end end, }, Def.Quad { Name = 'BannerFade', InitCommand = function(self) self :xy(208 - 16, -220 + 84 + 68) :SetSize(418, 164) :diffuse(ThemeColor.Primary) :diffusealpha(0.75) :faderight(0.75) :addy(6) end, -- Hiding this is a good idea, but I'm using it for the immervise banner action instead. ~Sudo CurrentSongChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() if not song then self:diffusealpha(0.5) --self:visible(false) else self:diffusealpha(0.75) --self:visible(true) end end, }, Def.BitmapText { Name = 'Group', Font = 'Common Normal', InitCommand = function(self) self :zoom(1.5) :addx(-15) :addy(-168) :horizalign('left') :maxwidth(278) end, CurrentSongChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local wheel = SCREENMAN:GetTopScreen():GetMusicWheel() if song then self:settext(song:GetGroupName()) elseif wheel:GetSelectedSection() then self:settext(wheel:GetSelectedSection()) else self:settext('') end end, }, Def.BitmapText { Name = 'BPM', Font = 'Common Normal', InitCommand = function(self) self :addy(-8) :horizalign('left') end, OnCommand = function(self) local bpmstr = 'BPM: ' local song = GAMESTATE:GetCurrentSong() if song then -- check if the bpm is hidden -y0sefu if song:IsDisplayBpmRandom() then self:settext('BPM: ???') -- The spaces seemed a bit unnecessary to me. ~Sudo -- return early -y0sefu return end local minBPM = math.floor(song:GetDisplayBpms()[1]) local maxBPM = math.floor(song:GetDisplayBpms()[2]) if minBPM == maxBPM then bpmstr = bpmstr .. math.floor(song:GetDisplayBpms()[2]) else bpmstr = bpmstr .. minBPM .. ' - ' .. maxBPM end else --bpmstr = bpmstr .. '--' bpmstr = '' end self:settext(bpmstr) end, CurrentSongChangedMessageCommand = function(self) local bpmstr = 'BPM: ' local song = GAMESTATE:GetCurrentSong() if song then -- check if the bpm is hidden -y0sefu if song:IsDisplayBpmRandom() then self:settext('BPM: ???') -- The spaces seemed a bit unnecessary to me. ~Sudo -- return early -y0sefu return end local minBPM = math.floor(song:GetDisplayBpms()[1]) local maxBPM = math.floor(song:GetDisplayBpms()[2]) if minBPM == maxBPM then bpmstr = bpmstr .. math.floor(song:GetDisplayBpms()[2]) else bpmstr = bpmstr .. minBPM .. ' - ' .. maxBPM end else --bpmstr = bpmstr .. '--' bpmstr = '' end self:settext(bpmstr) end, }, Def.BitmapText { Name = 'Length', Font = 'Common Normal', InitCommand = function(self) self :addy(-32) :horizalign('left') end, OnCommand = function(self) local lenstr = 'Length: ' local song = GAMESTATE:GetCurrentSong() if song then lenstr = lenstr .. math.floor(song:GetLastSecond() / 60)..':'..string.format('%02d',math.floor(song:GetLastSecond() % 60)) else --lenstr = lenstr .. '--' lenstr = '' end self:settext(lenstr) end, CurrentSongChangedMessageCommand = function(self) local lenstr = 'Length: ' local song = GAMESTATE:GetCurrentSong() if song then lenstr = lenstr .. math.floor(song:GetLastSecond() / 60)..':'..string.format('%02d',math.floor(song:GetLastSecond() % 60)) else --lenstr = lenstr .. '-:--' lenstr = '' end self:settext(lenstr) end, }, Def.ActorFrame { Name = 'SongInfo', InitCommand = function(self) self :zoom(1.5) :addy(-120 + 16) :addy(6) end, Def.BitmapText { Name = 'Title', Font = 'Common Normal', Text = '', InitCommand = function(self) self :addy(-12) :horizalign('left') :maxwidth(240) end, CurrentSongChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() if not song then -- local wheel = SCREENMAN:GetTopScreen():GetMusicWheel() self:settext('') return end self:settext(song:GetDisplayFullTitle()) end, }, Def.BitmapText { Name = 'Artist', Font = 'Common Normal', Text = '', InitCommand = function(self) self :addy(12) :horizalign('left') :maxwidth(240) end, CurrentSongChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() if not song then self:settext('') return end self:settext(song:GetDisplayArtist()) end, }, }, -- Let's move this down here uwu ~Sudo Def.Sprite { Name = 'Jacket', InitCommand = function(self) -- Now that we moved and squished it, we can support non-widescreen ^-^ ~Sudo self :visible(true) :horizalign('right') :vertalign('bottom') :addx(384) :addy(4) :scaletoclipped(48, 48) end, OnCommand = function(self) local song = GAMESTATE:GetCurrentSong() -- I kinda don't want the jacket to show up if there isn't one. ~Sudo --[[ if song then local jacketpath = '' if song:HasJacket() then jacketpath = song:GetJacketPath() elseif song:HasBackground() then jacketpath = song:GetBackgroundPath() else jacketpath = THEME:GetPathG('Common', 'fallback jacket') end self:Load(jacketpath) end --]] if song and song:HasJacket() then self :visible(true) :Load(song:GetJacketPath()) else self:visible(false) end end, CurrentSongChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() --[[ if song then local jacketpath = '' if song:HasJacket() then jacketpath = song:GetJacketPath() elseif song:HasBackground() then jacketpath = song:GetBackgroundPath() else jacketpath = THEME:GetPathG('Common', 'fallback jacket') end self:Load(jacketpath) end --]] if song and song:HasJacket() then self :visible(true) :Load(song:GetJacketPath()) else self:visible(false) end end, }, }, -- Chart Info Def.ActorFrame { Name = 'ChartInfo', InitCommand = function(self) self :x(152) :y(10) :addx(-SCREEN_CENTER_X + ((SCREEN_WIDTH / SCREEN_HEIGHT) - (640 / 480)) * 100) end, OnCommand = function(self) self :sleep(0.25) :easeoutexpo(0.25) :addx(SCREEN_CENTER_X) end, OffCommand = function(self) self :easeinexpo(0.25) :addx(-SCREEN_CENTER_X) end, Def.BitmapText { Name = 'StepNameP1', Font = 'Common Normal', Text = '--', InitCommand = function(self) self :x(-140) :addy(-138) :horizalign('left') :maxwidth(80) :visible(GAMESTATE:IsSideJoined(PLAYER_1)) :diffuse(ColorLightTone(ThemeColor.P1)) :diffusebottomedge(ThemeColor.P1) if GAMESTATE:GetCurrentSteps(PLAYER_1) then local diff = tostring(GAMESTATE:GetCurrentSteps(PLAYER_1):GetDifficulty()) local diff = diff:sub(diff:find('_') + 1, -1) self :diffuse(ColorLightTone(ThemeColor[diff])) :diffusebottomedge(ThemeColor[diff]) end end, PlayerJoinedMessageCommand = function(self, param) self:visible(GAMESTATE:IsSideJoined(PLAYER_1)) end, CurrentStepsP1ChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self :settext('--') :diffuse(ColorLightTone(ThemeColor.P1)) :diffusebottomedge(ThemeColor.P1) return end local diff = GAMESTATE:GetCurrentSteps(PLAYER_1) if diff then self:settext(THEME:GetString("CustomDifficulty",ToEnumShortString(diff:GetDifficulty()))) local diffname = diff:GetDifficulty() local diffname = diffname:sub(diffname:find('_') + 1, -1) self :diffuse(ColorLightTone(ThemeColor[diffname])) :diffusebottomedge(ThemeColor[diffname]) end end, }, Def.BitmapText { Name = 'StepArtistP1', Font = 'Common Normal', Text = '--', InitCommand = function(self) self :x(-140) :addy(-118) :horizalign('left') :maxwidth(80) :diffuse(ColorLightTone(ThemeColor.P1)) :diffusebottomedge(ThemeColor.P1) :visible(GAMESTATE:IsSideJoined(PLAYER_1)) end, PlayerJoinedMessageCommand = function(self, param) self:visible(GAMESTATE:IsSideJoined(PLAYER_1)) end, CurrentStepsP1ChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self:settext('--') return end local diff = GAMESTATE:GetCurrentSteps(PLAYER_1) if diff then self:settext(diff:GetAuthorCredit()) end end, }, Def.BitmapText { Name = 'StepHighScoreP1', Font = 'Common Normal', Text = '--', InitCommand = function(self) self :x(-140) :addy(-98) :horizalign('left') :maxwidth(80) :diffuse(ColorLightTone(ThemeColor.P1)) :diffusebottomedge(ThemeColor.P1) :visible(GAMESTATE:IsSideJoined(PLAYER_1)) end, PlayerJoinedMessageCommand = function(self, param) self:visible(GAMESTATE:IsSideJoined(PLAYER_1)) end, CurrentStepsP1ChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self:settext('--') return end local diff = GAMESTATE:GetCurrentSteps(PLAYER_1) if diff then local scorelist = PROFILEMAN:GetProfile(PLAYER_1):GetHighScoreList(song, diff) --self:settext(diff:GetAuthorCredit()) local highscore = scorelist:GetHighScores()[1] if highscore then local perc = highscore:GetPercentDP() * 100 --print() self:settext(string.format('%.2f', perc) .. '%') else self:settext('--') end end end, }, Def.BitmapText { Name = 'StepNameP2', Font = 'Common Normal', Text = '--', InitCommand = function(self) self :x(-40 + 72) :addy(-138) :horizalign('right') :maxwidth(80) :diffuse(ColorLightTone(ThemeColor.P2)) :diffusebottomedge(ThemeColor.P2) :visible(GAMESTATE:IsSideJoined(PLAYER_2)) if GAMESTATE:GetCurrentSteps(PLAYER_2) then local diff = tostring(GAMESTATE:GetCurrentSteps(PLAYER_2):GetDifficulty()) local diff = diff:sub(diff:find('_') + 1, -1) self :diffuse(ColorLightTone(ThemeColor[diff])) :diffusebottomedge(ThemeColor[diff]) end end, PlayerJoinedMessageCommand = function(self, param) self:visible(GAMESTATE:IsSideJoined(PLAYER_2)) end, CurrentStepsP2ChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self :settext('--') :diffuse(ColorLightTone(ThemeColor.P2)) :diffusebottomedge(ThemeColor.P2) return end local diff = GAMESTATE:GetCurrentSteps(PLAYER_2) if diff then self:settext(THEME:GetString("CustomDifficulty",ToEnumShortString(diff:GetDifficulty()))) local diffname = diff:GetDifficulty() local diffname = diffname:sub(diffname:find('_') + 1, -1) self :diffuse(ColorLightTone(ThemeColor[diffname])) :diffusebottomedge(ThemeColor[diffname]) end end, }, Def.BitmapText { Name = 'StepArtistP2', Font = 'Common Normal', Text = '--', InitCommand = function(self) self :x(-40 + 72) :addy(-118) :horizalign('right') :maxwidth(80) :diffuse(ColorLightTone(ThemeColor.P2)) :diffusebottomedge(ThemeColor.P2) :visible(GAMESTATE:IsSideJoined(PLAYER_2)) end, PlayerJoinedMessageCommand = function(self, param) self:visible(GAMESTATE:IsSideJoined(PLAYER_2)) end, CurrentStepsP2ChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self:settext('--') return end local diff = GAMESTATE:GetCurrentSteps(PLAYER_2) if diff then self:settext(diff:GetAuthorCredit()) end end, }, Def.BitmapText { Name = 'StepHighScoreP2', Font = 'Common Normal', Text = '--', InitCommand = function(self) self :x(-40 + 72) :addy(-98) :horizalign('right') :maxwidth(80) :diffuse(ColorLightTone(ThemeColor.P2)) :diffusebottomedge(ThemeColor.P2) :visible(GAMESTATE:IsSideJoined(PLAYER_2)) end, PlayerJoinedMessageCommand = function(self, param) self:visible(GAMESTATE:IsSideJoined(PLAYER_2)) end, CurrentStepsP2ChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self:settext('--') return end local diff = GAMESTATE:GetCurrentSteps(PLAYER_2) if diff then local scorelist = PROFILEMAN:GetProfile(PLAYER_2):GetHighScoreList(song, diff) --self:settext(diff:GetAuthorCredit()) local highscore = scorelist:GetHighScores()[1] if highscore then local perc = highscore:GetPercentDP() * 100 --print() self:settext(string.format('%.2f', perc) .. '%') else self:settext('--') end end end, }, -- TODO: Stop doing this bullshit. ~Sudo Def.BitmapText { Name = 'StepLabels', Font = 'Common Normal', Text = 'Notes\nHolds\nRolls\nJumps\nHands\n\nMines\nLifts\nFakes', InitCommand = function(self) self :x(-140) :addy(22) :horizalign('left') :addx(-SCREEN_CENTER_X) :maxwidth(60) end, OnCommand = function(self) self :sleep(0.25) :easeoutexpo(0.25) :addx(SCREEN_CENTER_X) end, OffCommand = function(self) self :easeinexpo(0.25) :addx(-SCREEN_CENTER_X) end, }, Def.BitmapText { Name = 'ChartInfoP1', Font = 'Common Normal', InitCommand = function(self) self :addx(-60) :addy(34) :horizalign('left') :maxwidth(36) :visible(GAMESTATE:IsSideJoined(PLAYER_1)) :diffuse(ColorLightTone(PlayerColor(PLAYER_1))) end, PlayerJoinedMessageCommand = function(self, param) self:visible(GAMESTATE:IsSideJoined(PLAYER_1)) end, CurrentStepsP1ChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self:y(22) self:settext('--\n--\n--\n--\n--\n\n--\n--\n--') else self:y(34) local cur_diff = GAMESTATE:GetCurrentSteps(PLAYER_1) if not cur_diff then return end local ret = '' for i, v in ipairs({ 'TapsAndHolds', 'Holds', 'Rolls', 'Jumps', 'Hands', 'Mines', 'Lifts', 'Fakes' }) do local num = cur_diff:GetRadarValues(PLAYER_1):GetValue('RadarCategory_'..v) ret = ret..num ..'\n' if v == 'Hands' then ret = ret..'\n' end end self:settext(ret) end end, CurrentSongChangedMessageCommand = function(self) MESSAGEMAN:Broadcast('CurrentStepsP1Changed') end, }, Def.BitmapText { Name = 'ChartInfoP2', Font = 'Common Normal', InitCommand = function(self) self :addx(-10 + 36) :addy(34) :horizalign('right') :maxwidth(36) :visible(GAMESTATE:IsSideJoined(PLAYER_2)) :diffuse(ColorLightTone(PlayerColor(PLAYER_2))) end, PlayerJoinedMessageCommand = function(self, param) self:visible(GAMESTATE:IsSideJoined(PLAYER_2)) end, CurrentStepsP2ChangedMessageCommand = function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self:y(22) self:settext('--\n--\n--\n--\n--\n\n--\n--\n--') else self:y(34) local cur_diff = GAMESTATE:GetCurrentSteps(PLAYER_2) if not cur_diff then return end local ret = '' for i, v in ipairs({ 'TapsAndHolds', 'Holds', 'Rolls', 'Jumps', 'Hands', 'Mines', 'Lifts', 'Fakes' }) do local num = cur_diff:GetRadarValues(PLAYER_2):GetValue('RadarCategory_'..v) ret = ret..num ..'\n' if v == 'Hands' then ret = ret..'\n' end end self:settext(ret) end end, CurrentSongChangedMessageCommand = function(self) MESSAGEMAN:Broadcast('CurrentStepsP2Changed') end, } }, }, LoadActor(THEME:GetPathG('ScreenSelectMusic', 'DifficultyList')), }
-- THIS FILE IS GENERATED. DO NOT EDIT MANUALLY. -- stylua: ignore start return {properties = {["perlnavigator.enableWarnings"] = {default = true,description = "Enable warnings using -Mwarnings command switch",scope = "resource",type = "boolean"},["perlnavigator.includePaths"] = {default = {},description = "Array of paths added to @INC. You can use $workspaceRoot as a placeholder.",scope = "resource",type = "array"},["perlnavigator.logging"] = {default = true,description = "Log to stdout from the navigator. Viewable in the Perl Navigator LSP log",scope = "resource",type = "boolean"},["perlnavigator.perlPath"] = {default = "perl",description = "Full path to the perl executable (no aliases, .bat files or ~/)",scope = "resource",type = "string"},["perlnavigator.perlcriticEnabled"] = {default = true,description = "Enable perl critic.",scope = "resource",type = "boolean"},["perlnavigator.perlcriticProfile"] = {default = "",description = "Path to perl critic profile. Otherwise perlcritic itself will default to ~/.perlcriticrc. (no aliases, .bat files or ~/)",scope = "resource",type = "string"},["perlnavigator.perltidyProfile"] = {default = "",description = "Path to perl tidy profile (no aliases, .bat files or ~/)",scope = "resource",type = "string"},["perlnavigator.severity1"] = {default = "hint",description = "Editor Diagnostic severity level for Critic severity 1",enum = { "error", "warning", "info", "hint", "none" },scope = "resource",type = "string"},["perlnavigator.severity2"] = {default = "hint",description = "Editor Diagnostic severity level for Critic severity 2",enum = { "error", "warning", "info", "hint", "none" },scope = "resource",type = "string"},["perlnavigator.severity3"] = {default = "hint",description = "Editor Diagnostic severity level for Critic severity 3",enum = { "error", "warning", "info", "hint", "none" },scope = "resource",type = "string"},["perlnavigator.severity4"] = {default = "info",description = "Editor Diagnostic severity level for Critic severity 4",enum = { "error", "warning", "info", "hint", "none" },scope = "resource",type = "string"},["perlnavigator.severity5"] = {default = "warning",description = "Editor Diagnostic severity level for Critic severity 5",enum = { "error", "warning", "info", "hint", "none" },scope = "resource",type = "string"},["perlnavigator.trace.server"] = {default = "messages",description = "Traces the communication between VS Code and the language server.",enum = { "off", "messages", "verbose" },scope = "window",type = "string"}},title = "Perl Navigator",type = "object"}
local addonName = "KibsItemLevelContinued" local addonNamespace = LibStub and LibStub(addonName .. "-1.0", true) if not addonNamespace or addonNamespace.loaded.CharacterFrameAdapter then return end addonNamespace.loaded.CharacterFrameAdapter = true local CharacterFrameAdapter = {} local CharacterFrameAdapterMetaTable = { __index = CharacterFrameAdapter } setmetatable(CharacterFrameAdapter, { __index = addonNamespace.FrameAdapter }) function CharacterFrameAdapter:new() local instance = addonNamespace.FrameAdapter:new(CharacterModelFrame, CharacterModelFrame, 'Character') instance.messages = { contentChanged = 'CharacterFrameAdapter.contentChanged', } setmetatable(instance, CharacterFrameAdapterMetaTable) instance:RegisterEvent("UNIT_INVENTORY_CHANGED", function(event, unit) if unit == 'player' then instance:Debug("UNIT_INVENTORY_CHANGED", unit) instance:SendMessage(instance.messages.contentChanged) end end) instance:RegisterEvent("PLAYER_EQUIPMENT_CHANGED", function(event, unit) instance:Debug("PLAYER_EQUIPMENT_CHANGED", unit) instance:SendMessage(instance.messages.contentChanged) end) instance:RegisterEvent("SOCKET_INFO_CLOSE", function() instance:Debug("SOCKET_INFO_CLOSE") instance:SendMessage(instance.messages.contentChanged) end) instance:RegisterEvent("SOCKET_INFO_SUCCESS", function() instance:Debug("SOCKET_INFO_SUCCESS") instance:SendMessage(instance.messages.contentChanged) end) instance:RegisterEvent("SOCKET_INFO_UPDATE", function() instance:Debug("SOCKET_INFO_UPDATE") instance:SendMessage(instance.messages.contentChanged) end) return instance end function CharacterFrameAdapter:GetUnit() return "player" end function CharacterFrameAdapter:Debug(...) addonNamespace.Debug('CharacterFrameAdapter:', ...) end addonNamespace.CharacterFrameAdapter = CharacterFrameAdapter
---@class src.app ---@field win src.app.win ---@field palettes src.app.palettes ---@field skins src.app.skins ---@field fonts src.app.fonts ---@field stack src.app.stack local app = proto.set_name({}, "src.app") function app:init() self.palettes = require("src.app.palettes"):init() self.skins = require("src.app.skins"):init(self.palettes) self.fonts = require("src.app.fonts"):init() self.stack = require("src.app.stack") self.win = require("src.app.win") self.win.app = self self.win:init() return self end return app
local appId = 'com.apple.Safari' local switchTabLeft = hs.hotkey.new({'cmd', 'alt'}, 'j', function() hs.eventtap.keyStroke({'cmd', 'alt'}, 'i') end) return { id = appId, enable= function() switchTabLeft:enable() end, disable = function() switchTabLeft:disable() end }
object_draft_schematic_dance_prop_prop_torch_r = object_draft_schematic_dance_prop_shared_prop_torch_r:new { } ObjectTemplates:addTemplate(object_draft_schematic_dance_prop_prop_torch_r, "object/draft_schematic/dance_prop/prop_torch_r.iff")
---@class lstg.mbg.Force local M = {} --local M = class('lstg.mbg.Batch') local Player = require('game.mbg.Player') local Time = require('game.mbg.Time') local Main = require('game.mbg.Main') local Math = require('game.mbg._math') --local MathHelper = Math M.record = 0 local function _ctor(data) local ret = {} M.ctor(ret, data) ret.update = M.update ret.clone = M.clone ret.copy = M.copy ret.getLayer = M.getLayer return ret end ---@param data mbg.ForceField function M:ctor(data) -- private self.clcount = 0 self.clwait = 0 -- public self.Selecting = false self.NeedDelete = false self.Searched = 0 self.id = 0 self.parentid = 0 self.parentcolor = 0 self.x = 0 self.y = 0 --- 起始 self.begin = 0 --- 持续 self.life = 0 self.halfw = 0 self.halfh = 0 --- 启用圆形 self.Circle = false --- 类型 self.type = 0 --- 编号 self.controlid = 0 --- 速度 self.speed = 0 --- 速度方向 self.speedd = 0 self.speedx = 0 self.speedy = 0 --- 加速度 self.aspeed = 0 self.aspeedx = 0 self.aspeedy = 0 --- 加速度方向 self.aspeedd = 0 self.addaspeed = 0 --- 力场加速度方向 self.addaspeedd = 0 --- 中心吸力 self.Suction = false --- 中心斥力 self.Repulsion = false --- 力场加速度 self.addspeed = 0 self.Parentevents = {} ---@type lstg.mbg.Force self.copys = nil if not data then return end local function value(v) return v.RandValue end self._data = data self.rand = _ctor() -- self.id = data["ID"] self.parentid = data["层ID"] self.x = data["位置坐标"].X self.y = data["位置坐标"].Y self.begin = data["生命"].Begin self.life = data["生命"].LifeTime self.halfw = data["半高"] --assert(type(self.halfw) == 'number') self.halfh = data["半宽"] --assert(type(self.halfh) == 'number') self.Circle = data["启用圆形"] self.type = data["类型"] self.controlid = data["控制ID"] self.speed = value(data["运动"].Speed) self.speedd = value(data["运动"].SpeedDirection) self.aspeed = value(data["运动"].Acceleration) self.aspeedd = value(data["运动"].AccelerationDirection) self.addspeed = data["力场加速度"] self.addaspeedd = data["力场加速度方向"] self.Suction = data["中心吸力"] self.Repulsion = data["中心斥力"] --self.addspeed = data["影响速度"] end function M:update() if self.clcount == 1 then self.clwait = self.clwait + 1 if self.clwait > 15 then self.clwait = 0 self.clcount = 0 end end local layer = self:getLayer() if not Time.Playing then self.aspeedx = self.aspeed * Math.Cos(Math.ToRadians(self.aspeedd)) self.aspeedy = self.aspeed * Math.Sin(Math.ToRadians(self.aspeedd)) self.speedx = self.speed * Math.Cos(Math.ToRadians(self.speedd)) self.speedy = self.speed * Math.Sin(Math.ToRadians(self.speedd)) self.begin = math.floor(Math.Clamp( self.begin, layer.begin, (1 + layer['end'] - layer.begin))) self.life = math.floor(Math.Clamp( self.life, 1, (layer['end'] - layer.begin + 2 - self.begin))) end if Time.Playing and (Time.now >= self.begin and Time.now <= self.begin + self.life - 1) then local now = Time.now self.speedx = self.speedx + self.aspeedx self.speedy = self.speedy + self.aspeedy self.x = self.x + self.speedx self.y = self.y + self.speedy if self.Circle then if Math.Sqrt(((self.x - 4 - Player.position.X) * (self.x - 4 - Player.position.X) + (self.y + 16 - Player.position.Y) * (self.y + 16 - Player.position.Y))) <= Math.Max(self.halfw, self.halfh) then if self.Suction then local degrees = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, Player.position.X, Player.position.Y)) Player.position.X = Player.position.X + self.addspeed * Math.Cos(Math.ToRadians(degrees)) Player.position.Y = Player.position.Y + self.addspeed * Math.Sin(Math.ToRadians(degrees)) elseif self.Repulsion then local num3 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, Player.position.X, Player.position.Y)) Player.position.X = Player.position.X + self.addspeed * Math.Cos(Math.ToRadians(180 + num3)) Player.position.Y = Player.position.Y + self.addspeed * Math.Sin(Math.ToRadians(180 + num3)) else Player.position.X = Player.position.X + self.addspeed * Math.Cos(Math.ToRadians(self.addaspeedd)) Player.position.Y = Player.position.Y + self.addspeed * Math.Sin(Math.ToRadians(self.addaspeedd)) end -- player position limit --[[ if (Player.position.X <= 4.5 + Player.add) Player.position.X = 4.5 + Player.add if (Player.position.X >= 625.5 - Player.add) Player.position.X = 625.5 - Player.add if (Player.position.Y <= 4.5) Player.position.Y = 4.5 if (Player.position.Y >= 475.5) Player.position.Y = 475.5 --]] end elseif Math.Abs(self.x - 4 - Player.position.X) <= self.halfw and Math.Abs(self.y + 16 - Player.position.Y) <= self.halfh then if self.Suction then local degrees2 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, Player.position.X, Player.position.Y)) Player.position.X = Player.position.X + self.addspeed * Math.Cos(Math.ToRadians(degrees2)) Player.position.Y = Player.position.Y + self.addspeed * Math.Sin(Math.ToRadians(degrees2)) elseif self.Repulsion then local num4 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, Player.position.X, Player.position.Y)) Player.position.X = Player.position.X + self.addspeed * Math.Cos(Math.ToRadians(180 + num4)) Player.position.Y = Player.position.Y + self.addspeed * Math.Sin(Math.ToRadians(180 + num4)) else Player.position.X = Player.position.X + self.addspeed * Math.Cos(Math.ToRadians(self.addaspeedd)) Player.position.Y = Player.position.Y + self.addspeed * Math.Sin(Math.ToRadians(self.addaspeedd)) end -- player position limit end -- barrage local barrages = layer.Barrages for _, barrage in ipairs(barrages) do if barrage.Force then if self.Circle then if self.type == 0 then if Math.Sqrt(((self.x - 4 - barrage.x) * (self.x - 4 - barrage.x) + (self.y + 16 - barrage.y) * (self.y + 16 - barrage.y))) <= Math.Max(self.halfw, self.halfh) then if self.Suction then local degrees3 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, barrage.x, barrage.y)) barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(degrees3)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(degrees3)) elseif self.Repulsion then local num5 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, barrage.x, barrage.y)) barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(180 + num5)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(180 + num5)) else barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(self.addaspeedd)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(self.addaspeedd)) end end elseif self.type == 1 and (barrage.parentid == self.controlid - 1 and Math.Sqrt(((self.x - 4 - barrage.x) * (self.x - 4 - barrage.x) + (self.y + 16 - barrage.y) * (self.y + 16 - barrage.y))) <= Math.Max(self.halfw, self.halfh)) then if self.Suction then local degrees4 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, barrage.x, barrage.y)) barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(degrees4)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(degrees4)) elseif self.Repulsion then local num6 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, barrage.x, barrage.y)) barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(180 + num6)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(180 + num6)) else barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(self.addaspeedd)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(self.addaspeedd)) end end elseif self.type == 0 then if Math.Abs(self.x - 4 - barrage.x) <= self.halfw and Math.Abs(self.y + 16 - barrage.y) <= self.halfh then if self.Suction then local degrees5 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, barrage.x, barrage.y)) barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(degrees5)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(degrees5)) elseif self.Repulsion then local num7 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, barrage.x, barrage.y)) barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(180 + num7)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(180 + num7)) else barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(self.addaspeedd)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(self.addaspeedd)) end end elseif self.type == 1 and (barrage.parentid == self.controlid - 1 and Math.Abs(self.x - 4 - barrage.x) <= self.halfw and Math.Abs(self.y + 16 - barrage.y) <= self.halfh) then if self.Suction then local degrees6 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, barrage.x, barrage.y)) barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(degrees6)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(degrees6)) elseif self.Repulsion then local num8 = Math.ToDegrees(Main.Twopointangle(self.x - 4, self.y + 16, barrage.x, barrage.y)) barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(180 + num8)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(180 + num8)) else barrage.speedx = barrage.speedx + barrage.xscale * self.addaspeed * Math.Cos(Math.ToRadians(self.addaspeedd)) barrage.speedy = barrage.speedy + barrage.yscale * self.addaspeed * Math.Sin(Math.ToRadians(self.addaspeedd)) end end end end end end function M:clone() local ret = M() for k, v in pairs(self) do ret[k] = table.deepcopy(v) end return ret end function M:copy() local ret = M() for k, v in pairs(self) do ret[k] = v end return ret end function M:getLayer() local Layer = require('game.mbg.Layer') return Layer.LayerArray[self.parentid + 1] end local mt = { __call = function(_, data) return _ctor(data) end } setmetatable(M, mt) return M
project "Selene" kind "StaticLib" language "C++" cppdialect "C++17" staticruntime "on" targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}") objdir ("%{wks.location}/bin/int/" .. outputdir .. "/%{prj.name}") pchheader "slnpch.h" pchsource "src/slnpch.cpp" defines { "_CRT_SECURE_NO_WARNINGS" } files { "src/**.h", "src/**.cpp", "vendor/stb_image/stb_image.cpp", "vendor/ImGui/imgui_build.cpp" } includedirs { "src", "%{IncludeDir.glfw}", "%{IncludeDir.glad}", "%{IncludeDir.glm}", "%{IncludeDir.imgui}", "%{IncludeDir.stb_image}", "%{IncludeDir.openal}", "%{IncludeDir.vulkan}", "%{IncludeDir.assimp}", "%{IncludeDir.entt}" } links { "Glfw", "Glad", "ImGui" } filter "system:windows" systemversion "latest" filter "configurations:Debug" defines "SLN_DEBUG" runtime "Debug" symbols "on" filter "configurations:Release" defines "SLN_RELEASE" runtime "Release" optimize "on"
--[[ This module implements an elementary mixin library with support for private fields. See the comments preceding the interface functions for documentation. ]] local Mixin = {} --# Constants local TYPE_ERROR_FORMAT = 'The non-table value %q cannot be mixed.' --# State local private = setmetatable({}, {__mode = 'k'}) --# Interface --[[ Calling Mixin.mix performs a simple copy of all fields from all the given tables into a new, combined table. None of the field values are altered in the process. Whenever more than one of the tables has the same field name, the table that comes later in the list is given precedence. ]] function Mixin.mix(mixins) local final_mixin = {} for _, mixin in ipairs(mixins) do -- Only tables can be mixed. if type(mixin) ~= 'table' then error(TYPE_ERROR_FORMAT:format(mixin)) end -- Copy all of the mixin's fields to the combined mixin. for field_name, field_value in pairs(mixin) do final_mixin[field_name] = field_value end end return final_mixin end --[[ Calling Mixin.new on a table and any number of other arguments creates a mixin instance, which is a table looks up its fields in the original table. As a special case, whenever the field value is a function that is passed a mixin instance as its first argument, it is instead passed that instance's private table, thus automatically making any private fields available to the function but not to most other code. The private table looks up any fields other than those specifically assigned to it in the original mixin instance table, thus allowing all methods to still be called from the private table. After creating the mixin instance and its private table, if the instance has an "initialize" field, the field is called as a method, thus allowing any required setup specific to the mixin. It is not this library's responsibility to call any initialize methods other than the one exposed through the passed mixin. In particular, any initialize methods from the mixins that it comprises will not be called except the one that ends up on the passed mixin. Instead, an initialize method can be defined that calls any other necessary ones. An example of this idiom: function MyMixin:initialize(argument_a, argument_b) SomeMixin.initialize(self) SomeOtherMixin.initialize(self, ":3") YetAnotherMixin.initialize(self, argument_a) self:do_something_with(argument_b) end --]] function Mixin.new(mixin, ...) local function index_metamethod(instance, field_name) local field_value = rawget(instance, field_name) if field_value == nil then field_value = mixin[field_name] end if type(field_value) == 'function' then -- Instead of the original function, use a proxy function that -- passes the private instance instead. If there isn't a relevant -- one, fall back to the actual value passed instead. return function (self, ...) return field_value(private[self] or self, ...) end else return field_value end end local instance = setmetatable({}, {__index = index_metamethod}) local private_instance = setmetatable({_public = instance}, {__index = instance}) -- Make the private instance available where proxy methods can find it. private[instance] = private_instance if instance.initialize ~= nil then instance:initialize(...) end return instance end --[[ Calling Mixin.augment on a table adds a "new" field to it that can be called as a method for the same effect as passing the table to Mixin.new. See Mixin.new for details. --]] function Mixin.augment(mixin) mixin.new = Mixin.new return mixin end --# Export return Mixin
local _M = { _VERSION = '0.0.1' } local style = '<style>div{border:24px solid #e3f2fd;border-top:24px solid #1e88e5;border-radius:50%;width:128px;height:128px;margin:128px auto 0;animation:spin 2s linear infinite;-webkit-animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{transform:rotate(0);-webkit-transform:rotate(0)}100%{transform:rotate(360deg);-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0);-webkit-transform:rotate(0)}100%{transform:rotate(360deg);-webkit-transform:rotate(360deg)}}</style>' local html = '<!doctype html><html><head><meta charset="utf-8"><link rel="icon" href="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="><title>%s</title>%s</head><body><div></div><script>%s</script></body></html>' function _M.get_html(title, script) return string.format(html, title, style, script) end return _M
-- Copyright (C) 2018 XiaoShan mivm.cn local m, s ,o m = Map("k3screenctrl", translate("Screen"), translate("Customize your device screen")) s = m:section(TypedSection, "general", translate("General Setting") ) s.anonymous = true o = s:option(ListValue, "screen_time", translate("Screen time :"), translate("This time no action, the screen will close.")) o:value("10",translate("10 s")) o:value("30",translate("30 s")) o:value("60",translate("1 m")) o:value("300",translate("5 m")) o:value("600",translate("10 m")) o:value("900",translate("15 m")) o:value("1800",translate("30 m")) o:value("3600",translate("60 m")) o.rmempty = false o = s:option(ListValue, "refresh_time", translate("Refresh interval :"), translate("Screen data refresh interval.")) o:value("1",translate("1 s")) o:value("2",translate("2 s")) o:value("5",translate("5 s")) o:value("10",translate("10 s")) o.rmempty = false o = s:option(ListValue, "check_stable", translate("Check update interval :"), translate("Stable openwrt version check interval")) o:value("1",translate("1 d")) o:value("2",translate("2 d")) o:value("3",translate("3 d")) o:value("5",translate("5 d")) o:value("10",translate("10 d")) o:value("20",translate("20 d")) o:value("30",translate("30 d")) o.rmempty = false o = s:option(Value, "weather_key", translate("Private Key :")) o = s:option(Value, "weather_city", translate("City :"), translate("Example: Beijing")) o = s:option(ListValue, "weather_delay", translate("Weather update interval :")) o:value("1",translate("1 m")) o:value("5",translate("5 m")) o:value("10",translate("10 m")) o:value("30",translate("30 m")) o:value("60",translate("1 h")) o:value("120",translate("2 h")) o.rmempty = false o = s:option(Flag, "psk_hide", translate("Hide Wireless password")) o.default = 0 o = s:option(Button,"test_print",translate("Test"),translate("Execute k3screenctrl -t and return the result")) o.inputtitle = translate("Print info") o.write = function() luci.sys.call("k3screenctrl -t > /tmp/k3screenctrl.log") luci.http.redirect(luci.dispatcher.build_url("admin","services","k3screenctrl")) end s = m:section(TypedSection, "device_custom", translate("Device customization") ,translate("Customize the fifth page of device information")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true o = s:option(Value,"mac",translate("Device")) o.datatype = "macaddr" o.rmempty = false luci.sys.net.mac_hints(function(t,a) o:value(t,"%s (%s)"%{a,t}) end) o = s:option(Value,"name",translate("Hostname")) o = s:option(ListValue,"icon",translate("Icon")) o:value("0",translate("Auto")) o:value("1",translate("OnePlus")) o:value("2","360") o:value("3",translate("Asus")) o:value("4",translate("Coolpad")) o:value("5",translate("Dell")) o:value("6",translate("Haier")) o:value("7",translate("Hasee")) o:value("8",translate("Honor")) o:value("9",translate("HP")) o:value("10","HTC") o:value("11",translate("Huawei")) o:value("12",translate("Apple")) o:value("13",translate("Lenovo")) o:value("14",translate("LeEco")) o:value("15","LG") o:value("16",translate("Meitu")) o:value("17",translate("Meizu")) o:value("18","OPPO") o:value("19",translate("Phicomm")) o:value("20",translate("Samsung")) o:value("21",translate("Smartisan")) o:value("22",translate("Sony")) o:value("23","TCL") o:value("24","ThinkPad") o:value("25",translate("TongfangPC")) o:value("26","VIVO") o:value("27",translate("Microsoft")) o:value("28",translate("XiaoMi")) o:value("29",translate("ZTE")) if nixio.fs.access("/tmp/k3screenctrl.log") then s = m:section(TypedSection, "general", translate("Output results")) s.anonymous = true o = s:option(TextValue,"test_output_results") o.readonly = true o.rows = 30 o.cfgvalue = function() return luci.sys.exec("cat /tmp/k3screenctrl.log && rm -f /tmp/k3screenctrl.log") end end return m
package.path = "../?.lua;"..package.path local colorman = require("lj2color.colorman") local function printColorValue(cv) --print(cv.name) print(string.format("%10s %-20s%4d %4d %4d", cv.dbname, cv.name, cv.color[1], cv.color[2], cv.color[3])); end local function printColors(name) local colors = colorman.getColorByName(name); for _, value in ipairs(colors) do print(string.format("%-20s%4d %4d %4d", name, value[1], value[2], value[3])); end end -- lookup some colors by name --printColors("cottoncandy"); local function testColorNameMatch(pattern) local found = getColorLikeName(pattern) --local found = colorman.matchColorByName(pattern, colorman.colordb.sgi, "sgi") for _, value in ipairs(found) do printColorValue(value) end end local function testNameMatch(pattern, dbname) local found = colorman.matchColorByName(pattern, colorman.colordb[dbname], dbname) for _, value in ipairs(found) do printColorValue(value) end end local function testColorByValue() --local found = colorman.matchColorByValue({255,255,255}, colorman.colordb.sgi, "sgi") --local found = colorman.matchColorByValue({127,70,80}, colorman.colordb.sgi, "sgi") local found = colorman.getColorByValue({255,255,255}) for _, value in ipairs(found) do printColorValue(value) end end --testColorNameMatch("gray") --testColorNameMatch("white") --testColorNameMatch("vio") testColorNameMatch("yellow") --testNameMatch("yellow", "crayola") --testColorByValue()
----------------------------------------------------------------------------- -- Valider class v1.1.1 -- Author: aimingoo@wandoujia.com -- Copyright (c) 2015.06 -- -- The promise module from NGX_4C architecture -- 1) N4C is programming framework. -- 2) N4C = a Controllable & Computable Communication Cluster architectur. -- -- Usage: -- checker = require('Valider'):new(opt) -- isInvalid = checker:invalid(key, isContinuous) -- -- History: -- 2015.10.29 release v1.1.1, update testcases -- 2015.08.12 release v1.1, rewirte invalid() without queue, publish on github -- 2015.08.11 release v1.0.1, full testcases -- 2015.03 release v1.0.0 ----------------------------------------------------------------------------- local Valider = { maxContinuousInterval = 3, maxContinuous = 100, -- continuous invalid X times (default 100), or maxTimes = 30, -- invalid X times in Y seconds history (default is 30 times in 30s) maxSeconds = 30 -- (max history seconds, default is 30s) } function Valider:invalid(key, isContinuous) -- key is '<channel>.<addr>' or anythings if not rawget(self, key) then rawset(self, key, { 1, 0, os.time(), 0 }) -- { count, seconds, lastTime, continuous } else local now, s = os.time(), rawget(self, key) local count, seconds, lastTime, continuous = s[1], s[2], s[3], s[4] -- or unpack(s) s[3], s[4] = now, (isContinuous or (lastTime+self.maxContinuousInterval) > now) and continuous + 1 or 0 local gapTime, maxSeconds = now - lastTime, self.maxSeconds if gapTime > maxSeconds then -- reset s[1], s[2] = 1, 0 return false end local saveTime = seconds + gapTime local dropTime = saveTime - maxSeconds if dropTime > 0 then local avgTime = seconds/count local dropN = math.ceil(dropTime/avgTime) s[1], s[2] = count - dropN + 1, math.ceil(seconds - dropN*avgTime) else s[1], s[2] = count + 1, saveTime end return ((s[4] >= self.maxContinuous) or (s[1] >= self.maxTimes)) end end function Valider:new(opt) -- options or nil return setmetatable({}, { -- instance is empty on init __index = opt and setmetatable(opt, {__index=self}) or self -- access options }) end return Valider
--[=[ Lexical scanner for creating a sequence of tokens from Lua source code. This is a heavily modified version of the original Penlight Lexer module: https://github.com/stevedonovan/Penlight Authors: stevedonovan <https://github.com/stevedonovan> ----------- Original Penlight lexer author ryanjmulder <https://github.com/ryanjmulder> ------------- Penlight lexer contributer mpeterv <https://github.com/mpeterv> --------------------- Penlight lexer contributer Tieske <https://github.com/Tieske> ----------------------- Penlight lexer contributer boatbomber <https://github.com/boatbomber> --------------- Roblox port, added builtin token, added patterns for incomplete syntax, bug fixes, behavior changes, token optimization Sleitnick <https://github.com/Sleitnick> ----------------- Roblox optimizations howmanysmall <https://github.com/howmanysmall> ----------- Lua + Roblox optimizations boatbomber <https://github.com/boatbomber> --------------- Added lexer.navigator() for non-sequential reads ccuser44 <https://github.com/ccuser44> ------------------- Forked from boatbomber, removed "plugin" and "self" from lua_keyword table as they are not keywords, made some changes with whitespace and made some other changes to make the use of the lexer be more applicable in uses outside of syntax highlighting List of possible tokens: - iden - keyword - string - number - comment - operator Usage: local source = "for i = 1, n do end" -- The 'scan' function returns a token iterator: for token,src in lexer.scan(source) do print(token, "'"..src.."'") end --> keyword 'for ' --> iden 'i ' --> operator '= ' --> number '1' --> operator ', ' --> iden 'n ' --> keyword 'do ' --> keyword 'end' -- The 'navigator' function returns a navigator object: -- Navigators allow you to use nav.Peek() for non-sequential reads local nav = lexer.navigator() nav:SetSource(source) -- You can reuse navigators by setting a new Source for token,src in nav.Next do print(token, "'"..src.."'") local peektoken, peeksrc = nav.Peek(2) -- You can peek backwards by passing a negative input if peektoken then print(" Peeked ahead by 2:", peektoken, "'"..peeksrc.."'") end end --> keyword 'for ' --> Peeked ahead by 2: operator '= ' --> iden 'i ' --> Peeked ahead by 2: number '1' --> operator '= ' --> Peeked ahead by 2: operator ', ' --> number '1' --> Peeked ahead by 2: iden 'n ' --> operator ', ' --> Peeked ahead by 2: keyword 'do ' --> iden 'n ' --> Peeked ahead by 2: keyword 'end' --> keyword 'do ' --> keyword 'end' --]=] local lexer = {} local Prefix, Suffix, Cleaner = "^[ \t\n\0\a\b\v\f\r]*", "[ \t\n\0\a\b\v\f\r]*", "[ \t\n\0\a\b\v\f\r]+" local NUMBER_A = "0[xX][%da-fA-F]+" local NUMBER_B = "%d+%.?%d*[eE][%+%-]?%d+" local NUMBER_C = "%d+[%.]?[%deE]*" local VARARG = "%.%.%" local CONCAT_OP = "%.%." local LOREQ_OP, GOREQ_OP, NOTEQ_OP, EQ_OP = "<=", ">=", "~=", "==" local OPERATORS = "[:;<>/%*%(%)%-=,{}%.#%^%+%%]" local BRACKETS = "[%[%]]" -- needs to be separate pattern from other operators or it'll mess up multiline strings local IDEN = "[%a_][%w_]*" local STRING_EMPTY = "(['\"])%1" --Empty String local STRING_PLAIN = "([\'\"])[^\n]-([^%\\]%1)" --TODO: Handle escaping escapes local STRING_INCOMP_A = "(['\"]).-\n" --Incompleted String with next line local STRING_INCOMP_B = "(['\"])[^\n]*" --Incompleted String without next line local STRING_MULTI = "%[(=*)%[.-%]%1%]" --Multiline-String local STRING_MULTI_INCOMP = "%[=*%[.-.*" --Incompleted Multiline-String local COMMENT_MULTI = "%-%-%[(=*)%[.-%]%1%]" --Completed Multiline-Comment local COMMENT_MULTI_INCOMP = "%-%-%[=*%[.-.*" --Incompleted Multiline-Comment local COMMENT_PLAIN = "%-%-.-\n" --Completed Singleline-Comment local COMMENT_INCOMP = "%-%-.*" --Incompleted Singleline-Comment local TABLE_EMPTY = {} local lua_keyword = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["while"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true, } local implementation_spesific = { Lua = { -- Any version of lua. Could be used for example where you want to have it for Lua in general not just a spesific version. If not specified a version the parser will default to this. keywords = { "continue", "goto", "<const>", "<toclose>" }, operators = { NOTEQ_OP, "%+=", "%-=", "%*=", "/=", "%%=", "%^=", "%.%.=", ">>", "<<", "::", "=>", "[&|~]", "//" }, numbers = { "0[bB][01_]+", "0[xX][_%da-fA-F]+", "%d+[%._]?[%_deE]*" }, }, ["Lua 5.2"] = { keywords = { "goto" }, operators = { "::" } }, ["Lua 5.3"] = { keywords = { "goto" }, operators = { NOTEQ_OP, --[[Has to be added due to bitwise operators]] ">>", "<<", "::", "[&|~]", "//" } }, ["Lua 5.4"] = { keywords = { "goto", "<const>", "<toclose>" }, operators = { NOTEQ_OP, --[[Has to be added due to bitwise operators]] ">>", "<<", "::", "[&|~]", "//" } }, Luau = { keywords = { "continue", }, operators = { NOTEQ_OP, "%+=", "%-=", "%*=", "/=", "%%=", "%^=", "%.%.=", "=>", "[|~]" }, numbers = { "0[bB][01_]+", "0[xX][_%da-fA-F]+", "%d+[%._]?[%_deE]*" }, } } local function idump(tok) --print("tok unknown:",tok) return coroutine.yield("iden", tok) end local function odump(tok) return coroutine.yield("operator", tok) end local function ndump(tok) return coroutine.yield("number", tok) end local function sdump(tok) return coroutine.yield("string", tok) end local function cdump(tok) return coroutine.yield("comment", tok) end local function kdump(tok) return coroutine.yield("keyword", tok) end local function lua_vdump(tok, implementation) -- Since we merge spaces into the tok, we need to remove them -- in order to check the actual word it contains local cleanTok = string.gsub(tok, Cleaner, "") if lua_keyword[cleanTok] then return coroutine.yield("keyword", tok) else return coroutine.yield("iden", tok) end end local lua_matches = { -- Indentifiers {Prefix.. IDEN ..Suffix, lua_vdump}, {Prefix.. VARARG ..Suffix, kdump}, -- Numbers {Prefix.. NUMBER_A ..Suffix, ndump}, {Prefix.. NUMBER_B ..Suffix, ndump}, {Prefix.. NUMBER_C ..Suffix, ndump}, -- Strings {Prefix.. STRING_EMPTY ..Suffix, sdump}, {Prefix.. STRING_PLAIN ..Suffix, sdump}, {Prefix.. STRING_INCOMP_A ..Suffix, sdump}, {Prefix.. STRING_INCOMP_B ..Suffix, sdump}, {Prefix.. STRING_MULTI ..Suffix, sdump}, {Prefix.. STRING_MULTI_INCOMP ..Suffix, sdump}, -- Comments {Prefix.. COMMENT_MULTI ..Suffix, cdump}, {Prefix.. COMMENT_MULTI_INCOMP ..Suffix, cdump}, {Prefix.. COMMENT_PLAIN ..Suffix, cdump}, {Prefix.. COMMENT_INCOMP ..Suffix, cdump}, -- Operators {Prefix.. CONCAT_OP ..Suffix, odump}, {Prefix.. LOREQ_OP ..Suffix, odump}, {Prefix.. GOREQ_OP ..Suffix, odump}, {Prefix.. NOTEQ_OP ..Suffix, odump}, {Prefix.. EQ_OP ..Suffix, odump}, {Prefix.. OPERATORS ..Suffix, odump}, {Prefix.. BRACKETS ..Suffix, odump}, -- Unknown {"^.", idump} } local implementation_spesific_matches = {} for version, data in pairs(implementation_spesific) do local NewTable = {} local keywords, operators, numbers = data.keywords, data.operators, data.numbers if keywords then for _, v in ipairs(keywords) do table.insert(NewTable, {Prefix.. v ..Suffix, kdump}) end end if numbers then for _, v in ipairs(numbers) do table.insert(NewTable, {Prefix.. v ..Suffix, ndump}) end end if operators then for _, v in ipairs(operators) do table.insert(NewTable, {Prefix.. v ..Suffix, odump}) end end implementation_spesific_matches[version] = NewTable end --- Create a plain token iterator from a string. -- @tparam string s a string. function lexer.scan(s, include_wspace, merge_wspace, implementation) local startTime = os.clock() lexer.finished = false assert((type(s) == "string" and s), "invalid argument #1 to 'scan' (string expected, got " .. type(s)) implementation = implementation and assert((type(implementation) == "string" and implementation), "bad argument #4 to 'scan' (string expected, got " .. type(implementation)) or "Lua" local matches = {} for _, v in ipairs(implementation_spesific_matches[implementation] or {}) do table.insert(matches, v) end for _, v in ipairs(lua_matches) do table.insert(matches, v) end local function lex(first_arg) local line_nr = 0 local sz = #s local idx = 1 -- res is the value used to resume the coroutine. local function handle_requests(res) while res do local tp = type(res) -- Insert a token list: if tp == "table" then res = coroutine.yield("", "") for _, t in ipairs(res) do res = coroutine.yield(t[1], t[2]) end elseif tp == "string" then -- Or search up to some special pattern: local i1, i2 = string.find(s, res, idx) if i1 then idx = i2 + 1 res = coroutine.yield("", string.sub(s, i1, i2)) else res = coroutine.yield("", "") idx = sz + 1 end else res = coroutine.yield(line_nr, idx) end end end handle_requests(first_arg) line_nr = 1 while true do if idx > sz then while true do handle_requests(coroutine.yield()) end end for _, m in ipairs(matches) do local findres = {} local i1, i2 = string.find(s, m[1], idx) findres[1], findres[2] = i1, i2 if i1 then local tok = string.sub(s, i1, i2) idx = i2 + 1 lexer.finished = idx > sz --if lexer.finished then -- print(string.format("Lex took %.2f ms", (os.clock()-startTime)*1000 )) --end local res = m[2](tok, findres) if string.find(tok, "\n") then -- Update line number: local _, newlines = string.gsub(tok, "\n", TABLE_EMPTY) line_nr = line_nr + newlines end handle_requests(res) break end end end end return coroutine.wrap(lex) end function lexer.navigator() local nav = { Source = ""; TokenCache = table.create and table.create(50) or {}; _RealIndex = 0; _UserIndex = 0; _ScanThread = nil; } function nav:Destroy() self.Source = nil self._RealIndex = nil; self._UserIndex = nil; self.TokenCache = nil; self._ScanThread = nil; end function nav:SetSource(SourceString) self.Source = assert((type(SourceString) == "string" and SourceString), "Attempt to SetSource failed: Passed value is not a string") self._RealIndex = 0; self._UserIndex = 0; if table.clear then table.clear(self.TokenCache) else self.TokenCache = {} end self._ScanThread = coroutine.create(function() for Token, Src in lexer.scan(self.Source) do self._RealIndex = self._RealIndex + 1 self.TokenCache[self._RealIndex] = {Token; Src;} coroutine.yield(Token,Src) end end) end function nav.Next() nav._UserIndex = nav._UserIndex + 1 if nav._RealIndex >= nav._UserIndex then -- Already scanned, return cached return (table.unpack or unpack)(nav.TokenCache[nav._UserIndex]) else if coroutine.status(nav._ScanThread) == "dead" then -- Scan thread dead return else local success, token, src = coroutine.resume(nav._ScanThread) if success and token then -- Scanned new data return token, src else -- Lex completed return end end end end function nav.Peek(PeekAmount) local GoalIndex = nav._UserIndex + PeekAmount if nav._RealIndex >= GoalIndex then -- Already scanned, return cached if GoalIndex > 0 then return (table.unpack or unpack)(nav.TokenCache[GoalIndex]) else -- Invalid peek return end else if coroutine.status(nav._ScanThread) == "dead" then -- Scan thread dead return else local IterationsAway = GoalIndex - nav._RealIndex local success, token, src = nil, nil, nil for i = 1, IterationsAway do success, token, src = coroutine.resume(nav._ScanThread) if not (success or token) then -- Lex completed break end end return token, src end end end return nav end return lexer
-- Editors: -- Earth Salamander #42, 03.02.2018 storegga_arm_slam = class({}) LinkLuaModifier( "modifier_storegga_arm_slam", "modifier/modifier_storegga_arm_slam", LUA_MODIFIER_MOTION_NONE ) -------------------------------------------------------------------------------- function storegga_arm_slam:ProcsMagicStick() return false end -------------------------------------------------------------------------------- function storegga_arm_slam:OnAbilityPhaseStart() if IsServer() then self.animation_time = self:GetSpecialValueFor( "animation_time" ) self.initial_delay = self:GetSpecialValueFor( "initial_delay" ) local kv = {} kv["duration"] = self.animation_time kv["initial_delay"] = self.initial_delay self:GetCaster():AddNewModifier( self:GetCaster(), self, "modifier_storegga_arm_slam", kv ) end return true end -------------------------------------------------------------------------------- function storegga_arm_slam:OnAbilityPhaseInterrupted() if IsServer() then self:GetCaster():RemoveModifierByName( "modifier_storegga_arm_slam" ) end end -------------------------------------------------------------------------------- function storegga_arm_slam:GetPlaybackRateOverride() return 0.5 end -------------------------------------------------------------------------------- function storegga_arm_slam:GetCastRange( vLocation, hTarget ) if IsServer() then if self:GetCaster():FindModifierByName( "modifier_storegga_arm_slam" ) ~= nil then return 99999 end end return self.BaseClass.GetCastRange( self, vLocation, hTarget ) end storegga_avalanche = class({}) LinkLuaModifier( "modifier_storegga_avalanche_thinker", "modifier/modifier_storegga_avalanche_thinker", LUA_MODIFIER_MOTION_NONE ) ----------------------------------------------------------------------- function storegga_avalanche:ProcsMagicStick() return false end -------------------------------------------------------------------------------- function storegga_avalanche:GetChannelAnimation() return ACT_DOTA_CHANNEL_ABILITY_1 end -------------------------------------------------------------------------------- function storegga_avalanche:GetPlaybackRateOverride() return 1 end -------------------------------------------------------------------------------- function storegga_avalanche:OnAbilityPhaseStart() if IsServer() then self.nChannelFX = ParticleManager:CreateParticle( "particles/act_2/storegga_channel.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetCaster() ) end return true end ----------------------------------------------------------------------- function storegga_avalanche:OnAbilityPhaseInterrupted() if IsServer() then ParticleManager:DestroyParticle( self.nChannelFX, false ) end end ----------------------------------------------------------------------- function storegga_avalanche:OnSpellStart() if IsServer() then self.flChannelTime = 0.0 self.hThinker = CreateModifierThinker( self:GetCaster(), self, "modifier_storegga_avalanche_thinker", { duration = self:GetChannelTime() }, self:GetCaster():GetOrigin(), self:GetCaster():GetTeamNumber(), false ) end end function storegga_avalanche:OnChannelThink( flInterval ) if IsServer() then self.flChannelTime = self.flChannelTime + flInterval if self.flChannelTime > 9.2 and self.bStartedGesture ~= true then self.bStartedGesture = true self:GetCaster():StartGesture( ACT_DOTA_CAST_ABILITY_2_END ) end end end ----------------------------------------------------------------------- function storegga_avalanche:OnChannelFinish( bInterrpted ) if IsServer() then ParticleManager:DestroyParticle( self.nChannelFX, false ) if self.hThinker ~= nil and self.hThinker:IsNull() == false then self.hThinker:ForceKill( false ) end end end storegga_grab = class({}) LinkLuaModifier( "modifier_storegga_grab", "modifier/modifier_storegga_grab", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_storegga_grabbed_buff", "modifier/modifier_storegga_grabbed_buff", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_storegga_grabbed_debuff", "modifier/modifier_storegga_grabbed_debuff", LUA_MODIFIER_MOTION_BOTH ) -------------------------------------------------------------------------------- function storegga_grab:ProcsMagicStick() return false end -------------------------------------------------------------------------------- function storegga_grab:OnAbilityPhaseStart() if IsServer() then if self:GetCaster():FindModifierByName( "modifier_storegga_grabbed_buff" ) ~= nil then return end self.animation_time = self:GetSpecialValueFor( "animation_time" ) self.initial_delay = self:GetSpecialValueFor( "initial_delay" ) local kv = {} kv["duration"] = self.animation_time kv["initial_delay"] = self.initial_delay local hBuff = self:GetCaster():AddNewModifier( self:GetCaster(), self, "modifier_storegga_grab", kv ) if hBuff ~= nil then hBuff.hTarget = self:GetCursorTarget() end end return true end -------------------------------------------------------------------------------- function storegga_grab:OnAbilityPhaseInterrupted() if IsServer() then self:GetCaster():RemoveModifierByName( "modifier_storegga_grab" ) end end -------------------------------------------------------------------------------- function storegga_grab:GetPlaybackRateOverride() return 0.35 end -------------------------------------------------------------------------------- function storegga_grab:GetCastRange( vLocation, hTarget ) if IsServer() then if self:GetCaster():FindModifierByName( "modifier_storegga_grab" ) ~= nil then return 99999 end end return self.BaseClass.GetCastRange( self, vLocation, hTarget ) end storegga_grab_throw = class({}) -------------------------------------------------------------------------------- function storegga_grab_throw:ProcsMagicStick() return false end -------------------------------------------------------------------------------- function storegga_grab_throw:OnAbilityPhaseStart() if IsServer() then end return true end -------------------------------------------------------------------------------- function storegga_grab_throw:OnAbilityPhaseInterrupted() if IsServer() then --ParticleManager:DestroyParticle( self.nTargetFX, false ) end end -------------------------------------------------------------------------------- function storegga_grab_throw:GetPlaybackRateOverride() return 0.7 end -------------------------------------------------------------------------------- function storegga_grab_throw:OnSpellStart() if IsServer() then self.hBuff = self:GetCaster():FindModifierByName( "modifier_storegga_grabbed_buff" ) if self.hBuff == nil then return false end self.hThrowTarget = self.hBuff.hThrowObject if self.hThrowTarget == nil then self:GetCaster():RemoveModifierByName( "modifier_storegga_grabbed_buff" ) return false end self.hThrowBuff = self.hThrowTarget:FindModifierByName( "modifier_storegga_grabbed_debuff" ) if self.hThrowBuff == nil then self:GetCaster():RemoveModifierByName( "modifier_storegga_grabbed_buff" ) return false end self.throw_speed = self:GetSpecialValueFor( "throw_speed" ) self.impact_radius = self:GetSpecialValueFor( "impact_radius" ) self.stun_duration = self:GetSpecialValueFor( "stun_duration" ) self.knockback_duration = self:GetSpecialValueFor( "knockback_duration" ) self.knockback_distance = self:GetSpecialValueFor( "knockback_distance" ) self.knockback_damage = self:GetSpecialValueFor( "knockback_damage" ) self.knockback_height = self:GetSpecialValueFor( "knockback_height" ) if self.hThrowTarget:GetUnitName() == "npc_dota_storegga_rock" then self.throw_speed = self.throw_speed * 1.5 self.impact_radius = self.impact_radius * 0.75 self.knockback_damage = self.knockback_damage * 0.75 end if self.hThrowTarget:GetUnitName() == "npc_dota_storegga_rock2" then self.throw_speed = self.throw_speed * 1 self.impact_radius = self.impact_radius * 1.25 self.knockback_damage = self.knockback_damage * 1.5 end if self.hThrowTarget:GetUnitName() == "npc_dota_storegga_rock3" then self.throw_speed = self.throw_speed * 0.5 self.impact_radius = self.impact_radius * 1.5 self.knockback_damage = self.knockback_damage * 3 end self.vDirection = self:GetCursorPosition() - self:GetCaster():GetOrigin() self.flDist = self.vDirection:Length2D() - 300 -- the direction is offset due to the attachment point self.vDirection.z = 0.0 self.vDirection = self.vDirection:Normalized() self.attach = self:GetCaster():ScriptLookupAttachment( "attach_attack2" ) self.vSpawnLocation = self:GetCaster():GetAttachmentOrigin( self.attach ) self.vEndPos = self.vSpawnLocation + self.vDirection * self.flDist local info = { EffectName = "", Ability = self, vSpawnOrigin = self.vSpawnLocation, fStartRadius = self.impact_radius, fEndRadius = self.impact_radius, vVelocity = self.vDirection * self.throw_speed, fDistance = self.flDist, Source = self:GetCaster(), iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY, iUnitTargetType = DOTA_UNIT_TARGET_HERO, } self.hThrowBuff.nProjHandle = ProjectileManager:CreateLinearProjectile( info ) self.hThrowBuff.flHeight = self.vSpawnLocation.z - GetGroundHeight( self:GetCaster():GetOrigin(), self:GetCaster() ) self.hThrowBuff.flTime = self.flDist / self.throw_speed self:GetCaster():RemoveModifierByName( "modifier_storegga_grabbed_buff" ) EmitSoundOn( "Hero_Tiny.Toss.Target", self:GetCaster() ) end end -------------------------------------------------------------------------------- function storegga_grab_throw:OnProjectileHit( hTarget, vLocation ) if IsServer() then if hTarget ~= nil then return end --ParticleManager:DestroyParticle( self.nTargetFX, false ) EmitSoundOnLocationWithCaster( vLocation, "Ability.TossImpact", self:GetCaster() ) -- EmitSoundOnLocationWithCaster( vLocation, "OgreTank.GroundSmash", self:GetCaster() ) if self.hThrowTarget ~= nil then self.hThrowBuff:Destroy() if self.hThrowTarget:IsRealHero() then local damageInfo = { victim = self.hThrowTarget, attacker = self:GetCaster(), damage = self.knockback_damage / 3, damage_type = DAMAGE_TYPE_PHYSICAL, ability = self, } ApplyDamage( damageInfo ) if self.hThrowTarget:IsAlive() == false then local nFXIndex = ParticleManager:CreateParticle( "particles/units/heroes/hero_phantom_assassin/phantom_assassin_crit_impact.vpcf", PATTACH_CUSTOMORIGIN, nil ) ParticleManager:SetParticleControlEnt( nFXIndex, 0, self.hThrowTarget, PATTACH_POINT_FOLLOW, "attach_hitloc", self.hThrowTarget:GetOrigin(), true ) ParticleManager:SetParticleControl( nFXIndex, 1, self.hThrowTarget:GetOrigin() ) ParticleManager:SetParticleControlForward( nFXIndex, 1, -self:GetCaster():GetForwardVector() ) ParticleManager:SetParticleControlEnt( nFXIndex, 10, self.hThrowTarget, PATTACH_ABSORIGIN_FOLLOW, nil, self.hThrowTarget:GetOrigin(), true ) ParticleManager:ReleaseParticleIndex( nFXIndex ) EmitSoundOn( "Hero_PhantomAssassin.Spatter", self.hThrowTarget ) else self.hThrowTarget:AddNewModifier( self:GetCaster(), self, "modifier_stunned", { duration = self.stun_duration } ) end end local nFXIndex = ParticleManager:CreateParticle( "particles/test_particle/ogre_melee_smash.vpcf", PATTACH_WORLDORIGIN, self:GetCaster() ) ParticleManager:SetParticleControl( nFXIndex, 0, GetGroundPosition( vLocation, self.hThrowTarget ) ) ParticleManager:SetParticleControl( nFXIndex, 1, Vector( self.impact_radius, self.impact_radius, self.impact_radius ) ) ParticleManager:ReleaseParticleIndex( nFXIndex ) local enemies = FindUnitsInRadius( self:GetCaster():GetTeamNumber(), vLocation, self:GetCaster(), self.impact_radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, 0, false ) for _,enemy in pairs( enemies ) do if enemy ~= nil and enemy:IsInvulnerable() == false and enemy ~= self.hThrowTarget then local damageInfo = { victim = enemy, attacker = self:GetCaster(), damage = self.knockback_damage, damage_type = DAMAGE_TYPE_PHYSICAL, ability = self, } ApplyDamage( damageInfo ) if enemy:IsAlive() == false then local nFXIndex = ParticleManager:CreateParticle( "particles/units/heroes/hero_phantom_assassin/phantom_assassin_crit_impact.vpcf", PATTACH_CUSTOMORIGIN, nil ) ParticleManager:SetParticleControlEnt( nFXIndex, 0, enemy, PATTACH_POINT_FOLLOW, "attach_hitloc", enemy:GetOrigin(), true ) ParticleManager:SetParticleControl( nFXIndex, 1, enemy:GetOrigin() ) ParticleManager:SetParticleControlForward( nFXIndex, 1, -self:GetCaster():GetForwardVector() ) ParticleManager:SetParticleControlEnt( nFXIndex, 10, enemy, PATTACH_ABSORIGIN_FOLLOW, nil, enemy:GetOrigin(), true ) ParticleManager:ReleaseParticleIndex( nFXIndex ) EmitSoundOn( "Hero_PhantomAssassin.Spatter", enemy ) else local kv = { center_x = vLocation.x, center_y = vLocation.y, center_z = vLocation.z, should_stun = true, duration = self.knockback_duration, knockback_duration = self.knockback_duration, knockback_distance = self.knockback_distance, knockback_height = self.knockback_height, } enemy:AddNewModifier( self:GetCaster(), self, "modifier_stunned", { duration = self.knockback_duration } ) end end end end return false end end ----------------------------------------------------------------------- storegga_passive = class({}) LinkLuaModifier( "modifier_storegga_passive", "modifier/modifier_storegga_passive", LUA_MODIFIER_MOTION_NONE ) ----------------------------------------------------------------------------------------- function storegga_passive:GetIntrinsicModifierName() return "modifier_storegga_passive" end -----------------------------------------------------------------------------------------
gl.setup(1024, 768) local image = resource.load_image "beamer.png" function node.render() gl.clear(1,1,1,1) util.draw_correct(image, 0, 0, WIDTH, HEIGHT) end
-- luacheck: globals include redraw util params local UI = include("lib/ui") local settings = include("lib/settings") local function round(value) return util.round(value, 0.0001) end return UI.Page.new({ title = "fall: delays", type = UI.Page.MENU, enc_handler = function(page, n, d) page.menu:handle_menu_enc(n, d) end, menu = UI.Menu.new( 1, { { name = "1 time", value = function() return round(params:get("short_delay_time")) end, enc_3_action = function(_, _, d) params:set("short_delay_time", util.clamp(params:get("short_delay_time") + d / 100, 1, 5)) redraw() end }, { name = "1 fdbk", value = function() return round(params:get("short_delay_feedback")) end, enc_3_action = function(_, _, d) params:set("short_delay_feedback", util.clamp(params:get("short_delay_feedback") + d / 1000, 0, 1)) redraw() end }, { name = "1 level", value = function() return round(params:get("short_delay_level")) end, enc_3_action = function(_, _, d) params:set("short_delay_level", util.clamp(params:get("short_delay_level") + d / 1000, 0, 1)) redraw() end }, { name = "2 time", value = function() return round(params:get("long_delay_time")) end, enc_3_action = function(_, _, d) params:set("long_delay_time", util.clamp(params:get("long_delay_time") + d / 10, 1, settings.max_loop_length)) redraw() end }, { name = "2 fdbk", value = function() return round(params:get("long_delay_feedback")) end, enc_3_action = function(_, _, d) params:set("long_delay_feedback", util.clamp(params:get("long_delay_feedback") + d / 1000, 0, 1)) redraw() end }, { name = "2 level", value = function() return round(params:get("long_delay_level")) end, enc_3_action = function(_, _, d) params:set("long_delay_level", util.clamp(params:get("long_delay_level") + d / 1000, 0, 1)) redraw() end }, } ) })
---@class UnityEngine.Camera : UnityEngine.Behaviour ---@field nearClipPlane float ---@field farClipPlane float ---@field fieldOfView float ---@field renderingPath UnityEngine.RenderingPath ---@field actualRenderingPath UnityEngine.RenderingPath ---@field allowHDR bool ---@field allowMSAA bool ---@field allowDynamicResolution bool ---@field forceIntoRenderTexture bool ---@field orthographicSize float ---@field orthographic bool ---@field opaqueSortMode UnityEngine.Rendering.OpaqueSortMode ---@field transparencySortMode UnityEngine.TransparencySortMode ---@field transparencySortAxis UnityEngine.Vector3 ---@field depth float ---@field aspect float ---@field velocity UnityEngine.Vector3 ---@field cullingMask int ---@field eventMask int ---@field layerCullSpherical bool ---@field cameraType UnityEngine.CameraType ---@field layerCullDistances table ---@field useOcclusionCulling bool ---@field cullingMatrix UnityEngine.Matrix4x4 ---@field backgroundColor UnityEngine.Color ---@field clearFlags UnityEngine.CameraClearFlags ---@field depthTextureMode UnityEngine.DepthTextureMode ---@field clearStencilAfterLightingPass bool ---@field usePhysicalProperties bool ---@field sensorSize UnityEngine.Vector2 ---@field lensShift UnityEngine.Vector2 ---@field focalLength float ---@field gateFit UnityEngine.Camera.GateFitMode ---@field rect UnityEngine.Rect ---@field pixelRect UnityEngine.Rect ---@field pixelWidth int ---@field pixelHeight int ---@field scaledPixelWidth int ---@field scaledPixelHeight int ---@field targetTexture UnityEngine.RenderTexture ---@field activeTexture UnityEngine.RenderTexture ---@field targetDisplay int ---@field cameraToWorldMatrix UnityEngine.Matrix4x4 ---@field worldToCameraMatrix UnityEngine.Matrix4x4 ---@field projectionMatrix UnityEngine.Matrix4x4 ---@field nonJitteredProjectionMatrix UnityEngine.Matrix4x4 ---@field useJitteredProjectionMatrixForTransparentRendering bool ---@field previousViewProjectionMatrix UnityEngine.Matrix4x4 ---@field main UnityEngine.Camera ---@field current UnityEngine.Camera ---@field scene UnityEngine.SceneManagement.Scene ---@field stereoEnabled bool ---@field stereoSeparation float ---@field stereoConvergence float ---@field areVRStereoViewMatricesWithinSingleCullTolerance bool ---@field stereoTargetEye UnityEngine.StereoTargetEyeMask ---@field stereoActiveEye UnityEngine.Camera.MonoOrStereoscopicEye ---@field allCamerasCount int ---@field allCameras table ---@field commandBufferCount int ---@field onPreCull UnityEngine.Camera.CameraCallback ---@field onPreRender UnityEngine.Camera.CameraCallback ---@field onPostRender UnityEngine.Camera.CameraCallback local m = {} function m:Reset() end function m:ResetTransparencySortSettings() end function m:ResetAspect() end function m:ResetCullingMatrix() end ---@param shader UnityEngine.Shader ---@param replacementTag string function m:SetReplacementShader(shader, replacementTag) end function m:ResetReplacementShader() end ---@overload fun(colorBuffer:table, depthBuffer:UnityEngine.RenderBuffer):void ---@param colorBuffer UnityEngine.RenderBuffer ---@param depthBuffer UnityEngine.RenderBuffer function m:SetTargetBuffers(colorBuffer, depthBuffer) end function m:ResetWorldToCameraMatrix() end function m:ResetProjectionMatrix() end ---@param clipPlane UnityEngine.Vector4 ---@return UnityEngine.Matrix4x4 function m:CalculateObliqueMatrix(clipPlane) end ---@overload fun(position:UnityEngine.Vector3):UnityEngine.Vector3 ---@param position UnityEngine.Vector3 ---@param eye UnityEngine.Camera.MonoOrStereoscopicEye ---@return UnityEngine.Vector3 function m:WorldToScreenPoint(position, eye) end ---@overload fun(position:UnityEngine.Vector3):UnityEngine.Vector3 ---@param position UnityEngine.Vector3 ---@param eye UnityEngine.Camera.MonoOrStereoscopicEye ---@return UnityEngine.Vector3 function m:WorldToViewportPoint(position, eye) end ---@overload fun(position:UnityEngine.Vector3):UnityEngine.Vector3 ---@param position UnityEngine.Vector3 ---@param eye UnityEngine.Camera.MonoOrStereoscopicEye ---@return UnityEngine.Vector3 function m:ViewportToWorldPoint(position, eye) end ---@overload fun(position:UnityEngine.Vector3):UnityEngine.Vector3 ---@param position UnityEngine.Vector3 ---@param eye UnityEngine.Camera.MonoOrStereoscopicEye ---@return UnityEngine.Vector3 function m:ScreenToWorldPoint(position, eye) end ---@param position UnityEngine.Vector3 ---@return UnityEngine.Vector3 function m:ScreenToViewportPoint(position) end ---@param position UnityEngine.Vector3 ---@return UnityEngine.Vector3 function m:ViewportToScreenPoint(position) end ---@overload fun(pos:UnityEngine.Vector3):UnityEngine.Ray ---@param pos UnityEngine.Vector3 ---@param eye UnityEngine.Camera.MonoOrStereoscopicEye ---@return UnityEngine.Ray function m:ViewportPointToRay(pos, eye) end ---@overload fun(pos:UnityEngine.Vector3):UnityEngine.Ray ---@param pos UnityEngine.Vector3 ---@param eye UnityEngine.Camera.MonoOrStereoscopicEye ---@return UnityEngine.Ray function m:ScreenPointToRay(pos, eye) end ---@param viewport UnityEngine.Rect ---@param z float ---@param eye UnityEngine.Camera.MonoOrStereoscopicEye ---@param outCorners table function m:CalculateFrustumCorners(viewport, z, eye, outCorners) end ---@param output UnityEngine.Matrix4x4 ---@param focalLength float ---@param sensorSize UnityEngine.Vector2 ---@param lensShift UnityEngine.Vector2 ---@param nearClip float ---@param farClip float ---@param gateFitParameters UnityEngine.Camera.GateFitParameters function m.CalculateProjectionMatrixFromPhysicalProperties(output, focalLength, sensorSize, lensShift, nearClip, farClip, gateFitParameters) end ---@param focalLength float ---@param sensorSize float ---@return float function m.FocalLengthToFOV(focalLength, sensorSize) end ---@param fov float ---@param sensorSize float ---@return float function m.FOVToFocalLength(fov, sensorSize) end ---@param eye UnityEngine.Camera.StereoscopicEye ---@return UnityEngine.Matrix4x4 function m:GetStereoNonJitteredProjectionMatrix(eye) end ---@param eye UnityEngine.Camera.StereoscopicEye ---@return UnityEngine.Matrix4x4 function m:GetStereoViewMatrix(eye) end ---@param eye UnityEngine.Camera.StereoscopicEye function m:CopyStereoDeviceProjectionMatrixToNonJittered(eye) end ---@param eye UnityEngine.Camera.StereoscopicEye ---@return UnityEngine.Matrix4x4 function m:GetStereoProjectionMatrix(eye) end ---@param eye UnityEngine.Camera.StereoscopicEye ---@param matrix UnityEngine.Matrix4x4 function m:SetStereoProjectionMatrix(eye, matrix) end function m:ResetStereoProjectionMatrices() end ---@param eye UnityEngine.Camera.StereoscopicEye ---@param matrix UnityEngine.Matrix4x4 function m:SetStereoViewMatrix(eye, matrix) end function m:ResetStereoViewMatrices() end ---@param cameras table ---@return int function m.GetAllCameras(cameras) end ---@overload fun(cubemap:UnityEngine.Cubemap):bool ---@overload fun(cubemap:UnityEngine.RenderTexture, faceMask:int):bool ---@overload fun(cubemap:UnityEngine.RenderTexture):bool ---@overload fun(cubemap:UnityEngine.RenderTexture, faceMask:int, stereoEye:UnityEngine.Camera.MonoOrStereoscopicEye):bool ---@param cubemap UnityEngine.Cubemap ---@param faceMask int ---@return bool function m:RenderToCubemap(cubemap, faceMask) end function m:Render() end ---@param shader UnityEngine.Shader ---@param replacementTag string function m:RenderWithShader(shader, replacementTag) end function m:RenderDontRestore() end ---@param cur UnityEngine.Camera function m.SetupCurrent(cur) end ---@param other UnityEngine.Camera function m:CopyFrom(other) end ---@param evt UnityEngine.Rendering.CameraEvent function m:RemoveCommandBuffers(evt) end function m:RemoveAllCommandBuffers() end ---@param evt UnityEngine.Rendering.CameraEvent ---@param buffer UnityEngine.Rendering.CommandBuffer function m:AddCommandBuffer(evt, buffer) end ---@param evt UnityEngine.Rendering.CameraEvent ---@param buffer UnityEngine.Rendering.CommandBuffer ---@param queueType UnityEngine.Rendering.ComputeQueueType function m:AddCommandBufferAsync(evt, buffer, queueType) end ---@param evt UnityEngine.Rendering.CameraEvent ---@param buffer UnityEngine.Rendering.CommandBuffer function m:RemoveCommandBuffer(evt, buffer) end ---@param evt UnityEngine.Rendering.CameraEvent ---@return table function m:GetCommandBuffers(evt) end UnityEngine = {} UnityEngine.Camera = m return m
local E, L = unpack(ElvUI) -- Import Functions/Constants, Config, Locales local CF = E:NewModule("CooldownFlash", "AceEvent-3.0", "AceHook-3.0") CF.modName = L["中部冷却闪光"] local cooldowns, animating, watching = { }, { }, { } local GetTime = GetTime local testtable local CreateFrame = CreateFrame local tinsert, select, tcount, ipairs, unpack, wipe, band, match = tinsert, select, tcount, ipairs, unpack, wipe, bit.band, string.match local NUM_PET_ACTION_SLOTS = NUM_PET_ACTION_SLOTS local GetPetActionInfo = GetPetActionInfo local GetSpellInfo = GetSpellInfo local GetSpellTexture = GetSpellTexture local GetSpellCooldown = GetSpellCooldown local GetItemCooldown = GetItemCooldown local GetActionInfo = GetActionInfo local GetPetActionCooldown = GetPetActionCooldown local GetPetActionIndexByName = GetPetActionIndexByName local GetInventoryItemID = GetInventoryItemID local GetInventoryItemTexture = GetInventoryItemTexture local GetContainerItemID = GetContainerItemID local GetItemInfo = GetItemInfo local COMBATLOG_OBJECT_TYPE_PET, COMBATLOG_OBJECT_AFFILIATION_MINE = COMBATLOG_OBJECT_TYPE_PET, COMBATLOG_OBJECT_AFFILIATION_MINE local IsInInstance = IsInInstance local DCP = CreateFrame("frame", "DCP", E.UIParent) DCP:SetAlpha(0) DCP:SetScript("OnEvent", function(self, event, ...) self[event](self, ...) end) DCP.TextFrame = DCP:CreateFontString(nil, "ARTWORK") DCP.TextFrame:SetPoint("TOP",DCP,"BOTTOM",0,-5) DCP.TextFrame:SetWidth(185) DCP.TextFrame:SetJustifyH("CENTER") DCP.TextFrame:SetTextColor(1,1,1) DCP.ignoredSpells = {} local DCPT = DCP:CreateTexture(nil,"BACKGROUND") DCPT:SetTexCoord(.08, .92, .08, .92) DCPT:SetAllPoints(DCP) ----------------------- -- Utility Functions -- ----------------------- local function tcount(tab) local n = 0 for _ in pairs(tab) do n = n + 1 end return n end local function GetPetActionIndexByName(name) for i=1, NUM_PET_ACTION_SLOTS, 1 do if (GetPetActionInfo(i) == name) then return i end end return nil end -------------------------- -- Cooldown / Animation -- -------------------------- local elapsed = 0 local runtimer = 0 local function OnUpdate(_,update) elapsed = elapsed + update if (elapsed > 0.05) then for i,v in pairs(watching) do if (GetTime() >= v[1] + 0.5) then if DCP.ignoredSpells[i] then watching[i] = nil else local start, duration, enabled, texture, isPet, name if (v[2] == "spell") then name = GetSpellInfo(v[3]) texture = GetSpellTexture(v[3]) start, duration, enabled = GetSpellCooldown(v[3]) elseif (v[2] == "item") then name = GetItemInfo(i) texture = v[3] start, duration, enabled = GetItemCooldown(i) elseif (v[2] == "pet") then texture = select(2,GetPetActionInfo(v[3])) start, duration, enabled = GetPetActionCooldown(v[3]) isPet = true end if (enabled ~= 0) then if (duration and duration > 2.0 and texture) then cooldowns[i] = { start, duration, texture, isPet, name, v[3], v[2] } end end if (not (enabled == 0 and v[2] == "spell")) then watching[i] = nil end end end end for i,v in pairs(cooldowns) do local start, duration, remaining if (v[7] == "spell") then start, duration = GetSpellCooldown(v[6]) elseif (v[7] == "item") then start, duration, enabled = GetItemCooldown(i) elseif (v[7] == "pet") then start, duration, enabled = GetPetActionCooldown(v[6]) end if start == 0 and duration == 0 then remaining = 0 else remaining = v[2]-(GetTime()-v[1]) end if (remaining <= 0) then tinsert(animating, {v[3],v[4],v[5]}) cooldowns[i] = nil end end elapsed = 0 if (#animating == 0 and tcount(watching) == 0 and tcount(cooldowns) == 0) then DCP:SetScript("OnUpdate", nil) return end end if (#animating > 0) then runtimer = runtimer + update if (runtimer > (CF.db.fadeInTime + CF.db.holdTime + CF.db.fadeOutTime)) then tremove(animating,1) runtimer = 0 DCP.TextFrame:SetText(nil) DCPT:SetTexture() DCPT:SetVertexColor(1,1,1) DCP:SetAlpha(0) DCP:SetSize(CF.db.iconSize, CF.db.iconSize) elseif CF.db.enable then if (not DCPT:GetTexture()) then if (animating[1][3] ~= nil and CF.db.showSpellName) then DCP.TextFrame:SetText(animating[1][3]) end DCPT:SetTexture(animating[1][1]) if animating[1][2] then DCPT:SetVertexColor(unpack(CF.db.petOverlay)) end end local alpha = CF.db.maxAlpha if (runtimer < CF.db.fadeInTime) then alpha = CF.db.maxAlpha * (runtimer / CF.db.fadeInTime) elseif (runtimer >= CF.db.fadeInTime + CF.db.holdTime) then alpha = CF.db.maxAlpha - ( CF.db.maxAlpha * ((runtimer - CF.db.holdTime - CF.db.fadeInTime) / CF.db.fadeOutTime)) end DCP:SetAlpha(alpha) local scale = CF.db.iconSize+(CF.db.iconSize*((CF.db.animScale-1)*(runtimer/(CF.db.fadeInTime+CF.db.holdTime+CF.db.fadeOutTime)))) DCP:SetWidth(scale) DCP:SetHeight(scale) end end end -------------------- -- Event Handlers -- -------------------- function DCP:UNIT_SPELLCAST_SUCCEEDED(unit,spell,spellID) if (unit == "player") then watching[spell] = {GetTime(),"spell",spellID} self:SetScript("OnUpdate", OnUpdate) end end function DCP:COMBAT_LOG_EVENT_UNFILTERED() local _, event, _, sourceGUID, sourceName, sourceFlags, _, _, _, _, _, spellID, _, _, arg15, arg16 = CombatLogGetCurrentEventInfo() if (event == "SPELL_CAST_SUCCESS") then if (band(sourceFlags,COMBATLOG_OBJECT_TYPE_PET) == COMBATLOG_OBJECT_TYPE_PET and bit.band(sourceFlags,COMBATLOG_OBJECT_AFFILIATION_MINE) == COMBATLOG_OBJECT_AFFILIATION_MINE) then local name = GetSpellInfo(spellID) local index = GetPetActionIndexByName(name) if (index and not select(6,GetPetActionInfo(index))) then watching[name] = {GetTime(),"pet",index} elseif (not index and name) then watching[name] = {GetTime(),"spell",spellID} else return end self:SetScript("OnUpdate", OnUpdate) end end end function DCP:PLAYER_ENTERING_WORLD() local inInstance,instanceType = IsInInstance() if (inInstance and instanceType == "arena") then self:SetScript("OnUpdate", nil) wipe(cooldowns) wipe(watching) end end function CF:UseAction(slot) local actionType,itemID = GetActionInfo(slot) if (actionType == "item") then local texture = GetActionTexture(slot) watching[itemID] = {GetTime(),"item",texture} DCP:SetScript("OnUpdate", OnUpdate) end end function CF:UseInventoryItem(slot) local itemID = GetInventoryItemID("player", slot); if (itemID) then local texture = GetInventoryItemTexture("player", slot) watching[itemID] = {GetTime(),"item",texture} DCP:SetScript("OnUpdate", OnUpdate) end end function CF:UseContainerItem(bag,slot) local itemID = GetContainerItemID(bag, slot) if (itemID) then local texture = select(10, GetItemInfo(itemID)) watching[itemID] = {GetTime(),"item",texture} DCP:SetScript("OnUpdate", OnUpdate) end end function CF:UseItemByName(itemName) local itemID if itemName then itemID = match(select(2, GetItemInfo(itemName)), "item:(%d+)") end if (itemID) then local texture = select(10, GetItemInfo(itemID)) watching[itemID] = {GetTime(),"item",texture} DCP:SetScript("OnUpdate", OnUpdate) end end function CF:EnableCooldownFlash() self:SecureHook("UseContainerItem") self:SecureHook("UseInventoryItem") self:SecureHook("UseAction") self:SecureHook("UseItemByName") DCP:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED") DCP:RegisterEvent("PLAYER_ENTERING_WORLD") if self.db.enablePet then DCP:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") end end function CF:DisableCooldownFlash() self:Unhook("UseContainerItem") self:Unhook("UseInventoryItem") self:Unhook("UseAction") self:Unhook("UseItemByName") DCP:UnregisterEvent("UNIT_SPELLCAST_SUCCEEDED") DCP:UnregisterEvent("PLAYER_ENTERING_WORLD") DCP:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") end function CF:Initialize() CF.db = E.db.CooldownFlash DCP:SetSize(CF.db.iconSize, CF.db.iconSize) DCP:CreateShadow() DCP.TextFrame:FontTemplate(E["media"].font, 18, "OUTLINE") DCP.TextFrame:SetShadowOffset(2, -2) if self.db.enable then self:EnableCooldownFlash() end DCP:SetPoint("CENTER", E.UIParent, "CENTER", -100, 50) E:CreateMover(DCP, "CooldownFlashMover", L["Middle CD Reminder"], true, nil, nil, "ALL, EUI", nil, "Watch,CooldownFlash", "db,CooldownFlash,enable") for _,v in ipairs({strsplit(",",CF.db.ignoredSpells)}) do DCP.ignoredSpells[strtrim(v)] = true end local spellname,_, icon = GetSpellInfo(16914) testtable = { icon, nil, spellname } DCP.animating = animating DCP.testtable = testtable end local function InitializeCallback() CF:Initialize() end E:RegisterModule(CF:GetName(), InitializeCallback)
local M = {} M.schema = require('candle.schema') M.highlight = setmetatable({}, { __newindex = function(_, hlgroup, opt) local cmd = {'hi', hlgroup} if opt.fg then table.insert(cmd, 'guifg='..opt.fg) end if opt.bg then table.insert(cmd, 'guibg='..opt.bg) end if opt.gui then table.insert(cmd, 'gui='..opt.gui) end if opt.sp then table.insert(cmd, 'guisp='..opt.sp) end vim.cmd(table.concat(cmd, ' ')) end }) function M.setup() local hi = M.highlight local s = M.schema -- Vim editor colors hi.Bold = { fg = nil, bg = nil, gui = 'bold', sp = nil } hi.ColorColumn = { fg = nil, bg = s.guide, gui = 'none', sp = nil } hi.Cursor = { fg = s.background, bg = s.foreground, gui = nil, sp = nil } hi.CursorColumn = { fg = nil, bg = s.line, gui = 'none', sp = nil } hi.CursorLine = { fg = nil, bg = s.line, gui = 'none', sp = nil } hi.CursorLineNr = { fg = s.gray200, bg = nil, gui = 'bold', sp = nil } hi.Debug = { fg = s.brown, bg = nil, gui = nil, sp = nil } hi.Directory = { fg = s.blue, bg = nil, gui = nil, sp = nil } hi.Error = { fg = s.red, bg = 'none', gui = nil, sp = nil } hi.ErrorMsg = { fg = s.background, bg = s.red, gui = nil, sp = nil } hi.Exception = { fg = s.purple, bg = nil, gui = nil, sp = nil } hi.FoldColumn = { fg = s.selection, bg = s.background, gui = nil, sp = nil } hi.Folded = { fg = s.comment, bg = s.background, gui = 'underline', sp = nil } hi.IncSearch = { fg = s.yellow, bg = s.dark_yellow, gui = 'bold', sp = nil } hi.Italic = { fg = nil, bg = nil, gui = 'none', sp = nil } hi.LineNr = { fg = s.gray200, bg = s.background, gui = nil, sp = nil } hi.Macro = { fg = s.purple, bg = nil, gui = nil, sp = nil } hi.MatchParen = { fg = nil, bg = s.selection, gui = nil, sp = nil } hi.ModeMsg = { fg = s.green, bg = nil, gui = 'bold', sp = nil } hi.MoreMsg = { fg = s.green, bg = nil, gui = 'bold', sp = nil } hi.NonText = { fg = s.gray500, bg = nil, gui = nil, sp = nil } hi.Normal = { fg = s.foreground, bg = 'none', gui = nil, sp = nil } hi.PMenu = { fg = s.foreground, bg = s.gray500, gui = 'none', sp = nil } hi.PMenuSbar = { fg = nil, bg = s.window, gui = nil, sp = nil } hi.PMenuSel = { fg = s.foreground, bg = s.selection, gui = nil, sp = nil } hi.PMenuThumb = { fg = nil, bg = s.gray300, gui = nil, sp = nil } hi.Question = { fg = s.background, bg = s.green, gui = nil, sp = nil } hi.Search = { fg = s.yellow, bg = s.dark_yellow, gui = 'bold', sp = nil } hi.SignColumn = { fg = s.gray200, bg = s.background, gui = nil, sp = nil } hi.SpecialKey = { fg = s.dark_aqua, bg = nil, gui = 'none', sp = nil } hi.StatusLine = { fg = s.comment, bg = s.window, gui = 'none', sp = nil } hi.StatusLineNC = { fg = s.comment, bg = s.window, gui = 'none', sp = nil } hi.TabLine = { fg = s.comment, bg = s.window, gui = 'none', sp = nil } hi.TabLineFill = { fg = s.comment, bg = s.window, gui = 'none', sp = nil } hi.TabLineSel = { fg = s.window, bg = s.foreground, gui = 'none', sp = nil } hi.Title = { fg = s.foreground, bg = nil, gui = 'bold', sp = nil } hi.Underlined = { fg = s.blue, bg = nil, gui = 'underline', sp = nil } hi.VertSplit = { fg = s.window, bg = s.window, gui = 'none', sp = nil } hi.Visual = { fg = nil, bg = s.selection, gui = nil, sp = nil } hi.WarningMsg = { fg = s.red, bg = nil, gui = nil, sp = nil } hi.WildMenu = { fg = s.yellow, bg = s.background, gui = nil, sp = nil } hi.BorderedFloat = { fg = s.foreground, bg = s.background, gui = nil, sp = nil } hi.FloatBorder = { fg = s.foreground, bg = s.background, gui = nil, sp = nil } hi.NvimInternalError = { fg = s.background, bg = s.red, gui = 'none', sp = nil } -- Standard syntax highlighting hi.Boolean = { fg = s.orange, bg = nil, gui = nil, sp = nil } hi.Character = { fg = s.orange, bg = nil, gui = nil, sp = nil } hi.Comment = { fg = s.comment, bg = nil, gui = nil, sp = nil } hi.Conditional = { fg = s.purple, bg = nil, gui = nil, sp = nil } hi.Constant = { fg = s.yellow, bg = nil, gui = nil, sp = nil } hi.Define = { fg = s.purple, bg = nil, gui = 'none', sp = nil } hi.Delimiter = { fg = s.gray200, bg = nil, gui = nil, sp = nil } hi.Float = { fg = s.orange, bg = nil, gui = nil, sp = nil } hi.Function = { fg = s.pink, bg = nil, gui = nil, sp = nil } hi.Identifier = { fg = s.blue, bg = nil, gui = 'none', sp = nil } hi.Include = { fg = s.purple, bg = nil, gui = nil, sp = nil } hi.Keyword = { fg = s.purple, bg = nil, gui = nil, sp = nil } hi.Label = { fg = s.purple, bg = nil, gui = nil, sp = nil } hi.Number = { fg = s.orange, bg = nil, gui = nil, sp = nil } hi.Operator = { fg = s.aqua, bg = nil, gui = 'none', sp = nil } hi.PreProc = { fg = s.brown, bg = nil, gui = nil, sp = nil } hi.Repeat = { fg = s.purple, bg = nil, gui = nil, sp = nil } hi.Special = { fg = s.aqua, bg = nil, gui = nil, sp = nil } hi.SpecialChar = { fg = s.bright_green, bg = nil, gui = nil, sp = nil } hi.SpecialComment = { fg = s.green, bg = nil, gui = nil, sp = nil } hi.Statement = { fg = s.purple, bg = nil, gui = nil, sp = nil } hi.StorageClass = { fg = s.yellow, bg = nil, gui = nil, sp = nil } hi.String = { fg = s.green, bg = nil, gui = nil, sp = nil } hi.Structure = { fg = s.purple, bg = nil, gui = nil, sp = nil } hi.Tag = { fg = s.yellow, bg = nil, gui = nil, sp = nil } hi.Todo = { fg = s.background, bg = s.comment, gui = nil, sp = nil } hi.Type = { fg = s.yellow, bg = nil, gui = 'none', sp = nil } hi.Typedef = { fg = s.purple, bg = nil, gui = nil, sp = nil } -- Spelling highlighting hi.SpellBad = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_red } hi.SpellLocal = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_aqua } hi.SpellCap = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_blue } hi.SpellRare = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_purple } -- Diff highlighting hi.DiffAdd = { fg = s.green, bg = 'none', gui = 'none', sp = nil } hi.DiffChange = { fg = s.blue, bg = 'none', gui = 'none', sp = nil } hi.DiffDelete = { fg = s.red, bg = 'none', gui = 'none', sp = nil } hi.DiffText = { fg = s.blue, bg = 'none', gui = 'bold', sp = nil } -- LSP -- hi.LspReferenceText = { fg = nil, bg = nil, gui = nil, sp = nil } hi.LspDiagnosticsDefaultError = { fg = s.red, bg = nil, gui = 'none', sp = nil } hi.LspDiagnosticsDefaultWarning = { fg = s.yellow, bg = nil, gui = 'none', sp = nil } hi.LspDiagnosticsDefaultInformation = { fg = s.blue, bg = nil, gui = 'none', sp = nil } hi.LspDiagnosticsDefaultHint = { fg = s.green, bg = nil, gui = 'none', sp = nil } hi.LspDiagnosticsUnderlineError = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_red } hi.LspDiagnosticsUnderlineWarning = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_yellow } hi.LspDiagnosticsUnderlineInformation = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_blue } hi.LspDiagnosticsUnderlineHint = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_green } -- Treesitter -- hi.TSError = { fg = nil, bg = s.dark_red, gui = 'none', sp = nil } hi.TSAnnotation = { fg = s.brown, bg = nil, gui = 'none', sp = nil } hi.TSAttribute = { fg = s.yellow, bg = nil, gui = 'none', sp = nil } hi.TSConstBuiltin = { fg = s.yellow, bg = nil, gui = 'italic', sp = nil } hi.TSConstMacro = { fg = s.yellow, bg = nil, gui = 'bold', sp = nil } hi.TSConstant = { fg = s.orange, bg = nil, gui = 'none', sp = nil } hi.TSConstructor = { fg = s.yellow, bg = nil, gui = 'none', sp = nil } hi.TSEmphasis = { fg = nil, bg = nil, gui = 'italic', sp = nil } hi.TSField = { fg = s.brown, bg = nil, gui = 'none', sp = nil } hi.TSFuncBuiltin = { fg = s.pink, bg = nil, gui = 'italic', sp = nil } hi.TSFuncMacro = { fg = s.pink, bg = nil, gui = 'bold', sp = nil } hi.TSKeywordOperator = { fg = s.aqua, bg = nil, gui = 'italic', sp = nil } hi.TSLiteral = { fg = s.orange, bg = nil, gui = 'none', sp = nil } hi.TSNamespace = { fg = s.brown, bg = nil, gui = 'none', sp = nil } hi.TSNone = { fg = s.foreground, bg = nil, gui = 'none', sp = nil } hi.TSProperty = { fg = s.brown, bg = nil, gui = 'none', sp = nil } hi.TSStrike = { fg = nil, bg = nil, gui = 'strikethrough', sp = nil } hi.TSStringEscape = { fg = s.dark_aqua, bg = nil, gui = 'none', sp = nil } hi.TSStringRegex = { fg = s.aqua, bg = nil, gui = 'none', sp = nil } hi.TSStrong = { fg = nil, bg = nil, gui = 'bold', sp = nil } hi.TSSymbol = { fg = s.red, bg = nil, gui = 'none', sp = nil } hi.TSTag = { fg = s.yellow, bg = nil, gui = 'none', sp = nil } hi.TSTagDelimiter = { fg = s.gray200, bg = nil, gui = 'none', sp = nil } hi.TSTypeBuiltin = { fg = s.yellow, bg = nil, gui = 'italic', sp = nil } hi.TSURI = { fg = nil, bg = nil, gui = 'underline', sp = s.bright_blue } hi.TSUnderline = { fg = nil, bg = nil, gui = 'underline', sp = nil } hi.TSVariable = { fg = s.blue, bg = nil, gui = 'none', sp = nil } hi.TSVariableBuiltin = { fg = s.blue, bg = nil, gui = 'italic', sp = nil } -- custom hi.StatusLineL0 = { fg = s.foreground, bg = s.window, gui = nil, sp = nil } hi.StatusLineMode = { fg = s.foreground, bg = s.window, gui = nil, sp = nil } hi.StatusLineDiagnosticsError = { fg = s.red, bg = s.window, gui = 'none', sp = nil } hi.StatusLineDiagnosticsWarning = { fg = s.yellow, bg = s.window, gui = 'none', sp = nil } hi.StatusLineDiagnosticsInfo = { fg = s.blue, bg = s.window, gui = 'none', sp = nil } hi.StatusLineDiagnosticsHint = { fg = s.green, bg = s.window, gui = 'none', sp = nil } hi.FullwidthSpace = { fg = nil, bg = s.dark_purple, gui = nil, sp = nil } hi.GitConflictMarker = { fg = s.red, bg = s.dark_red, gui = nil, sp = nil } hi.ExtraWhitespace = { fg = nil, bg = s.line, gui = nil, sp = nil } hi.SnipPlaceholder = { fg = s.blue, bg = s.dark_blue, gui = nil, sp = nil } -- coc.nvim hi.CocHighlightText = { fg = nil, bg = s.selection, gui = 'none', sp = nil } hi.CocErrorSign = { fg = s.red, bg = nil, gui = nil, sp = nil } hi.CocWarningSign = { fg = s.yellow, bg = nil, gui = nil, sp = nil } hi.CocInfoSign = { fg = s.blue, bg = nil, gui = nil, sp = nil } hi.CocHintSign = { fg = s.green, bg = nil, gui = nil, sp = nil } hi.CocErrorHighlight = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_red } hi.CocWarningHighlight = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_yellow } hi.CocInfoHighlight = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_blue } hi.CocHintHighlight = { fg = nil, bg = nil, gui = 'undercurl', sp = s.bright_green } hi.CocDiffAdd = { fg = s.dark_green, bg = 'none', gui = 'none', sp = nil } hi.CocDiffChange = { fg = s.dark_blue, bg = 'none', gui = 'none', sp = nil } hi.CocDiffDelete = { fg = s.dark_red, bg = 'none', gui = 'none', sp = nil } hi.CocFadeOut = { fg = s.gray200, bg = 'none', gui = 'none', sp = nil } -- vim-searchhi hi.CurrentSearch = { fg = s.background, bg = s.yellow, gui = 'bold', sp = nil } -- markdown hi.markdownH1 = { fg = s.brown, bg = nil, gui = 'bold', sp = nil } hi.markdownH2 = { fg = s.brown, bg = nil, gui = 'bold', sp = nil } hi.markdownH3 = { fg = s.brown, bg = nil, gui = 'bold', sp = nil } hi.markdownH4 = { fg = s.brown, bg = nil, gui = 'bold', sp = nil } hi.markdownH5 = { fg = s.brown, bg = nil, gui = 'bold', sp = nil } hi.markdownH6 = { fg = s.brown, bg = nil, gui = 'bold', sp = nil } hi.markdownLink = { fg = s.comment, bg = nil, gui = nil, sp = nil } hi.markdownLinkText = { fg = s.blue, bg = nil, gui = 'underline', sp = nil } hi.markdownCode = { fg = s.green, bg = nil, gui = nil, sp = nil } hi.markdownCodeBlock = { fg = s.green, bg = nil, gui = nil, sp = nil } end M.current_mode = 'n' function M.update_mode_highlight() local mode = vim.api.nvim_get_mode().mode if mode == M.current_mode then return end M.current_mode = mode local hi = M.highlight local s = M.schema local color = s.foreground if string.match(mode, '^i') then color = s.green elseif string.match(mode, '[vV\22]$') then color = s.orange elseif string.match(mode, '^R') or string.match(mode, 'o') then color = s.purple elseif string.match(mode, '[sS\19]$') then color = s.blue end hi.StatusLineMode = { fg = color, bg = s.window, gui = nil, sp = nil } hi.Cursor = { fg = s.background, bg = color, gui = nil, sp = nil } if string.match(mode, '[sS]$') then hi.Visual = { fg = s.blue, bg = s.dark_blue, gui = 'bold', sp = nil } vim.cmd('redraw') else hi.Visual = { fg = 'none', bg = s.selection, gui = 'none', sp = nil } end end return M
require "Scripts/PlayerAccount/menu" signinmenu = menu:new{canvasName = "SignIn"} function signinmenu:Show() menu.Show(self) if self.context.username then self:SetText("UsernameText", self.context.username) end end function signinmenu:OnAction(entityId, actionName) if actionName == "SignInClick" then local username = self:GetText("UsernameText") local password = self:GetText("PasswordText") self.context.username = username Debug.Log("Signing in as " .. username .. "...") CloudGemPlayerAccountRequestBus.Broadcast.InitiateAuth(username, password); return end if actionName == "ForgotPasswordClick" then local username = self:GetText("UsernameText") self.context.username = username self.menuManager:ShowMenu("ForgotPassword") return end menu.OnAction(self, entityId, actionName) end function signinmenu:OnInitiateAuthComplete(result) self:RunOnMainThread(function() if (result.wasSuccessful) then Debug.Log("Sign in success") self.menuManager:ShowMenu("MainMenu") else if result.errorTypeName == "ACCOUNT_BLACKLISTED" then Debug.Log("Unable to sign in: the account is blacklisted.") elseif result.errorTypeName == "FORCE_CHANGE_PASSWORD" then Debug.Log("Unable to sign in: A password change is required.") self.menuManager:ShowMenu("ForceChangePassword") elseif result.errorTypeName == "UserNotConfirmedException" then Debug.Log("Unable to sign in: A confirmation code is required.") self.menuManager:ShowMenu("ConfirmSignUp") else Debug.Log("Sign in failed: " .. result.errorMessage) end end end) end return signinmenu
--- Module File local Message = { } --- Message Variables local messages = { } local messageDrawX = false local messageDrawY = false local messageDrawWidth = 300 local messageDrawHeight = 300 local messageDrawOpacity = 0.75 local messageCurrentTurn = 0 local messageTime = false function Message.loadAssets() print("Loading Message Assets") messageDrawX = love.graphics.getWidth() - 315 messageDrawY = 30 end function Message.draw(gameFonts) --- Break Down Message Data local width, text = 0, '' local messagetodraw = { } local lines = 1 local maxlines = math.floor(love.graphics.getHeight() / 14) - 4 for i = # messages, 1, -1 do width, text = gameFonts.slkscr14:getWrap(messages[i].text, messageDrawWidth - 20) for j = 1, # text do table.insert(messagetodraw, {text = text[j], color = messages[i].color}) lines = lines + 1 end end love.graphics.setLineWidth(3) --- Background love.graphics.setColor(0, 0, 0, messageDrawOpacity) love.graphics.rectangle('fill', messageDrawX, messageDrawY, messageDrawWidth, ((maxlines) + 1) * 14) --- Foreground love.graphics.setColor(1, 1, 1, 1) love.graphics.rectangle('line', messageDrawX, messageDrawY, messageDrawWidth, ((maxlines) + 1) * 14) --- Draw Message for i = 1, math.min(lines - 1, maxlines - 1) do love.graphics.setFont(gameFonts.slkscr14) love.graphics.setColor(messagetodraw[i].color[1], messagetodraw[i].color[2], messagetodraw[i].color[3]) love.graphics.printf(messagetodraw[i].text, messageDrawX + 10, messageDrawY + i * 14, messageDrawWidth - 20, "left") end love.graphics.setFont(gameFonts.pixelu24) love.graphics.setColor(1, 1, 1, 1) love.graphics.printf('INFO', messageDrawX, messageDrawY - 32, messageDrawWidth - 10, "right") love.graphics.setLineWidth(1) love.graphics.setFont(gameFonts.slkscr18) love.graphics.printf(Message.clockString(), messageDrawX, messageDrawY - 27, messageDrawWidth - 90, "left") love.graphics.printf(Message.dateString(), messageDrawX, messageDrawY - 27, messageDrawWidth, "center") end function Message.dateString() local str = '' return str .. messageTime.day .. '/' .. messageTime.month .. '/' .. messageTime.year end function Message.clockString() local str = '' local hrstr = messageTime.hour local append = ' AM' if hrstr > 12 then hrstr = hrstr - 12 append = ' PM' end if string.len(messageTime.hour) == 1 then str = str .. '0' .. hrstr else str = str .. hrstr end str = str .. ':' if string.len(messageTime.minute) == 1 then str = str .. '0' .. messageTime.minute else str = str .. messageTime.minute end return str .. append end function Message.receiveMessage(msg) msg['turn'] = messageCurrentTurn table.insert(messages, msg) end function Message.setCurrentTurn(turn) messageCurrentTurn = turn end function Message.sendTime(time) messageTime = time end --- Takes a passed text and returns either 'a' or 'an' based --- on which would be more grammatically correct preceding function Message.aOrAn(text) local check = {'a','e','o','i','u'} local letter = string.lower(string.sub(text, 1, 1)) local ret = 'a' for i = 1, # check do if letter == check[i] then ret = 'an' break end end return ret end return Message
Monsters = {} local numberOfEnemies = 5 local function hasValue (tab, val) for i,value in ipairs(tab) do if value.x == val.x then return true end end return false end function Monsters:init() math.randomseed(os.time()) while #Monsters < numberOfEnemies do local layer = Overworld.layers["Monsters"].objects math.random(#layer) local i = math.random(#layer) local obj = layer[i] local monster = { x = obj.x, y = obj.y, width = obj.width, height = obj.height, type = "Monster", isDead = false, animation = LoveAnimation.new('assets/sprites/monsterAnimation.lua') } if not hasValue(Monsters, monster) then print(i) World:add(monster, obj.x, obj.y, 8, 16) table.insert(Monsters, monster) end end end function Monsters:update(dt) for i,m in ipairs(Monsters) do m.animation:setPosition(m.x, m.y) m.animation:update(dt) end for i=#Monsters, 1, -1 do local m = Monsters[i] if m.isDead then if m.animation:getCurrentState() ~= "dead" then m.animation:setState("dead") m.animation:onStateEnd("dead", function() table.remove(Monsters, i) World:remove(m) end) end end end if #Monsters < numberOfEnemies then Monsters:init() end end
-- Importing modules local MGet = require "elasticsearch.endpoints.MGet" local parser = require "elasticsearch.parser" local MockTransport = require "lib.MockTransport" local getmetatable = getmetatable -- Setting up environment local _ENV = lunit.TEST_CASE "tests.endpoints.MGetTest" -- Declaring local variables local endpoint local mockTransport = MockTransport:new() -- Testing the constructor function constructorTest() assert_function(MGet.new) local o = MGet:new() assert_not_nil(o) local mt = getmetatable(o) assert_table(mt) assert_equal(mt, mt.__index) end -- The setup function function setup() endpoint = MGet:new{ transport = mockTransport } end -- Testing request function requestTest() mockTransport.method = "POST" mockTransport.uri = "/test/type/_mget" mockTransport.params = {} mockTransport.body = parser.jsonEncode{ ids = {"1", "2"} } endpoint:setParams{ index = "test", type = "type", body = { ids = {"1", "2"} } } local _, err = endpoint:request() assert_nil(err) end
local IComparable = require("api.IComparable") local IDrawable = require("api.gui.IDrawable") local Draw = require("api.Draw") local FigureDrawable = class.class("FigureDrawable", { IDrawable, IComparable }) function FigureDrawable:init(chip_id, color) self.batch = nil self.dirty = true self.chip_id = chip_id self.color = color or { 255, 255, 255 } self.color[4] = 150 end function FigureDrawable:serialize() self.batch = nil end function FigureDrawable:deserialize() self.dirty = true end function FigureDrawable:update(dt) end function FigureDrawable:draw(x, y, w, h, centered, rot) if self.dirty then self.batch = Draw.make_chip_batch("chip") self.dirty = false end -- >>>>>>>> shade2/module.hsp:577 :if %%1=531:pos 8,1058-chipCh(%%2):gcopy selChr,chi ... if self.chip_id and self.chip_id ~= "" then local width, height = self.batch:tile_size(self.chip_id) Draw.set_color(255, 255, 255, 255) self.batch:clear() self.batch:add(self.chip_id, x+8, y+2 - (height-48), width-16, height-8, self.color) self.batch:draw() end -- <<<<<<<< shade2/module.hsp:577 :if %%1=531:pos 8,1058-chipCh(%%2):gcopy selChr,chi .. end function FigureDrawable:compare(other) if self.chip_id ~= other.chip_id then return false end if self.color and other.color then return table.deepcompare(self.color, other.color) end return self.color == nil and other.color == nil end return FigureDrawable
print("Loading lua file") print("CTEST_FULL_OUTPUT") function initScene() print("in initScene()") transform = osg.PositionAttitudeTransform() geode = osg.Geode() shape = osg.ShapeDrawable() shape:setShape( osg.Sphere(osg.Vec3(0,0,0),15) ) geode:addDrawable(shape) transform:addChild(geode) return true end initScene()
-------------------------------- -- @module MovementData -- @extend Ref -- @parent_module ccs ---@class ccs.MovementData:ccs.Ref local MovementData = {} ccs.MovementData = MovementData -------------------------------- --- ---@param boneName string ---@return ccs.MovementBoneData function MovementData:getMovementBoneData(boneName) end -------------------------------- --- ---@param movBoneData ccs.MovementBoneData ---@return ccs.MovementData function MovementData:addMovementBoneData(movBoneData) end -------------------------------- --- ---@return ccs.MovementData function MovementData:create() end -------------------------------- --- js ctor ---@return ccs.MovementData function MovementData:MovementData() end return nil
local LookupTable, parent = torch.class('LookupTable_ft', 'nn.LookupTable') LookupTable.__version = 1 function LookupTable:__init(nIndex, nOutput, updateMask) parent.__init(self, nIndex, nOutput) self.updateMask = torch.ones(nIndex):view(nIndex, 1):expand(nIndex, nOutput) if updateMask ~= nil then self:setUpdateMask(updateMask) end end function LookupTable:setUpdateMask(updateMask) local nIndex = self.weight:size(1) local nOutput = self.weight:size(2) assert(updateMask:nElement() == nIndex) self.updateMask:copy( updateMask:view(nIndex, 1):expand(nIndex, nOutput) ) end function LookupTable:applyGradMask() -- a slow solution self.gradWeight:cmul( self.updateMask ) end -- we do not need to accumulate parameters when sharing LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG Bugtracker: https://forum.404rq.com/bug-reports Suggestions: https://forum.404rq.com/mta-servers-development Donations: https://www.404rq.com/donations Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- GUI components local work_window = nil local btn_accept = nil local btn_cancel = nil local lbl_info = nil local lst_skins = nil local cooldown = nil local cooldown2 = nil -- Global data local dummyped = nil local playerSkinID = 0 local playerCurrentSkin = 0 --[[ Create the job window ]]-- addEventHandler("onClientResourceStart", resourceRoot, function() -- Adding the gui local guiX,guiY = guiGetScreenSize() work_window = exports.GTWgui:createWindow(0, (guiY-350)/2, 372, 350, "Civilians", false) guiSetVisible(work_window, false) -- Tab panel tab_panel = guiCreateTabPanel(0, 30, 372, 276, false, work_window) tab_info = guiCreateTab("Information", tab_panel) tab_skin = guiCreateTab("Select skin", tab_panel) tab_weapons = guiCreateTab("Rent weapons/tools", tab_panel) -- Button accept btn_accept = guiCreateButton(10, 310, 110, 36, "Accept", false, work_window) guiSetProperty(btn_accept, "NormalTextColour", "FF00FF00") addEventHandler("onClientGUIClick", btn_accept, accept_work, false) exports.GTWgui:setDefaultFont(btn_accept, 10) -- Button close btn_cancel = guiCreateButton(252, 310, 110, 36, "Cancel", false, work_window) addEventHandler("onClientGUIClick", btn_cancel, close_guibutton, false) exports.GTWgui:setDefaultFont(btn_cancel, 10) -- Memo with info lbl_info = guiCreateMemo(0, 0, 1, 1, "Loading info...", true, tab_info) guiMemoSetReadOnly( lbl_info, true ) exports.GTWgui:setDefaultFont(lbl_info, 10) -- Skin selection list lst_skins = guiCreateGridList( 0, 0, 1, 1, true, tab_skin ) guiGridListSetSelectionMode( lst_skins, 2 ) guiGridListAddColumn( lst_skins, "Skin name", 0.65 ) guiGridListAddColumn( lst_skins, "ID", 0.15 ) exports.GTWgui:setDefaultFont(lst_skins, 10) guiGridListSetSelectionMode(lst_skins, 0) guiGridListSetSortingEnabled(lst_skins, false) -- Weapons and tools selection list lst_weapons = guiCreateGridList( 0, 0, 1, 1, true, tab_weapons ) guiGridListSetSelectionMode( lst_weapons, 2 ) guiGridListAddColumn( lst_weapons, "Weapon name", 0.5 ) guiGridListAddColumn( lst_weapons, "Ammo", 0.15 ) guiGridListAddColumn( lst_weapons, "Price", 0.15 ) guiGridListAddColumn( lst_weapons, "ID", 0.10 ) exports.GTWgui:setDefaultFont(lst_weapons, 10) guiGridListSetSelectionMode(lst_weapons, 0) guiGridListSetSortingEnabled(lst_weapons, false) -- Add all markers created by this system if any addMarkersAndClearTable() end) function addMarkersAndClearTable() -- Add job markers to the map for k, v in pairs(markers) do -- Unpack data local ID, inter,dim, x,y,z, j_type = unpack(v) if not ID or not inter or not dim or not x or not y or not z or not j_type then return end -- Update color profiles local red,green,blue = 255,150,0 if j_type == "government" then red,green,blue = 110,110,110 elseif j_type == "emergency" then red,green,blue = 0,150,255 end -- Create the marker local mark = createMarker(x, y, z-1, "cylinder", 2.0, red, green, blue, 70) if inter == 0 then createBlipAttachedTo( mark, 56, 2, 0, 0, 0, 0, 0, 180) end setElementInterior(mark, inter) setElementDimension(mark, dim) addEventHandler("onClientMarkerHit", mark, showGUI) addEventHandler("onClientMarkerLeave", mark, close_gui) setElementData( mark, "jobID", ID ) end -- Clear the table markers = { } end -- Check if a refresh is needed setTimer(addMarkersAndClearTable, 5000, 0) --[[ Shows the gui on marker hit and edit it's variables ]]-- function showGUI( hitElement, matchingdimension, jobID ) if not isTimer(cooldown) and hitElement and isElement(hitElement) and getElementType(hitElement) == "player" and not getPedOccupiedVehicle(hitElement) and getElementData(hitElement, "Jailed") ~= "Yes" and hitElement == localPlayer and matchingdimension then -- Get job id from marker local ID = "" if source then ID = getElementData( source, "jobID" ) else ID = jobID end local team, max_wl, description, skins, skin_names, work_tools, welcome_message = unpack(work_items[ID]) -- Check group membership local is_staff = exports.GTWstaff:isStaff(localPlayer) if restricted_jobs[ID] then if restricted_jobs[ID] ~= getElementData(localPlayer, "Group") and not is_staff then exports.GTWtopbar:dm( ID..": This job is restricted to: "..restricted_jobs[ID], 255, 100, 0 ) return end end -- Check wanted level if getPlayerWantedLevel() > max_wl then exports.GTWtopbar:dm( ID..": Go away, we don't hire criminals!", 255, 0, 0 ) return end if getElementData(localPlayer, "Occupation") == ID then guiSetEnabled(tab_info, false) guiSetEnabled(tab_skin, false) guiSetSelectedTab(tab_panel, tab_weapons) guiSetVisible(btn_accept, false) guiSetText(btn_cancel, "OK") else guiSetEnabled(tab_info, true) guiSetEnabled(tab_skin, true) guiSetSelectedTab(tab_panel, tab_info) guiSetVisible(btn_accept, true) guiSetText(btn_cancel, "Cancel") end -- Freeze the player setTimer(setElementFrozen, 250, 1, localPlayer, true) -- Move to skin selection area g_px,g_py,g_pz = getElementPosition(localPlayer) g_prx,g_pry,g_prz = getElementRotation(localPlayer) g_pdim = getElementDimension(localPlayer) g_pint = getElementInterior(localPlayer) fadeCamera(false) dummyped = createPed(0, -1618.2958984375, 1400.9755859375, 7.1753273010254, 180) -- Fade and move the camera local new_dim = math.random(100,200) setTimer(fadeCamera, 1000, 1, true) setTimer(setElementDimension, 1000, 1, localPlayer, new_dim) setTimer(setElementInterior, 1000, 1, localPlayer, 0) setTimer(setElementDimension, 1000, 1, dummyped, new_dim) setTimer(setElementInterior, 1000, 1, dummyped, 0) setTimer(setCameraMatrix, 1000, 1, -1618.2958984375, 1398, 7.1753273010254, -1618.2958984375, 1400.9755859375, 7.1753273010254, 5, 100) -- Set GUI information and save skin information guiSetText(lbl_info, ID.."\n"..description) setElementData(localPlayer, "jobID", ID) setElementData(localPlayer, "GTWcivilians.skins.current", getElementModel(localPlayer)) playerCurrentSkin = getElementModel(localPlayer) -- Clear skins list guiGridListClear( lst_skins ) -- Add category local tmp_row_cat = guiGridListAddRow( lst_skins ) guiGridListSetItemText( lst_skins, tmp_row_cat, 1,ID.." skins",true,false) -- Add available skins for k=1, #skins do if skins[k] == -1 then -- Alias for default skin local tmp_row = guiGridListAddRow( lst_skins ) guiGridListSetItemText( lst_skins, tmp_row, 1,"Default",false,false) elseif skins[k] > -1 then -- All other available skins local tmp_row = guiGridListAddRow( lst_skins ) guiGridListSetItemText( lst_skins,tmp_row,2,skins[k],false,false) guiGridListSetItemText( lst_skins,tmp_row,1,skin_names[k],false,false) end end -- Clear weapons list guiGridListClear( lst_weapons ) -- Add available weapons for i=1, #work_tools do local tmp_row = guiGridListAddRow( lst_weapons ) local wep_id,ammo,price,name = unpack(work_tools[i]) guiGridListSetItemText(lst_weapons,tmp_row,1, name, false,false) guiGridListSetItemText(lst_weapons,tmp_row,2, ammo, false,false) guiGridListSetItemText(lst_weapons,tmp_row,3, price, false,false) guiGridListSetItemText(lst_weapons,tmp_row,4, wep_id, false,false) end -- Select default item guiGridListSetSelectedItem( lst_skins, 0, 0 ) row,col = 0,0 -- Default setTimer(function() if skins[1] > -1 then setElementModel( dummyped, skins[1] ) playerSkinID = skins[1] else local currSkinID = tonumber(getElementData(localPlayer, "GTWclothes.personal.skin")) or 0 setElementModel( dummyped, currSkinID ) playerSkinID = currSkinID end end, 1000, 1) -- On skin change addEventHandler("onClientGUIClick",lst_skins, function() row,col = guiGridListGetSelectedItem( lst_skins ) if row and col and row > 0 then playerSkinID = (skins[row] or 0) if playerSkinID > -1 then setElementModel( dummyped, playerSkinID ) elseif playerSkinID == -1 then local currSkinID = tonumber(getElementData(localPlayer, "GTWclothes.personal.skin")) or 0 setElementModel( dummyped, currSkinID ) end end end) addEventHandler( "onClientGUIDoubleClick", lst_weapons, function( ) local r,c = guiGridListGetSelectedItem(lst_weapons) local name = guiGridListGetItemText(lst_weapons, r,1) local ammo = guiGridListGetItemText(lst_weapons, r,2) local price = guiGridListGetItemText(lst_weapons, r,3) local weapon_id = guiGridListGetItemText(lst_weapons, r,4) if not isTimer(cooldown2) and r > -1 and c > -1 then triggerServerEvent("GTWcivilians.buyTools", localPlayer, name, ammo, price, weapon_id) cooldown2 = setTimer(function() end, 200, 1) end end) -- Showing the gui setTimer(guiSetVisible, 1000, 1, work_window, true) setTimer(guiSetInputEnabled, 1000, 1, true) exports.GTWgui:showGUICursor(true) end end function staffWork(cmdName, ID) -- Configuration -- Setup by name if isPedDead( localPlayer ) then return end if cmdName ~= "gowork" then if cmdName == "gobusdriver" then ID = "Bus Driver" elseif cmdName == "gotrain" then ID = "Train Driver" elseif cmdName == "gotaxi" then ID = "Taxi Driver" elseif cmdName == "gotrucker" then ID = "Trucker" elseif cmdName == "gopilot" then ID = "Pilot" elseif cmdName == "gomechanic" then ID = "Mechanic" elseif cmdName == "gofisher" then ID = "Fisher" elseif cmdName == "gofarmer" then ID = "Farmer" elseif cmdName == "gotram" then ID = "Tram Driver" elseif cmdName == "gofireman" then ID = "Fireman" elseif cmdName == "gomedic" then ID = "Paramedic" elseif cmdName == "goironminer" then ID = "Iron miner" elseif cmdName == "golaw" then ID = "Police officer" elseif cmdName == "sapd" then ID = "SAPD officer" elseif cmdName == "swat" then ID = "SWAT officer" elseif cmdName == "fbi" then ID = "FBI agent" elseif cmdName == "army" then ID = "Armed forces" end end -- Check if a user is in the staff team, if so, allow access local is_staff = exports.GTWstaff:isStaff(localPlayer) if not is_staff and restricted_jobs[ID] and restricted_jobs[ID] ~= getElementData(localPlayer, "Group") then exports.GTWtopbar:dm( ID..": Only staff and official groups can use this command!", 255, 100, 0 ) return end if ID then showGUI(localPlayer, true, ID) end end addCommandHandler( "gowork", staffWork ) addCommandHandler( "gobusdriver", staffWork ) addCommandHandler( "gotrucker", staffWork ) addCommandHandler( "gotaxi", staffWork ) addCommandHandler( "gotrain", staffWork ) addCommandHandler( "gopilot", staffWork ) addCommandHandler( "gofisher", staffWork ) addCommandHandler( "gofarmer", staffWork ) addCommandHandler( "gomechanic", staffWork ) addCommandHandler( "gotram", staffWork ) addCommandHandler( "gofireman", staffWork ) addCommandHandler( "gomedic", staffWork ) addCommandHandler( "goironminer", staffWork ) addCommandHandler( "golaw", staffWork ) -- Group commands addCommandHandler( "fbi", staffWork ) addCommandHandler( "swat", staffWork ) addCommandHandler( "sapd", staffWork ) addCommandHandler( "army", staffWork ) --[[ Closes the GUI on marker leave ]]-- function close_gui( leaveElement, matchingdimension ) if ( leaveElement and isElement(leaveElement) and getElementType(leaveElement) == "player" and not getPedOccupiedVehicle(leaveElement) and leaveElement == localPlayer and matchingdimension ) then end end --[[ When the user clicks on the Accept job button ]]-- function accept_work() -- Trigger server event local ID = getElementData(localPlayer, "jobID") if not playerSkinID then playerSkinID = 0 end -- Accept job if ID then triggerServerEvent("GTWcivilians.accept", localPlayer, ID, playerSkinID) end -- Reset camera details fadeCamera(false) setTimer(reset_close_gui, 1000, 1) cooldown = setTimer(function() end, 3000, 1) -- Unfreeze player setTimer(setElementFrozen, 2000, 1, localPlayer, false) -- Closing the gui guiSetVisible( work_window, false ) guiSetInputEnabled( false ) exports.GTWgui:showGUICursor( false ) -- Display job info message in chat box local team, max_wl, description, skins, skin_names, work_tools, welcome_message = unpack(work_items[ID]) outputChatBox("["..ID.."]#FFFFFF "..welcome_message, 200,200,200, true) end --[[ When the user clicks on the Close button ]]-- function close_guibutton() -- Closing the gui guiSetVisible( work_window, false ) guiSetInputEnabled( false ) exports.GTWgui:showGUICursor( false ) -- Unfreeze player setTimer(setElementFrozen, 2000, 1, localPlayer, false) -- Reset camera details fadeCamera(false) setTimer(reset_close_gui, 1000, 1) cooldown = setTimer(function() end, 3000, 1) -- Reset Skin --local skinID = getElementData(localPlayer, "GTWcivilians.skins.current") or 0 --setElementModel(localPlayer, skinID) end function reset_close_gui() -- Fade and move the camera back to default fadeCamera(true) setElementDimension(localPlayer, g_pdim) setElementInterior(localPlayer, g_pint) setElementPosition(localPlayer, g_px,g_py,g_pz) setElementRotation(localPlayer, g_prx,g_pry,g_prz) destroyElement(dummyped) setCameraTarget(localPlayer) setElementFrozen(localPlayer, false) end
--[[ lexer.lua Created by Masatoshi Teruya on 14/04/28. Copyright 2014 Masatoshi Teruya. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] -- patterns local PAT_SYMBOL = '[-+*/^.<>=~"\'(){}%%%[%],:;#%s]'; local PAT_NONIDENT = '[^%w_]'; local PAT_NUMBER = '%d+'; local PAT_TRIM = '^[%s]*(.*[^%s])[%s]*$'; -- types local T_EPAIR = -1; local T_UNKNOWN = 0; local T_SPACE = 1; local T_LITERAL = 2; local T_LABEL = 3; local T_VAR = 4; local T_MEMBER = 5; local T_VLIST = 6; local T_KEYWORD = 7; local T_OPERATOR = 8; local T_NUMBER = 9; local T_BRACKET_OPEN = 10; local T_BRACKET_CLOSE = 11; local T_PAREN_OPEN = 12; local T_PAREN_CLOSE = 13; local T_CURLY_OPEN = 14; local T_CURLY_CLOSE = 15; -- set keywords local KEYWORD = {}; do for _, v in ipairs({ 'break', 'goto', 'do', 'end', 'while', 'repeat', 'until', 'for', 'in', 'if', 'elseif', 'else', 'then', 'function', 'return', 'local', 'true', 'false', 'nil' }) do KEYWORD[v] = T_KEYWORD; end end -- symbol type table local SYMBOL_TYPE = { [' '] = T_SPACE, ['::'] = T_LABEL, ['.'] = T_MEMBER, [':'] = T_MEMBER, [','] = T_VLIST, ['['] = T_BRACKET_OPEN, [']'] = T_BRACKET_CLOSE, ['('] = T_PAREN_OPEN, [')'] = T_PAREN_CLOSE, ['{'] = T_CURLY_OPEN, ['}'] = T_CURLY_CLOSE }; do -- literal for _, v in ipairs({ '"', '\'', '[[', ']]', '[=' }) do SYMBOL_TYPE[v] = T_LITERAL; end -- operator for _, v in ipairs({ '+', '-', '*', '/', '%', '^', ';', '..', '<', '<=', '>', '>=', '=', '==', '~=', '#', 'and', 'or', 'not' }) do SYMBOL_TYPE[v] = T_OPERATOR; end end -- symbol look-ahead table local SYMBOL_LA = {}; do for _, v in ipairs({ '+', '-', '*', '/', '%', '^', ',', ';', '(', ')', '{', '}', '"', '\'', '#', ']' }) do SYMBOL_LA[v] = 0; end for _, v in ipairs({ '.', '[', '<', '>', '=', '~', ':' }) do SYMBOL_LA[v] = 1; end end local function trim( str ) return str:match( PAT_TRIM ); end local function handleBracketLiteralToken( state, head, tail, token ) local category = SYMBOL_TYPE[token]; local lhead, ltail, pat; if token == '[[' then pat = ']]'; else -- find end of open bracket lhead, ltail = state.expr:find( '^%[=+%[', head ); if not lhead then state.error = T_EPAIR; return head, tail, T_EPAIR, token; end -- update tail index tail = ltail; -- create close bracket pattern pat = ']' .. state.expr:sub( lhead + 1, ltail - 1 ) .. ']'; end lhead = tail; while( lhead ) do lhead, ltail = state.expr:find( pat, lhead + 1, true ); -- found close symbol and not escape sequence: [\] at front if lhead and state.expr:byte( lhead - 1 ) ~= 0x5C then -- substruct literal token = state.expr:sub( head, ltail ); -- update cursor state.cur = ltail + 1; return head, ltail, category, token; end end state.error = T_EPAIR; return head, tail, T_EPAIR, token; end local function handleEnclosureToken( state, head, tail, token ) if token ~= ']]' then local category = SYMBOL_TYPE[token]; local pat = token; local lhead = tail; local ltail; while( lhead ) do lhead, ltail = state.expr:find( pat, lhead + 1, true ); -- found close symbol and not escape sequence: [\] at front if lhead and state.expr:byte( lhead - 1 ) ~= 0x5C then -- substruct literal token = state.expr:sub( head, ltail ); -- update cursor state.cur = ltail + 1; return head, ltail, category, token; end end end state.error = T_EPAIR; return head, tail, T_EPAIR, token; end local function handleSymToken( state, head, tail, token ) local category = token == '~' and T_OPERATOR or SYMBOL_TYPE[token]; if not category then category = T_UNKNOWN; elseif category == T_LITERAL then return handleEnclosureToken( state, head, tail, token ); elseif category == T_OPERATOR or category == T_MEMBER or category == T_BRACKET_OPEN or category == T_BRACKET_CLOSE then local len = SYMBOL_LA[token]; -- check next char if len > 0 then local chk = state.expr:sub( head, head + len ); local t = SYMBOL_TYPE[chk]; if t == T_OPERATOR then token = chk; tail = head + len; category = t; elseif t == T_LITERAL or t == T_LABEL then token = chk; tail = head + len; -- bracket literal if token:byte( 1 ) == 0x5B then return handleBracketLiteralToken( state, head, tail, token ); end return handleEnclosureToken( state, head, tail, token ); end end end -- update cursor state.cur = tail + 1; return head, tail, category, token; end local function handleNameToken( state, head, tail, token ) local shead, stail = token:find( PAT_NONIDENT ); local category; -- found unknown symbol if shead then category = T_UNKNOWN; if shead == 1 then token = token:sub( shead, stail ); tail = head; else token = token:sub( 1, shead - 1 ); tail = tail - shead; end else category = KEYWORD[token] or SYMBOL_TYPE[token]; if not category then if token:find( PAT_NUMBER ) then category = T_NUMBER; else category = T_VAR; end end end -- update cursor state.cur = tail + 1; return head, tail, category, token; end local function nextToken( state ) local head, tail, token, handle; if state.error or state.cur >= state.len then return head, tail; end -- lookup symbol head, tail = state.expr:find( PAT_SYMBOL, state.cur ); -- found symbol if head then -- substract symbol token if state.cur == head then token = state.expr:sub( head, tail ); handle = handleSymToken; -- substract left token else token = trim( state.expr:sub( state.cur, head - 1 ) ); tail = head - 1; head = state.cur; handle = handleNameToken; end -- substract remain else head = state.cur; tail = state.len; token = trim( state.expr:sub( head ) ); handle = handleNameToken; end return handle( state, head, tail, token ); end local function scan( expr ) return nextToken, { iden = false, expr = expr, len = #expr + 1, cur = 1, head = 0, tail = 0 }, 1; end return { scan = scan, -- types T_EPAIR = T_EPAIR, T_UNKNOWN = T_UNKNOWN, T_SPACE = T_SPACE, T_LITERAL = T_LITERAL, T_LABEL = T_LABEL, T_VAR = T_VAR, T_MEMBER = T_MEMBER, T_VLIST = T_VLIST, T_KEYWORD = T_KEYWORD, T_OPERATOR = T_OPERATOR, T_NUMBER = T_NUMBER, T_BRACKET_OPEN = T_BRACKET_OPEN, T_BRACKET_CLOSE = T_BRACKET_CLOSE, T_PAREN_OPEN = T_PAREN_OPEN, T_PAREN_CLOSE = T_PAREN_CLOSE, T_CURLY_OPEN = T_CURLY_OPEN, T_CURLY_CLOSE = T_CURLY_CLOSE };
pg = pg or {} pg.enemy_data_statistics_322 = { [14601102] = { cannon = 20, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, speed = 25, dodge = 11, id = 14601102, cannon_growth = 936, rarity = 4, reload_growth = 0, dodge_growth = 162, luck = 0, star = 4, hit = 14, antisub_growth = 0, air_growth = 0, reload = 150, base = 466, durability = 760, armor_growth = 0, torpedo_growth = 3366, luck_growth = 0, antiaircraft_growth = 3744, armor = 0, torpedo = 27, durability_growth = 30500, antisub = 0, antiaircraft = 28, battle_unit_type = 55, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003117, 1003122, 1003127, 1003132 }, buff_list = {} }, [14601103] = { cannon = 24, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, speed = 18, dodge = 7, id = 14601103, cannon_growth = 2016, rarity = 4, reload_growth = 0, dodge_growth = 102, luck = 0, star = 4, hit = 14, antisub_growth = 0, air_growth = 0, reload = 150, base = 467, durability = 890, armor_growth = 0, torpedo_growth = 2763, luck_growth = 0, antiaircraft_growth = 2880, armor = 0, torpedo = 33, durability_growth = 41600, antisub = 0, antiaircraft = 35, battle_unit_type = 60, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003137, 1003142, 1003147, 1003152 }, buff_list = {} }, [14601104] = { cannon = 31, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, speed = 18, dodge = 3, id = 14601104, cannon_growth = 2592, rarity = 3, reload_growth = 0, dodge_growth = 48, luck = 0, star = 4, hit = 14, antisub_growth = 0, air_growth = 0, reload = 150, base = 468, durability = 1360, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, antiaircraft_growth = 3744, armor = 0, torpedo = 0, durability_growth = 59840, antisub = 0, antiaircraft = 45, battle_unit_type = 65, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003157, 1003162, 1003167, 1003172 }, buff_list = { { ID = 50510, LV = 2 } } }, [14601105] = { cannon = 0, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 44, speed = 18, dodge = 5, id = 14601105, cannon_growth = 0, rarity = 3, reload_growth = 0, dodge_growth = 72, luck = 0, star = 4, hit = 14, antisub_growth = 0, air_growth = 3627, reload = 150, base = 469, durability = 1070, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, antiaircraft_growth = 3744, armor = 0, torpedo = 0, durability_growth = 54400, antisub = 0, antiaircraft = 45, battle_unit_type = 70, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003177, 1003182, 1003187, 1003192 }, buff_list = {} }, [14601201] = { cannon = 28, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, luck = 4, dodge = 14, cannon_growth = 1600, speed = 20, reload = 150, reload_growth = 0, dodge_growth = 198, antisub = 0, torpedo = 52, hit = 14, antisub_growth = 0, air_growth = 0, durability_growth = 125600, base = 466, durability = 1480, armor_growth = 0, torpedo_growth = 2000, luck_growth = 0, battle_unit_type = 90, armor = 0, antiaircraft = 115, antiaircraft_growth = 3600, id = 14601201, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003117, 1003122, 1003127, 1003132, 1003197, 1003206 }, buff_list = {} }, [14601202] = { cannon = 30, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, speed = 20, dodge = 12, id = 14601202, cannon_growth = 1700, rarity = 3, reload_growth = 0, dodge_growth = 170, luck = 4, star = 4, hit = 14, antisub_growth = 0, air_growth = 0, reload = 150, base = 467, durability = 1820, armor_growth = 0, torpedo_growth = 1500, luck_growth = 0, antiaircraft_growth = 3200, armor = 0, torpedo = 24, durability_growth = 133600, antisub = 0, antiaircraft = 95, battle_unit_type = 90, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003137, 1003142, 1003147, 1003152, 1003197, 1003212, 1003252 }, buff_list = {} }, [14601203] = { cannon = 28, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, luck = 4, dodge = 14, cannon_growth = 1600, speed = 20, reload = 150, reload_growth = 0, dodge_growth = 198, antisub = 0, torpedo = 52, hit = 14, antisub_growth = 0, air_growth = 0, durability_growth = 125600, base = 466, durability = 1480, armor_growth = 0, torpedo_growth = 2000, luck_growth = 0, battle_unit_type = 90, armor = 0, antiaircraft = 115, antiaircraft_growth = 3600, id = 14601203, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003117, 1003122, 1003127, 1003132, 1003197, 1003207 }, buff_list = {} }, [14601204] = { cannon = 34, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, speed = 20, dodge = 12, id = 14601204, cannon_growth = 1700, rarity = 3, reload_growth = 0, dodge_growth = 170, luck = 4, star = 4, hit = 14, antisub_growth = 0, air_growth = 0, reload = 150, base = 467, durability = 1820, armor_growth = 0, torpedo_growth = 1500, luck_growth = 0, antiaircraft_growth = 3200, armor = 0, torpedo = 27, durability_growth = 133600, antisub = 0, antiaircraft = 95, battle_unit_type = 90, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003137, 1003142, 1003147, 1003152, 1003197, 1003212, 1003252 }, buff_list = {} }, [14601205] = { cannon = 55, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, luck = 4, dodge = 11, cannon_growth = 1600, speed = 20, reload = 150, reload_growth = 0, dodge_growth = 156, antisub = 0, torpedo = 80, hit = 14, antisub_growth = 0, air_growth = 0, durability_growth = 125600, base = 466, durability = 1480, armor_growth = 0, torpedo_growth = 2000, luck_growth = 0, battle_unit_type = 90, armor = 0, antiaircraft = 145, antiaircraft_growth = 3600, id = 14601205, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003117, 1003122, 1003127, 1003132, 1003197, 1003207 }, buff_list = {} }, [14601206] = { cannon = 61, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, speed = 20, dodge = 11, id = 14601206, cannon_growth = 1700, rarity = 3, reload_growth = 0, dodge_growth = 156, luck = 4, star = 4, hit = 14, antisub_growth = 0, air_growth = 0, reload = 150, base = 467, durability = 2010, armor_growth = 0, torpedo_growth = 1500, luck_growth = 0, antiaircraft_growth = 3200, armor = 0, torpedo = 55, durability_growth = 128000, antisub = 0, antiaircraft = 120, battle_unit_type = 90, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003137, 1003142, 1003147, 1003152, 1003197, 1003212, 1003252 }, buff_list = {} }, [14601207] = { cannon = 120, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, speed = 20, dodge = 11, id = 14601207, cannon_growth = 3600, rarity = 3, reload_growth = 0, dodge_growth = 156, luck = 4, star = 4, hit = 14, antisub_growth = 0, air_growth = 0, reload = 150, base = 468, durability = 3850, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, antiaircraft_growth = 3200, armor = 0, torpedo = 0, durability_growth = 249600, antisub = 0, antiaircraft = 135, battle_unit_type = 90, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "appearQ" }, equipment_list = { 1003157, 1003162, 1003167, 1003172, 1003197 }, buff_list = { { ID = 50500, LV = 2 } } }, [14601301] = { cannon = 120, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, speed = 16, dodge = 14, id = 14601301, cannon_growth = 0, rarity = 4, reload_growth = 0, dodge_growth = 156, luck = 8, star = 4, hit = 14, antisub_growth = 0, air_growth = 0, reload = 150, base = 467, durability = 21800, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, antiaircraft_growth = 0, armor = 0, torpedo = 114, durability_growth = 0, antisub = 0, antiaircraft = 165, scale = 144, battle_unit_type = 95, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "bossguangxiao", "appearQ" }, equipment_list = { 771001, 771002, 771003, 771004, 771005 }, buff_list = {} }, [14601302] = { cannon = 160, hit_growth = 210, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, speed = 20, dodge = 11, id = 14601302, cannon_growth = 0, rarity = 3, reload_growth = 0, dodge_growth = 108, luck = 8, star = 4, hit = 16, antisub_growth = 0, air_growth = 0, reload = 150, base = 468, durability = 24680, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, antiaircraft_growth = 0, armor = 0, torpedo = 0, durability_growth = 0, antisub = 0, antiaircraft = 180, scale = 144, battle_unit_type = 95, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "bossguangxiao", "appearQ" }, equipment_list = { 771101, 771102, 771103, 771104, 771105, 771106 }, buff_list = { { ID = 50500, LV = 2 } } }, [14601303] = { cannon = 180, battle_unit_type = 95, bubble_fx = "", speed_growth = 0, pilot_ai_template_id = 10001, air = 0, luck = 8, dodge = 14, cannon_growth = 0, speed = 18, reload = 150, reload_growth = 0, dodge_growth = 156, antisub = 0, torpedo = 120, hit = 14, antisub_growth = 0, air_growth = 0, durability_growth = 0, base = 519, durability = 31500, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, hit_growth = 210, armor = 0, antiaircraft = 360, antiaircraft_growth = 0, id = 14601303, scale = 144, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, specific_fx_scale = {}, appear_fx = { "bossguangxiao", "appearQ" }, equipment_list = { 771210 }, buff_list = { { ID = 50500, LV = 2 } } }, [14601304] = { cannon = 40, reload = 150, speed_growth = 0, cannon_growth = 1000, pilot_ai_template_id = 20006, air = 0, base = 520, dodge = 0, durability_growth = 50000, antiaircraft = 0, speed = 50, reload_growth = 0, dodge_growth = 0, luck = 0, battle_unit_type = 40, hit = 35, antisub_growth = 0, air_growth = 0, antiaircraft_growth = 1000, torpedo = 0, durability = 4000, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, hit_growth = 144, armor = 0, id = 14601304, bubble_fx = "", antisub = 0, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, equipment_list = {}, buff_list = {} }, [14602001] = { cannon = 7, reload = 150, speed_growth = 0, cannon_growth = 560, pilot_ai_template_id = 20005, air = 0, base = 123, dodge = 0, durability_growth = 10000, antiaircraft = 60, speed = 15, reload_growth = 0, dodge_growth = 0, luck = 0, battle_unit_type = 25, hit = 10, antisub_growth = 0, air_growth = 0, antiaircraft_growth = 1000, torpedo = 33, durability = 300, armor_growth = 0, torpedo_growth = 3250, luck_growth = 0, hit_growth = 144, armor = 0, id = 14602001, bubble_fx = "", antisub = 0, world_enhancement = { 0, 0, 0, 0, 0, 0, 0 }, equipment_list = { 1000592, 1000597, 1000602 }, buff_list = {} } } return
return { HOOK_EXECUTE_COMMAND = { CalledWhen = "A player executes an in-game command, or the admin issues a console command. Note that built-in console commands are exempt to this hook - they are always performed and the hook is not called.", DefaultFnName = "OnExecuteCommand", -- also used as pagename Desc = [[ A plugin may implement a callback for this hook to intercept both in-game commands executed by the players and console commands executed by the server admin. The function is called for every in-game command sent from any player and for those server console commands that are not built in in the server.</p> <p> If the command is in-game, the first parameter to the hook function is the {{cPlayer|player}} who's executing the command. If the command comes from the server console, the first parameter is nil. ]], Params = { { Name = "Player", Type = "{{cPlayer}}", Notes = "For in-game commands, the player who has sent the message. For console commands, nil" }, { Name = "Command", Type = "table of strings", Notes = "The command and its parameters, broken into a table by spaces" }, }, Returns = [[ If the plugin returns true, the command will be blocked and none of the remaining hook handlers will be called. If the plugin returns false, MCServer calls all the remaining hook handlers and finally the command will be executed. ]], }, -- HOOK_EXECUTE_COMMAND }
object_tangible_collection_rebel_battle_leggings = object_tangible_collection_shared_rebel_battle_leggings:new { gameObjectType = 8211,} ObjectTemplates:addTemplate(object_tangible_collection_rebel_battle_leggings, "object/tangible/collection/rebel_battle_leggings.iff")
local Theme = require 'supernova.core.theme' local Style = require 'supernova.core.style' local ANSI = require 'supernova.core.ansi' local ChainMetatable = require 'supernova.core.chain_metatable' local Color = require 'supernova.core.color' local Sgr = require 'supernova.core.sgr' local Controller = { is_controller = true, enabled = true, chain = {}, style_to_register = nil, handlers = { default = {} }, styles = { default = {} }, active_theme = 'default', colors = 'true-color' } function Controller:init() self.enabled = true self.chain = {} self.style_to_register = nil self.handlers = { default = {} } self.styles = { default = {} } self.active_theme = 'default' -- TODO: -- 0 8 16 256 true-color self.colors = 'true-color' -- echo $COLORTERM local env_colors = os.getenv('SUPERNOVA_COLORS') if env_colors ~= nil then if tostring(tonumber(env_colors)) == env_colors then self.colors = tonumber(env_colors) elseif env_colors == 't' or env_colors == 'true_color' then self.colors = 'true-color' else self.colors = env_colors end end self.handlers.default['apply_command'] = Controller.apply_command for _, style in pairs(ANSI.SGR_COMMANDS) do Style.register(self, style) end Style.register(self, { identifier = 'gradient', command = 'gradient' }) Style.register(self, { identifier = 'bg_gradient', command = 'bg_gradient' }) Style.register(self, { identifier = 'background_gradient', command = 'background_gradient' }) end function Controller:set_colors(colors) if colors == 't' or colors == 'true_color' then colors = 'true-color' end self.colors = colors end Controller['set-colors'] = Controller.set_colors function Controller:enable() self.enabled = true end function Controller:disable() self.enabled = false end function Controller:set_theme(theme) Theme.set(self, theme) end Controller['set-theme'] = Controller.set_theme function Controller:get_theme(identifier) return Theme.get(self, identifier) end Controller['get-theme'] = Controller.get_theme function Controller.apply_command(a, b, c, d, e, f) local instance, content, command, extra if type(a) == 'table' and a.is_controller then instance, content, command = a, b, c extra = {d, e, f} else content, command = a, b extra = {c, d, e} end if instance ~= nil and not instance.enabled then return content end local colors = 'true-color' if instance ~= nil then colors = instance.colors end if command == 'gradient' or command == 'bg_gradient' or command == 'background_gradient' then local sgr_code = ANSI.SGR_CODES.color if command == 'bg_gradient' or command == 'background_gradient' then sgr_code = ANSI.SGR_CODES.background end if type(extra[1]) ~= 'table' and extra[2] ~= nil then return Color.apply_gradient(content, sgr_code, { extra[1], extra[2] }, colors) else return Color.apply_gradient(content, sgr_code, extra[1], colors) end elseif( command == ANSI.SGR_CODES.color or command == ANSI.SGR_CODES.background or command == ANSI.SGR_CODES.underline_color ) then if type(extra[1]) == 'string' then return Color.apply_string(content, command, extra[1], colors) elseif type(extra[1]) == 'table' then return Color.apply_rgb(content, command, extra[1], colors) elseif extra[3] ~= nil then return Color.apply_rgb(content, command, { extra[1], extra[2], extra[3] }, colors) else return Color.apply_code(content, command, extra[1], colors) end end local sgr_modifier = nil if type(extra[1]) == 'boolean' and extra[1] then sgr_modifier = '1' end if ( (command >= 30 and command <= 37) or (command >= 40 and command <= 47) or (command >= 90 and command <= 97) or (command >= 100 and command <= 107) ) then return Color.apply_sgr_code(content, command, sgr_modifier, colors) end return Sgr.apply(content, command, sgr_modifier) end Controller = setmetatable(Controller, ChainMetatable) return Controller
-- Requirements local composer = require "composer" local fx = require "com.ponywolf.ponyfx" -- Variables local to scene local scene = composer.newScene() local field, moon, ship, stars, info, music function scene:create( event ) local sceneGroup = self.view -- add display objects to this group -- music music = audio.loadSound("scene/menu/sfx/titletheme.mp3") -- load our title sceen field = display.newImage(sceneGroup, "scene/menu/img/field.png", display.contentCenterX, display.contentCenterY) stars = display.newImage(sceneGroup, "scene/menu/img/stars.png", display.contentCenterX, display.contentCenterY) ship = display.newImage(sceneGroup, "scene/menu/img/ship.png", display.contentCenterX, display.contentCenterY) moon = display.newImage(sceneGroup, "scene/menu/img/moon.png", display.contentCenterX, display.actualContentHeight) -- place everything moon.anchorY = 1 moon.xScale, moon.yScale = 1.0, 1.0 field.xScale, field.yScale = 3, 3 stars.xScale, stars.yScale = 3, 3 ship.xScale, ship.yScale = 2, 2 -- title and help text local txt = { parent = sceneGroup, x=display.contentCenterX, y=100, text="Match Three Space RPG", font="scene/menu/font/Dosis-Bold.ttf", fontSize=68 } local title = display.newText(txt) txt = { parent = sceneGroup, x=display.contentCenterX, y=220, text="Tap/Click to Begin", font="scene/menu/font/Dosis-Bold.ttf", fontSize=52 } local help = display.newText(txt) fx.bounce(help) function sceneGroup:tap() composer.gotoScene( "scene.help", { effect = "slideDown", params = { } }) end sceneGroup:addEventListener("tap") end local function enterFrame(event) local elapsed = event.time field:rotate(0.1) stars:rotate(0.15) ship:rotate(-0.2) end function scene:show( event ) local phase = event.phase if ( phase == "will" ) then Runtime:addEventListener("enterFrame", enterFrame) elseif ( phase == "did" ) then audio.play(music, { loops = -1, fadein = 750, channel = 16 } ) end end function scene:hide( event ) local phase = event.phase if ( phase == "will" ) then audio.fadeOut( {channel = 16, time = 1500 } ) elseif ( phase == "did" ) then Runtime:removeEventListener("enterFrame", enterFrame) end end function scene:destroy( event ) audio.stop() audio.dispose(music) end scene:addEventListener("create") scene:addEventListener("show") scene:addEventListener("hide") scene:addEventListener("destroy") return scene
local server = require('test.luatest_helpers.server') local t = require('luatest') local g = t.group() g.before_all = function() g.server = server:new{ alias = 'default', } g.server:start() end g.after_all = function() g.server:drop() end g.test_different_logs_on_new_and_free = function() g.server:exec(function() local s = box.schema.create_space('test') s:create_index('pk') box.cfg{log_level = 7} s:replace{0, 0, 0, 0, 0, 0, 0} box.cfg{log_level = 5} end) local str = g.server:grep_log('tuple_new[%w_]*%(%d+%) = 0x%x+$', 1024) local new_tuple_address = string.match(str, '0x%x+$') new_tuple_address = string.sub(new_tuple_address, 3) g.server:exec(function() box.cfg{log_level = 7} box.space.test:replace{0, 1} collectgarbage('collect') box.cfg{log_level = 5} end) str = g.server:grep_log('tuple_delete%w*%(0x%x+%)', 1024) local deleted_tuple_address = string.match(str, '0x%x+%)') deleted_tuple_address = string.sub(deleted_tuple_address, 3, -2) t.assert_equals(new_tuple_address, deleted_tuple_address) end
----------------------------------- -- Area: Lower Jeuno -- NPC: Zauko -- Involved in Quests: Save the Clock Tower, Community Service -- !pos -3 0 11 245 ----------------------------------- require("scripts/zones/Lower_Jeuno/globals") local ID = require("scripts/zones/Lower_Jeuno/IDs") require("scripts/globals/keyitems") require("scripts/globals/npc_util") require("scripts/globals/quests") require("scripts/globals/status") require("scripts/globals/titles") ----------------------------------- function onTrade(player, npc, trade) ----- Save The Clock Tower Quest ----- if (trade:hasItemQty(555, 1) == true and trade:getItemCount() == 1) then a = player:getCharVar("saveTheClockTowerNPCz2") -- NPC Zone2 if (a == 0 or (a ~= 256 and a ~= 288 and a ~= 320 and a ~= 384 and a ~= 768 and a ~= 352 and a ~= 896 and a ~= 416 and a ~= 832 and a ~= 448 and a ~= 800 and a ~= 480 and a ~= 864 and a ~= 928 and a ~= 960 and a ~= 992)) then player:startEvent(50, 10 - player:getCharVar("saveTheClockTowerVar")) -- "Save the Clock Tower" Quest end end end function onTrigger(player, npc) local hour = VanadielHour() local playerOnQuestId = GetServerVariable("[JEUNO]CommService") local doneCommService = (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.COMMUNITY_SERVICE) == QUEST_COMPLETED) and 1 or 0 local currCommService = player:getCharVar("currCommService") local hasMembershipCard = player:hasKeyItem(tpz.ki.LAMP_LIGHTERS_MEMBERSHIP_CARD) and 1 or 0 local allLampsLit = true for i=0, 11 do local lamp = GetNPCByID(ID.npc.STREETLAMP_OFFSET + i) if (lamp:getAnimation() == tpz.anim.CLOSE_DOOR) then allLampsLit = false break end end -- quest has already been accepted. if (currCommService == 1) then if (playerOnQuestId ~= player:getID()) then player:startEvent(119) -- quest left over from previous day. fail quest. else if (hour >= 18 and hour < 21) then player:startEvent(115) -- tell player it's too early to start lighting lamps. elseif (allLampsLit) then player:startEvent(117, doneCommService) -- all lamps are lit. win quest. elseif (hour >= 21 or hour < 1) then player:startEvent(114) -- tell player they can start lighting lamps. else SetServerVariable("[JEUNO]CommService", -1) -- frees player from quest, but don't allow anyone else to take it today. player:startEvent(119) -- player didn't light lamps in time. fail quest. end end -- quest is available to player, nobody is currently on it, and the hour is right elseif (player:getFameLevel(JEUNO) >= 1 and playerOnQuestId == 0 and (hour >= 18 or hour < 1)) then player:startEvent(116, doneCommService) -- default dialog including option to drop membership card else player:startEvent(118, hasMembershipCard) end end function onEventUpdate(player, csid, option) if (csid == 116 and option == 0) then -- player accepts quest -- if nobody else has already been assigned to the quest, including Vhana, give it to this player local doneCommService = (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.COMMUNITY_SERVICE) == QUEST_COMPLETED) and 1 or 0 local playerOnQuestId = GetServerVariable("[JEUNO]CommService") local hour = VanadielHour() if (playerOnQuestId == 0 and (hour >= 18 or hour < 1)) then -- nobody is currently on the quest SetServerVariable("[JEUNO]CommService", player:getID()) player:addQuest(JEUNO, tpz.quest.id.jeuno.COMMUNITY_SERVICE) player:setCharVar("currCommService", 1) player:updateEvent(1, doneCommService) else -- either another player or vasha have been assigned the quest player:updateEvent(0, doneCommService) end end end function onEventFinish(player, csid, option) -- SAVE THE CLOCKTOWER if (csid == 50) then player:addCharVar("saveTheClockTowerVar", 1) player:addCharVar("saveTheClockTowerNPCz2", 256) -- COMMUNITY SERVICE elseif (csid == 117) then local params = {title = tpz.title.TORCHBEARER, var = "currCommService"} if (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.COMMUNITY_SERVICE) ~= QUEST_COMPLETED) then -- first victory params.fame = 30 else -- repeat victory. offer membership card. params.fame = 15 if (option == 1) then params.keyItem = tpz.ki.LAMP_LIGHTERS_MEMBERSHIP_CARD end end npcUtil.completeQuest(player, JEUNO, tpz.quest.id.jeuno.COMMUNITY_SERVICE, params) elseif (csid == 118 and option == 1) then -- player drops membership card player:delKeyItem(tpz.ki.LAMP_LIGHTERS_MEMBERSHIP_CARD) elseif (csid == 119) then -- player fails quest player:setCharVar("currCommService", 0) end end
-- TrafficConeGod local VECTOR3_NEW = Vector3.new return function(Sunshine, entity) local transform = entity.transform local oscillator = entity.oscillator if transform and oscillator then local cFrame = transform.cFrame Sunshine:update(function() local offset = math.sin(entity.core.tick * oscillator.frequency) * oscillator.amplitude if oscillator.axis == "x" then transform.cFrame = cFrame + VECTOR3_NEW(offset, 0, 0) elseif oscillator.axis == "y" then transform.cFrame = cFrame + VECTOR3_NEW(0, offset, 0) elseif oscillator.axis == "z" then transform.cFrame = cFrame + VECTOR3_NEW(0, 0, offset) end end, entity) end end
require"luarocks.require" require"luarocks.pack" require"luarocks.build" require"luarocks.make_manifest" pcall("require", "luadoc") require"lfs" require"markdown" require"cosmo" require"logging" require"logging.console" --pcall("require", "luadoc") require"luadoc" taglet = require"luadoc.taglet.standard" --------------------------------------------------------------------------------------------------- -- The main HTML template --------------------------------------------------------------------------------------------------- HTML_TEMPLATE = [[<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="description" content="$package: $summary"/> <meta name="keywords" content="$keywords"/> <link rel="shortcut icon" href="$favicon"/> <link rel="alternate" type="application/rss+xml" title="New releases of $package" href='$rss'/> <title>$package</title> <style type="text/css"> body { color:#000; background:#fff; } #header { width:100%; text-align:center; border-top:solid #aaa 1px; border-bottom:solid #aaa 1px; } #header p { margin-left:0; } p { margin-left:3px; } sup.return {font-size: small;} a.return {text-decoration: none; color: gray;} pre { background-color:#ffe; white-space:pre; padding-left:3ex; border-left: 1px solid gray; margin-left: 10px} table.index { border: 1px #00007f; } table.index td { text-align: left; vertical-align: top; } table.index ul { padding-top: 0em; margin-top: 0em; } table { border: 1px solid black; border-collapse: collapse; margin-left: auto; margin-right: auto; } th { border: 1px solid black; padding: 0.5em; } td { border: 1px solid black; padding: 0.5em; } div.header, div.footer { margin-left: 0em; } </style> </head> <body> <div id="header"> <a name="top"></a> <img border=0 alt="$package logo" src="$logo"/> <p>$summary</p> <p> <a name="toc"></a>$do_toc[=[<a href="#$anchor">$item</a>]=],[=[ &middot; <a href="#$anchor">$item</a>]=] </p> </div> $body </body> </html> ]] --------------------------------------------------------------------------------------------------- -- A template for an RSS feed about releases --------------------------------------------------------------------------------------------------- RSS = [===[<rss version="2.0"> <channel> <title>$package</title> <description/> <link>$homepage</link> $do_versions[[ <item> <link>$download</link> <title>$package $version</title> <guid isPermalink="true">$url</guid> <description>$comment</description> </item>]] </channel> </rss> ]===] --------------------------------------------------------------------------------------------------- -- The template for the LuaDoc section --------------------------------------------------------------------------------------------------- LUADOC = [[ <table style="width:100%" class="function_list"> $do_modules[=[ <tr> <td colspan=2 style='background: #dddddd;'> <h2>$module</h2> <p>$description</p> $if_release[==[Release: $release]==] </td> </tr> $do_functions[==[ <tr> <td class="name" width="300px" style="vertical-align: top;"><b>$fname()</b></td> <td class="summary" >$summary <dl> $do_params[===[<dt><color="green"><b>$param</b></font>: <dd>$description</dd></dt>]===] </dl> Returns: $do_returns[====[<font color="purple">$ret</color>]====],[====[<b>$i.</b> <font color="purple">$ret</color>]====] </td> </tr> ]==] ]=] </table> ]] --------------------------------------------------------------------------------------------------- -- The rockspec template --------------------------------------------------------------------------------------------------- ROCKSPEC_TEMPLATE = [[package = "$package" version = "$last_version-$revision" source = { url = "$last_release_url", } description = { summary = "$summary", detailed = [===[$detailed]===], license = "$license", homepage = "$homepage", maintainer = "$maintainer", } dependencies = { $dependencies} build = { $build} ]] --------------------------------------------------------------------------------------------------- -- A template for the build section of the rockspec --------------------------------------------------------------------------------------------------- BUILD_TEMPLATE = [[ type = "none", install = { lua = {%s } } ]] --------------------------------------------------------------------------------------------------- -- Generates LuaDoc --------------------------------------------------------------------------------------------------- function make_luadoc(modules) if not luadoc then return "Luadoc is not installed" end lfs.chdir("lua") local logger = logging.console("[%level] %message\n") taglet.logger = logger luadoc.logger = logger assert(taglet.logger) taglet.options = {} local doc = taglet.start(modules) lfs.chdir("..") return cosmo.f(LUADOC){ do_modules = function() for i, name in ipairs(doc.modules) do local m = doc.modules[name] cosmo.yield { module = name, description = m.description, if_release = cosmo.c(m.release){release = m.release}, do_functions = function() for j, fname in ipairs(m.functions) do local f = m.functions[fname] cosmo.yield{ fname = fname, summary = f.summary, do_params = function() for p = 1, #(f.param or {})do cosmo.yield{param=f.param[p], description = f.param[f.param[p]] } end end, do_returns = function() if type(f.ret) == "string" then cosmo.yield{ret=f.ret, i=1} elseif type(f.ret) == "table" then for k,r in ipairs(f.ret) do cosmo.yield{ i=k, ret=r, _template=2} end end end, } end end, } end end, } end --------------------------------------------------------------------------------------------------- -- Includes the content of another file. --------------------------------------------------------------------------------------------------- function include(path) print("Reading: "..path) local f, x = io.open(path) return f:read("*all") end --------------------------------------------------------------------------------------------------- -- Makes a map from module names to file paths for the "none" build. --------------------------------------------------------------------------------------------------- function make_module_map(dir, subtract) local mode = lfs.attributes(dir).mode if mode == "file" then local path = string.gsub(dir, subtract, "") if string.match(path, "%.lua$") then local mod = path:gsub("%.lua$", ""):gsub("%/", ".") return string.format([=[ ["%s"] = "%s",]=], mod, path) end elseif mode == "directory" then local buffer = "" for child in lfs.dir(dir) do if not (child=="." or child=="..") then buffer=buffer..make_module_map(dir.."/"..child, subtract).."\n" end end return buffer end return "" end --------------------------------------------------------------------------------------------------- -- Does everything ("Main") --------------------------------------------------------------------------------------------------- function petrodoc(spec, revision, server) -- fill in the default values spec.homepage = spec.homepage or "" spec.favicon = spec.favicon or '' spec.download = spec.download or '' spec.push = spec.push or '#' spec.logo = spec.logo or '' spec.keywords = spec.keywords or '' spec.rss = spec.rss or '' spec.dependencies = spec.dependencies or '' spec.TOC = spec.TOC or {} local name = spec.package:lower() -- an auxiliary function to build file paths function fill_and_save(path, content) print("Writing: "..path) local f = io.open(path, "w") f:write(cosmo.fill(content, spec)) f:close() end -- fill in the necessary parameters spec.name = spec.package:lower() spec.last_version = spec.versions[1][1] spec.version = spec.last_version spec.last_release_url = cosmo.fill(spec.download, spec) spec.favicon = spec.favicon or 'http://www.lua.org/favicon.ico' spec.do_versions = function() for i, version in ipairs(versions) do spec.version = version[1] spec.date = version[2] spec.comment = version[3] spec.url = cosmo.fill(spec.download, spec) cosmo.yield(spec) end end if not spec.build then spec.build = string.format(BUILD_TEMPLATE, make_module_map("lua", name:gsub("%-", "%%-").."/lua/")) end -- generate the documentation page spec.body = "" for i,item in ipairs(spec.TOC) do spec.anchor = item[1] spec.h1 = item[1] spec.text = cosmo.fill(item[2], spec) spec.body=spec.body..cosmo.fill('\n\n<a name="$anchor"></a><h1>$h1<sup class="return"><a class="return" href="#top">&uarr;</a></sup></h1>\n$text\n', spec) end spec.do_toc = function() for i, item in ipairs(spec.TOC) do --item.anchor = string.gsub(item[1], "([^%w]*)", "_") local template = 1 if i > 1 then template = 2 end cosmo.yield { anchor = item[1], item = item[1], _template = template } end end spec.dependencies = spec.dependencies or "" spec.revision = revision spec.download_filled = cosmo.fill(spec.download, spec) if #spec.TOC > 0 then fill_and_save("doc/index.html", HTML_TEMPLATE) end if spec.rss:len() > 0 then fill_and_save("doc/releases.rss", RSS) end -- make a rockspec fill_and_save("rockspec", ROCKSPEC_TEMPLATE) -- make a release local released_rock_dir = name.."-"..spec.last_version os.execute("mkdir "..released_rock_dir) for i,v in ipairs{"lua", "bin", "README.txt", "LICENSE.txt"} do os.execute("cp -r "..v.." "..released_rock_dir) end os.execute("tar czvpf "..released_rock_dir..".tar.gz "..released_rock_dir) -- publish it if spec.push:len() > 0 then os.execute(string.format(spec.push, released_rock_dir..".tar.gz")) end -- make a rockspec for the release local rockspec = released_rock_dir.."-"..revision..".rockspec" fill_and_save(rockspec, ROCKSPEC_TEMPLATE) print(rockspec) -- make the rockspec local rockspec = released_rock_dir.."-"..revision..".rockspec" fill_and_save(rockspec, ROCKSPEC_TEMPLATE) print(rockspec) --[[if spec.download:len() > 0 then -- pack the rock luarocks.pack.run(rockspec) luarocks.build.run(rockspec) luarocks.make_manifest.run() luarocks.pack.run(name, spec.last_version.."-"..revision) end]] end --local cwd = lfs.currentdir() --local rock = arg[1] --lfs.chdir(rock) --print(lfs.currentdir()) local petrofunc, err = loadfile("petrodoc") if not petrofunc then error(err) end local spec = getfenv(petrofunc()) --lfs.chdir(cwd) petrodoc(spec, arg[2] or "0")
-- -- Script to format code -- local script_path = path.getdirectory(_SCRIPT) local source_path = path.join(script_path, "..", "src") function doformat() local srcfiles = table.flatten { os.matchfiles(path.join(script_path, "..", "Decoder", "**.h")), os.matchfiles(path.join(script_path, "..", "Decoder", "**.c")), os.matchfiles(path.join(script_path, "..", "Decoder", "**.m")), os.matchfiles(path.join(script_path, "..", "Decoder", "**.cpp")), os.matchfiles(path.join(script_path, "..", "Decoder", "**.mm")), } local cmd = "clang-format -i " .. table.concat(srcfiles, " ") print(cmd) io.flush() os.execute(cmd) end