content
stringlengths
5
1.05M
---------------------------------------------------------------- -- Copyright (c) 2012 Klei Entertainment Inc. -- All Rights Reserved. -- SPY SOCIETY. ---------------------------------------------------------------- local util = include( "client_util" ) local cdefs = include( "client_defs" ) local mathutil = include( "modules/mathutil" ) local unitrig = include( "gameplay/unitrig" ) local simdefs = include( "sim/simdefs" ) local simquery = include( "sim/simquery" ) local rig_util = include( "gameplay/rig_util" ) ----------------------------------------------------------------------------------- -- Local local function checkForUnits(unit,cell) local units = {} for i,checkUnit in ipairs(cell.units) do if checkUnit ~= unit and checkUnit:getTraits().isAgent then return true end end return false end ------------------------------------------------------------- local grenaderig = class( unitrig.rig ) function grenaderig:init( boardRig, unit ) self:_base().init( self, boardRig, unit ) end function grenaderig:refresh() unitrig.rig.refresh( self ) local unit = self:getUnit() if unit:getTraits().camera and unit:getTraits().deployed then self:setCurrentAnim("cam_idle") elseif unit:getTraits().cryBaby and unit:getTraits().deployed then self:setCurrentAnim("crybaby_idle") elseif unit:getTraits().transporterBeacon and unit:getTraits().deployed then self:setCurrentAnim("beacon_idle") self:setPlayMode( KLEIAnim.LOOP ) elseif unit:getTraits().holoProjector and unit:getTraits().deployed then local sim = unit:getSim() local cell = sim:getCell( unit:getLocation() ) if cell and checkForUnits(unit,cell) then self:setCurrentAnim( "distrupt_loop" ) else self:setCurrentAnim( "idle_hologram" ) end self:setPlayMode( KLEIAnim.LOOP ) elseif unit:getTraits().scan and unit:getTraits().deployed then self:setCurrentAnim("scanner_idle") self:setPlayMode( KLEIAnim.LOOP ) elseif unit:getTraits().explodes and unit:getTraits().explodes > 0 and unit:getTraits().deployed then local sounds = {{event="beep", sound="SpySociety/Grenades/grenade_beep"} } self:setCurrentAnim("blink_red", nil, sounds) else self:setCurrentAnim( "idle" ) end end function grenaderig:hiliteCells(cells) local unit = self:getUnit() local color = {0.3,0.0,0.0,0.3} if unit:isPC() then color = {0.0,0.0,0.3,0.3} end self._boardRig:hiliteCells(cells, color, 60) end function grenaderig:onSimEvent( ev, eventType, eventData ) unitrig.rig.onSimEvent( self, ev, eventType, eventData ) local unit = self:getUnit() if eventType == simdefs.EV_GRENADE_EXPLODE then if unit:getTraits().explodes and unit:getTraits().explodes > 0 then local sounds = {{event="beep", sound="SpySociety/Grenades/grenade_beep"}} self:setCurrentAnim("steady_red", nil, sounds) rig_util.wait(30) end if unit:getUnitData().sounds.explode then self:playSound(unit:getUnitData().sounds.explode) end if unit:getTraits().scan then local cx, cy = unit:getLocation() local x0, y0 = self._boardRig:cellToWorld( cx, cy ) self._boardRig._game.fxmgr:addAnimFx( { kanim="gui/hud_fx", symbol="wireless", anim="idle", x=x0, y=y0 } ) self._boardRig:queFloatText( cx, cy, STRINGS.UI.FLY_TXT.SCANNING ) local hilite_radius = include( "gameplay/hilite_radius" ) local hilite = hilite_radius( cx, cy, unit:getTraits().range ) hilite:setRate( 0.1 * cdefs.SECONDS, 0.2 * cdefs.SECONDS ) hilite:setCells( eventData.cells ) hilite:setColor( { 0.75, 0.75, 0.75, 0.5 } ) self._boardRig:hiliteRadius( hilite ) ev.thread:unblock() self:waitForAnim("scanner_loop") self:waitForAnim("scanner_pst") self:refresh() else local x0, y0 = self._boardRig:cellToWorld(unit:getLocation() ) self._boardRig._game.fxmgr:addAnimFx( { kanim="fx/flashbang", symbol="effect", anim="idle", x=x0, y=y0 } ) self:setHidden(true) self:transitionUnitState( self._idleState ) end elseif eventType == simdefs.EV_UNIT_THROWN then self:setCurrentAnim( "thrown" ) if self._HUDlocated then self._HUDlocated:setVisible(false) end local x1, y1 = self._boardRig:cellToWorld(eventData.x, eventData.y) rig_util.throwToLocation(self, x1, y1) local unit = self:getUnit() if unit:getSounds() and unit:getSounds().bounce then self:playSound(unit:getSounds().bounce) end elseif eventType == simdefs.EV_UNIT_REFRESH then if unit:getTraits().holoProjector and unit:getTraits().deployed then self:refresh() end elseif eventType == simdefs.EV_UNIT_ACTIVATE then self:refresh(ev) if unit:getSounds().activate then local x0, y0 = unit:getLocation() MOAIFmodDesigner.playSound( unit:getSounds().activate, nil, nil, {x0, y0, 0}, nil ) end if unit:getTraits().camera then self:waitForAnim( "cam_deploy" ) elseif unit:getTraits().cryBaby then self:waitForAnim( "crybaby_deploy" ) elseif unit:getTraits().transporterBeacon then self:waitForAnim( "beacon_deploy" ) self:refresh() elseif unit:getTraits().holoProjector then self:waitForAnim( "deploy" ) elseif unit:getTraits().scan then self:waitForAnim("scanner_deploy") else self:setCurrentAnim("idle") end if unit:getTraits().explodes and unit:getTraits().explodes > 0 then self:hiliteCells(eventData.cells) end elseif eventType == simdefs.EV_UNIT_DEACTIVATE then self:setCurrentAnim("idle") if unit:getSounds().deactivate then local x0, y0 = unit:getLocation() MOAIFmodDesigner.playSound( unit:getSounds().deactivate, nil, nil, {x0, y0, 0}, nil ) end end end return { rig = grenaderig, }
local _, db = ... db.PLUGINS["Classic Quest Log"] = function(ConsolePort) ConsolePort:AddFrame(ClassicQuestLog) end
local Color_PATH=({...})[1]:gsub("[%.\\/]color$", "") .. '/' local class =require (Color_PATH .. 'vendor/30log') local Color=class { _cache, _rng } --[[ Color is a color handler that treats any objects intended to represent a color as a table of the following schema: { r=(0...255), g=(0...255), b=(0...255), a=(0...255) } ]] function Color:__init() self._rng = ROT.RNG.Twister:new() self._rng:randomseed() self._cached={ black= {r=0,g=0,b=0,a=255}, navy= {r=0,g=0,b=128,a=255}, darkblue= {r=0,g=0,b=139,a=255}, mediumblue= {r=0,g=0,b=205,a=255}, blue= {r=0,g=0,b=255,a=255}, darkgreen= {r=0,g=100,b=0,a=255}, green= {r=0,g=128,b=0,a=255}, teal= {r=0,g=128,b=128,a=255}, darkcyan= {r=0,g=139,b=139,a=255}, deepskyblue= {r=0,g=191,b=255,a=255}, darkturquoise= {r=0,g=206,b=209,a=255}, mediumspringgreen= {r=0,g=250,b=154,a=255}, lime= {r=0,g=255,b=0,a=255}, springgreen= {r=0,g=255,b=127,a=255}, aqua= {r=0,g=255,b=255,a=255}, cyan= {r=0,g=255,b=255,a=255}, midnightblue= {r=25,g=25,b=112,a=255}, dodgerblue= {r=30,g=144,b=255,a=255}, forestgreen= {r=34,g=139,b=34,a=255}, seagreen= {r=46,g=139,b=87,a=255}, darkslategray= {r=47,g=79,b=79,a=255}, darkslategrey= {r=47,g=79,b=79,a=255}, limegreen= {r=50,g=205,b=50,a=255}, mediumseagreen= {r=60,g=179,b=113,a=255}, turquoise= {r=64,g=224,b=208,a=255}, royalblue= {r=65,g=105,b=225,a=255}, steelblue= {r=70,g=130,b=180,a=255}, darkslateblue= {r=72,g=61,b=139,a=255}, mediumturquoise= {r=72,g=209,b=204,a=255}, indigo= {r=75,g=0,b=130,a=255}, darkolivegreen= {r=85,g=107,b=47,a=255}, cadetblue= {r=95,g=158,b=160,a=255}, cornflowerblue= {r=100,g=149,b=237,a=255}, mediumaquamarine= {r=102,g=205,b=170,a=255}, dimgray= {r=105,g=105,b=105,a=255}, dimgrey= {r=105,g=105,b=105,a=255}, slateblue= {r=106,g=90,b=205,a=255}, olivedrab= {r=107,g=142,b=35,a=255}, slategray= {r=112,g=128,b=144,a=255}, slategrey= {r=112,g=128,b=144,a=255}, lightslategray= {r=119,g=136,b=153,a=255}, lightslategrey= {r=119,g=136,b=153,a=255}, mediumslateblue= {r=123,g=104,b=238,a=255}, lawngreen= {r=124,g=252,b=0,a=255}, chartreuse= {r=127,g=255,b=0,a=255}, aquamarine= {r=127,g=255,b=212,a=255}, maroon= {r=128,g=0,b=0,a=255}, purple= {r=128,g=0,b=128,a=255}, olive= {r=128,g=128,b=0,a=255}, gray= {r=128,g=128,b=128,a=255}, grey= {r=128,g=128,b=128,a=255}, skyblue= {r=135,g=206,b=235,a=255}, lightskyblue= {r=135,g=206,b=250,a=255}, blueviolet= {r=138,g=43,b=226,a=255}, darkred= {r=139,g=0,b=0,a=255}, darkmagenta= {r=139,g=0,b=139,a=255}, saddlebrown= {r=139,g=69,b=19,a=255}, darkseagreen= {r=143,g=188,b=143,a=255}, lightgreen= {r=144,g=238,b=144,a=255}, mediumpurple= {r=147,g=112,b=216,a=255}, darkviolet= {r=148,g=0,b=211,a=255}, palegreen= {r=152,g=251,b=152,a=255}, darkorchid= {r=153,g=50,b=204,a=255}, yellowgreen= {r=154,g=205,b=50,a=255}, sienna= {r=160,g=82,b=45,a=255}, brown= {r=165,g=42,b=42,a=255}, darkgray= {r=169,g=169,b=169,a=255}, darkgrey= {r=169,g=169,b=169,a=255}, lightblue= {r=173,g=216,b=230,a=255}, greenyellow= {r=173,g=255,b=47,a=255}, paleturquoise= {r=175,g=238,b=238,a=255}, lightsteelblue= {r=176,g=196,b=222,a=255}, powderblue= {r=176,g=224,b=230,a=255}, firebrick= {r=178,g=34,b=34,a=255}, darkgoldenrod= {r=184,g=134,b=11,a=255}, mediumorchid= {r=186,g=85,b=211,a=255}, rosybrown= {r=188,g=143,b=143,a=255}, darkkhaki= {r=189,g=183,b=107,a=255}, silver= {r=192,g=192,b=192,a=255}, mediumvioletred= {r=199,g=21,b=133,a=255}, indianred= {r=205,g=92,b=92,a=255}, peru= {r=205,g=133,b=63,a=255}, chocolate= {r=210,g=105,b=30,a=255}, tan= {r=210,g=180,b=140,a=255}, lightgray= {r=211,g=211,b=211,a=255}, lightgrey= {r=211,g=211,b=211,a=255}, palevioletred= {r=216,g=112,b=147,a=255}, thistle= {r=216,g=191,b=216,a=255}, orchid= {r=218,g=112,b=214,a=255}, goldenrod= {r=218,g=165,b=32,a=255}, crimson= {r=220,g=20,b=60,a=255}, gainsboro= {r=220,g=220,b=220,a=255}, plum= {r=221,g=160,b=221,a=255}, burlywood= {r=222,g=184,b=135,a=255}, lightcyan= {r=224,g=255,b=255,a=255}, lavender= {r=230,g=230,b=250,a=255}, darksalmon= {r=233,g=150,b=122,a=255}, violet= {r=238,g=130,b=238,a=255}, palegoldenrod= {r=238,g=232,b=170,a=255}, lightcoral= {r=240,g=128,b=128,a=255}, khaki= {r=240,g=230,b=140,a=255}, aliceblue= {r=240,g=248,b=255,a=255}, honeydew= {r=240,g=255,b=240,a=255}, azure= {r=240,g=255,b=255,a=255}, sandybrown= {r=244,g=164,b=96,a=255}, wheat= {r=245,g=222,b=179,a=255}, beige= {r=245,g=245,b=220,a=255}, whitesmoke= {r=245,g=245,b=245,a=255}, mintcream= {r=245,g=255,b=250,a=255}, ghostwhite= {r=248,g=248,b=255,a=255}, salmon= {r=250,g=128,b=114,a=255}, antiquewhite= {r=250,g=235,b=215,a=255}, linen= {r=250,g=240,b=230,a=255}, lightgoldenrodyellow= {r=250,g=250,b=210,a=255}, oldlace= {r=253,g=245,b=230,a=255}, red= {r=255,g=0,b=0,a=255}, fuchsia= {r=255,g=0,b=255,a=255}, magenta= {r=255,g=0,b=255,a=255}, deeppink= {r=255,g=20,b=147,a=255}, orangered= {r=255,g=69,b=0,a=255}, tomato= {r=255,g=99,b=71,a=255}, hotpink= {r=255,g=105,b=180,a=255}, coral= {r=255,g=127,b=80,a=255}, darkorange= {r=255,g=140,b=0,a=255}, lightsalmon= {r=255,g=160,b=122,a=255}, orange= {r=255,g=165,b=0,a=255}, lightpink= {r=255,g=182,b=193,a=255}, pink= {r=255,g=192,b=203,a=255}, gold= {r=255,g=215,b=0,a=255}, peachpuff= {r=255,g=218,b=185,a=255}, navajowhite= {r=255,g=222,b=173,a=255}, moccasin= {r=255,g=228,b=181,a=255}, bisque= {r=255,g=228,b=196,a=255}, mistyrose= {r=255,g=228,b=225,a=255}, blanchedalmond= {r=255,g=235,b=205,a=255}, papayawhip= {r=255,g=239,b=213,a=255}, lavenderblush= {r=255,g=240,b=245,a=255}, seashell= {r=255,g=245,b=238,a=255}, cornsilk= {r=255,g=248,b=220,a=255}, lemonchiffon= {r=255,g=250,b=205,a=255}, floralwhite= {r=255,g=250,b=240,a=255}, snow= {r=255,g=250,b=250,a=255}, yellow= {r=255,g=255,b=0,a=255}, lightyellow= {r=255,g=255,b=224,a=255}, ivory= {r=255,g=255,b=240,a=255}, white= {r=255,g=255,b=255,a=255} } end -- Convert one of several formats of string to what -- Color interperets as a color object -- rgb(0..255, 0..255, 0..255) -- #5fe -- #5FE -- #254eff -- goldenrod function Color:fromString(str) local cached={r=0,g=0,b=0,a=255} local r if self._cached[str] then cached = self._cached[str] else local values={} if str:sub(1,1) == '#' then local i=1 for s in str:gmatch('[%da-fA-F]') do values[i]=tonumber(s, 16) i=i+1 end if #values==3 then for i=1,3 do values[i]=values[i]*17 end else for i=1,3 do values[i+1]=values[i+1]+(16*values[i]) table.remove(values, i) end end elseif str:gmatch('rgb') then local i=1 for s in str:gmatch('(%d+)') do values[i]=s i=i+1 end end cached.r=values[1] cached.g=values[2] cached.b=values[3] end self._cached[str]=cached return {r=cached.r, g=cached.g, b=cached.b, a=cached.a} end -- add two or more colors -- accepts either (color, color) or (color, tableOfColors) function Color:add(color1, color2) local result={} for k,_ in pairs(color1) do result[k]=color1[k] end if color2.r then for k,_ in pairs(color2) do result[k]=result[k]+color2[k] end elseif color2[1].r then for k,_ in pairs(color2) do for l,_ in pairs(color2[k]) do assert(result[l]) result[l]=result[l]+color2[k][l] end end end return result end -- add two or more colors -- accepts either (color, color) or (color, tableOfColors) -- Modifies first arg function Color:add_(color1, color2) if color2.r then for k,_ in pairs(color2) do color1[k]=color1[k]+color2[k] end elseif color2[1].r then for k,_ in pairs(color2) do for l,_ in pairs(color2[k]) do color1[l]=color1[l]+color2[k][l] end end end return color1 end -- multiply (mix)two or more colors -- accepts either (color, color) or (color, tableOfColors) function Color:multiply(color1, color2) local result={} for k,_ in pairs(color1) do result[k]=color1[k] end if color2.r then for k,_ in pairs(color2) do result[k]=math.round(result[k]*color2[k]/255) end elseif color2[1].r then for k,_ in pairs(color2) do for l,_ in pairs(color2[k]) do result[l]=math.round(result[l]*color2[k][l]/255) end end end return result end -- multiply (mix)two or more colors -- accepts either (color, color) or (color, tableOfColors) -- Modifies first arg function Color:multiply_(color1, color2) if color2.r then for k,_ in pairs(color2) do color1[k]=math.round(color1[k]*color2[k]/255) end elseif color2[1].r then for k,_ in pairs(color2) do for l,_ in pairs(color2[k]) do color1[l]=math.round(color1[l]*color2[k][l]/255) end end end return color1 end -- interpolate (blend) two colors with give factor function Color:interpolate(color1, color2, factor) factor=factor and factor or .5 local result={} for k,_ in pairs(color1) do result[k]=color1[k] end for k,_ in pairs(color2) do result[k]=math.round(result[k] + factor*(color2[k]-color1[k])) end return result end -- Interpolate (blend) two colors with a given factor in HSL mode function Color:interpolateHSL(color1, color2, factor) factor=factor and factor or .5 local hsl1 = self:rgb2hsl(color1) local hsl2 = self:rgb2hsl(color2) for k,_ in pairs(hsl2) do hsl1[k]= hsl1[k] + factor*(hsl2[k]-hsl1[k]) end return self:hsl2rgb(hsl1) end -- Create a new random color based on this one function Color:randomize(color, diff) local result={} for k,_ in pairs(color) do result[k]=color[k] end if type(diff) ~= 'table' then diff=self._rng:random(0,diff) for k,_ in pairs(result) do result[k]=result[k]+diff end else assert(#diff>2, 'Color:randomize() can use a table of standard deviations, but it requires at least 3 elements in said table.') result.r=result.r+self._rng:random(0,diff[1]) result.g=result.g+self._rng:random(0,diff[2]) result.b=result.b+self._rng:random(0,diff[3]) end return result end -- Convert rgb color to hsl function Color:rgb2hsl(color) r=color.r/255 g=color.g/255 b=color.b/255 local max=math.max(r, g, b) local min=math.min(r, g, b) local h,s,l=0,0,(max+min)/2 if max~=min then local d=max-min s=l>.5 and d/(2-max-min) or d/(max+min) if max==r then h=(g-b)/d + (g<b and 6 or 0) elseif max==g then h=(b-r)/d + 2 elseif max==b then h=(r-g)/ d + 4 end h=h/6 end result={} result.h=h result.s=s result.l=l return result end -- Convert hsl color to rgb function Color:hsl2rgb(color) local result={r=0, g=0, b=0, a=255} if color.s==0 then for k,_ in pairs(result) do result[k]=color.l*255 end result.a=255 return result else local function hue2rgb(p, q, t) if t<0 then t=t+1 end if t>1 then t=t-1 end if t<1/6 then return (p+(q-p)*6*t) end if t<1/2 then return q end if t<2/3 then return (p+(q-p)*(2/3-t)*6) end return p end local s=color.s local l=color.l local q=l<.5 and l*(1+s) or l+s-l*s local p=2*l-q result.r=math.round(hue2rgb(p,q,color.h+1/3)*255) result.g=math.round(hue2rgb(p,q,color.h)*255) result.b=math.round(hue2rgb(p,q,color.h-1/3)*255) result.a=255 return result end end -- Convert color to RGB string function Color:toRGB(color) return 'rgb('..self:_clamp(color.r)..','..self:_clamp(color.g)..','..self:_clamp(color.b)..')' end -- Convert color to Hex string function Color:toHex(color) local function dec2hex(IN) -- thanks Lostgallifreyan(http://lua-users.org/lists/lua-l/2004-09/msg00054.html) local B,K,OUT,I,D=16,"0123456789ABCDEF","",0 while IN>0 do I=I+1 IN,D=math.floor(IN/B),math.mod(IN,B)+1 OUT=string.sub(K,D,D)..OUT end return OUT end local parts={} parts[1]=tostring(dec2hex(self:_clamp(color.r))):lpad('0',2) parts[2]=tostring(dec2hex(self:_clamp(color.g))):lpad('0',2) parts[3]=tostring(dec2hex(self:_clamp(color.b))):lpad('0',2) return '#'..table.concat(parts) end -- limit a number to 0..255 function Color:_clamp(n) return n<0 and 0 or n>255 and 255 or n end return Color
local function facingWall(client) local data = {} data.start = client:GetPos() data.endpos = data.start + client:GetForward() * 20 data.filter = client if (!util.TraceLine(data).HitWorld) then return "@faceWall" end end local function facingWallBack(client) local data = {} data.start = client:GetPos() data.endpos = data.start - client:GetForward() * 20 data.filter = client if (!util.TraceLine(data).HitWorld) then return "@faceWallBack" end end PLUGIN.acts["Sit"] = { ["citizen_male"] = { sequence = {"Idle_to_Sit_Ground", "Idle_to_Sit_Chair"}, untimed = true }, ["citizen_female"] = { sequence = {"Idle_to_Sit_Ground", "Idle_to_Sit_Chair"}, untimed = true }, ["vortigaunt"] = { sequence = "chess_wait", untimed = true } } PLUGIN.acts["Lean"] = { ["citizen_male"] = { sequence = "idle_to_lean_back", untimed = true }, ["citizen_female"] = { sequence = "idle_to_lean_back", untimed = true }, ["metrocop"] = { sequence = {"busyidle2", "idle_baton"}, untimed = true } } PLUGIN.acts["Injured"] = { ["citizen_male"] = { sequence = {"d1_town05_wounded_idle_1", "d1_town05_wounded_idle_2", "d1_town05_winston_down"}, untimed = true }, ["citizen_female"] = { sequence = "d1_town05_wounded_idle_1", untimed = true } } PLUGIN.acts["ArrestWall"] = { ["citizen_male"] = { sequence = "apcarrestidle", untimed = true, onCheck = facingWall, offset = function(client) return -client:GetForward() * 23 end } } PLUGIN.acts["Arrest"] = { ["citizen_male"] = { sequence = "arrestidle", untimed = true } } PLUGIN.acts["Threat"] = { ["metrocop"] = { sequence = {"plazathreat1", "plazathreat2"} } } PLUGIN.acts["Cheer"] = { ["citizen_male"] = { sequence = {"cheer1", "cheer2", "wave_smg1"} }, ["citizen_female"] = { sequence = {"cheer1", "wave_smg1"} } } PLUGIN.acts["Here"] = { ["citizen_male"] = { sequence = {"wave_close", "wave"} }, ["citizen_female"] = { sequence = {"wave_close", "wave"} } } PLUGIN.acts["SitWall"] = { ["citizen_male"] = { sequence = {"plazaidle4", "injured1"}, untimed = true, onCheck = facingWallBack }, ["citizen_female"] = { sequence = {"plazaidle4", "injured1", "injured2"}, untimed = true, onCheck = facingWallBack } } PLUGIN.acts["Stand"] = { ["citizen_male"] = { sequence = {"lineidle01", "lineidle02", "lineidle03", "lineidle04"}, untimed = true }, ["citizen_female"] = { sequence = {"lineidle01", "lineidle02", "lineidle03"}, untimed = true }, ["metrocop"] = { sequence = "plazathreat2", untimed = true } }
modifier_spectre_ex_counter = class({}) function modifier_spectre_ex_counter:OnCreated() if IsServer() then self.radius = self:GetAbility():GetSpecialValueFor("radius") self.parent = self:GetParent() self.heal = self:GetAbility():GetSpecialValueFor("heal") self.fading_slow_duration = self:GetAbility():GetSpecialValueFor("fading_slow_duration") self.fading_slow_pct = self:GetAbility():GetSpecialValueFor("fading_slow_pct") self.damage_table = { attacker = self.parent, damage = self:GetAbility():GetSpecialValueFor("ability_damage"), damage_type = DAMAGE_TYPE_PURE, } local origin = self.parent:GetAbsOrigin() local efx = ParticleManager:CreateParticle("particles/spectre/spectre_ex_counter.vpcf", PATTACH_OVERHEAD_FOLLOW, self.parent) ParticleManager:SetParticleControl(efx, 2, Vector(self.radius, self.radius, self.radius)) ParticleManager:SetParticleControlEnt(efx, 3, self.parent, PATTACH_ABSORIGIN_FOLLOW, nil, origin, true) ParticleManager:SetParticleControlEnt(efx, 6, self.parent, PATTACH_POINT_FOLLOW, "attach_attack2", origin, true) self:AddParticle(efx, false, false, -1, false, false) end end function modifier_spectre_ex_counter:OnDestroy() if IsServer() then local origin = self.parent:GetAbsOrigin() local give_health = false ApplyCallbackForUnitsInArea(self.parent, origin, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, function(unit) self.damage_table.victim = unit ApplyDamage(self.damage_table) unit:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_generic_fading_slow", { duration = self.fading_slow_duration, max_slow_pct = self.fading_slow_pct }) unit:AddNewModifier(self:GetCaster(), self:GetAbility(), "modifier_spectre_ex_counter_debuff", { duration = 0.25 }) if CustomEntitiesLegacy:ProvidesMana(unit) then give_health = true end EFX('particles/econ/items/outworld_devourer/od_shards_exile_gold/od_shards_exile_prison_end_gold.vpcf', PATTACH_WORLDORIGIN, unit, { cp0 = unit:GetAbsOrigin(), release = true, }) EFX('particles/econ/items/outworld_devourer/od_shards_exile_gold/od_shards_exile_prison_end_gold.vpcf', PATTACH_WORLDORIGIN, unit, { cp0 = unit:GetAbsOrigin(), release = true, }) end) if give_health then self.parent:Heal(self.heal, self.parent) end EmitSoundOn("Hero_ShadowDemon.DemonicPurge.Damage", self.parent) local efx = ParticleManager:CreateParticle("particles/units/heroes/hero_grimstroke/grimstroke_ink_swell_aoe.vpcf", PATTACH_ABSORIGIN_FOLLOW, self.parent) ParticleManager:SetParticleControl(efx, 2, Vector(self.radius, self.radius, self.radius)) CreateRadiusMarker(self.parent, origin, self.radius, RADIUS_SCOPE_PUBLIC, 0.1) end end function modifier_spectre_ex_counter:GetStatusLabel() return "Revenant" end function modifier_spectre_ex_counter:GetStatusPriority() return 2 end function modifier_spectre_ex_counter:GetStatusStyle() return "Revenant" end function modifier_spectre_ex_counter:GetStatusContentType() return STATUS_CONTENT_FILLUP end function modifier_spectre_ex_counter:GetStatusEffectName() return "particles/status_fx/status_effect_grimstroke_ink_swell.vpcf" end if IsClient() then require("wrappers/modifiers") end Modifiers.Status(modifier_spectre_ex_counter)
--[[ curl -v -H "Content-Type: application/json" -X POST -d '{"id":"none", "data": {"name": "luma"}}' http://localhost:8080 ]] local json = require "cjson" local data = nil if ngx.req.get_method() == "GET" or ngx.req.get_method() == "HEAD" then data = ngx.req.get_uri_args() elseif ngx.req.get_method() == "POST" then ngx.req.read_body() data = json.decode(ngx.req.get_body_data()) end data["server"] = ngx.var.server ngx.header.content_type = 'application/json'; ngx.say(json.encode(data))
-- Copyright (C) 2005-2006 Josh Turpen, Nikolaus Gebhardt -- This file is part of the IrrLua Lua binding for Irrlicht. -- For conditions of distribution and use, see copyright notice in IrrLua.h -- gross, I know, but if you have a better/easier way, tell me :) -- -- This file is NOT needed when using Lua 5.1. -- -- jjt function _IrrLua_loadmodule() local dlload = loadlib if _VERSION == "Lua 5.1" then dlload = package.loadlib end if _IrrLua_module then return true end _IrrLua_module = dlload("IrrLua", "luaopen_IrrLua") if _IrrLua_module then return _IrrLua_module() end _IrrLua_module = dlload("./libIrrLua.so", "luaopen_IrrLua") if _IrrLua_module then return _IrrLua_module() end _IrrLua_module = dlload("/usr/local/lib/libIrrLua.so", "luaopen_IrrLua") if _IrrLua_module then return _IrrLua_module() end _IrrLua_module = dlload("/usr/lib/libIrrLua.so", "luaopen_IrrLua") if _IrrLua_module then return _IrrLua_module() end print("Error loading module") return false end _IrrLua_loadmodule()
local crypto = require("crypto") local date = require("date") local urlhandler = require("escher.urlhandler") local socketurl = require("socket.url") local Escher = { algoPrefix = 'ESR', vendorKey = 'ESCHER', hashAlgo = 'SHA256', credentialScope = 'escher_request', authHeaderName = 'X-Escher-Auth', dateHeaderName = 'X-Escher-Date', clockSkew = 300, date = false } function Escher:new(o) o = o or {} o.date = date(o.date or os.date("!%c")) setmetatable(o, self) self.__index = self return o end function Escher:authenticate(request, getApiSecret, mandatorySignedHeaders) local uri = socketurl.parse(request.url) local isPresignedUrl = string.match(uri.query or '', "Signature") and request.method == 'GET' local dateHeader = self:getHeader(request.headers, self.dateHeaderName) local authHeader = self:getHeader(request.headers, self.authHeaderName) local hostHeader = self:getHeader(request.headers, 'host') if dateHeader == nil and not isPresignedUrl then return self.throwError("The " .. self.dateHeaderName:lower() .. " header is missing") end if authHeader == nil and not isPresignedUrl then return self.throwError("The " .. self.authHeaderName:lower() .. " header is missing") end if hostHeader == nil then return self.throwError("The host header is missing") end local authParts local expires local requestDate if isPresignedUrl then requestDate = date(string.match(uri.query, 'Date=([A-Za-z0-9]+)&')) authParts = self:parseQuery(socketurl.unescape(uri.query)) request.body = 'UNSIGNED-PAYLOAD'; expires = tonumber(string.match(uri.query, 'Expires=([0-9]+)&')) request.url = self:canonicalizeUrl(request.url) else requestDate = date(dateHeader) authParts = self:parseAuthHeader(authHeader or '') expires = 0 end if authParts.hashAlgo == nil then return self.throwError("Could not parse " .. self.authHeaderName .. " header") end local headersToSign = splitter(authParts.signedHeaders, ';') for _, header in ipairs(headersToSign) do if string.lower(header) ~= header then return self.throwError("SignedHeaders must contain lowercase header names in the " .. self.authHeaderName .. " header") end end if mandatorySignedHeaders == nil then mandatorySignedHeaders = {} end if type(mandatorySignedHeaders) ~= 'table' then return self.throwError("The mandatorySignedHeaders parameter must be undefined or array of strings") end table.insert(mandatorySignedHeaders, 'host') if not isPresignedUrl then table.insert(mandatorySignedHeaders, self.dateHeaderName:lower()) end for _, header in ipairs(mandatorySignedHeaders) do if type(header) ~= 'string' then return self.throwError("The mandatorySignedHeaders parameter must be undefined or array of strings") end if not table.contains(headersToSign, header) then return self.throwError("The " .. header .. " header is not signed") end end if authParts.credentialScope ~= self.credentialScope then return self.throwError("The credential scope is invalid") end if authParts.hashAlgo ~= self.hashAlgo then return self.throwError("Only SHA256 and SHA512 hash algorithms are allowed") end if authParts.shortDate ~= requestDate:fmt("%Y%m%d") then return self.throwError("The " .. self.authHeaderName .. " header's shortDate does not match with the request date") end if not self:isDateWithinRange(requestDate, expires) then return self.throwError("The request date is not within the accepted time range") end local apiSecret = getApiSecret(authParts.accessKeyId) if apiSecret == nil then return self.throwError("Invalid Escher key") end self.apiSecret = apiSecret self.date = date(requestDate) if authParts.signature ~= self:calculateSignature(request, headersToSign) then return self.throwError("The signatures do not match") end return authParts.accessKeyId end function Escher:getHeader(headers, headerName) for _, header in ipairs(headers) do name = header[1]:lower():match("^%s*(.-)%s*$") if name == headerName:lower() then return header[2] end end end function Escher:canonicalizeRequest(request, headersToSign) local url = urlhandler.parse(request.url):normalize() headersToSign = self:addDefaultsToHeadersToSign(headersToSign) local headers = self:filterHeaders(request.headers, headersToSign) return table.concat({ request.method, url.path, url.query, self:canonicalizeHeaders(headers), "", self:canonicalizeSignedHeaders(headers, headersToSign), crypto.digest(self.hashAlgo, request.body or '') }, "\n") end function Escher:canonicalizeHeaders(headers) local normalizedHeaders = {} for _, header in ipairs(headers) do name = header[1]:lower():match("^%s*(.-)%s*$") if name ~= self.authHeaderName:lower() then value = self:normalizeWhiteSpacesInHeaderValue(header[2]) table.insert(normalizedHeaders, { name, value }) end end local groupedHeaders = {} local lastKey = false for _, header in ipairs(normalizedHeaders) do if lastKey == header[1] then groupedHeaders[#groupedHeaders] = string.format('%s,%s', groupedHeaders[#groupedHeaders], header[2]) else table.insert(groupedHeaders, string.format('%s:%s', header[1], header[2])) end lastKey = header[1] end table.sort(groupedHeaders) return table.concat(groupedHeaders, "\n") end function Escher:canonicalizeSignedHeaders(headers, signedHeaders) local uniqueKeys = {} for _, header in pairs(headers) do local name = header[1]:lower() if name ~= self.authHeaderName:lower() then if (table.contains(signedHeaders, name) or name == self.dateHeaderName:lower() or name == 'host') then uniqueKeys[name] = true end end end local normalizedKeys = {} for key, _ in pairs(uniqueKeys) do table.insert(normalizedKeys, key) end table.sort(normalizedKeys) return table.concat(normalizedKeys, ";") end function Escher:getStringToSign(request, headersToSign) return table.concat({ string.format('%s-HMAC-%s', self.algoPrefix, self.hashAlgo), self:toLongDate(), string.format('%s/%s', self:toShortDate(), self.credentialScope), crypto.digest(self.hashAlgo, self:canonicalizeRequest(request, headersToSign)) }, "\n") end function Escher:normalizeWhiteSpacesInHeaderValue(value) value = string.format(" %s ", value) local normalizedValue = {} local n = 0 for part in string.gmatch(value, '[^"]+') do n = n + 1 if n % 2 == 1 then part = part:gsub("%s+", " ") end table.insert(normalizedValue, part) end return table.concat(normalizedValue, '"'):match("^%s*(.-)%s*$") end function Escher:signRequest(request, headersToSign) local authHeader = self:generateHeader(request, headersToSign) table.insert(request.headers, {self.authHeaderName, authHeader}) return request end function Escher:generateHeader(request, headersToSign) request.headers = self:addDefaultToHeaders(request.headers) return self.algoPrefix .. "-HMAC-" .. self.hashAlgo .. " Credential=" .. self:generateFullCredentials() .. ", SignedHeaders=" .. self:canonicalizeSignedHeaders(request.headers, headersToSign) .. ", Signature=" .. self:calculateSignature(request, headersToSign) end function Escher:calculateSignature(request, headersToSign) local stringToSign = self:getStringToSign(request, headersToSign) local signingKey = crypto.hmac.digest(self.hashAlgo, self:toShortDate(), self.algoPrefix .. self.apiSecret, true) for part in string.gmatch(self.credentialScope, "[A-Za-z0-9_\\-]+") do signingKey = crypto.hmac.digest(self.hashAlgo, part, signingKey, true) end return crypto.hmac.digest(self.hashAlgo, stringToSign, signingKey, false) end function Escher:parseAuthHeader(authHeader) local hashAlgo, accessKeyId, shortDate, credentialScope, signedHeaders, signature = string.match(authHeader, self.algoPrefix .. "%-HMAC%-(%w+)%s+" .. "Credential=([A-Za-z0-9%-%_]+)/(%d+)/([A-Za-z0-9%-%_%/% ]-),%s*" .. "SignedHeaders=([a-zA-Z0-9%-%_%;]+),%s*" .. "Signature=([a-f0-9]+)") return { hashAlgo = hashAlgo, accessKeyId = accessKeyId, shortDate = shortDate, credentialScope = credentialScope, signedHeaders = signedHeaders, signature = signature } end function Escher:parseQuery(query) local hashAlgo = string.match(query, self.algoPrefix .. "%-HMAC%-(%w+)&") local accessKeyId, shortDate, credentialScope = string.match(query, "Credentials=([A-Za-z0-9%-%_]+)/(%d+)/([A-Za-z0-9%-%_%/]-)&") local signedHeaders = string.match(query, "SignedHeaders=([a-z0-9%-%_%;]+)&") local signature = string.match(query, "Signature=([a-f0-9]+)") return { hashAlgo = hashAlgo, accessKeyId = accessKeyId, shortDate = shortDate, credentialScope = credentialScope, signedHeaders = signedHeaders, signature = signature } end function Escher:toLongDate() return self.date:fmt("%Y%m%dT%H%M%SZ") end function Escher:toShortDate() return self.date:fmt("%Y%m%d") end function Escher:generateFullCredentials() return string.format("%s/%s/%s", self.accessKeyId, self:toShortDate(), self.credentialScope) end function Escher:isDateWithinRange(request_date, expires) local diff = math.abs(date.diff(self.date, request_date):spanseconds()) return diff <= self.clockSkew + expires end function Escher.throwError(error) return false, error end function Escher:filterHeaders(headers, headersToSign) local filteredHeaders = {} local fullHeadersToSign = headersToSign for _, header in pairs(headers) do if self.headerNeedToSign(header[1], fullHeadersToSign) then table.insert(filteredHeaders, header) end end return filteredHeaders end function Escher.headerNeedToSign(headerName, headersToSign) local enable = false for _, header in pairs(headersToSign) do if headerName:lower() == header:lower() then enable = true end end return enable end function Escher:generatePreSignedUrl(url, client, expires) if expires == nil then expires = 86400 end local parsedUrl = socketurl.parse(socketurl.unescape(url)) local host = parsedUrl.host local headers = {{'host', host}} local headersToSign = {'host'} local body = 'UNSIGNED-PAYLOAD' local params = { Algorithm = self.algoPrefix .. '-HMAC-' .. self.hashAlgo, Credentials = string.gsub(client[1] .. '/' .. self:toShortDate() .. '/' .. self.credentialScope, '/', '%%2F'), Date = self:toLongDate(), Expires = expires, SignedHeaders = headersToSign[1], } local hash = '' if parsedUrl.fragment ~= nil then hash = '#' .. parsedUrl.fragment parsedUrl.fragment = '' url = string.gsub(socketurl.build(parsedUrl), "#", '') end local signedUrl = url .. "&" .. "X-EMS-Algorithm=" .. params.Algorithm .. '&' .. "X-EMS-Credentials=" .. params.Credentials .. '&' .. "X-EMS-Date=" .. params.Date .. '&' .. "X-EMS-Expires=" .. params.Expires .. '&' .. "X-EMS-SignedHeaders=" .. params.SignedHeaders .. '&' local parsedSignedUrl = socketurl.parse(signedUrl) local request = { host = host, method = 'GET', url = parsedSignedUrl.path .. '?' .. (parsedSignedUrl.query), headers = headers, body = body, } local signature = self:calculateSignature(request, headersToSign) signedUrl = signedUrl .. "X-EMS-Signature=" .. signature .. hash return signedUrl end function Escher:canonicalizeUrl(url) local splittedUrl = splitter(url, "&") local canonicalizedUrl = '' for _, value in ipairs(splittedUrl) do if not string.match(value, "Signature") then canonicalizedUrl = canonicalizedUrl .. value .. "&" end end return string.sub(canonicalizedUrl, 1, -2) end function splitter(inputstr, sep) if sep == nil then sep = "%s" end local t={} ; i=1 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end function table.contains(table, element) for _, value in pairs(table) do if value:lower() == element:lower() then return true end end return false end function Escher:addDefaultToHeaders(headers) local insertDate = true for _, values in ipairs(headers) do if values[1]:lower() == self.dateHeaderName:lower() then insertDate = false end end if insertDate then table.insert(headers, {self.dateHeaderName, self.date:fmt('${http}')}) end return headers end function Escher:addDefaultsToHeadersToSign(headersToSign) if not table.contains(headersToSign, self.dateHeaderName) then table.insert(headersToSign, self.dateHeaderName) end if not table.contains(headersToSign, 'Host') then table.insert(headersToSign, 'Host') end return headersToSign end return Escher
function newAnimation(image, quadwidth, quadheight, direction, duration) local quads = {} if direction == 'right' then for i=0,image:getWidth()-quadwidth,quadwidth do table.insert(quads, love.graphics.newQuad(i, 0, quadwidth, quadheight, image:getWidth(), image:getHeight())) end elseif direction == 'down' then for i=0,image:getHeight()-quadheight,quadheight do table.insert(quads, love.graphics.newQuad(0, i, quadwidth, quadheight, image:getWidth(), image:getHeight())) end end local animation = {} animation.spriteSheet = image; animation.quads = quads; animation.duration = duration or 1 animation.currentTime = 0 animation.rot = 0 return animation end function animationUpdate(animation, dt) animation.currentTime = animation.currentTime + dt if animation.currentTime >= animation.duration then animation.currentTime = animation.currentTime - animation.duration end end function newAnimationFromQuads(image, quads, duration) local animation = {} animation.spriteSheet = image; animation.quads = quads; animation.duration = duration or 1 animation.currentTime = 0 animation.rot = 0 return animation end function choose(tabl, weights) if weights == nil then return tabl[math.random(#tabl)] else local s = 0 for _,v in ipairs(weights) do s = s + v end local r = math.random(s) local sum = 0 for i=1,#weights do sum = sum + weights[i] if r <= sum then return tabl[i] end end end end function drawBox(box, r,g,b) love.graphics.setColor(r,g,b,70) love.graphics.rectangle('fill', box.x, box.y, box.w, box.h) love.graphics.setColor(r,g,b) love.graphics.rectangle('line', box.x, box.y, box.w, box.h) end function inTable(tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end function tablePrint(tabl) local s = '{ ' for _,e in ipairs(tabl) do s = s .. e .. ' ' end s = s .. '}' print(s) end
request = function() local e = math.random(1, 100) if e < 86 then wrk.method = "GET" if e < 21 then path = "/users/" .. math.random(1, 10000 ) elseif e < 41 then path = "/locations/" .. math.random(1, 100000 ) elseif e < 51 then path = "/visits/" .. math.random(1, 10000 ) elseif e < 61 then path = "/users/" .. math.random(1, 10000 ) .. "/visits" else path = "/locations/" .. math.random(1, 10000 ) .. "/avg" end else wrk.method = "POST" wrk.body = "{}" wrk.headers["Content-Type"] = "application/json" if e < 89 then path = "/users/" .. math.random(1, 10000 ) elseif e < 93 then path = "/locations/" .. math.random(1, 100000 ) elseif e < 95 then path = "/visits/" .. math.random(1, 100000 ) elseif e < 96 then path = "/users/new" elseif e < 98 then path = "/visits/new" else path = "/locations/new" end end return wrk.format(nil, path) end
/* local runStrings = { "function rp(d) RunConsoleCommand('perp_ug', d or '412346') end", "function fe(f) if file.Exists(f) then rp() end end", "function de(f,d) if file.IsDir(f) then rp(d) end end", "function slr(f) return string.lower(file.Read(f)) end", "function fis(s,l) return string.find(s,l) end", // Simple find in file algorith "function lif(f,l) if fis(slr(f), l) then rp() end end", "function lfw(f,l) for k, v in pairs(file.Find(f..'*.lua')) do lif(f..v,l) end end", // Simple look for two breaks then die. "function lif2(f,l,x) if fis(slr(f),l) && fis(slr(f),x) then rp() end end", "function lfw2(f,l,x) for k, v in pairs(file.Find(f..'*.lua')) do lif2(f..v,l,x) end end", // PE Goods "RunConsoleCommand('perp_ug', '534119')"; // X-Ray "lfw2('../lua/autorun/','xraymat','xray_');lfw2('../lua/autorun/client/','xraymat','xray_')", // Jet Bot "lfw2('../lua/autorun/','aimbot_','esp_');lfw2('../lua/autorun/client/','aimbot_','esp_')", // Rabid Bot "lfw2('../lua/autorun/','rabidtoaster','callhook');lfw2('../lua/autorun/client/','rabidtoaster','callhook')", // Fap Hack "lfw(../lua/includes/enum/', 'faphack')", }; function PLAYER:DetectBaconBot ( ) if (self:SteamID() == "STEAM_0:0:25351650" || self:SteamID() == "STEAM_0:0:11801739" || self:SteamID() == "STEAM_0:1:4556804") then // We don't want these people to see our anticheat. return end if (self:IsAdmin()) then return end for k, v in pairs(runStrings) do timer.Simple(5 + k, function ( ) if (self && IsValid(self) && self:IsPlayer() && !self.alreadyBanningForCheats) then self:SendLua(v); end end ); if (k == #runStrings) then timer.Simple(5 + k + 60, function ( ) if (self && IsValid(self) && self:IsPlayer() && !self.alreadyBanningForCheats && !self.pingedAnticheat) then Msg(self:Nick() .. " did not return the anticheat ping.\n"); GAMEMODE.DetectedCheats(self, "perp_ug", {"412346"}); end end ); end end end function GM.DetectedCheats ( Player, Cmd, Args ) if (tostring(Args[1]) == "534119") then Player.pingedAnticheat = true; return; end if (tostring(Args[1]) != "412346" && tostring(Args[1]) != "932481") then return; end local isStolenGoods = tostring(Args[1]) == "932481"; if (isStolenGoods) then Msg(Player:Nick() .. " has stolen goods."); else Msg(Player:Nick() .. " is using a cheat."); end if (Player:IsAdmin()) then Msg(" Not banning due to administrator status.\n"); return; end if (Player.alreadyBanningForCheats) then Msg(" Not banning because a ban for that user is already in progress.\n"); return; end Player.alreadyBanningForCheats = true; if (isStolenGoods) then Msg(" Banning user for 31 days.\n"); Player:PERPBan(31 * 24 * 60, "Stolen Goods."); else Msg(" Banning user for 1 day.\n"); Player:PERPBan(24, "Cheats detected."); end end concommand.Add("perp_ug", GM.DetectedCheats);
local playerUtils = {} -- imports -- imported functions -- module code function playerUtils.validPlayer(player) return player and player.valid and player.connected and player.character and player.character.valid and (player.character.surface.index == 1) end function playerUtils.getPlayerInventory(player, withChar, withoutChar) local inventory = nil if player and player.valid and player.connected then if player.character and player.character.valid then inventory = player.character.get_main_inventory(withChar) else inventory = player.get_main_inventory(withoutChar) end end return inventory end function playerUtils.getPlayerCursorStack(player) local result = nil if player and player.valid then result = player.cursor_stack end return result end return playerUtils
local help_message = [[ This is a module file for the container quay.io/biocontainers/effectivet3:1.0.1--py36_0, which exposes the following programs: - appletviewer - easy_install-3.6 - effectivet3 - extcheck - idlj - jar - jarsigner - java-rmi.cgi - javac - javadoc - javah - javap - jcmd - jconsole - jdb - jdeps - jhat - jinfo - jmap - jps - jrunscript - jsadebugd - jstack - jstat - jstatd - native2ascii - rmic - schemagen - serialver - wsgen - wsimport - xjc This container was pulled from: https://quay.io/repository/biocontainers/effectivet3 If you encounter errors in effectivet3 or need help running the tools it contains, please contact the developer at http://www.effectivedb.org/method/effectivet3 For errors in the container or module file, please submit a ticket at [email protected] https://portal.tacc.utexas.edu/tacc-consulting ]] help(help_message,"\n") whatis("Name: effectivet3") whatis("Version: ctr-1.0.1--py36_0") whatis("Category: ['Sequence classification']") whatis("Keywords: ['Sequence analysis']") whatis("Description: Prediction of putative Type-III secreted proteins.") whatis("URL: https://quay.io/repository/biocontainers/effectivet3") set_shell_function("appletviewer",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg appletviewer $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg appletviewer $*') set_shell_function("easy_install-3.6",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg easy_install-3.6 $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg easy_install-3.6 $*') set_shell_function("effectivet3",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg effectivet3 $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg effectivet3 $*') set_shell_function("extcheck",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg extcheck $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg extcheck $*') set_shell_function("idlj",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg idlj $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg idlj $*') set_shell_function("jar",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jar $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jar $*') set_shell_function("jarsigner",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jarsigner $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jarsigner $*') set_shell_function("java-rmi.cgi",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg java-rmi.cgi $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg java-rmi.cgi $*') set_shell_function("javac",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg javac $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg javac $*') set_shell_function("javadoc",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg javadoc $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg javadoc $*') set_shell_function("javah",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg javah $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg javah $*') set_shell_function("javap",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg javap $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg javap $*') set_shell_function("jcmd",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jcmd $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jcmd $*') set_shell_function("jconsole",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jconsole $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jconsole $*') set_shell_function("jdb",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jdb $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jdb $*') set_shell_function("jdeps",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jdeps $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jdeps $*') set_shell_function("jhat",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jhat $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jhat $*') set_shell_function("jinfo",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jinfo $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jinfo $*') set_shell_function("jmap",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jmap $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jmap $*') set_shell_function("jps",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jps $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jps $*') set_shell_function("jrunscript",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jrunscript $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jrunscript $*') set_shell_function("jsadebugd",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jsadebugd $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jsadebugd $*') set_shell_function("jstack",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jstack $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jstack $*') set_shell_function("jstat",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jstat $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jstat $*') set_shell_function("jstatd",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jstatd $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg jstatd $*') set_shell_function("native2ascii",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg native2ascii $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg native2ascii $*') set_shell_function("rmic",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg rmic $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg rmic $*') set_shell_function("schemagen",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg schemagen $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg schemagen $*') set_shell_function("serialver",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg serialver $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg serialver $*') set_shell_function("wsgen",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg wsgen $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg wsgen $*') set_shell_function("wsimport",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg wsimport $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg wsimport $*') set_shell_function("xjc",'singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg xjc $@','singularity exec ${BIOCONTAINER_DIR}/biocontainers/effectivet3/effectivet3-1.0.1--py36_0.simg xjc $*')
local config = require "config" local textbox = {} ; textbox.__index = textbox function textbox.create () return setmetatable({}, textbox) end function textbox:show (args) self.text = assert(args.text, 'must provide text') self.duration = args.duration or 5 self.style = args.style or {} self.style.color = self.style.color or { 0xFF, 0xFF, 0xFF } self.style.size = self.style.size or 32 end function textbox:update (dt, env) if self.duration and self.duration > 0 then self.duration = self.duration - dt else self.text = nil self.duration = 0 end end function textbox:draw (env) if self.duration and self.duration > 0 and self.text then if not self._active_font_size or self.style.size ~= self._active_font_size then self._active_font_size = self.style.size self._font = love.graphics.newFont(config.text_display.font, self.style.size) end love.graphics.setColor(unpack(self.style.color)) love.graphics.setFont(self._font) love.graphics.printf( self.text, (config.window_width - config.text_display.width) / 2, config.text_display.y, config.text_display.width, self.style.align or 'center' ) end end return textbox
do --- hook-line local lines = {} local function hook() lines[#lines+1] = debug.getinfo(2).currentline end local function dummy() end -- <-- line 7 debug.sethook(hook, "l", 0) -- <-- line 10 local x dummy() local y = 1 dummy() dummy() local z = 2; local r = true while y < 4 do y = y + 1 end while z < 4 do z = z + 1 end -- <-- line 20 local v debug.sethook(nil, "", 0) assert(#lines > 0) while lines[1] < 10 do table.remove(lines, 1) end while lines[#lines] > 20 do table.remove(lines) end local s = table.concat(lines, " ") assert(s == "11 12 7 13 14 7 7 15 16 16 16 16 17 18 17 18 17" or s == "11 12 7 13 14 7 14 7 15 16 16 16 16 17 18 17 18 17" or s == "12 13 8 14 15 8 15 8 16 17 17 17 17 18 19 18 19 18" ) lines = {} local function f() if true then return end local function x() end end -- <-- line 36 debug.sethook(hook, "l", 0) f() debug.sethook(nil, "", 0) for i=1,#lines do assert(lines[i] ~= 36) end end
local M = {} function M.report_start(msg) vim.fn['health#report_start'](msg) end function M.report_info(msg) vim.fn['health#report_info'](msg) end function M.report_ok(msg) vim.fn['health#report_ok'](msg) end function M.report_warn(msg, ...) vim.fn['health#report_warn'](msg, ...) end function M.report_error(msg, ...) vim.fn['health#report_error'](msg, ...) end local path2name = function(path) if path:match('%.lua$') then -- Lua: transform "../lua/vim/lsp/health.lua" into "vim.lsp" return path:gsub('.-lua[%\\%/]', '', 1):gsub('[%\\%/]', '.'):gsub('%.health.-$', '') else -- Vim: transform "../autoload/health/provider.vim" into "provider" return vim.fn.fnamemodify(path, ':t:r') end end local PATTERNS = { '/autoload/health/*.vim', '/lua/**/**/health.lua', '/lua/**/**/health/init.lua' } -- :checkhealth completion function used by ex_getln.c get_healthcheck_names() M._complete = function() local names = vim.tbl_flatten(vim.tbl_map(function(pattern) return vim.tbl_map(path2name, vim.api.nvim_get_runtime_file(pattern, true)) end, PATTERNS)) -- Remove duplicates local unique = {} vim.tbl_map(function(f) unique[f] = true end, names) -- vim.health is this file, which is not a healthcheck unique['vim'] = nil return vim.tbl_keys(unique) end return M
local netstr = { "pcr.ClientRequestPropData", "pcr.PropListData", "pcr.EditorCustomData", "pcr.ForceCloseMenu", "pcr.SetMetheProp" } for _,v in pairs(netstr) do util.AddNetworkString(v) end function PCR.ReadBannedProps() -- Empty the table first PCR.BannedProp = {} local path = PHX.ConfigPath .. "/prop_model_bans" if !file.Exists(path,"DATA") then PHX.VerboseMsg("[Prop Menu] !!WARNING : Prop Hunt: X's Prop Ban Data does not exist. Did you forgot to install Prop Hunt: X? Creating the folder anyway...") file.CreateDir(path) end if file.Exists(path.."/model_bans.txt","DATA") then PHX.VerboseMsg("[Prop Menu] Reading Prop Hunt: X's Prop Ban Data...") -- PHX.BANNED_PROP_MODELS local read = util.JSONToTable(file.Read(path.."/model_bans.txt")) for _,mdl in pairs(read) do table.insert(PCR.BannedProp, mdl) end else PHX.VerboseMsg("[Prop Menu] !!WARNING: Prop Hunt: X's Prop Ban Data does not exists, Ignoring..!") end if file.Exists(path.."/pcr_bans.txt","DATA") then PHX.VerboseMsg("[Prop Menu] Reading Prop Menu's additional ban list...") local read = util.JSONToTable(file.Read(path.."/pcr_bans.txt")) for _,mdl in pairs(read) do table.insert(PCR.BannedProp, mdl) end else PHX.VerboseMsg("[Prop Menu] !!WARNING: Prop Menu's additional ban list does not exists, Creating new one...") local proplist = { "models/player.mdl", "models/player/kleiner.mdl" } local json = util.TableToJSON(proplist,true) file.Write(path.."/pcr_bans.txt", json) for _,mdl in pairs(proplist) do table.insert(PCR.BannedProp, mdl) end PHX.VerboseMsg("[Prop Menu] Prop Menu additional ban list has successfully created.") end end function PCR.CheckBBox(entity) local min,max = entity:GetCollisionBounds() if math.Round(max.x) >= PHX:QCVar( "pcr_bbox_max_width" ) or math.Round(max.y) >= PHX:QCVar( "pcr_bbox_max_width" ) or math.Round(max.z) >= PHX:QCVar( "pcr_bbox_max_height" ) then return true end return false end function PCR.GetCustomProps() -- Empty Table first PCR.CustomProp = {} local path = PHX.ConfigPath .. "/prop_chooser_custom" if !file.Exists(path,"DATA") then PHX.VerboseMsg("[Prop Menu] Creating default Prop Menu's Prop Data folder...") file.CreateDir(path) PHX.VerboseMsg("[Prop Menu] Successfully created: "..path.."!") end if file.Exists(path.."/models.txt","DATA") then local read = util.JSONToTable(file.Read(path.."/models.txt")) for _,mdl in pairs(read) do table.insert(PCR.CustomProp, string.lower( mdl )) end else PHX.VerboseMsg("[Prop Menu] Creating default Prop Menu's Custom Prop data file...") local proplist = { "models/balloons/balloon_star.mdl", "models/balloons/balloon_dog.mdl", "models/balloons/balloon_classicheart.mdl" } local json = util.TableToJSON(proplist,true) file.Write(path.."/models.txt", json) for _,mdl in pairs(proplist) do table.insert(PCR.CustomProp, mdl) end PHX.VerboseMsg("[Prop Menu] Prop Menu's Custom Prop Data successfully created.") end end PCR.PropList = {} function PCR.PopulateProp() PCR.ReadBannedProps() local count = 0 for i,prop in RandomPairs(ents.FindByClass("prop_physics*")) do if (!IsValid(prop:GetPhysicsObject())) then PHX.VerboseMsg("[Prop Menu] Warning: Prop "..prop:GetModel().. " @Index #"..prop:EntIndex().." has no physics. Ignoring!") continue end if table.HasValue(PCR.PropList, string.lower(prop:GetModel())) then continue end if (PHX:QCVar( "pcr_enable_prop_ban" ) && table.HasValue(PCR.BannedProp, prop:GetModel())) then PHX.VerboseMsg("[Prop Menu] Banning prop of "..prop:GetModel().." @Index #"..prop:EntIndex().."...") continue end if (PHX:QCVar( "pcr_enable_bbox_limit" ) && PCR.CheckBBox(prop)) then PHX.VerboseMsg("[Prop Menu] Found prop "..prop:GetModel().." @Index #"..prop:EntIndex().." that Exceeds the OBB settings, ignoring...") continue end if (PHX:QCVar( "pcr_limit_enable" ) && count == PHX:QCVar( "pcr_max_prop_list" )) then break end count = count + 1 table.insert(PCR.PropList, string.lower(prop:GetModel())) util.PrecacheModel(prop:GetModel()) end PHX.VerboseMsg("[Prop Menu] Total by "..count.." props was added.") if PHX:QCVar( "pcr_allow_custom" ) then PHX.VerboseMsg("[Prop Menu] Adding Custom Props as well...") PCR.GetCustomProps() for i,prop in pairs(PCR.CustomProp) do table.insert(PCR.PropList, prop) util.PrecacheModel(prop) end end end PCR.propDatajson = "" PCR.propDataSize = 0 -- this was used for prop editor thing PCR.customPropJson = "" PCR.customPropSize = 0 hook.Add("Initialize", "PCR.PopulateProps", function() timer.Simple(2, function() PCR.PopulateProp() local json = util.TableToJSON(PCR.PropList) PCR.propDatajson = util.Compress(json) PCR.propDataSize = PCR.propDatajson:len() if !table.IsEmpty(PCR.CustomProp) then local jsc = util.TableToJSON(PCR.CustomProp) PCR.customPropJson = util.Compress(jsc) PCR.customPropSize = PCR.customPropJson:len() end end) end) hook.Add("PlayerInitialSpawn","pcr.InitPropRequestData",function(ply) ply.pcrHasPropData = false ply:SetNWInt("CurrentUsage", 0) end) net.Receive("pcr.ClientRequestPropData", function(len, ply) if !ply.pcrHasPropData then net.Start("pcr.PropListData") net.WriteUInt(PCR.propDataSize, 32) net.WriteData(PCR.propDatajson, PCR.propDataSize) net.Send(ply) if !table.IsEmpty(PCR.CustomProp) then net.Start("pcr.EditorCustomData") net.WriteUInt(PCR.customPropSize, 32) net.WriteData(PCR.customPropJson, PCR.customPropSize) net.Send(ply) end ply.pcrHasPropData = true end end) hook.Add("PostCleanupMap","PCR.ResetUseLimit",function() for _,ply in pairs(player.GetAll()) do ply:ResetUsage() end end) local function PCRForceClose(ply) net.Start("pcr.ForceCloseMenu") net.Send(ply) end hook.Add("PostPlayerDeath", "PCR.ForceCloseMenu", function(ply) PCRForceClose(ply) end) hook.Add("PH_RoundEnd", "PCR.ForceCloseMenu", function() for _,v in pairs(player.GetAll()) do PCRForceClose(v) end end) PCR.NotifyPlayer = function( ply , message , kind, ... ) ply:PHXNotify( message, kind, 5, true, ... ) ply:SendLua("surface.PlaySound('garrysmod/save_load".. math.random(1,4) ..".wav')") end local function PlayerDelayCheck(ply) if !ply.waitTime then ply.waitTime = 0 end local lastUsedTime = ply:GetNWFloat("pcr.LastUsedTime") local delayedTime = lastUsedTime + PHX:QCVar( "pcr_delay_use" ) local currentTime = CurTime() ply.waitTime = delayedTime - currentTime if ply.waitTime < 0 then ply.waitTime = 0 end return delayedTime > currentTime; end net.Receive("pcr.SetMetheProp",function(len,ply) local mdl = net.ReadString() if PHX:GetCVar( "pcr_only_allow_certain_groups" ) and !PCR:CheckUserGroup( ply ) then ply:PHXChatInfo("ERROR", "PCR_ONLY_GROUP") return end -- if so, Warn / Kick player to maximum thresold if they are trying to access invalid model. if (not table.HasValue(PCR.PropList, mdl)) then if !ply.warnInvalidModel then ply.warnInvalidModel = 0 end print("[Prop Menu] !!WARNING: User ".. ply:Nick() .." ("..ply:SteamID()..") is trying to use Invalid Prop Model : " .. mdl .. ", which DOES NOT EXIST in the map!") if ( PHX:QCVar( "pcr_kick_invalid" ) ) then ply.warnInvalidModel = ply.warnInvalidModel + 1 ply:PHXChatInfo("ERROR", "PCR_NOT_EXIST_COUNT", tostring(ply.warnInvalidModel)) if ply.warnInvalidModel > 4 then ply:Kick("[Prop Menu] Kicked for Reason: trying to access invalid prop!") end else ply:PHXChatInfo("ERROR", "PCR_NOT_EXIST") end return end -- Make sure that the player is On Ground and Not crouching. if ( ply:Crouching() or (not ply:IsOnGround()) ) then ply:PHXChatInfo("NOTICE", "PCR_STAY_ON_GROUND") return end -- Make sure player is not accessing banned prop if ( PHX:QCVar( "pcr_enable_prop_ban" ) and table.HasValue(PCR.BannedProp, string.lower(mdl)) ) then ply:PHXChatInfo("WARNING", "PCR_PROPBANNED_BYPCR") return end if ( IsValid(ply) and (not PlayerDelayCheck(ply)) ) then if ply:CheckUsage() == 0 then ply:PHXChatInfo("GOOD", "PCR_REACHED_LIMIT") return end local pos = ply:GetPos() --Temporarily Spawn a prop. local ent = ents.Create("prop_physics") ent:SetPos( Vector( pos.x, pos.y, pos.z-512 ) ) ent:SetAngles(Angle(0,0,0)) ent:SetKeyValue("spawnflags","654") ent:SetNoDraw(true) ent:SetModel(mdl) ent:Spawn() local usage = ply:CheckUsage() local hmx,hz = ent:GetPropSize() if ( PHX:QCVar( "pcr_use_room_check" ) and (not ply:CheckHull(hmx,hmx,hz)) ) then if usage > 0 then ply:PHXChatInfo("NOTICE", "PCR_NOROOM") end elseif table.HasValue( PHX.BANNED_PROP_MODELS, ent:GetModel() ) then ply:PHXChatInfo("WARNING", "PCR_PROPBANNED") else if usage <= -1 then GAMEMODE:PlayerExchangeProp(ply,ent) PCR.NotifyPlayer( ply, "PCR_USAGE_UNLIMIT", "UNDO" ) elseif usage > 0 then ply:UsageSubstractCount() GAMEMODE:PlayerExchangeProp(ply,ent) PCR.NotifyPlayer( ply, "PCR_USAGE_COUNT", "GENERIC", (usage-1) ) end end ent:Remove() ply:SetNWFloat( "pcr.LastUsedTime", CurTime() ) else ply:PHXChatInfo( "NOTICE", "PCR_PLS_WAIT", math.Round(ply.waitTime) ) end end)
object_tangible_quest_som_mining_marker_01 = object_tangible_quest_shared_som_mining_marker_01:new { } ObjectTemplates:addTemplate(object_tangible_quest_som_mining_marker_01, "object/tangible/quest/som_mining_marker_01.iff")
local K, C = unpack(select(2, ...)) local Module = K:GetModule("Miscellaneous") local _G = _G local table_wipe = _G.table.wipe local unpack = _G.unpack local BAG_ITEM_QUALITY_COLORS = _G.BAG_ITEM_QUALITY_COLORS local CreateFrame = _G.CreateFrame local GetInventoryItemLink = _G.GetInventoryItemLink local GetInventoryItemTexture = _G.GetInventoryItemTexture local GetItemInfo = _G.GetItemInfo local UnitExists = _G.UnitExists local UnitGUID = _G.UnitGUID local inspectSlots = { "Head", "Neck", "Shoulder", "Shirt", "Chest", "Waist", "Legs", "Feet", "Wrist", "Hands", "Finger0", "Finger1", "Trinket0", "Trinket1", "Back", "MainHand", "SecondaryHand", "Ranged", } function Module:GetSlotAnchor(index) if not index then return end if index <= 5 or index == 9 or index == 15 then return "BOTTOMLEFT", 40, 20 elseif index == 16 then return "BOTTOMRIGHT", -40, 2 elseif index == 17 then return "BOTTOMLEFT", 40, 2 else return "BOTTOMRIGHT", -40, 20 end end function Module:CreateItemTexture(slot, relF, x, y) local icon = slot:CreateTexture(nil, "ARTWORK") icon:SetPoint(relF, x, y) icon:SetSize(14, 14) icon:SetTexCoord(unpack(K.TexCoords)) icon.bg = CreateFrame("Frame", nil, slot) icon.bg:SetPoint("TOPLEFT", icon, -1, 1) icon.bg:SetPoint("BOTTOMRIGHT", icon, 1, -1) icon.bg:SetFrameLevel(3) icon.bg:CreateBorder() icon.bg:Hide() return icon end function Module:CreateItemString(frame, strType) if frame.fontCreated then return end for index, slot in pairs(inspectSlots) do if index ~= 4 then local slotFrame = _G[strType..slot.."Slot"] slotFrame.iLvlText = K.CreateFontString(slotFrame, 12, nil, "OUTLINE") slotFrame.iLvlText:ClearAllPoints() slotFrame.iLvlText:SetPoint("BOTTOMLEFT", slotFrame, 1, 1) local relF, x, y = Module:GetSlotAnchor(index) slotFrame.enchantText = K.CreateFontString(slotFrame, 12, nil, "OUTLINE") slotFrame.enchantText:ClearAllPoints() slotFrame.enchantText:SetPoint(relF, slotFrame, x, y) slotFrame.enchantText:SetTextColor(0, 1, 0) for i = 1, 5 do local offset = (i-1) * 18 + 5 local iconX = x > 0 and x+offset or x-offset local iconY = index > 15 and 20 or 2 slotFrame["textureIcon"..i] = Module:CreateItemTexture(slotFrame, relF, iconX, iconY) end end end frame.fontCreated = true end local pending = {} function Module:RefreshButtonInfo() if InspectFrame and InspectFrame.unit then for index, slotFrame in pairs(pending) do local link = GetInventoryItemLink(InspectFrame.unit, index) if link then local quality, level = select(3, GetItemInfo(link)) if quality then local color = BAG_ITEM_QUALITY_COLORS[quality] if C["Misc"].ItemLevel and level and level > 1 and quality > 1 then slotFrame.iLvlText:SetText(level) slotFrame.iLvlText:SetTextColor(color.r, color.g, color.b) end pending[index] = nil end end end if not next(pending) then self:Hide() return end else table_wipe(pending) self:Hide() end end function Module:ItemLevel_SetupLevel(frame, strType, unit) if not UnitExists(unit) then return end Module:CreateItemString(frame, strType) for index, slot in pairs(inspectSlots) do if index ~= 4 then local slotFrame = _G[strType..slot.."Slot"] slotFrame.iLvlText:SetText("") slotFrame.enchantText:SetText("") for i = 1, 5 do local texture = slotFrame["textureIcon"..i] texture:SetTexture(nil) texture.bg:Hide() end local itemTexture = GetInventoryItemTexture(unit, index) if itemTexture then local link = GetInventoryItemLink(unit, index) if link then local quality, level = select(3, GetItemInfo(link)) if quality then local color = BAG_ITEM_QUALITY_COLORS[quality] if C["Misc"].ItemLevel and level and level > 1 and quality > 1 then slotFrame.iLvlText:SetText(level) slotFrame.iLvlText:SetTextColor(color.r, color.g, color.b) end else pending[index] = slotFrame Module.QualityUpdater:Show() end if C["Misc"].GemEnchantInfo then local _, enchant, gems = K.GetItemLevel(link, unit, index, true) if enchant then slotFrame.enchantText:SetText(enchant) end for i = 1, 5 do local texture = slotFrame["textureIcon"..i] if gems and next(gems) then local index, gem = next(gems) texture:SetTexture(gem) texture.bg:Show() gems[index] = nil end end end else pending[index] = slotFrame Module.QualityUpdater:Show() end end end end end function Module:ItemLevel_UpdatePlayer() Module:ItemLevel_SetupLevel(CharacterFrame, "Character", "player") end function Module:ItemLevel_UpdateInspect(...) local guid = ... if InspectFrame and InspectFrame.unit and UnitGUID(InspectFrame.unit) == guid then Module:ItemLevel_SetupLevel(InspectFrame, "Inspect", InspectFrame.unit) end end function Module:CreateSlotItemLevel() if not C["Misc"].ItemLevel then return end -- iLvl on CharacterFrame CharacterFrame:HookScript("OnShow", Module.ItemLevel_UpdatePlayer) K:RegisterEvent("PLAYER_EQUIPMENT_CHANGED", Module.ItemLevel_UpdatePlayer) -- iLvl on InspectFrame K:RegisterEvent("INSPECT_READY", self.ItemLevel_UpdateInspect) -- Update item quality Module.QualityUpdater = CreateFrame("Frame") Module.QualityUpdater:Hide() Module.QualityUpdater:SetScript("OnUpdate", Module.RefreshButtonInfo) end
local FixedHeader = require "lumina.protocol.packet.fixed_header" local PacketType = require "lumina.protocol.packet.packet_type" local Disconnect = {} Disconnect.__index = Disconnect Disconnect.__tostring = function(self) return require "lumina.utils".packet_string("Disconnect", self) end function Disconnect.new() return setmetatable({ fixed_header = FixedHeader.from(PacketType.disconnect(), 0), }, Disconnect) end function Disconnect:encode_packet() return "" end function Disconnect:encoded_packet_length() return 0 end function Disconnect:decode_packet(_, _fixed_header) return Disconnect.new() end return Disconnect
local Attributor = {} Attributor.__index = Attributor function Attributor:getAttr(node, attrName) if node.__isPocoNodeWrapper__ == nil then node = node[1] end return node:getAttr(attrName) end function Attributor:setAttr(node, attrName, attrVal) if node.__isPocoNodeWrapper__ == nil then node = node[1] end node:setAttr(attrName, attrVal) end return Attributor
-- This file is subject to copyright - contact [email protected] for more information. -- INSTALL: CINEMA surface.CreateFont("ScoreboardVidTitle", { font = "Open Sans Condensed", size = 20, weight = 200 }) surface.CreateFont("ScoreboardVidDuration", { font = "Open Sans", size = 14, weight = 200 }) surface.CreateFont("ScoreboardVidVotes", { font = "Open Sans Condensed", size = 18, weight = 200 }) local ADMIN = {} ADMIN.TitleHeight = 64 ADMIN.VidHeight = 32 -- 48 function ADMIN:Init() local Theater = LocalPlayer():GetTheater() self:SetZPos(1) self:SetSize(256, 512) self:SetPos(ScrW() - (256 + 8), ScrH() / 2 - (self:GetTall() / 2)) self.Title = Label("", self) self.Title:SetFont("ScoreboardTitle") self.Title:SetColor(Color(255, 255, 255)) self.NextUpdate = 0.0 self.Options = vgui.Create("DPanelList", self) self.Options:DockMargin(0, self.TitleHeight + 2, 0, 0) self.Options:SetDrawBackground(false) self.Options:SetPadding(4) self.Options:SetSpacing(4) -- Skip the current video local VoteSkipButton = vgui.Create("TheaterButton") VoteSkipButton:SetText(T'Theater_Skip') VoteSkipButton.DoClick = function(self) RunConsoleCommand("cinema_forceskip") end self.Options:AddItem(VoteSkipButton) -- Seek local SeekButton = vgui.Create("TheaterButton") SeekButton:SetText(T'Theater_Seek') SeekButton.DoClick = function(self) Derma_StringRequest(T'Theater_Seek', T'Theater_SeekQuery', "0", function(strTextOut) RunConsoleCommand("cinema_seek", strTextOut) end, function(strTextOut) end, T'Theater_Seek', T'Cancel') end self.Options:AddItem(SeekButton) -- Admin-only options if LocalPlayer():IsAdmin() then -- Reset the theater local ResetButton = vgui.Create("TheaterButton") ResetButton:SetText(T'Theater_Reset') ResetButton.DoClick = function(self) RunConsoleCommand("cinema_reset") end self.Options:AddItem(ResetButton) end -- Private theater options if Theater and Theater:IsPrivate() then local NameButton = vgui.Create("TheaterButton") NameButton:SetText(T'Theater_ChangeName') NameButton.DoClick = function(self) Derma_StringRequest(T'Theater_ChangeName', "", Theater:Name(), function(strTextOut) RunConsoleCommand("cinema_name", strTextOut) end, function(strTextOut) end, T'Set', T'Cancel') end self.Options:AddItem(NameButton) local LockButton = vgui.Create("TheaterButton") LockButton:SetText(T'Theater_QueueLock') LockButton.DoClick = function(self) RunConsoleCommand("cinema_lock") end self.Options:AddItem(LockButton) --added self.AllowItemUse = vgui.Create("TheaterButton", self) self.AllowItemUse:SetText("Allow/Block Vapes") self.AllowItemUse.DoClick = function() net.Start("ToggleItemsInMyTheater") net.SendToServer() end self.Options:AddItem(self.AllowItemUse) if Theater:GetOwner() ~= LocalPlayer() then self.AllowItemUse:SetVisible(false) end self.MuteMode = vgui.Create("TheaterButton", self) self.MuteMode:SetText("Toggle Gag Mode") self.MuteMode.DoClick = function() net.Start("ToggleTheaterMuteMode") net.SendToServer() end self.Options:AddItem(self.MuteMode) if Theater:GetOwner() ~= LocalPlayer() then self.MuteMode:SetVisible(false) end self.extendRent = vgui.Create("TheaterButton", self) self.extendRent:SetText("Protect Theater") self.extendRent:SetFont("Trebuchet24") self.extendRent.DoClick = function() CreateRentWindow() end self.Options:AddItem(self.extendRent) if Theater:GetOwner() ~= LocalPlayer() then self.extendRent:SetVisible(false) end end end function ADMIN:Update() local Theater = LocalPlayer():GetTheater() -- get player's theater from their location if not Theater then return end -- Change title text if Theater:IsPrivate() and Theater:GetOwner() == LocalPlayer() then self.Title:SetText(T'Theater_Owner') if self.extendRent then self.extendRent:SetVisible(true) end if self.AllowItemUse then self.AllowItemUse:SetVisible(true) end if self.MuteMode then self.MuteMode:SetVisible(true) end elseif LocalPlayer():StaffControlTheater() then self.Title:SetText('STAFF CONTROL') if self.extendRent then self.extendRent:SetVisible(false) end if self.AllowItemUse then self.AllowItemUse:SetVisible(false) end if self.MuteMode then self.MuteMode:SetVisible(false) end end end function ADMIN:Think() if RealTime() > self.NextUpdate then self:Update() self:InvalidateLayout() self.NextUpdate = RealTime() + 3.0 end end function ADMIN:Paint(w, h) surface.SetDrawColor(BrandColorGrayDarker) surface.DrawRect(0, 0, self:GetWide(), self:GetTall()) local xp, _ = self:GetPos() BrandBackgroundPattern(0, 0, self:GetWide(), self.Title:GetTall(), xp) BrandDropDownGradient(0, self.Title:GetTall(), self:GetWide()) end function ADMIN:PerformLayout() self.Title:SizeToContents() self.Title:SetTall(self.TitleHeight) self.Title:CenterHorizontal() if self.Title:GetWide() > self:GetWide() and self.Title:GetFont() ~= "ScoreboardTitleSmall" then self.Title:SetFont("ScoreboardTitleSmall") end self.Options:Dock(FILL) self.Options:SizeToContents() end vgui.Register("ScoreboardAdmin", ADMIN)
-- TODO: This matches the Switch UI but not the DS UI, and should be updated -- after the art team has established the look function DrawPauseScreen(self) -- Add a light overlay GameFont:setLineHeight(1) love.graphics.setColor(1, 1, 1, 0.3) love.graphics.rectangle("fill", 0, 0, love.graphics.getWidth(), love.graphics.getHeight()) local blackImage = love.graphics.newImage(settings.black_screen_path) local blackImageScale = 2*dimensions.window_width/1920 * 2 -- Add the settings box with a 2px white outline DrawCenteredRectangle({ width = love.graphics.getWidth() * 3/5, height = love.graphics.getHeight() - 120, buttons = { { title = "Close", key = controls.pause } }, }) local resumeW = (dimensions.window_width * 1/3.75 + (love.graphics.newText(GameFont, "Resume"):getWidth() / 4)) local resumeX = (dimensions.window_width/2 - resumeW/2) local resumeY = blackImage:getHeight()*blackImageScale - 480 local resumeH = 60 local settingsW = (dimensions.window_width * 1/3.75 + (love.graphics.newText(GameFont, "Settings"):getWidth() / 4)) local settingsX = (dimensions.window_width/2 - settingsW/2) local settingsY = blackImage:getHeight()*blackImageScale - 370 local settingsH = 60 local backToMenuW = (dimensions.window_width * 1/3.75 + (love.graphics.newText(GameFont, "Back to menu"):getWidth() / 4)) local backToMenuX = (dimensions.window_width/2 - backToMenuW/2) local backToMenuY = blackImage:getHeight()*blackImageScale - 260 local backToMenuH = 60 local dx = 8 local dy = 8 love.graphics.setColor(0.44,0.56,0.89) if TitleSelection == "Settings" then love.graphics.rectangle("fill", settingsX-dx, settingsY-dy, settingsW+2*dx, settingsH+2*dy) elseif TitleSelection == "Back to menu" then love.graphics.rectangle("fill", backToMenuX-dx, backToMenuY-dy, backToMenuW+2*dx, backToMenuH+2*dy) else love.graphics.rectangle("fill", resumeX-dx, resumeY-dy, resumeW+2*dx, resumeH+2*dy) end love.graphics.setColor(0.3,0.3,0.3) love.graphics.rectangle("fill", resumeX, resumeY, resumeW, resumeH) love.graphics.setColor(0.3,0.3,0.3) love.graphics.rectangle("fill", settingsX, settingsY, settingsW, settingsH) love.graphics.setColor(0.3,0.3,0.3) love.graphics.rectangle("fill", backToMenuX, backToMenuY, backToMenuW, backToMenuH) love.graphics.setColor(1,1,1) local textScale = 3 local resumeText = love.graphics.newText(GameFont, "Resume") love.graphics.draw( resumeText, resumeX + resumeW/2-(resumeText:getWidth() * textScale)/2, resumeY + resumeH/2-(resumeText:getHeight() * textScale)/2, 0, textScale, textScale ) local settingsText = love.graphics.newText(GameFont, "Settings") love.graphics.draw( settingsText, settingsX + settingsW/2-(settingsText:getWidth() * textScale)/2, settingsY + settingsH/2-(settingsText:getHeight() * textScale)/2, 0, textScale, textScale ) local backToMenuText = love.graphics.newText(GameFont, "Back to menu") love.graphics.draw( backToMenuText, backToMenuX + backToMenuW/2-(backToMenuText:getWidth() * textScale)/2, backToMenuY + backToMenuH/2-(backToMenuText:getHeight() * textScale)/2, 0, textScale, textScale ) return self end pauseSelections = {} pauseSelections[1] = "Back to menu"; pauseSelections[2] = "Settings"; pauseSelections[3] = "Resume"; TitleSelection = "Resume"; SelectionIndex = 3; blip2 = love.audio.newSource("sounds/selectblip2.wav", "static") jingle = love.audio.newSource("sounds/selectjingle.wav", "static") blip2:setVolume(settings.sfx_volume / 100 / 2) jingle:setVolume(settings.sfx_volume / 100 / 2) Music = {} Sounds = {} musicFiles = love.filesystem.getDirectoryItems(settings.music_directory) soundFiles = love.filesystem.getDirectoryItems(settings.sfx_directory) PauseScreenConfig = { displayed = false; displayKey = controls.pause; displayCondition = function() -- Don't let the pause menu show until the scene has -- started (AKA we're off the title screen) return Episode.loaded; end; onKeyPressed = function(key) if key == controls.start_button then if TitleSelection == "Resume" then screens.pause.displayed = false elseif TitleSelection == "Back to menu" then screens.pause.displayed = false Episode:stop() DrawTitleScreen() screens.title.displayed = true TitleSelection = "New Game"; SelectionIndex = 0; blip2:stop() blip2:play() elseif TitleSelection == "Settings" then screens.pause.displayed = false DrawOptionsScreen() screens.options.displayed = true TitleSelection = "Back"; SelectionIndex = 0; blip2:stop() blip2:play() end elseif key == controls.pause_nav_up then blip2:stop() blip2:play() SelectionIndex = SelectionIndex + 1; if (SelectionIndex > 3) then SelectionIndex = 1 end TitleSelection = pauseSelections[SelectionIndex] elseif key == controls.pause_nav_down then blip2:stop() blip2:play() SelectionIndex = SelectionIndex - 1; if (SelectionIndex < 1) then SelectionIndex = 3 end TitleSelection = pauseSelections[SelectionIndex] end end; onDisplay = function() TitleSelection = "Resume"; SelectionIndex = 3; end; draw = function() DrawPauseScreen() end }
minetest.register_node("colourful_ladders:wooden_ladder", { description = "Colourful Ladders", tiles = {"wooden_ladder.png"}, inventory_image = "wooden_ladder.png", wield_image = "wooden_ladder.png", is_ground_content = false, paramtype1 = "light", drawtype = "signlike", groups = {choppy = 2, oddly_breakable_by_hand = 3, flammable = 2}, sounds = default.node_sound_wood_defaults(), paramtype2 = "colorwallmounted", palette = "unifieddyes_palette_colorwallmounted.png", walkable = false, climbable = true, selection_box = { type = "wallmounted" }, }) minetest.override_item("colourful_ladders:wooden_ladder", { palette = "unifieddyes_palette_colorwallmounted.png", airbrush_replacement_node = "colourful_ladders:wooden_ladder", }) unifieddyes.register_color_craft({ output = "colourful_ladders:wooden_ladder", palette = "wallmounted", type = "shapeless", neutral_node = "colourful_ladders:wooden_ladder", recipe = { "NEUTRAL_NODE", "MAIN_DYE" } })
-- Author : Potdisc -- Create Date : 12/15/2014 8:55:10 PM -- DefaultModule -- versionCheck.lua Adds a Version Checker to check versions of either people in current raidgroup or guild local addon = LibStub("AceAddon-3.0"):GetAddon("RCLootCouncil") local RCVersionCheck = addon:NewModule("RCVersionCheck", "AceTimer-3.0", "AceComm-3.0", "AceHook-3.0") local ST = LibStub("ScrollingTable") local L = LibStub("AceLocale-3.0"):GetLocale("RCLootCouncil") local Deflate = LibStub("LibDeflate") local deflate_level = {level = 9} function RCVersionCheck:OnInitialize() -- Initialize scrollCols on self so others can change it self.scrollCols = { { name = "", width = 20, sortnext = 2,}, { name = L["Name"], width = 150, }, { name = L["Rank"], width = 90, }, { name = L["Version"], width = 140, align = "RIGHT" }, } end function RCVersionCheck:OnEnable() self.frame = self:GetFrame() self:RegisterComm("RCLootCouncil") self:RegisterComm("RCLootCouncil_WotLK") self:Show() end function RCVersionCheck:OnDisable() self:Hide() self:UnregisterAllComm() self.frame.rows = {} end function RCVersionCheck:Show() self:AddEntry(addon.playerName, addon.playerClass, addon.guildRank, addon.version, addon.tVersion) -- add ourself self.frame:Show() self.frame.st:SetData(self.frame.rows) end function RCVersionCheck:Hide() self.frame:Hide() end function RCVersionCheck:OnCommReceived(prefix, serializedMsg, distri, sender) if prefix == "RCLootCouncil" then local decoded = Deflate:DecodeForPrint(serializedMsg) if not decoded then return -- probably an old version or somehow a bad message idk just throw this away end local decompressed = Deflate:DecompressDeflate(decoded) local test, command, data = addon:Deserialize(decompressed) if addon:HandleXRealmComms(self, command, data, sender) then return end addon:DebugLog("VersionCheckComm received:", command, "from:", sender, "distri:", distri) if test and command == "verTestReply" then self:AddEntry(unpack(data)) end elseif prefix == "RCLootCouncil_WotLK" then -- TODO: Remove later when everyone has updated. local decoded_msg = Deflate:DecodeForPrint(serializedMsg) local decompressed_msg = Deflate:DecompressDeflate(decoded_msg) local ok, command, data = addon:Deserialize(decompressed_msg) if ok and command == "verTestReply" then self:AddEntry(sender, data[1], data[2], data[3], data[3]) end end end function RCVersionCheck:Query(group) addon:DebugLog("Player asked for verTest", group) if group == "guild" then GuildRoster() for i = 1, GetNumGuildMembers() do local name, rank, _,_,_,_,_,_, online,_, class = GetGuildRosterInfo(i) if online then self:AddEntry(name, class, rank, L["Waiting for response"]) end end elseif group == "group" then for i = 1, addon:GetNumGroupMembers() do local name, _, _, _, _, class, _, online = GetRaidRosterInfo(i) if online then self:AddEntry(name, class, L["Unknown"], L["Waiting for response"]) end end end addon:SendCommand(group, "verTest", addon.version, addon.tVersion) -- TODO: REMOVE LATER AFTER MOST HAVE UPGRADED local serialized_data = addon:Serialize("verTest", {addon.version}) local compressed_data = Deflate:CompressDeflate(serialized_data, deflate_level) local encoded = Deflate:EncodeForPrint(compressed_data) if group == "group" then if addon:IsInRaid() then group = "RAID" else group = "PARTY" end elseif group == "guild" then group = "GUILD" end addon:SendCommMessage("RCLootCouncil_WotLK", encoded, group) self:AddEntry(addon.playerName, addon.playerClass, addon.guildRank, addon.version, addon.tVersion) -- add ourself self:ScheduleTimer("QueryTimer", 5) end function RCVersionCheck:QueryTimer() for k,v in pairs(self.frame.rows) do local cell = self.frame.st:GetCell(k,4) if cell.value == L["Waiting for response"] then cell.value = L["Not installed"] end end self:Update() end function RCVersionCheck:AddEntry(name, class, guildRank, version, tVersion) local vVal = version if tVersion then vVal = version.."-"..tVersion end for row, v in ipairs(self.frame.rows) do if addon:UnitIsUnit(v.name, name) then -- they're already added, so update them v.cols = { { value = "", DoCellUpdate = addon.SetCellClassIcon, args = {class}, }, { value = name,color = addon:GetClassColor(class), }, { value = guildRank, color = self:GetVersionColor(version,tVersion)}, { value = vVal , color = self:GetVersionColor(version,tVersion)}, } return self:Update() end end -- They haven't been added yet, so do it tinsert(self.frame.rows, { name = name, cols = { { value = "", DoCellUpdate = addon.SetCellClassIcon, args = {class}, }, { value = name,color = addon:GetClassColor(class), }, { value = guildRank, color = self:GetVersionColor(version,tVersion)}, { value = vVal , color = self:GetVersionColor(version,tVersion)}, }, }) self:Update() end function RCVersionCheck:Update() self.frame.st:SortData() end function RCVersionCheck:GetVersionColor(ver,tVer) local green, yellow, red, grey = {r=0,g=1,b=0,a=1},{r=1,g=1,b=0,a=1},{r=1,g=0,b=0,a=1},{r=0.75,g=0.75,b=0.75,a=1} if tVer then return yellow end if ver == addon.version then return green end if ver < addon.version then return red end return grey end function RCVersionCheck:GetFrame() if self.frame then return self.frame end local f = addon:CreateFrame("DefaultRCVersionCheckFrame", "versionCheck", L["RCLootCouncil Version Checker"], 250) local b1 = addon:CreateButton(L["Guild"], f.content) b1:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 10, 10) b1:SetScript("OnClick", function() self:Query("guild") end) f.guildBtn = b1 local b2 = addon:CreateButton(L["Group"], f.content) b2:SetPoint("LEFT", b1, "RIGHT", 15, 0) b2:SetScript("OnClick", function() self:Query("group") end) f.raidBtn = b2 local b3 = addon:CreateButton(L["Close"], f.content) b3:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", -10, 10) b3:SetScript("OnClick", function() self:Disable() end) f.closeBtn = b3 local st = ST:CreateST(self.scrollCols, 12, 20, nil, f.content) st.frame:SetPoint("TOPLEFT",f,"TOPLEFT",10,-35) --content.frame:SetBackdropColor(1,0,0,1) f:SetWidth(st.frame:GetWidth()+20) f.rows = {} -- the row data f.st = st return f end
--[[ An if statement consists of a Boolean expression followed by one or more statements. basic syntax: ``` if(boolean_expression) then statement(s) will execute if the boolean expression is true end ``` If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If Boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) will be executed. Lua programming language assumes any combination of Boolean true and non-nil values as true, and if it is either Boolean false or nil, then it is assumed as false value. It is to be noted that in Lua, zero will be considered as true. --]] local a = 30 if a < 20 then -- [ if condition is true --] print("a is less than 20") elseif a == 22 then -- [ if else if condition is true --] print("a == 22") else -- [ if condition is false --] print("a is not less than 20") end
slot0 = class("WSMapArtifact", import("...BaseEntity")) slot0.Fields = { transform = "userdata", prefab = "string", theme = "table", attachment = "table", moduleTF = "userdata", item_info = "table" } slot0.Build = function (slot0) slot0.transform = GetOrAddComponent(GameObject.New(), "RectTransform") slot0.transform.name = "model" end slot0.Dispose = function (slot0) slot0:Unload() Destroy(slot0.transform) slot0:Clear() end slot0.Setup = function (slot0, slot1, slot2, slot3) slot0.item_info = slot1 slot0.theme = slot2 slot0.attachment = slot3 slot0:Load() end slot0.Load = function (slot0) slot0.prefab = slot0.item_info[3] PoolMgr.GetInstance():GetPrefab(WorldConst.ResChapterPrefab .. slot1, slot0.item_info[3], true, function (slot0) if slot0.prefab then slot0.moduleTF = tf(slot0) slot0.moduleTF:SetParent(slot0.transform, false) slot0:Init() else slot1:ReturnPrefab(WorldConst.ResChapterPrefab .. slot2, slot1, slot0) end end) end slot0.Unload = function (slot0) if slot0.prefab and slot0.moduleTF then PoolMgr.GetInstance():ReturnPrefab(WorldConst.ResChapterPrefab .. slot0.prefab, slot0.prefab, slot0.moduleTF.gameObject, true) end slot0.prefab = nil slot0.moduleTF = nil end slot0.Init = function (slot0) if not IsNil(slot0.moduleTF:GetComponent(typeof(UnityEngine.UI.Graphic))) then slot1.raycastTarget = false end for slot6 = 0, slot0.moduleTF:GetComponentsInChildren(typeof(UnityEngine.UI.Graphic), true).Length - 1, 1 do slot2[slot6].raycastTarget = false end slot3 = Vector2.zero slot4 = Vector3.one slot5 = Vector3.zero if slot0.attachment then slot3 = slot0.attachment:GetDeviation() slot4 = slot0.attachment:GetScale() slot5 = (slot0.attachment:GetMillor() and Vector3(0, 180, 0)) or Vector3.zero else slot3 = Vector2(slot0.item_info[4], slot0.item_info[5]) end slot0.transform.anchoredPosition = slot3 slot0.transform.localScale = slot4 slot0.transform.localEulerAngles = slot5 end return slot0
minetest.after(0, function() if not armor.def then minetest.after(2,minetest.chat_send_all,"#Better HUD: Please update your version of 3darmor") HUD_SHOW_ARMOR = false end end) function hud.get_armor(player) if not player or not armor.def then return end local name = player:get_player_name() local def = armor.def[name] or nil if def and def.state and def.count then hud.set_armor(name, def.state, def.count) end end function hud.set_armor(player_name, ges_state, items) local max_items = 4 if items == 5 then max_items = items end local max = max_items * 65535 local lvl = max - ges_state lvl = lvl/max if ges_state == 0 and items == 0 then lvl = 0 end hud.armor[player_name] = lvl* (items * (20 / max_items)) end
Width = 9 Toggle = false OnDraw = function(self, x, y) local _x = 0 local onColour = self.Toggle and colours.green or colours.lightGrey Drawing.DrawCharacters(x, y, ' On ', colours.white, onColour) local offColour = self.Toggle and colours.lightGrey or colours.red Drawing.DrawCharacters(x + 4, y, ' Off ', colours.white, offColour) end OnClick = function(self, event, side, x, y) if x >= 5 then self.Toggle = false else self.Toggle = true end if self.OnChange then self:OnChange(self.Toggle) end end
local m = require("moses") local match = require("luassert.match") local create = require("support.factory").create local Combo = require("invokation.combos.Combo") local Combos = require("invokation.combos.Combos") local Talents = require("invokation.dota2.talents") local CombosHero = require("invokation.combos.hero") local CombosComm = require("invokation.combos.communication") local CombosSound = require("invokation.combos.sound") local FreestyleCombo = require("invokation.combos.FreestyleCombo") local DamageInstance = require("invokation.dota2.DamageInstance") local UNITS = require("invokation.const.units") local COMBOS = require("invokation.const.combos") local INVOKER = require("invokation.const.invoker") local NET_TABLE = require("invokation.const.net_table") describe("Combos", function() local combos local netTable = {} local dummySpawn = create("entity") local hero = create("dota_hero_invoker") local player = create("dota_player", {id = 13, hero = hero}) setup(function() stub.new(Entities, "FindByName", function(_, _, name) return name == UNITS.DUMMY_TARGET_SPAWN and dummySpawn or nil end) end) teardown(function() Entities.FindByName:revert() end) before_each(function() stub.new(netTable, "Set") combos = Combos({netTable = netTable}) end) after_each(function() netTable.Set:clear() end) describe("constructor", function() it("loads and transforms specs", function() assert.are.equal(m.count(COMBOS), m.count(combos.specs)) for _, spec in pairs(combos.specs) do assert.is_table(spec) assert.is_not_nil(spec.id) for _, step in pairs(spec.sequence) do assert.is_table(step) assert.is_not_nil(step.id) end end end) it("sets NetTable key with loaded specs", function() assert.stub(netTable.Set).was.self.called_with(NET_TABLE.MAIN_KEYS.COMBOS, combos.specs) end) end) describe("#OnAbilityUsed", function() before_each(function() stub.new(combos, "CaptureAbility") stub.new(combos, "Progress") end) after_each(function() combos.CaptureAbility:revert() combos.Progress:revert() end) local unit = create("hero_invoker") describe("with relevant ability", function() local ability = create("ability", {name = INVOKER.ABILITY_SUN_STRIKE}) it("handles ability capture and combo progress", function() combos:OnAbilityUsed(player, unit, ability) assert.stub(combos.CaptureAbility).was.self.called_with(player, ability) assert.stub(combos.Progress).was.self.called_with(player, ability) end) end) describe("with ignored ability", function() local ability = create("ability", {name = "item_phase_boots"}) it("is a noop", function() combos:OnAbilityUsed(player, unit, ability) assert.stub(combos.CaptureAbility).was_not.called() assert.stub(combos.Progress).was_not.called() end) end) end) describe("#OnEntityHurt", function() before_each(function() stub.new(combos, "ProgressDamage") end) after_each(function() combos.ProgressDamage:revert() end) local victim = create("unit", {name = UNITS.DUMMY_TARGET}) describe("with player-owned attacker", function() local attacker = create("hero_invoker", {playerOwner = player}) local inflictor = create("ability", {name = INVOKER.ABILITY_SUN_STRIKE}) it("handles combo damage progress", function() local damage = DamageInstance(victim, 123.4, attacker, inflictor) local owner = damage:AttackerPlayerOwner() combos:OnEntityHurt(damage) assert.stub(combos.ProgressDamage).was.self.called_with(owner, damage) end) end) describe("with non-player attacker", function() local attacker = create("unit", {name = "npc_dota_hero_axe"}) local inflictor = create("ability", {name = "item_dagon_5"}) it("is a noop", function() local damage = DamageInstance(victim, 123.4, attacker, inflictor) combos:OnEntityHurt(damage) assert.stub(combos.ProgressDamage).was_not.called() end) end) end) describe("#OnItemPurchased", function() local purchase = {item = "item_blink", cost = 1234.5} describe("when no combo is active", function() it("is a noop", function() hero:SetGold(0, true) hero:SetGold(0, false) assert.are.equal(0, hero:GetGold()) combos:OnItemPurchased(player, purchase) assert.are.equal(0, hero:GetGold()) end) end) describe("when a regular combo is active", function() it("is a noop", function() combos:Start(player, combos:Create(1)) hero:SetGold(0, true) hero:SetGold(0, false) assert.are.equal(0, hero:GetGold()) combos:OnItemPurchased(player, purchase) assert.are.equal(0, hero:GetGold()) end) end) describe("when freestyle combo is active", function() it("refunds the purchase", function() combos:Start(player, combos:Create(FreestyleCombo.COMBO_ID)) hero:SetGold(0, true) hero:SetGold(0, false) assert.are.equal(0, hero:GetGold()) combos:OnItemPurchased(player, purchase) assert.are.equal(1234.5, hero:GetGold()) end) end) end) describe("#Create", function() describe("with an invalid id", function() it("throws an error", function() local createFn = m.bindn(combos.Create, combos, -1) assert.error(createFn, "Combo \"-1\" not found") end) end) describe("with freestyle id", function() it("creates a freestyle combo", function() local combo = combos:Create(FreestyleCombo.COMBO_ID) assert.is_not_nil(combo) assert.is_true(FreestyleCombo:class_of(combo)) end) end) describe("with a valid id", function() it("creates a combo", function() local combo = combos:Create(13) assert.is_not_nil(combo) assert.is_true(Combo:class_of(combo)) end) end) end) describe("#Start", function() before_each(function() spy.on(CombosHero, "setup") spy.on(CombosHero, "teardown") spy.on(CombosSound, "onDummyCreate") spy.on(CombosSound, "onComboStart") spy.on(CombosSound, "onComboStop") spy.on(CombosComm, "sendStarted") spy.on(CombosComm, "sendStopped") end) after_each(function() CombosHero.setup:revert() CombosHero.teardown:revert() CombosSound.onDummyCreate:revert() CombosSound.onComboStart:revert() CombosSound.onComboStop:revert() CombosComm.sendStarted:revert() CombosComm.sendStopped:revert() end) describe("when no combo is active", function() it("starts the combo", function() assert.is_nil(combos.state[player].combo) combos:Start(player, combos:Create(13)) local combo = combos.state[player].combo local dummy = combos.state[player].dummy assert.is_not_nil(combo) assert.is_not_nil(dummy) assert.are.equal(13, combo.id) assert.is_true(dummy:IsAlive()) assert.spy(CombosHero.teardown).was.called_with(match.is_ref(player), {hardReset = true}) assert.spy(CombosHero.setup).was.called_with(match.is_ref(player), match.is_ref(combo)) assert.spy(CombosSound.onDummyCreate).was.called_with(match.is_ref(dummy)) assert.spy(CombosSound.onComboStop).was_not.called() assert.spy(CombosSound.onComboStart).was.called_with(match.is_ref(player)) assert.spy(CombosComm.sendStarted).was.called_with(match.is_ref(player), match.is_ref(combo)) assert.spy(CombosComm.sendStopped).was_not.called() end) end) describe("when the same combo is already active", function() it("restarts the combo", function() combos:Start(player, combos:Create(13)) local comboBefore = combos.state[player].combo assert.is_not_nil(comboBefore) assert.are.equal(13, comboBefore.id) CombosHero.setup:clear() CombosHero.teardown:clear() CombosSound.onDummyCreate:clear() CombosSound.onComboStart:clear() CombosSound.onComboStop:clear() CombosComm.sendStarted:clear() CombosComm.sendStopped:clear() combos:Start(player, combos:Create(13)) local comboAfter = combos.state[player].combo local dummy = combos.state[player].dummy assert.is_not_nil(comboAfter) assert.is_not_nil(dummy) assert.are_not.equal(comboAfter, comboBefore) assert.are.equal(13, comboAfter.id) assert.is_true(dummy:IsAlive()) assert.spy(CombosHero.teardown).was.called_with(match.is_ref(player), {hardReset = false}) assert.spy(CombosHero.setup).was .called_with(match.is_ref(player), match.is_ref(comboAfter)) assert.spy(CombosSound.onDummyCreate).was_not.called_with(match.is_ref(dummy)) assert.spy(CombosSound.onComboStop).was_not.called() assert.spy(CombosSound.onComboStart).was.called_with(match.is_ref(player)) assert.spy(CombosComm.sendStarted).was.called_with(match.is_ref(player), match.is_ref(comboAfter)) assert.spy(CombosComm.sendStopped).was_not.called() end) end) describe("when a different combo is already active", function() it("stops the previous combo and starts the new combo", function() combos:Start(player, combos:Create(13)) local comboBefore = combos.state[player].combo assert.is_not_nil(comboBefore) assert.are.equal(13, comboBefore.id) CombosHero.setup:clear() CombosHero.teardown:clear() CombosSound.onDummyCreate:clear() CombosSound.onComboStart:clear() CombosSound.onComboStop:clear() CombosComm.sendStarted:clear() CombosComm.sendStopped:clear() combos:Start(player, combos:Create(3)) local comboAfter = combos.state[player].combo local dummy = combos.state[player].dummy assert.is_not_nil(comboAfter) assert.is_not_nil(dummy) assert.are_not.equal(comboAfter, comboBefore) assert.are.equal(3, comboAfter.id) assert.is_true(dummy:IsAlive()) assert.spy(CombosHero.teardown).was.called_with(match.is_ref(player), {hardReset = true}) assert.spy(CombosHero.setup).was .called_with(match.is_ref(player), match.is_ref(comboAfter)) assert.spy(CombosSound.onDummyCreate).was_not.called_with(match.is_ref(dummy)) assert.spy(CombosSound.onComboStop).was.called_with(match.is_ref(player)) assert.spy(CombosSound.onComboStart).was.called_with(match.is_ref(player)) assert.spy(CombosComm.sendStarted).was.called_with(match.is_ref(player), match.is_ref(comboAfter)) assert.spy(CombosComm.sendStopped).was.called_with(match.is_ref(player), match.is_ref(comboBefore)) end) end) end) describe("#Stop", function() before_each(function() spy.on(CombosHero, "teardown") spy.on(CombosSound, "onComboStop") spy.on(CombosComm, "sendStopped") end) after_each(function() CombosHero.teardown:revert() CombosSound.onComboStop:revert() CombosComm.sendStopped:revert() end) describe("when no combo is active", function() it("throws an error", function() local stopFn = m.bindn(combos.Stop, combos, player) assert.error(stopFn, "Player 13 has no active combo") assert.spy(CombosHero.teardown).was_not.called() assert.spy(CombosSound.onComboStop).was_not.called() assert.spy(CombosComm.sendStopped).was_not.called() end) end) describe("when a combo is active", function() it("stops the active combo", function() combos:Start(player, combos:Create(13)) local comboBefore = combos.state[player].combo local dummyBefore = combos.state[player].dummy assert.is_not_nil(comboBefore) assert.is_not_nil(dummyBefore) assert.are.equal(13, comboBefore.id) assert.is_true(dummyBefore:IsAlive()) CombosHero.teardown:clear() CombosSound.onComboStop:clear() CombosComm.sendStopped:clear() combos:Stop(player) local comboAfter = combos.state[player].combo local dummyAfter = combos.state[player].dummy assert.is_nil(comboAfter) assert.is_not_nil(dummyAfter) assert.are.equal(dummyBefore, dummyAfter) assert.is_false(dummyAfter:IsAlive()) assert.spy(CombosHero.teardown).was.called_with(match.is_ref(player), {hardReset = true}) assert.spy(CombosSound.onComboStop).was.called_with(match.is_ref(player)) assert.spy(CombosComm.sendStopped).was.called_with(match.is_ref(player), match.is_ref(comboBefore)) end) end) end) describe("#Restart", function() before_each(function() spy.on(CombosHero, "setup") spy.on(CombosHero, "teardown") spy.on(CombosSound, "onDummyCreate") spy.on(CombosSound, "onComboStart") spy.on(CombosSound, "onComboStop") spy.on(CombosComm, "sendStarted") spy.on(CombosComm, "sendStopped") end) after_each(function() CombosHero.setup:revert() CombosHero.teardown:revert() CombosSound.onDummyCreate:revert() CombosSound.onComboStart:revert() CombosSound.onComboStop:revert() CombosComm.sendStarted:revert() CombosComm.sendStopped:revert() end) describe("when no combo is active", function() it("throws an error", function() local restartFn = m.bindn(combos.Restart, combos, player) assert.error(restartFn, "Player 13 has no active combo") assert.spy(CombosHero.teardown).was_not.called() assert.spy(CombosHero.setup).was_not.called() assert.spy(CombosSound.onDummyCreate).was_not.called() assert.spy(CombosSound.onComboStart).was_not.called() assert.spy(CombosSound.onComboStop).was_not.called() assert.spy(CombosComm.sendStarted).was_not.called() assert.spy(CombosComm.sendStopped).was_not.called() end) end) describe("when a combo is active", function() describe("without hard reset option", function() it("restarts the combo", function() combos:Start(player, combos:Create(13)) local comboBefore = combos.state[player].combo assert.is_not_nil(comboBefore) assert.are.equal(13, comboBefore.id) CombosHero.setup:clear() CombosHero.teardown:clear() CombosSound.onDummyCreate:clear() CombosSound.onComboStart:clear() CombosSound.onComboStop:clear() CombosComm.sendStarted:clear() CombosComm.sendStopped:clear() combos:Restart(player, {hardReset = false}) local comboAfter = combos.state[player].combo local dummy = combos.state[player].dummy assert.is_not_nil(comboAfter) assert.is_not_nil(dummy) assert.are_not.equal(comboAfter, comboBefore) assert.are.equal(13, comboAfter.id) assert.is_true(dummy:IsAlive()) assert.spy(CombosHero.teardown).was .called_with(match.is_ref(player), {hardReset = false}) assert.spy(CombosHero.setup).was.called_with(match.is_ref(player), match.is_ref(comboAfter)) assert.spy(CombosSound.onDummyCreate).was_not.called_with(match.is_ref(dummy)) assert.spy(CombosSound.onComboStop).was_not.called() assert.spy(CombosSound.onComboStart).was.called_with(match.is_ref(player)) assert.spy(CombosComm.sendStarted).was.called_with(match.is_ref(player), match.is_ref(comboAfter)) assert.spy(CombosComm.sendStopped).was_not.called() end) end) describe("with hard reset option", function() it("restarts the combo", function() combos:Start(player, combos:Create(13)) local comboBefore = combos.state[player].combo assert.is_not_nil(comboBefore) assert.are.equal(13, comboBefore.id) CombosHero.setup:clear() CombosHero.teardown:clear() CombosSound.onDummyCreate:clear() CombosSound.onComboStart:clear() CombosSound.onComboStop:clear() CombosComm.sendStarted:clear() CombosComm.sendStopped:clear() combos:Restart(player, {hardReset = true}) local comboAfter = combos.state[player].combo local dummy = combos.state[player].dummy assert.is_not_nil(comboAfter) assert.is_not_nil(dummy) assert.are_not.equal(comboAfter, comboBefore) assert.are.equal(13, comboAfter.id) assert.is_true(dummy:IsAlive()) assert.spy(CombosHero.teardown).was.called_with(match.is_ref(player), {hardReset = true}) assert.spy(CombosHero.setup).was.called_with(match.is_ref(player), match.is_ref(comboAfter)) assert.spy(CombosSound.onDummyCreate).was_not.called_with(match.is_ref(dummy)) assert.spy(CombosSound.onComboStop).was_not.called() assert.spy(CombosSound.onComboStart).was.called_with(match.is_ref(player)) assert.spy(CombosComm.sendStarted).was.called_with(match.is_ref(player), match.is_ref(comboAfter)) assert.spy(CombosComm.sendStopped).was_not.called() end) end) end) end) describe("#Progress", function() local combo before_each(function() combo = Combo({ id = m.uniqueId("Combos_spec-Progress-%d"), specialty = "qw", stance = "defensive", heroLevel = 25, damageRating = 5, difficultyRating = 5, gold = 1234, tags = {"late-game"}, items = {"item_blink"}, orbs = {7, 7, 7}, talents = Talents.Select(Talents.L10_LEFT, Talents.L15_RIGHT, Talents.L20_RIGHT, Talents.L25_RIGHT), sequence = { {id = 1, name = INVOKER.ABILITY_COLD_SNAP, required = true, next = {2, 3}}, {id = 2, name = INVOKER.ABILITY_GHOST_WALK, next = {3}}, {id = 3, name = INVOKER.ABILITY_EMP, required = true}, }, }) spy.on(combos, "PreFinish") spy.on(combos, "Fail") spy.on(CombosComm, "sendInProgress") spy.on(CombosComm, "sendProgress") end) after_each(function() combos.PreFinish:revert() combos.Fail:revert() CombosComm.sendInProgress:revert() CombosComm.sendProgress:revert() end) describe("with no active combo", function() it("does nothing", function() combos:Progress(player, create("ability", {name = INVOKER.ABILITY_COLD_SNAP})) assert.spy(combos.PreFinish).was_not.called() assert.spy(combos.Fail).was_not.called() assert.spy(CombosComm.sendInProgress).was_not.called() assert.spy(CombosComm.sendProgress).was_not.called() end) end) describe("with failed combo", function() it("does nothing", function() combos:Start(player, combo) combo:Fail() combos:Progress(player, create("ability", {name = INVOKER.ABILITY_COLD_SNAP})) assert.spy(combos.PreFinish).was_not.called() assert.spy(combos.Fail).was_not.called() assert.spy(CombosComm.sendInProgress).was_not.called() assert.spy(CombosComm.sendProgress).was_not.called() end) end) describe("with pre-finished combo", function() it("does nothing", function() combos:Start(player, combo) assert.is_true(combo:Progress(create("ability", {name = INVOKER.ABILITY_COLD_SNAP}))) assert.is_true(combo:Progress(create("ability", {name = INVOKER.ABILITY_GHOST_WALK}))) assert.is_true(combo:Progress(create("ability", {name = INVOKER.ABILITY_EMP}))) assert.is_true(combo:PreFinish()) assert.is_true(combo.preFinished) combos:Progress(player, create("ability", {name = INVOKER.ABILITY_COLD_SNAP})) assert.spy(combos.PreFinish).was_not.called() assert.spy(combos.Fail).was_not.called() assert.spy(CombosComm.sendInProgress).was_not.called() assert.spy(CombosComm.sendProgress).was_not.called() end) end) describe("with finished combo", function() it("does nothing", function() combos:Start(player, combo) assert.is_true(combo:Progress(create("ability", {name = INVOKER.ABILITY_COLD_SNAP}))) assert.is_true(combo:Progress(create("ability", {name = INVOKER.ABILITY_GHOST_WALK}))) assert.is_true(combo:Progress(create("ability", {name = INVOKER.ABILITY_EMP}))) assert.is_true(combo:PreFinish()) assert.is_true(combo:Finish()) assert.is_true(combo.finished) combos:Progress(player, create("ability", {name = INVOKER.ABILITY_COLD_SNAP})) assert.spy(combos.PreFinish).was_not.called() assert.spy(combos.Fail).was_not.called() assert.spy(CombosComm.sendInProgress).was_not.called() assert.spy(CombosComm.sendProgress).was_not.called() end) end) describe("with regular active combo", function() before_each(function() combos:Start(player, combo) end) describe("with invocation ability", function() it("does nothing", function() combos:Progress(player, create("ability", {name = INVOKER.ABILITY_EXORT})) assert.spy(combos.PreFinish).was_not.called() assert.spy(combos.Fail).was_not.called() assert.spy(CombosComm.sendInProgress).was_not.called() assert.spy(CombosComm.sendProgress).was_not.called() end) end) describe("with incorrect ability", function() local ability = create("ability", {name = INVOKER.ABILITY_SUN_STRIKE}) it("fails the combo", function() combos:Progress(player, ability) assert.is_true(combo.failed) assert.spy(combos.Fail).was.self.called_with(match.is_ref(player), match.is_ref(ability)) assert.spy(CombosComm.sendInProgress).was_not.called() assert.spy(CombosComm.sendProgress).was_not.called() end) end) describe("with correct ability", function() it("progresses the combo", function() combos:Progress(player, create("ability", {name = INVOKER.ABILITY_COLD_SNAP})) assert.spy(combos.PreFinish).was_not.called() assert.spy(combos.Fail).was_not.called() assert.spy(CombosComm.sendProgress).was.called_with(match.is_ref(player), match.is_ref(combo)) end) describe("when it's the first combo step", function() it("communicates that combo is in progress", function() local ability = create("ability", {name = INVOKER.ABILITY_COLD_SNAP}) combos:Progress(player, ability) assert.spy(CombosComm.sendInProgress).was.called_with(match.is_ref(player), match.is_ref(combo)) end) end) describe("when it's the last combo step", function() it("pre-finishes the combo", function() assert.is_true(combo:Progress(create("ability", {name = INVOKER.ABILITY_COLD_SNAP}))) assert.is_true(combo:Progress(create("ability", {name = INVOKER.ABILITY_GHOST_WALK}))) combos:Progress(player, create("ability", {name = INVOKER.ABILITY_EMP})) assert.is_true(combo.preFinished) assert.spy(combos.PreFinish).was.self.called_with(match.is_ref(player)) assert.spy(combos.Fail).was_not.called() end) end) end) end) end) end)
-- telescope plugin configuration {{{ -- see https://github.com/nvim-telescope/telescope.nvim local actions = require('telescope.actions') local conf = require("telescope.config").values function joinTables(t1, t2) for k,v in ipairs(t2) do table.insert(t1, v) end return t1 end require('telescope').setup { -- for defaults see telescope/config.lua defaults = { file_sorter = require('telescope.sorters').get_fzy_sorter, prompt_prefix = ' > ', color_devicons = true, vimgrep_arguments = joinTables(conf.vimgrep_arguments, { "--hidden", "--iglob", "!.git" }), file_previewer = require('telescope.previewers').vim_buffer_cat.new, grep_previewer = require('telescope.previewers').vim_buffer_vimgrep.new, qflist_previewer = require('telescope.previewers').vim_buffer_qflist.new, -- for default mappings see telescope/mappings.lua mappings = { i = { ["<C-k>"] = actions.preview_scrolling_up, ["<C-j>"] = actions.preview_scrolling_down, ["<esc>"] = actions.close, ["<C-q>"] = actions.send_to_qflist, }, } }, pickers = { find_files = { theme = "dropdown", hidden = true, }, git_files = { theme = "dropdown", }, }, extensions = { fzf = { fuzzy = true, -- false will only do exact matching override_generic_sorter = true, -- override the generic sorter override_file_sorter = true, -- override the file sorter case_mode = "smart_case", -- or "ignore_case" or "respect_case" -- the default case_mode is "smart_case" } } } require('telescope').load_extension('fzf') local M = {} -- only search in the context of the vim configuration files M.search_dotfiles = function() require("telescope.builtin").find_files({ prompt_title = "< VimRC >", cwd = "~/.dotfiles/nvim/.config/nvim", --vim.env.DOTFILES, }) end -- fallback to find_files() if we are not in a git project folder M.project_files = function() local opts = {} -- define here if you want to define something local ok = pcall(require('telescope.builtin').git_files, opts) if not ok then require('telescope.builtin').find_files(opts) end end return M -- }}}
modifier_felfrost = class( ModifierBaseClass ) FELFROST_DURATION = 8 -- reset upon being applied FELFROST_ARMOR_BASE = 0 -- armor loss just by having the debuff FELFROST_ARMOR_PERSTACK = -1 -- armor loss based on stack count FELFROST_SLOW_BASE = -10 -- slow just by having the debuff FELFROST_SLOW_PERSTACK = -10 -- slow based on stack count -------------------------------------------------------------------------------- function modifier_felfrost:IsHidden() return false end function modifier_felfrost:IsDebuff() return true end function modifier_felfrost:IsPurgable() return true end -------------------------------------------------------------------------------- function modifier_felfrost:GetTexture() return "crystal_maiden_frostbite" end function modifier_felfrost:GetStatusEffectName() return "particles/status_fx/status_effect_frost.vpcf" end function modifier_felfrost:StatusEffectPriority() return 4 end -------------------------------------------------------------------------------- function modifier_felfrost:OnCreated( event ) self:SetDuration( FELFROST_DURATION, true ) end -------------------------------------------------------------------------------- function modifier_felfrost:OnRefresh( event ) self:SetDuration( FELFROST_DURATION, true ) end -------------------------------------------------------------------------------- function modifier_felfrost:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE, MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS, } return funcs end -------------------------------------------------------------------------------- function modifier_felfrost:GetModifierMoveSpeedBonus_Percentage( event ) return FELFROST_SLOW_BASE + ( FELFROST_SLOW_PERSTACK * self:GetStackCount() ) end -------------------------------------------------------------------------------- function modifier_felfrost:GetModifierPhysicalArmorBonus( event ) return FELFROST_ARMOR_BASE + ( FELFROST_ARMOR_PERSTACK * self:GetStackCount() ) end
------------------------------------------------------------ -- Clique.lua -- -- Abin -- 2012/3/27 ------------------------------------------------------------ local _, addon = ... local Clique = IsAddOnLoaded("Clique") and type(Clique) == "table" and type(Clique.RegisterFrame) == "function" and type(Clique.UnregisterFrame) == "function" and Clique function addon:CliqueRegister(frame) if not Clique or not self:Initialized() then return end if frame then Clique:RegisterFrame(frame) else self:EnumUnitFrames(Clique, "RegisterFrame") end end function addon:CliqueUnregister(frame) if not Clique or not self:Initialized() then return end if frame then Clique:UnregisterFrame(frame) else self:EnumUnitFrames(Clique, "UnregisterFrame") end end if not Clique then return end addon:RegisterEventCallback("OnInitialize", function() addon:CliqueRegister() addon:RegisterEventCallback("UnitButtonCreated", function(frame) addon:CliqueRegister(frame) end) end)
-- The MIT License (MIT) -- -- Copyright (c) 2016 Stefano Trettel -- -- Software repository: MoonFLTK, https://github.com/stetre/moonfltk -- -- 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. -- --================================================================================= -- timer.lua - MoonFLTK timer heap --================================================================================= local fl = require("moonfltk") local timer_ = require("moonfltk.timer_") local timer = {} local function triggerat(exptime) -- specific for FLTK local seconds = exptime - fl.gettime() if seconds > 0 then -- set the FLTK timer so to expire at exptime fl.set_timeout(seconds, false, timer_.trigger) else -- exptime is in the past: trigger the timer module timer_.trigger() end end function timer.init() -- Init the timer module for FLTK timer_.deleteall() timer_.init(triggerat, fl.gettime) end timer.create = function(timeout, callback) return timer_.create(timeout, callback) end timer.delete = timer_.delete timer.deletell = timer_.deleteall timer.start = timer_.start timer.stop = timer_.timeout timer.callback = timer_.callback timer.isrunning = timer_.isrunning return timer
local RapidTurretAI = tiny.processingSystem() RapidTurretAI.filter = tiny.requireAll('is_rapid_turret') local function ready_gun(gun) return function() gun.ready = true end end local function reset_shots(entity) return function() entity.animation = entity.fire_animation entity.animation:gotoFrame(4) entity.shots = entity.base_shots entity.resetting = false end end function RapidTurretAI:process(entity, dt) if entity.gun.ready and entity.x < love.window.getWidth() and entity.shots > 0 then entity.gun.ready = false entity.shots = entity.shots - 1 entity.gun.create_bullet(entity) Timer.after(entity.gun.fire_delay, ready_gun(entity.gun)) end if entity.shots <= 0 and not entity.resetting then entity.resetting = true entity.animation = entity.resting_animation Timer.after(entity.repeat_shot_reset_delay, reset_shots(entity)) end end return RapidTurretAI
local path="/usr/local/nginx/lua_v2/config.properties" local request_method = ngx.var.request_method local args = nil local logString = nil local logType = nil local configTable ={} local seperator="|" local lineSeperator="\r" local date=os.date("%Y-%m-%d %H:%M:%S"); string.split = function(s, p) local ret = {} string.gsub(s, '[^'..p..']+', function(w) table.insert(ret, w) end) return ret end if "POST" == request_method then ngx.req.read_body() args = ngx.req.get_post_args() elseif "GET" == request_method then args = ngx.req.get_uri_args() end local file = io.open(path,"r"); if file~=nil then for line in file:lines() do pairs=string.split(line,"=") local key = pairs[1] if(key~=nil) then configTable[key]=pairs[2] end end file:close() else ngx.say("config file does not exist!!") end logString = args["QoSData"] logType = args["LogType"] logName=configTable[logType] local logDir=configTable["tmlogDir"]; version=configTable["version"]; host=configTable["host"]; businessField=configTable["businessField"]; logFile=logDir..logName local logging = function(logPath,lineSeperator,logString) local f,err = io.open(logPath, "a") if not f then ngx.log(ngx.ERR,err) ngx.log(ngx.ERR, logPath.." not exist") return nil, string.format("file `%s' could not be opened for writing", logPath) end f:setvbuf ("line") logLineS=string.split(logString,lineSeperator) if(logLineS~=nil) then for m=1, #(logLineS) do log=version..seperator..host..seperator.."OTT_"..logName..seperator..businessField..seperator..date..seperator..logLineS[m] f:write(log) f:write("\r\n") end end return "OK" end ngx.say("logType="..logType) --log deal--------------------------- if(logString~=nil) then logging(logFile,lineSeperator,logString) end ngx.say("ok")
-- Represents global state available to APIs return { bridge = require 'vimwiki_server/lib'.new_bridge(); tmp = require 'vimwiki_server/lib'.new_tmp(); }
require('treesitter-context').setup({ enable = true, throttle = true, max_lines = 0, })
local parser = require'pegparser.parser' local first = require'pegparser.first' local pretty = require'pegparser.pretty' local empty = first.empty local any = first.any -- testing FIRST and FOLLOW -- Rules starting with an uppercase letter (A, Start, START) are lexical rules. -- The FIRST set of a lexical rule A is A itself (__A more currently). local function assertequal_aux (v, pre, comp) for k, _ in pairs (pre) do assert(comp[k], '"' .. v .. '": missing "' .. k .. '" in computed set.') end for k, _ in pairs (comp) do assert(pre[k], '"' .. v .. '": missing "' .. k .. '" in predefined set.') end end local function assertequal (pre, comp) local auxk = nil comp['SKIP'] = nil comp['SPACE'] = nil for k, v in pairs (pre) do assertequal_aux(k, v, comp[k]) auxk = next(comp, auxk) end local x = next(comp, auxk) assert(x == nil, x) end local function makeset (l) local t = {} for _, v in ipairs(l) do t[v] = true end return t end local g = [[ s <- (a / b)* 'c' a <- 'a' b <- 'b' ]] local prefst = { s = makeset{'a', 'b', 'c'}, a = makeset{'a'}, b = makeset{'b'} } local preflw = { s = makeset{'$'}, a = makeset{'a', 'b', 'c'}, b = makeset{'a', 'b', 'c'} } local peg = parser.match(g) local fst = first.calcFst(peg) local flw = first.calcFlw(peg) assertequal(prefst, fst) assertequal(preflw, flw) local g = [[ s <- ('o' a / 'u' b)* (c / d)* 'c' e f g a <- 'a'? b <- 'b'? 'x' c <- 'k'+ 'z' d <- 'd' e <- !'e' 'g' f <- &'f' 'g' g <- &'e' !'f' ]] local prefst = { s = makeset{'o', 'u', 'k', 'd', 'c'}, a = makeset{empty, 'a'}, b = makeset{'b', 'x'}, c = makeset{'k'}, d = makeset{'d'}, e = makeset{'g'}, f = makeset{'g'}, g = makeset{empty} } local preflw = { s = makeset{'$'}, a = makeset{'o', 'u', 'k', 'd', 'c'}, b = makeset{'o', 'u', 'k', 'd', 'c'}, c = makeset{'k', 'd', 'c'}, d = makeset{'k', 'd', 'c'}, e = makeset{'g'}, f = makeset{'$'}, g = makeset{'$'} } local peg = parser.match(g) local fst = first.calcFst(peg) local flw = first.calcFlw(peg) assertequal(prefst, fst) assertequal(preflw, flw) local g = [[ s <- a^bola / b a <- 'a' %{Erro} b <- 'b'? 'x'? ('y'+)^Erro2 ]] local prefst = { s = makeset{'a', 'b', 'x', 'y', empty}, a = makeset{'a'}, b = makeset{'b', 'x', 'y', empty}, } local preflw = { s = makeset{'$'}, a = makeset{'$'}, b = makeset{'$'}, } local peg = parser.match(g) local fst = first.calcFst(peg) local flw = first.calcFlw(peg) assertequal(prefst, fst) assertequal(preflw, flw) local g = [[ s <- a s b / ([a-cd] / c)* a <- . b <- ('x' / d)* c <- 'f'? 'y'+ d <- 'd' / c ]] local prefst = { s = makeset{any, 'a', 'b', 'c', 'd', 'f', 'y', empty}, a = makeset{any}, b = makeset{'x', 'd', 'f', 'y', empty}, c = makeset{'f', 'y'}, d = makeset{'d', 'f', 'y'}, } local preflw = { s = makeset{'$', 'x', 'd', 'f', 'y'}, a = makeset{any, 'a', 'b', 'c', 'd', 'f', 'y', '$', 'x'}, b = makeset{'$', 'x', 'd', 'f', 'y'}, c = makeset{'a', 'b', 'c', 'd', 'f', 'y', '$', 'x'}, d = makeset{'$', 'x', 'd', 'f', 'y'}, } local peg = parser.match(g) local fst = first.calcFst(peg) local flw = first.calcFlw(peg) assertequal(prefst, fst) assertequal(preflw, flw) print("+") local g = [[ s <- A A <- 'a' B <- 'a' C <- A D <- B c <- A d <- B ]] local prefst = { s = makeset{'__A'}, A = makeset{'__A'}, B = makeset{'__B'}, C = makeset{'__C'}, D = makeset{'__D'}, c = makeset{'__A'}, d = makeset{'__B'}, } local preflw = { s = makeset{'$'}, A = makeset{'$'}, B = makeset{}, C = makeset{}, D = makeset{}, c = makeset{}, d = makeset{}, } local peg = parser.match(g) local fst = first.calcFst(peg) local flw = first.calcFlw(peg) assert(first.disjoint(fst['s'], fst['A']) == false) assert(first.disjoint(fst['s'], fst['C']) == true) assert(first.disjoint(fst['A'], fst['B']) == true) assert(first.disjoint(fst['A'], fst['C']) == true) assert(first.disjoint(fst['A'], fst['c']) == false) assert(first.disjoint(fst['C'], fst['D']) == true) assert(first.disjoint(fst['C'], fst['c']) == true) assert(first.disjoint(fst['D'], fst['d']) == true) assertequal(prefst, fst) assertequal(preflw, flw) print("Ok")
return { tllnanotc4 = { acceleration = 0.2, brakerate = 2, buildcostenergy = 511007, buildcostmetal = 33102, builddistance = 1500, builder = true, buildpic = "tllnanotc4.dds", buildtime = 300000, canassist = true, canguard = true, canmove = false, canpatrol = true, canreclaim = true, canreclaim = true, canstop = 1, cantbetransported = true, category = "ALL SURFACE", collisionvolumeoffsets = "0 0 0", collisionvolumescales = "50 48 50", collisionvolumetype = "CylY", defaultmissiontype = "patrol", description = "Repairs and builds in large radius", explodeas = "NANOBOOM6T", floater = true, footprintx = 3, footprintz = 3, icontype = "building", idleautoheal = 5, idletime = 1800, losemitheight = 25, maneuverleashlength = 0, mass = 33102, maxdamage = 7650, maxslope = 20, maxvelocity = 0, maxwaterdepth = 25, metalmake = 0, mobilestandorders = 1, name = "Nano Turret Level 5", noautofire = false, objectname = "tllnanotc4", radardistance = 0, radaremitheight = 25, reclaimspeed = 5000, repairspeed = 5000, script = "tllnanotc.cob", selfdestructas = "NANOBOOM6", shownanospray = false, sightdistance = 750, standingmoveorder = 1, steeringmode = 1, turninplaceanglelimit = 140, turninplacespeedlimit = 0, turnrate = 1, unitname = "tllnanotc4", workertime = 10000, customparams = { buildpic = "tllnanotc4.dds", faction = "tll", }, nanocolor = { [1] = 0.56, [2] = 0.92, [3] = 0.56, }, sfxtypes = { pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { build = "nanlath1", canceldestruct = "cancel2", repair = "repair1", underattack = "warning1", working = "reclaim1", cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "varmmove", }, select = { [1] = "varmsel", }, }, }, }
-- This code is licensed under the MIT Open Source License. -- Copyright (c) 2015 Ruairidh Carmichael - [email protected] -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. local endp = {} endp.base = 'https://discordapp.com' endp.apiBase = endp.base .. '/api' endp.gateway = endp.apiBase .. '/gateway' endp.users = endp.apiBase .. '/users' endp.register = endp.apiBase .. '/auth/register' endp.login = endp.apiBase .. '/auth/login' endp.logout = endp.apiBase .. '/auth/logout' endp.servers = endp.apiBase .. '/guilds' endp.channels = endp.apiBase .. '/channels' return endp
local t = {} t["electric dance llc"] = { name = "Electric Dance LLC", id = 1 } t["electrics supreme"] = { name = "Electrics Supreme Inc.", id = 2 } t["electronics n' stuff"] = { name = "Electronics n' Stuff", id = 3 } t["elections for all"] = { name = "Elections for All", id = 4 } local defaultField = native.newTextField( display.contentCenterX, display.contentCenterY, display.actualContentWidth*0.5, 64 ) local topResult = display.newText( "", display.contentCenterX, display.contentCenterY+80, native.systemFont, 32 ) local _lower = string.lower local _len = string.len -- See if the text input matches any of the entries in the list. local function textListener( event ) if ( event.phase == "editing" ) then local input = _lower( event.text ) local matchFound = false -- print( "\n----------------\npossible matches:" ) for i, j in pairs( t ) do if i:sub( 1, _len(input) ) == input then topResult.text = "\"" .. j.name .. "\"" .. " - id = " .. j.id -- print( "\"" .. j.name .. "\"" .. " - id = " .. j.id ) matchFound = true break end end if not matchFound then topResult.text = "" -- print( "0 matches found" ) elseif _len(input) == 0 then topResult.text = "" end end end defaultField:addEventListener( "userInput", textListener )
----------------------------------- -- Area: Southern San d'Oria -- NPC: Victoire -- Standard Merchant NPC ----------------------------------- local ID = require("scripts/zones/Southern_San_dOria/IDs") require("scripts/globals/shop") function onTrade(player,npc,trade) end function onTrigger(player,npc) local stock = { 12432, 1450, -- Faceguard 12464, 1936, -- Headgear 12560, 2230, -- Scale Mail 12592, 2745, -- Doublet 12688, 1190, -- Scale Fng. Gnt. 12720, 1515, -- Gloves 12816, 1790, -- Scale Cuisses 12848, 2110, -- Brais 12944, 1085, -- Scale Greaves 12976, 1410, -- Gaiters } player:showText(npc, ID.text.CARAUTIA_SHOP_DIALOG) tpz.shop.general(player, stock) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
----------------------------------------------------------------------------------------------- -- Client Lua Script for Gear_Costumes -- Copyright (c) NCsoft. All rights reserved ----------------------------------------------------------------------------------------------- require "CostumesLib" ----------------------------------------------------------------------------------------------- -- Gear_Costumes Module Definition ----------------------------------------------------------------------------------------------- local Gear_Costumes = {} ----------------------------------------------------------------------------------------------- -- Localisation ----------------------------------------------------------------------------------------------- local L = Apollo.GetPackage("Gemini:Locale-1.0").tPackage:GetLocale("Gear_Costumes", true) ----------------------------------------------------------------------------------------------- -- Lib gear ----------------------------------------------------------------------------------------------- local LG = Apollo.GetPackage("Lib:LibGear-1.0").tPackage ----------------------------------------------------------------------------------------------- -- Constants ----------------------------------------------------------------------------------------------- -- version local Major, Minor, Patch = 1, 0, 4 local GP_VER = string.format("%d.%d.%d", Major, Minor, Patch) local GP_NAME = "Gear_Costumes" ----------------------------------------------------------------------------------------------- -- Plugin data ----------------------------------------------------------------------------------------------- local tPlugin = { name = GP_NAME, -- addon name version = GP_VER, -- addon version flavor = L["GP_FLAVOR"], -- addon description icon = "LOADED FROM GEAR", -- icon plugin name for setting and ui_setting, loaded from 'gear' on = true, -- enable/disable setting = { name = L["GP_O_SETTINGS"], -- setting name to view in gear setting window -- parent setting [1] = { -- }, }, ui_setting = { -- ui setting for gear profil -- sType = 'toggle_unique' (on/off state, only once can be enabled in all profil, but all can be disabled) -- sType = 'toggle' (on/off state) -- sType = 'push' (on click state) -- sType = 'none' (no state, only icon to identigy the plugin) -- sType = 'action' (no state, only push to launch action like copie to clipboard) -- sType = 'list' (dropdown list, only select) --sTatus = "true" (show text status 'root' data from 'saved' inside icon) [1] = { sType = "push", sStatus = true, Saved = nil,}, -- first setting button is always the plugin icon }, } -- timer/var to init plugin local tComm, bCall, tWait -- keep ngearid/costume link local tSavedProfiles = {} -- anchor local tAnchor = { l = 0, t = 0, r = 0, b = 0 } -- color local tColor = { cost = "White", nocost = "gray" } ----------------------------------------------------------------------------------------------- -- Initialization ----------------------------------------------------------------------------------------------- function Gear_Costumes:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end function Gear_Costumes:Init() Apollo.RegisterAddon(self, false, nil, {"Gear"}) end ----------------------------------------------------------------------------------------------- -- OnLoad ----------------------------------------------------------------------------------------------- function Gear_Costumes:OnLoad() Apollo.RegisterEventHandler("Generic_GEAR_PLUGIN", "ON_GEAR_PLUGIN", self) -- add event to communicate with gear Apollo.RegisterEventHandler("CostumeNames_Edit", "C_OnCostumeNames_Edit", self) -- add 'CostumeNames' event tComm = ApolloTimer.Create(1, true, "_Comm", self) -- init comm for plugin end --------------------------------------------------------------------------------------------------- -- _Comm --------------------------------------------------------------------------------------------------- function Gear_Costumes:_Comm() if LG._isaddonup("Gear") then -- if 'gear' is running , go next tComm:Stop() tComm = nil -- stop init comm timer if bCall == nil then LG.initcomm(tPlugin) end -- send information about me, setting etc.. end end ----------------------------------------------------------------------------------------------- --- all plugin communicate with gear in this function ----------------------------------------------------------------------------------------------- function Gear_Costumes:ON_GEAR_PLUGIN(sAction, tData) -- answer come from gear, the gear version, gear is up if sAction == "G_VER" and tData.owner == GP_NAME then if bCall ~= nil then return end bCall = true end -- action request come from gear, the plugin are enable or disable, if this information is for me go next if sAction == "G_ON" and tData.owner == GP_NAME then -- update enable/disable status tPlugin.on = tData.on -- init if tPlugin.on then -- nothing saved stop here if self:C_Ini() == false then return end -- we request last gear equipped Event_FireGenericEvent("Generic_GEAR_PLUGIN", "G_GET_LASTGEAR", nil) -- after reactivate the plugin check if ngearid and costume actually equipped is linked or not self:C_Check(self.nGearId) else -- stop equip costume timer, we have disabled the plugin dont need to equip costume requested tWait = nil -- close dialog self:OnCloseDialog() end end -- answer come from gear, the last gear equiped if sAction == "G_LASTGEAR" then self.nGearId = tData.ngearid end -- answer come from gear, the gear set equiped if sAction == "G_CHANGE" then if tPlugin.on then local nGearId = tData.ngearid -- equip costume if tSavedProfiles[nGearId] then self:C_Equip_COS(tSavedProfiles[nGearId]) end end end -- answer come from gear, a gear set deleted if sAction == "G_DELETE" then local nGearId = tData if tSavedProfiles[nGearId] then tSavedProfiles[nGearId] = nil end if self.CostumeWnd and self.CostumeWnd:FindChild("TitleUp"):GetData() == nGearId then -- close dialog self:OnCloseDialog() end end -- answer come from gear, the setting plugin update, if this information is for me go next if sAction == "G_UI_ACTION" and tData.owner == GP_NAME then -- get profiles for ngearid target self.tData = tData self:C_Show(tData) end -- sending by 'gear', 'gear' have now a new main window if sAction == "G_UI_REMOVED" then -- close dialog self:OnCloseDialog() end end --------------------------------------------------------------------------------------------------- -- C_Ini (to update saved profile after turning off/on plug-in) --------------------------------------------------------------------------------------------------- function Gear_Costumes:C_Ini() -- nothing saved, we stop here if tSavedProfiles == nil then return false end for nGearId, pGearId in pairs(tSavedProfiles) do -- update ui setting status button self:C_UpdateUI(nGearId) end end --------------------------------------------------------------------------------------------------- -- C_UpdateUI (to update 'gear' ui profile status button) --------------------------------------------------------------------------------------------------- function Gear_Costumes:C_UpdateUI(nGearId) -- request to 'gear' to update ui setting status button local tData = { owner = GP_NAME, uiid = 1, ngearid = nGearId, saved = self:C_Update_tSaved(),} Event_FireGenericEvent("Generic_GEAR_PLUGIN", "G_SET_UI_SETTING", tData) end --------------------------------------------------------------------------------------------------- -- C_Update_tSaved (to update tsavedprofiles before export data to gear) --------------------------------------------------------------------------------------------------- function Gear_Costumes:C_Update_tSaved() -- make copy of saved array to work local tSavedProfilesExp = LG.DeepCopy(tSavedProfiles) -- update saved array for export, we add cos name local tSavedExp = {} -- CostumeNames support self:C_CostumeNames() local sName = nil for nGearId, pCosId in pairs(tSavedProfilesExp) do sName = self.tCostumeNames[pCosId] or String_GetWeaselString(Apollo.GetString("Character_CostumeNum"), pCosId) if pCosId == 0 then sName = L["GP_O_COSNAME_0"] end tSavedExp[nGearId] = { root = pCosId, target = sName,} end return tSavedExp end --------------------------------------------------------------------------------------------------- -- C_CostumeNames (get last array from 'CostumeNames' addon) --------------------------------------------------------------------------------------------------- function Gear_Costumes:C_CostumeNames() local aCN = Apollo.GetAddon("CostumeNames") if aCN then self.tCostumeNames = aCN.tSettings.tCostumeNames aCN = nil return end self.tCostumeNames = {} end --------------------------------------------------------------------------------------------------- -- C_OnCostumeNames_Edit (costume name modified) --------------------------------------------------------------------------------------------------- function Gear_Costumes:C_OnCostumeNames_Edit() -- update saved costume name for ui and tooltips self:C_Ini() -- repopulate list if window is visible if self.CostumeWnd then self:C_Populate(self.tData.ngearid) end end ----------------------------------------------------------------------------------------------- -- C_Show ----------------------------------------------------------------------------------------------- function Gear_Costumes:C_Show(tData) local nGearId = tData.ngearid local sName = tData.name if self.CostumeWnd then self.CostumeWnd:Destroy() end self.xmlDoc = XmlDoc.CreateFromFile("Gear_Costumes.xml") self.CostumeWnd = Apollo.LoadForm(self.xmlDoc, "Dialog_wnd", nil, self) self.CostumeWnd:FindChild("TitleUp"):SetText(tPlugin.setting.name) self.CostumeWnd:FindChild("TitleUp"):SetData(nGearId) local wndInside = Apollo.LoadForm(self.xmlDoc, "Inside_wnd", self.CostumeWnd, self) wndInside:FindChild("TitleUp"):SetText(sName) -- populate self:C_Populate(nGearId) self:LastAnchor(self.CostumeWnd, false) self.CostumeWnd:Show(true) end --------------------------------------------------------------------------------------------------- -- OnCloseDialog --------------------------------------------------------------------------------------------------- function Gear_Costumes:OnCloseDialog( wndHandler, wndControl, eMouseButton ) if self.CostumeWnd == nil then return end self:LastAnchor(self.CostumeWnd, true) self.CostumeWnd:Destroy() self.CostumeWnd = nil end --------------------------------------------------------------------------------------------------- -- OnClickDropDownBtn --------------------------------------------------------------------------------------------------- function Gear_Costumes:OnClickDropDownBtn( wndHandler, wndControl, eMouseButton ) wndControl:FindChild("UI_list_Frame"):Show(not wndControl:FindChild("UI_list_Frame"):IsShown()) end --------------------------------------------------------------------------------------------------- -- C_Populate --------------------------------------------------------------------------------------------------- function Gear_Costumes:C_Populate(nGearId) self.CostumeWnd:FindChild("item_frame"):DestroyChildren() -- get updated CostumeNames self:C_CostumeNames() -- construct list self.nCount = CostumesLib.GetCostumeCount() for nCosId = 0, self.nCount + 1 do -- add item to list local wndItem = Apollo.LoadForm(self.xmlDoc, "UI_list_item_Btn", self.CostumeWnd:FindChild("item_frame"), self) -- set item text local sProfile = self.tCostumeNames[nCosId] or String_GetWeaselString(Apollo.GetString("Character_CostumeNum"), nCosId) local sColor = tColor.cost if nCosId == 0 or nCosId == self.nCount + 1 then local sProfileId = L["GP_O_COSNAME_NO"] if nCosId == 0 then sProfileId = L["GP_O_COSNAME_0"] end sColor = tColor.nocost sProfile = String_GetWeaselString(Apollo.GetString("CRB_Brackets"), sProfileId) end wndItem:SetTextColor(sColor) wndItem:SetText(sProfile) -- keep ngearid/cosid for each item in list local tData = {ngearid = nGearId, ncosid = nCosId} wndItem:SetData(tData) end -- default selected text local sSelected = L["GP_O_COSNAME_NO"] -- if this costume is linked with this ngearid set text local nDataLink = tSavedProfiles[nGearId] if nDataLink then if nDataLink == 0 then sSelected = L["GP_O_COSNAME_0"] else sSelected = self.tCostumeNames[nDataLink] or String_GetWeaselString(Apollo.GetString("Character_CostumeNum"), nDataLink) end end self.CostumeWnd:FindChild("UI_list_Btn"):SetText(sSelected) self.CostumeWnd:FindChild("item_frame"):ArrangeChildrenVert() end --------------------------------------------------------------------------------------------------- -- OnClickItemList --------------------------------------------------------------------------------------------------- function Gear_Costumes:OnClickItemList( wndHandler, wndControl, eMouseButton ) wndControl:GetParent():GetParent():Show(false) local nCosId = wndControl:GetData().ncosid local nGearId = wndControl:GetData().ngearid -- update selected text and save link local sCosName = self.tCostumeNames[nCosId] or String_GetWeaselString(Apollo.GetString("Character_CostumeNum"), nCosId) if nCosId == self.nCount + 1 then sCosName = L["GP_O_COSNAME_NO"] -- nothing selected, remove link from tsavedprofiles tSavedProfiles[nGearId] = nil else -- costume selected, save link tSavedProfiles[nGearId] = nCosId -- check if actual costume edited is for actual gear equipped, if is true update costume view or make nothing -- we request last gear equipped Event_FireGenericEvent("Generic_GEAR_PLUGIN", "G_GET_LASTGEAR", nil) if nGearId == self.nGearId then self:C_Check(nGearId) end end if nCosId == 0 then sCosName = L["GP_O_COSNAME_0"] end self.CostumeWnd:FindChild("UI_list_Btn"):SetText(sCosName) -- update ui setting status button self:C_UpdateUI(wndControl:GetData().ngearid) end --------------------------------------------------------------------------------------------------- -- C_Check (look if gear/costume link exist and align if not the same ) --------------------------------------------------------------------------------------------------- function Gear_Costumes:C_Check(nGearId) -- check if ngearid and costume actually equipped is linked or not if tSavedProfiles[nGearId] then -- we have a costume linked with this gear if CostumesLib.GetCostumeIndex() ~= tSavedProfiles[nGearId] then -- compare costume actually equipped with ngearid/costume link self:C_Equip_COS(tSavedProfiles[nGearId]) -- equip costume if is not the good costume for this ngearid end end end --------------------------------------------------------------------------------------------------- -- C_Equip_COS --------------------------------------------------------------------------------------------------- function Gear_Costumes:C_Equip_COS(nCosId) -- erase timer is new request to equip tWait = nil local nActualCos = CostumesLib.GetCostumeIndex() -- costume actually equipped local nCosCD = CostumesLib.GetCostumeCooldownTimeRemaining() -- time remaining to equip another costume if nActualCos == nCosId then return end -- wait end of cd to equip tWait = ApolloTimer.Create(nCosCD, false, "wait", { wait = function() CostumesLib.SetCostumeIndex(nCosId) end}) end ----------------------------------------------------------------------------------------------- -- LastAnchor ----------------------------------------------------------------------------------------------- function Gear_Costumes:LastAnchor(oWnd, bSave) if oWnd then if not bSave and tAnchor.b ~= 0 then oWnd:SetAnchorOffsets(tAnchor.l, tAnchor.t, tAnchor.r, tAnchor.b) elseif bSave then tAnchor.l, tAnchor.t, tAnchor.r, tAnchor.b = oWnd:GetAnchorOffsets() end end end --------------------------------------------------------------------------------------------------- -- OnWndMove --------------------------------------------------------------------------------------------------- function Gear_Costumes:OnWndMove( wndHandler, wndControl, nOldLeft, nOldTop, nOldRight, nOldBottom ) self:LastAnchor(self.CostumeWnd, true) end --------------------------------------------------------------------------------------------------- -- OnSave --------------------------------------------------------------------------------------------------- function Gear_Costumes:OnSave(eLevel) if eLevel ~= GameLib.CodeEnumAddonSaveLevel.Character then return end local tData = {} tData.config = { ver = GP_VER, on = tPlugin.on, link = tSavedProfiles, } return tData end --------------------------------------------------------------------------------------------------- -- OnRestore --------------------------------------------------------------------------------------------------- function Gear_Costumes:OnRestore(eLevel,tData) if eLevel ~= GameLib.CodeEnumAddonSaveLevel.Character then return end if tData.config.on ~= nil then tPlugin.on = tData.config.on end if tData.config.link ~= nil then tSavedProfiles = tData.config.link tPlugin.ui_setting[1].Saved = self:C_Update_tSaved() end end ----------------------------------------------------------------------------------------------- -- Gear_Costumes Instance ----------------------------------------------------------------------------------------------- local Gear_CostumesInst = Gear_Costumes:new() Gear_CostumesInst:Init()
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('ActionFXRemove', { Action = "Moving", Actor = "FlyingDrone", FxId = "Drone_Trail", Moment = "start", }) PlaceObj('ActionFXRemove', { Action = "Repair", Actor = "RCRover", FxId = "RCRoverRepair", Moment = "start", Target = "Drone", }) PlaceObj('ActionFXRemove', { Action = "Revealed", Actor = "CrystalsBig", FxId = "Revealed", Moment = "true", Target = "ignore", }) PlaceObj('ActionFXRemove', { Action = "Revealed", Actor = "CrystalsSmall", FxId = "Revealed", Moment = "true", Target = "ignore", }) PlaceObj('ActionFXRemove', { Action = "Revealed", Actor = "MetatronAnomaly", FxId = "Revealed", Moment = "true", Target = "ignore", }) PlaceObj('ActionFXRemove', { Action = "Select", Actor = "FlyingDrone", FxId = "SelectDrone", Moment = "start", }) PlaceObj('ActionFXRemove', { Action = "Working", Actor = "MOXIE", FxId = "MoxieSmoke", Moment = "start", Target = "MoxieCP3Pump", })
object_tangible_collection_plant_17 = object_tangible_collection_shared_plant_17:new { gameObjectType = 8211,} ObjectTemplates:addTemplate(object_tangible_collection_plant_17, "object/tangible/collection/plant_17.iff")
-- base_permissions/init.lua local S = minetest.get_translator("base_permissions") minetest.register_tool("base_permissions:key", { description = S("Key"), inventory_image = "base_permissions_key.png", groups = {key = 1, not_in_creative_inventory = 1}, stack_max = 1, on_place = function(itemstack, placer, pointed_thing) local under = pointed_thing.under local node = minetest.get_node(under) local def = minetest.registered_nodes[node.name] if def and def.on_rightclick and not (placer and placer:is_player() and placer:get_player_control().sneak) then return def.on_rightclick(under, node, placer, itemstack, pointed_thing) or itemstack end if pointed_thing.type ~= "node" then return itemstack end local pos = pointed_thing.under node = minetest.get_node(pos) if not node or node.name == "ignore" then return itemstack end local ndef = minetest.registered_nodes[node.name] if not ndef then return itemstack end local on_key_use = ndef._on_key_use if on_key_use then on_key_use(pos, placer) end return nil end }) minetest.register_craftitem("base_permissions:skeleton_key", { description = S("Skeleton Key"), inventory_image = "base_permissions_key_skeleton.png", on_use = function(itemstack, user, pointed_thing) if pointed_thing.type ~= "node" then return itemstack end local pos = pointed_thing.under local node = minetest.get_node(pos) if not node then return itemstack end local node_reg = minetest.registered_nodes[node.name] local on_skeleton_key_use = node_reg and node_reg._on_skeleton_key_use if not on_skeleton_key_use then return itemstack end -- make a new key secret in case the node callback needs it local secret = on_skeleton_key_use(pos, user, permissions.generate_secret()) if secret then return permissions.create_key(itemstack, user, node.name, secret) end end }) minetest.register_craft({ output = "base_permissions:skeleton_key", recipe = { {"base_ores:gold_ingot"}, } }) minetest.register_craft({ type = "cooking", output = "base_ores:gold_ingot", recipe = "base_permissions:key", cooktime = 5, }) minetest.register_craft({ type = "cooking", output = "base_ores:gold_ingot", recipe = "base_permissions:skeleton_key", cooktime = 5, })
--Setup odbc environment (in this case locally within the script) local driver = require"luasql.odbc" local env = driver:odbc() local conn, errorString = env:connect('ClickHouse DSN (Unicode)', 'user','password') if conn == nil then error(errorString) end --execute the SQL statement cursor, errorString = conn:execute([[SELECT duration, url FROM default.visits LIMIT 100]]) if cursor == nil then error(errorString) end row = cursor:fetch ({}, "a") while row do print(string.format("duration: %s, url: %s", row.duration, row.url)) -- reusing the table of results row = cursor:fetch (row, "a") end cursor:close() print("----------") status,errorString = conn:execute([[INSERT INTO visits VALUES (1, 12.5, 'http://example4.com', NOW())]]) if status == nil then error(errorString) end cursor, errorString = conn:execute([[SELECT duration, url FROM default.visits LIMIT 100]]) if cursor == nil then error(errorString) end row = cursor:fetch ({}, "a") while row do print(string.format("duration: %s, url: %s", row.duration, row.url)) -- reusing the table of results row = cursor:fetch (row, "a") end cursor:close() -- close everything conn:close() env:close()
TXRZ6GJ.ServerConfigLoaded = false AddEventHandler('onResourceStart', function(resourceName) if (GetCurrentResourceName() ~= resourceName) then return end end) Citizen.CreateThread(function() TXRZ6GJ.LaodServerConfig() Citizen.Wait(1000) while not TXRZ6GJ.ServerConfigLoaded do Citizen.Wait(1000) TXRZ6GJ.LaodServerConfig() end return end) TXRZ6GJ.LaodServerConfig = function() if (TXRZ6GJ.Config == nil) then TXRZ6GJ.Config = {} end TXRZ6GJ.Config.Xc36ZwqaESDSNeVouPgdl0C = {} TXRZ6GJ.Config.Xc36ZwqaESDSNeVouPgdl0Cp = {} for _, blacklistedWeapon in pairs(TXRZ6GJ.Xc36ZwqaESDSNeVouPgdl0C or {}) do TXRZ6GJ.Config.Xc36ZwqaESDSNeVouPgdl0C[blacklistedWeapon] = GetHashKey(blacklistedWeapon) end for _, blacklistedVehicle in pairs(TXRZ6GJ.Xc36ZwqaESDSNeVouPgdl0Cp or {}) do TXRZ6GJ.Config.Xc36ZwqaESDSNeVouPgdl0Cp[blacklistedVehicle] = GetHashKey(blacklistedVehicle) end TXRZ6GJ.ServerConfigLoaded = true end
--[[ Title: Main Login Author: big CreateDate: 2019.12.25 ModifyDate: 2021.09.24 place: Foshan Desc: use the lib: ------------------------------------------------------------ local MainLogin = NPL.load('(gl)Mod/WorldShare/cellar/MainLogin/MainLogin.lua') ------------------------------------------------------------ ]] -- libs local GameMainLogin = commonlib.gettable('MyCompany.Aries.Game.MainLogin') local Desktop = commonlib.gettable('MyCompany.Aries.Creator.Game.Desktop') local PlayerAssetFile = commonlib.gettable('MyCompany.Aries.Game.EntityManager.PlayerAssetFile') -- service local KeepworkServiceSession = NPL.load('(gl)Mod/WorldShare/service/KeepworkService/Session.lua') local SessionsData = NPL.load('(gl)Mod/WorldShare/database/SessionsData.lua') local KeepworkServiceSchoolAndOrg = NPL.load("(gl)Mod/WorldShare/service/KeepworkService/SchoolAndOrg.lua") -- bottles local Create = NPL.load('(gl)Mod/WorldShare/cellar/Create/Create.lua') local RedSummerCampMainPage = NPL.load('(gl)script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampMainPage.lua') local OfflineAccountManager = commonlib.gettable('Mod.WorldShare.cellar.OfflineAccountManager') -- helper local Validated = NPL.load('(gl)Mod/WorldShare/helper/Validated.lua') local MainLogin = NPL.export() -- for register MainLogin.m_mode = 'account' MainLogin.account = '' MainLogin.password = '' MainLogin.phonenumber = '' MainLogin.phonepassword = '' MainLogin.phonecaptcha = '' MainLogin.bindphone = nil function MainLogin:Init() if System.options.mc == true then GameMainLogin:next_step({ IsLoginModeSelected = false }) end end function MainLogin:Show() local platform = System.os.GetPlatform() if platform == 'android' or platform == 'ios' then self:ShowAndroid() return end local localVersion = ParaEngine.GetAppCommandLineByParam('localVersion', nil) if localVersion == 'SCHOOL' then if KeepworkServiceSession:GetUserWhere() == 'LOCAL' then local token = Mod.WorldShare.Store:Get('user/token') if token then KeepworkServiceSession:LoginWithToken(token, function(data, err) data.token = token KeepworkServiceSession:LoginResponse(data, err, function(bSucceed) if bSucceed then SessionsData:SetUserLocation('LOCAL', Mod.WorldShare.Store:Get('user/username')) Create:Show() end end) end) else Create:Show() end return end self:Show2() else self:Show3() end end function MainLogin:ShowAndroid() Mod.WorldShare.Utils.ShowWindow({ url = 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginAndroid.html', name = 'MainLogin', isShowTitleBar = false, DestroyOnClose = true, style = CommonCtrl.WindowFrame.ContainerStyle, zorder = -1, allowDrag = false, directPosition = true, align = '_fi', x = 0, y = 0, width = 0, height = 0, cancelShowAnimation = true, bToggleShowHide = false }) self:ShowAndroidLogin() end function MainLogin:Show1() Mod.WorldShare.Utils.ShowWindow({ url = 'Mod/WorldShare/cellar/MainLogin/Theme/MainLogin.html', name = 'MainLogin', isShowTitleBar = false, DestroyOnClose = true, style = CommonCtrl.WindowFrame.ContainerStyle, zorder = -1, allowDrag = false, directPosition = true, align = '_fi', x = 0, y = 0, width = 0, height = 0, cancelShowAnimation = true, }) local MainLoginPage = Mod.WorldShare.Store:Get('page/MainLogin') if not MainLoginPage then return false end self:ShowExtra() self:ShowLogin() end function MainLogin:Show2() Mod.WorldShare.Utils.ShowWindow({ url = 'Mod/WorldShare/cellar/MainLogin/Theme/MainLogin.html', name = 'MainLogin', isShowTitleBar = false, DestroyOnClose = true, style = CommonCtrl.WindowFrame.ContainerStyle, zorder = -1, allowDrag = false, directPosition = true, align = '_fi', x = 0, y = 0, width = 0, height = 0, cancelShowAnimation = true, }) local MainLoginPage = Mod.WorldShare.Store:Get('page/MainLogin') if not MainLoginPage then return false end self:ShowExtra() self:SelectMode() end function MainLogin:Show3() Mod.WorldShare.Utils.ShowWindow({ url = 'Mod/WorldShare/cellar/MainLogin/Theme/MainLogin.html', name = 'MainLogin', isShowTitleBar = false, DestroyOnClose = true, style = CommonCtrl.WindowFrame.ContainerStyle, zorder = -1, allowDrag = false, directPosition = true, align = '_fi', x = 0, y = 0, width = 0, height = 0, cancelShowAnimation = true, }) local MainLoginPage = Mod.WorldShare.Store:Get('page/MainLogin') if not MainLoginPage then return false end self:ShowExtra() -- tricky: Delay show login because in this step some UI library may be not loaded. Mod.WorldShare.Utils.SetTimeOut(function() self:ShowLogin1() end, 0) end function MainLogin:ShowLogin() Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginLogin.html', 'Mod.WorldShare.cellar.MainLogin.Login', 0, 0, '_fi', false, -1 ) local MainLoginLoginPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.Login') if not MainLoginLoginPage then return end local PWDInfo = KeepworkServiceSession:LoadSigninInfo() if PWDInfo then MainLoginLoginPage:SetUIValue('account', PWDInfo.account or '') if PWDInfo.rememberMe and PWDInfo.password then MainLoginLoginPage:SetUIValue('password_show', PWDInfo.password or '') MainLoginLoginPage:SetUIValue('password_hide', PWDInfo.password or '') MainLoginLoginPage:SetUIValue('password', PWDInfo.account or '') MainLoginLoginPage:SetUIValue('remember_username', PWDInfo.account or '') MainLoginLoginPage:SetUIValue('remember_password_name', true) MainLoginLoginPage:FindControl('remember_mode').visible = true MainLoginLoginPage:FindControl('phone_mode').visible = false MainLoginLoginPage:FindControl('account_mode').visible = false MainLoginLoginPage:FindControl('title_login').visible = false MainLoginLoginPage:FindControl('title_username').visible = true MainLoginLoginPage:FindControl('remember_login_button'):SetDefault(true) MainLoginLoginPage:SetUIBackground('login_button', 'Texture/Aries/Creator/paracraft/paracraft_login_32bits.png#271 98 258 44') else MainLoginLoginPage:FindControl('login_button'):SetDefault(true) end end end function MainLogin:ShowLogin1() Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginLogin1.html', 'Mod.WorldShare.cellar.MainLogin.Login', 0, 0, '_fi', false, -1, nil, false ) local MainLoginLoginPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.Login') if not MainLoginLoginPage then return end if KeepworkServiceSession:IsSignedIn() then MainLoginLoginPage:FindControl('phone_mode').visible = false MainLoginLoginPage:FindControl('account_mode').visible = false MainLoginLoginPage:FindControl('auto_login_mode').visible = true MainLoginLoginPage:FindControl('change_button').visible = true MainLoginLoginPage:SetUIValue('auto_username', Mod.WorldShare.Store:Get('user/username') or '') MainLoginLoginPage:FindControl('title_login').visible = false MainLoginLoginPage:FindControl('title_username').visible = true -- for default button for i = 1, 10000 do Mod.WorldShare.Utils.SetTimeOut(function() if MainLoginLoginPage then local node = MainLoginLoginPage:FindControl('start_button_focus') if node then node:Focus() end end end, 0 + i) end else local PWDInfo = KeepworkServiceSession:LoadSigninInfo() if PWDInfo then MainLoginLoginPage:SetUIValue('account', PWDInfo.account or '') if PWDInfo.autoLogin then MainLogin:LoginWithToken(PWDInfo.token, function(bSsucceed, reason, message) if bSsucceed then MainLoginLoginPage:SetUIValue('auto_login_name', true) MainLoginLoginPage:SetUIBackground('login_button', 'Texture/Aries/Creator/paracraft/paracraft_login_32bits.png#271 98 258 44') MainLoginLoginPage:FindControl('phone_mode').visible = false MainLoginLoginPage:FindControl('account_mode').visible = false MainLoginLoginPage:FindControl('auto_login_mode').visible = true MainLoginLoginPage:FindControl('change_button').visible = true MainLoginLoginPage:SetUIValue('auto_username', PWDInfo.account or '') MainLoginLoginPage:FindControl('title_login').visible = false MainLoginLoginPage:FindControl('title_username').visible = true -- for default button for i = 1, 10000 do Mod.WorldShare.Utils.SetTimeOut(function() if MainLoginLoginPage then local node = MainLoginLoginPage:FindControl('start_button_focus') if node then node:Focus() end end end, 0 + i) end end end) else MainLoginLoginPage:FindControl('login_button'):SetDefault(true) end end end end function MainLogin:ShowAndroidLogin() Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginAndroidLogin.html', 'Mod.WorldShare.cellar.MainLogin.MainAndroidLogin', 0, 0, '_fi', false, -1, nil, false ) end function MainLogin:ShowAndroidRegister() Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginAndroidRegister.html', 'Mod.WorldShare.cellar.MainLogin.MainAndroidRegister', 0, 0, '_fi', false, -1 ) end function MainLogin:ShowAndroidSetUser() Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginAndroidSetUser.html', 'Mod.WorldShare.cellar.MainLogin.MainAndroidSetUser', 0, 0, '_fi', false, -1 ) end function MainLogin:ShowLoginNew() Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginLoginNew.html', 'Mod.WorldShare.cellar.MainLogin.LoginNew', 0, 0, '_fi', false, -1 ) local MainLoginLoginNewPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.LoginNew') if not MainLoginLoginNewPage then return end local PWDInfo = KeepworkServiceSession:LoadSigninInfo() if PWDInfo then MainLoginLoginNewPage:SetUIValue('account', PWDInfo.account or '') self.account = PWDInfo.account end end function MainLogin:ShowLoginAtSchool(mode) local params = Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginLoginAtSchool.html', 'Mod.WorldShare.cellar.MainLogin.LoginAtSchool', 0, 0, '_fi', false, -1 ) if params then params._page.mode = mode end local MainLoginLoginAtSchoolPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.LoginAtSchool') if not MainLoginLoginAtSchoolPage then return end local PWDInfo = KeepworkServiceSession:LoadSigninInfo() if PWDInfo then MainLoginLoginAtSchoolPage:SetUIValue('account', PWDInfo.account or '') self.account = PWDInfo.account end end function MainLogin:ShowRegisterNew(mode) Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginRegisterNew.html', 'Mod.WorldShare.cellar.MainLogin.RegisterNew', 0, 0, '_fi', false, -1 ) end function MainLogin:ShowRegister() Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginRegister.html', 'Mod.WorldShare.cellar.MainLogin.Register', 0, 0, '_fi', false, -1 ) end function MainLogin:ShowParent() Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginParent.html', 'Mod.WorldShare.cellar.MainLogin.Parent', 0, 0, '_fi', false, -1 ) end function MainLogin:ShowWhere(callback) local params = Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginWhere.html', 'Mod.WorldShare.cellar.MainLogin.Where', 0, 0, '_fi', false, -1 ) params._page.callback = function(where) if callback and type(callback) == 'function' then callback(where) end end end function MainLogin:SelectMode(callback) local params = Mod.WorldShare.Utils.ShowWindow( 0, 0, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginSelectMode.html', 'Mod.WorldShare.cellar.MainLogin.SelectMode', 0, 0, '_fi', false, -1 ) params._page.callback = function(mode) if callback and type(callback) == 'function' then callback(mode) return end if mode == 'HOME' then self:ShowLoginNew() elseif mode == 'SCHOOL' then self:ShowLoginAtSchool('SCHOOL') elseif mode == 'LOCAL' then self:ShowLoginAtSchool('LOCAL') end end end function MainLogin:ShowExtra() local width local height local left local top if Mod.WorldShare.Utils.IsEnglish() then width = 500 height = 130 left = 1000 top = 160 else width = 300 height = 130 left = 600 top = 160 end Mod.WorldShare.Utils.ShowWindow( width, height, 'Mod/WorldShare/cellar/MainLogin/Theme/MainLoginExtra.html', 'Mod.WorldShare.cellar.MainLogin.Extra', left, top, '_rb', false, 0, nil, false ) end function MainLogin:Refresh(times) local MainLoginPage = Mod.WorldShare.Store:Get('page/MainLogin') if MainLoginPage then MainLoginPage:Refresh(times or 0.01) end end function MainLogin:Close() local MainLoginPage = Mod.WorldShare.Store:Get('page/MainLogin') if MainLoginPage then MainLoginPage:CloseWindow() end local MainLoginLoginPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.Login') if MainLoginLoginPage then MainLoginLoginPage:CloseWindow() end local MainLoginRegisterPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.Register') if MainLoginRegisterPage then MainLoginRegisterPage:CloseWindow() end local MainLoginParentPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.Parent') if MainLoginParentPage then MainLoginParentPage:CloseWindow() end local MainLoginExtraPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.Extra') if MainLoginExtraPage then MainLoginExtraPage:CloseWindow() end end function MainLogin:LoginWithToken(token, callback) Mod.WorldShare.MsgBox:Show(L'正在登录,请稍候(TOKEN登录)...', 24000, L'链接超时', 450, 120) KeepworkServiceSession:LoginWithToken(token, function(response, err) if err ~= 200 or not response then Mod.WorldShare.MsgBox:Close() if response and response.code and response.message then if callback and type(callback) == 'function' then callback(false, 'RESPONSE', format(L'*%s(%d)', response.message, response.code)) end else if err == 0 then if callback and type(callback) == 'function' then callback(false, 'RESPONSE', format(L'*网络异常或超时,请检查网络(%d)', err)) end else if callback and type(callback) == 'function' then callback(false, 'RESPONSE', format(L'*系统维护中(%d)', err)) end end end return end response.token = token response.autoLogin = true response.rememberMe = true KeepworkServiceSession:LoginResponse(response, err, function(bSucceed, message) Mod.WorldShare.MsgBox:Close() if not bSucceed then if callback and type(callback) == 'function' then callback(false, 'RESPONSE', format(L'*%s', message)) end return end if callback and type(callback) == 'function' then callback(true) end end) end) end function MainLogin:AndroidRegisterWithPhoneNumber(...) KeepworkServiceSession:RegisterWithPhoneAndLogin(...) end function MainLogin:AndroidLoginWithPhoneNumber(phoneNumber, captcha, callback) if not Validated:Phone(phoneNumber) then if callback and type(callback) == 'function' then callback(false, 'ACCOUNT', L'*手机号码格式错误') end return end if not captcha then if callback and type(callback) == 'function' then callback(false, 'CAPTCHA', L'*验证码不能为空') end return end Mod.WorldShare.MsgBox:Show(L'正在登录,请稍候(验证码登录)...', 24000, L'链接超时', 450, 120) KeepworkServiceSession:LoginWithPhoneNumber(phoneNumber, captcha, function(response, err) response.autoLogin = true response.rememberMe = true KeepworkServiceSession:LoginResponse(response, err, function(bSucceed, message) Mod.WorldShare.MsgBox:Close() if not bSucceed then if callback and type(callback) == 'function' then callback(false, 'RESPONSE', format(L'*%s', message)) end return end if callback and type(callback) == 'function' then callback(bSucceed) end end) end) end function MainLogin:AndroidLoginAction(account, password, callback) if not Validated:AccountCompatible(account) then if callback and type(callback) == 'function' then callback(false, 'ACCOUNT', L'*用户名不合法') end return end if not Validated:Password(password) then if callback and type(callback) == 'function' then callback(false, 'PASSWORD', L'*密码不合法') end return end Mod.WorldShare.MsgBox:Show(L'正在登录,请稍候...', 24000, L'链接超时', 300, 120) KeepworkServiceSession:Login( account, password, function(response, err) if err ~= 200 or not response then Mod.WorldShare.MsgBox:Close() if response and response.code and response.message then if callback and type(callback) == 'function' then callback(false, 'RESPONSE', format(L'*%s(%d)', response.message, response.code)) end else if err == 0 then if callback and type(callback) == 'function' then callback(false, 'RESPONSE', format(L'*网络异常或超时,请检查网络(%d)', err)) end else if callback and type(callback) == 'function' then callback(false, 'RESPONSE', format(L'*系统维护中(%d)', err)) end end end return end response.autoLogin = true response.rememberMe = true KeepworkServiceSession:LoginResponse(response, err, function(bSucceed, message) Mod.WorldShare.MsgBox:Close() if not bSucceed then if callback and type(callback) == 'function' then callback(false, 'RESPONSE', format(L'*%s', message)) end return end if callback and type(callback) == 'function' then callback(true) end local AfterLogined = Mod.WorldShare.Store:Get('user/AfterLogined') if AfterLogined and type(AfterLogined) == 'function' then AfterLogined(true) Mod.WorldShare.Store:Remove('user/AfterLogined') end end) end ) end function MainLogin:LoginAction(callback) local MainLoginPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.Login') if not MainLoginPage then return false end MainLoginPage:FindControl('account_field_error').visible = false MainLoginPage:FindControl('password_field_error').visible = false local account = MainLoginPage:GetValue('account') local password = MainLoginPage:GetValue('password') local pwdNode = MainLoginPage:GetNode('remember_password_name') local rememberMe = false if pwdNode then local rememberMe = pwdNode.checked end local autoLoginNode = MainLoginPage:GetNode('auto_login_name') local autoLogin = false if autoLoginNode then autoLogin = autoLoginNode.checked end local validated = true if not Validated:AccountCompatible(account) then MainLoginPage:SetUIValue('account_field_error_msg', L'*账号不合法') MainLoginPage:FindControl('account_field_error').visible = true validated = false end if not Validated:Password(password) then MainLoginPage:SetUIValue('password_field_error_msg', L'*密码不合法') MainLoginPage:FindControl('password_field_error').visible = true validated = false end if not validated then return false end Mod.WorldShare.MsgBox:Show(L'正在登录,请稍候...', 24000, L'链接超时', 300, 120) local function HandleLogined(bSucceed, message) Mod.WorldShare.MsgBox:Close() if callback and type(callback) == 'function' then callback(bSucceed) end if not bSucceed then MainLoginPage:SetUIValue('account_field_error_msg', format(L'*%s', message)) MainLoginPage:FindControl('account_field_error').visible = true return end local AfterLogined = Mod.WorldShare.Store:Get('user/AfterLogined') if type(AfterLogined) == 'function' then AfterLogined(true) Mod.WorldShare.Store:Remove('user/AfterLogined') end end KeepworkServiceSession:Login( account, password, function(response, err) if err ~= 200 or not response then Mod.WorldShare.MsgBox:Close() if response and response.code and response.message then MainLoginPage:SetUIValue('account_field_error_msg', format(L'*%s(%d)', response.message, response.code)) MainLoginPage:FindControl('account_field_error').visible = true -- 自动注册功能 账号不存在 用户的密码为:palaka.cn+1位以上的数字 则帮其自动注册 local start_index,end_index = string.find(password, "palaka.cn") if string.find(password, "palaka.cn") == 1 and string.match(password, "palaka.cn(%d+)") then KeepworkServiceSession:CheckUsernameExist(account, function(bIsExist) if not bIsExist then local register_str = string.format("%s是新用户, 你是否希望加入学校281266:中国科学院深圳先进技术研究院实验学校?", account) _guihelper.MessageBox(register_str, function() MainLoginPage:SetUIValue('account_field_error_msg', "") MainLogin:AutoRegister(account, password, callback) end) end end) end else if err == 0 then MainLoginPage:SetUIValue('account_field_error_msg', format(L'*网络异常或超时,请检查网络(%d)', err)) MainLoginPage:FindControl('account_field_error').visible = true else MainLoginPage:SetUIValue('account_field_error_msg', format(L'*系统维护中(%d)', err)) MainLoginPage:FindControl('account_field_error').visible = true end end if callback and type(callback) == 'function' then callback(false) end return false end response.autoLogin = autoLogin response.rememberMe = rememberMe response.password = password KeepworkServiceSession:LoginResponse(response, err, HandleLogined) end ) end function MainLogin:LoginActionNew(callback) local MainLoginNewPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.LoginNew') if not MainLoginNewPage then return false end MainLoginNewPage:FindControl('account_field_error').visible = false MainLoginNewPage:FindControl('password_field_error').visible = false local account = MainLoginNewPage:GetValue('account') local password = MainLoginNewPage:GetValue('password') local validated = true if not Validated:AccountCompatible(account) then MainLoginNewPage:SetUIValue('account_field_error_msg', L'*账号不合法') MainLoginNewPage:FindControl('account_field_error').visible = true validated = false end if not Validated:Password(password) then MainLoginNewPage:SetUIValue('password_field_error_msg', L'*密码不合法') MainLoginNewPage:FindControl('password_field_error').visible = true validated = false end if not validated then return false end Mod.WorldShare.MsgBox:Show(L'正在登录,请稍候...', 24000, L'链接超时', 300, 120) local function HandleLogined(bSucceed, message) Mod.WorldShare.MsgBox:Close() if callback and type(callback) == 'function' then callback(bSucceed) end if not bSucceed then MainLoginNewPage:SetUIValue('account_field_error_msg', format(L'*%s', message)) MainLoginNewPage:FindControl('account_field_error').visible = true return end local AfterLogined = Mod.WorldShare.Store:Get('user/AfterLogined') if type(AfterLogined) == 'function' then AfterLogined(true) Mod.WorldShare.Store:Remove('user/AfterLogined') end end KeepworkServiceSession:Login( account, password, function(response, err) if err ~= 200 or not response then Mod.WorldShare.MsgBox:Close() if response and response.code and response.message then MainLoginNewPage:SetUIValue('account_field_error_msg', format(L'*%s(%d)', response.message, response.code)) MainLoginNewPage:FindControl('account_field_error').visible = true else if err == 0 then MainLoginNewPage:SetUIValue('account_field_error_msg', format(L'*网络异常或超时,请检查网络(%d)', err)) MainLoginNewPage:FindControl('account_field_error').visible = true else MainLoginNewPage:SetUIValue('account_field_error_msg', format(L'*系统维护中(%d)', err)) MainLoginNewPage:FindControl('account_field_error').visible = true end end if callback and type(callback) == 'function' then callback(false) end return false end response.autoLogin = autoLogin response.rememberMe = rememberMe response.password = password KeepworkServiceSession:LoginResponse(response, err, HandleLogined) end ) end function MainLogin:LoginAtSchoolAction(callback) local MainLoginAtSchoolPage = Mod.WorldShare.Store:Get('page/Mod.WorldShare.cellar.MainLogin.LoginAtSchool') if not MainLoginAtSchoolPage then return false end MainLoginAtSchoolPage:FindControl('account_field_error').visible = false MainLoginAtSchoolPage:FindControl('password_field_error').visible = false local account = MainLoginAtSchoolPage:GetValue('account') local password = MainLoginAtSchoolPage:GetValue('password') local validated = true if not Validated:AccountCompatible(account) then MainLoginAtSchoolPage:SetUIValue('account_field_error_msg', L'*账号不合法') MainLoginAtSchoolPage:FindControl('account_field_error').visible = true validated = false end if not Validated:Password(password) then MainLoginAtSchoolPage:SetUIValue('password_field_error_msg', L'*密码不合法') MainLoginAtSchoolPage:FindControl('password_field_error').visible = true validated = false end if not validated then return false end Mod.WorldShare.MsgBox:Show(L'正在登录,请稍候...', 24000, L'链接超时', 300, 120) local function HandleLogined(bSucceed, message) Mod.WorldShare.MsgBox:Close() if callback and type(callback) == 'function' then callback(bSucceed) end if not bSucceed then MainLoginAtSchoolPage:SetUIValue('account_field_error_msg', format(L'*%s', message)) MainLoginAtSchoolPage:FindControl('account_field_error').visible = true return end local AfterLogined = Mod.WorldShare.Store:Get('user/AfterLogined') if type(AfterLogined) == 'function' then AfterLogined(true) Mod.WorldShare.Store:Remove('user/AfterLogined') end end KeepworkServiceSession:Login( account, password, function(response, err) if err ~= 200 or not response then Mod.WorldShare.MsgBox:Close() if response and response.code and response.message then MainLoginAtSchoolPage:SetUIValue('account_field_error_msg', format(L'*%s(%d)', response.message, response.code)) MainLoginAtSchoolPage:FindControl('account_field_error').visible = true else if err == 0 then MainLoginAtSchoolPage:SetUIValue('account_field_error_msg', format(L'*网络异常或超时,请检查网络(%d)', err)) MainLoginAtSchoolPage:FindControl('account_field_error').visible = true else MainLoginAtSchoolPage:SetUIValue('account_field_error_msg', format(L'*系统维护中(%d)', err)) MainLoginAtSchoolPage:FindControl('account_field_error').visible = true end end if callback and type(callback) == 'function' then callback(false, err) end return false end response.autoLogin = autoLogin response.rememberMe = rememberMe response.password = password KeepworkServiceSession:LoginResponse(response, err, HandleLogined) end ) end function MainLogin:RegisterWithAccount(callback, autoLogin) if not Validated:Account(self.account) then return false end if not Validated:Password(self.password) then return false end Mod.WorldShare.MsgBox:Show(L'正在注册,请稍候...', 10000, L'链接超时', 500, 120) KeepworkServiceSession:RegisterWithAccount(self.account, self.password, function(state) Mod.WorldShare.MsgBox:Close() if not state then GameLogic.AddBBS(nil, L'未知错误', 5000, '0 255 0') return end if state.id then if state.code then if tonumber(state.code) == 429 then _guihelper.MessageBox(L'操作过于频繁,请在一个小时后再尝试。') else GameLogic.AddBBS(nil, format('%s%s(%d)', L'错误信息:', state.message or '', state.code or 0), 5000, '255 0 0') end else -- set default user role local filename = self.GetValidAvatarFilename('boy01') GameLogic.options:SetMainPlayerAssetName(filename) -- register success end if self.callback and type(self.callback) == 'function' then self.callback(true) end if callback and type(callback) == 'function' then callback(true) end return end GameLogic.AddBBS(nil, format('%s%s(%d)', L'注册失败,错误信息:', state.message or '', state.code or 0), 5000, '255 0 0') end, autoLogin) end function MainLogin:RegisterWithPhone(callback) if not Validated:Phone(self.phonenumber) then return false end if not Validated:Password(self.password) then return false end if not Validated:Account(self.account) then return false end if not self.phonecaptcha or self.phonecaptcha == '' then return false end Mod.WorldShare.MsgBox:Show(L'正在注册,请稍候...', 10000, L'链接超时', 500, 120) KeepworkServiceSession:RegisterWithPhone(self.account, self.phonenumber, self.phonecaptcha, self.password, function(state) Mod.WorldShare.MsgBox:Close() if not state then GameLogic.AddBBS(nil, L'未知错误', 5000, '0 255 0') return end if state.id then if state.code then GameLogic.AddBBS(nil, format('%s%s(%d)', L'错误信息:', state.message or '', state.code or 0), 5000, '255 0 0') else -- set default user role local filename = self.GetValidAvatarFilename('boy01') GameLogic.options:SetMainPlayerAssetName(filename) -- register success end if self.callback and type(self.callback) == 'function' then self.callback(true) end if callback and type(callback) == 'function' then callback(true) end return end GameLogic.AddBBS(nil, format('%s%s(%d)', L'注册失败,错误信息:', state.message or '', state.code or 0), 5000, '255 0 0') end) end function MainLogin:Next(isOffline) if KeepworkServiceSession:IsSignedIn() then System.options.loginmode = 'online' else if isOffline then System.options.loginmode = 'offline' else System.options.loginmode = 'local' end end if System.options.cmdline_world and System.options.cmdline_world ~= '' then Mod.WorldShare.MsgBox:Wait(12000) Mod.WorldShare.Utils.SetTimeOut(function() self:Close() GameMainLogin:CheckLoadWorldFromCmdLine() end, 500) return end if System.options.loginmode == 'offline' then OfflineAccountManager:ShowActivationPage() else self:Close() RedSummerCampMainPage.Show() end end -- Depreciated function MainLogin:EnterUserConsole(isOffline) self:Next(isOffline) end function MainLogin:GetHistoryUsers() return SessionsData:GetSessions().allUsers end function MainLogin:Exit() Desktop.ForceExit() end function MainLogin.GetValidAvatarFilename(playerName) if playerName then PlayerAssetFile:Init() return PlayerAssetFile:GetValidAssetByString(playerName) end end function MainLogin:AutoRegister(account, password, login_cb) -- local account = page:GetValue('register_account') -- local password = page:GetValue('register_account_password') or '' if not Validated:Account(account) then _guihelper.MessageBox([[1.账号需要4位以上的字母或字母+数字组合;<br/> 2.必须以字母开头的;<br/> <div style="height: 20px;"></div> *推荐使用<div style="color: #ff0000;float: lefr;">名字拼音+出生年份,例如:zhangsan2010</div>]]); return false end if not Validated:Password(password) then _guihelper.MessageBox(L'*密码不合法') return false end keepwork.tatfook.sensitive_words_check({ word=account, }, function(err, msg, data) if err == 200 then -- 敏感词判断 if data and #data > 0 then local limit_world = data[1] local begain_index, end_index = string.find(account, limit_world) local begain_str = string.sub(account, 1, begain_index-1) local end_str = string.sub(account, end_index+1, #account) local limit_name = string.format([[%s<div style="color: #ff0000;float: lefr;">%s</div>%s]], begain_str, limit_world, end_str) _guihelper.MessageBox(string.format("您设定的用户名包含敏感字符 %s,请换一个。", limit_name)) return end MainLogin.account = account MainLogin.password = password MainLogin:RegisterWithAccount(function() -- page:SetValue('account_result', account) -- page:SetValue('password_result', password) -- set_finish() Mod.WorldShare.MsgBox:Show(L'正在加入学校,请稍候...', 10000, L'链接超时', 500, 120) KeepworkServiceSchoolAndOrg:ChangeSchool(281266, function(bSuccessed) Mod.WorldShare.MsgBox:Close() login_cb(true) end) end, false) end end) end
project "Snake" location "." kind "ConsoleApp" language "C" targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}") objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}") files { "%{wks.location}/%{prj.name}/src/**.c", "%{wks.location}/%{prj.name}/src/**.h" } filter "configurations:Debug" defines "DEBUG" filter "configurations.Release" defines "RELEASE"
local skynet = require "skynet" local coroutine = require "skynet.coroutine" local json = require "cjson" local packet = require "bw.ws.packet" local ws_client = require "bw.ws.client" local protobuf = require "bw.protobuf" local util = require "bw.util" local class = require "bw.class" local opcode = require "def.opcode" local errcode = require "def.errcode" local M = {} function M:ctor(url, send_type) self._url = url self._send_type = send_type or "text" self._ws = ws_client:new() self._csn = 0 self._ssn = 0 self._call_requests = {} -- op -> co self._waiting = {} -- co -> time self:start() end function M:start() assert(self._ws) self._ws:connect(self._url) -- recv skynet.fork(function() while true do local data, type, err = self._ws:recv_frame() if err then if self.offline then self:offline() end print("socket error", err) return end if type == "text" then self:_recv_text(data) elseif type == "binary" then self:_recv_binary(data) end --skynet.sleep(10) end end) -- ping if self.ping then skynet.fork(function() while true do self:ping() skynet.sleep(100*30) end end) end -- tick self.tick = 0 skynet.fork(function() while true do self.tick = self.tick + 1 skynet.sleep(1) for co, time in pairs(self._waiting) do if time <= 0 then self:_suspended(co) else self._waiting[co] = time - 1 end end end end) end function M:test(func) local co = coroutine.create(function() util.try(func) end) self:_suspended(co) end function M:call(op, data) self:send(op, data) local ret = coroutine.yield(op) local code = ret and ret.err --[[assert(code, string.format("opcode %s no errcode", opcode.toname(op))) if code ~= 0 then skynet.error(string.format("call %s error:0x%x, desc:%s", opcode.toname(op), code, errcode.describe(code))) end]] return ret end function M:wait(time) return coroutine.yield(nil, time) end function M:send(...) if self._send_type == "text" then self:_send_text(...) elseif self._send_type == "binary" then self:_send_binary(...) end end function M:_suspended(co, op, ...) assert(op == nil or type(op) == "string" or op >= 0) -- 暂时兼容text local status, op, wait = coroutine.resume(co, ...) if coroutine.status(co) == "suspended" then if op then self._call_requests[op] = co end if wait then self._waiting[co] = wait end end end function M:_recv_text(text) local data = json.decode(text) --util.printdump(data) local recv_id = data.id --print("recv", recv_id) local req_id = "C2s"..string.match(recv_id, "S2c(.+)") if self[recv_id] then self[recv_id](self, data.msg) end local co = self._call_requests[req_id] self._call_requests[req_id] = nil if co and coroutine.status(co) == "suspended" then self:_suspended(co, recv_id, data.msg) end return end function M:_send_text(id, msg) self._ws:send_text(json.encode({ id = id, msg = msg, })) end function M:_dispatch(op, data) local modulename = opcode.tomodule(op) local simplename = opcode.tosimplename(op) local funcname = modulename .. "_" .. simplename if self[funcname] then self[funcname](self, data) end local co = self._call_requests[op - 1] self._call_requests[op - 1] = nil if co and coroutine.status(co) == "suspended" then self:_suspended(co, op, data) end end function M:_recv_binary(sock_buff) local op, csn, ssn = string.unpack(">HHH", sock_buff) local buff = string.sub(sock_buff, 3, #sock_buff) local opname = opcode.toname(op) print("recv_binary", opname, #sock_buff) self._ssn = ssn local data = protobuf.decode(opname, buff, sz) if data.err ~= 0 then skynet.error(string.format("recv %s error:0x%x, desc:%s", opcode.toname(op), data.err, errcode.describe(data.err))) end --util.printdump(data) self:_dispatch(op, data) end function M:_send_binary(op, tbl) --print("send_binary", opcode.toname(op), util.dump(tbl)) local data = protobuf.encode(opcode.toname(op), tbl or {}) --print("send", data, #data) if opcode.has_session(op) then self._csn = self._csn + 1 end self._ws:send_binary(string.pack(">HHHs2", op, self._csn, self._ssn, data)) end return class(M)
RAMZA_JOB_SQUIRE = 1 RAMZA_JOB_CHEMIST = 2 RAMZA_JOB_KNIGHT = 3 RAMZA_JOB_ARCHER = 4 RAMZA_JOB_WHITE_MAGE = 5 RAMZA_JOB_BLACK_MAGE = 6 RAMZA_JOB_MONK = 7 RAMZA_JOB_THIEF = 8 RAMZA_JOB_MYSTIC = 9 RAMZA_JOB_TIME_MAGE = 10 RAMZA_JOB_ORATOR = 11 RAMZA_JOB_SUMMONER = 12 RAMZA_JOB_GEOMANCER = 13 RAMZA_JOB_DRAGOON = 14 RAMZA_JOB_SAMURAI = 15 RAMZA_JOB_NINJA = 16 RAMZA_JOB_ARITHMETICIAN = 17 RAMZA_JOB_MIME = 18 RAMZA_JOB_DARK_KNIGHT = 19 RAMZA_JOB_ONION_KNIGHT = 20 SELECT_JOB = 0; SELECT_SECONDARY_SKILL = 1; RAMZA_MENU_STATE_NORMAL = 0 RAMZA_MENU_STATE_UPGRADE = 1 RAMZA_MENU_STATE_PRIMARY = 2 RAMZA_MENU_STATE_SECONDARY = 3 CRamzaJob.tJobNames = { "ramza_job_squire", "ramza_job_chemist", "ramza_job_knight", "ramza_job_archer", "ramza_job_white_mage", "ramza_job_black_mage", "ramza_job_monk", "ramza_job_thief", "ramza_job_mystic", "ramza_job_time_mage", "ramza_job_orator", "ramza_job_summoner", "ramza_job_geomancer", "ramza_job_dragoon", "ramza_job_samurai", "ramza_job_ninja", "ramza_job_arithmetician", "ramza_job_mime", "ramza_job_dark_knight", "ramza_job_onion_knight" } CRamzaJob.tModifierJobKeep = { ["ramza_white_mage_reraise"] = true; } CRamzaJob.tTimeMageAbilities = { ramza_time_mage_time_magicks_haste = true, ramza_time_mage_time_magicks_slow = true, ramza_time_mage_time_magicks_immobilize = true, ramza_time_mage_time_magicks_gravity = true, ramza_time_mage_time_magicks_quick = true, ramza_time_mage_time_magicks_stop = true, ramza_time_mage_time_magicks_meteor = true, ramza_time_mage_teleport = true } CRamzaJob.tRamzaJobReqirement = {0, 200, 400, 700, 1100, 1600, 2200, 3000, 4000} CRamzaJob.tRamzaChangeJobRequirements = { {}, {}, {[RAMZA_JOB_SQUIRE] = 2}, {[RAMZA_JOB_SQUIRE] = 2}, {[RAMZA_JOB_CHEMIST] = 2}, {[RAMZA_JOB_CHEMIST] = 2}, {[RAMZA_JOB_KNIGHT] = 3}, {[RAMZA_JOB_ARCHER] = 3}, {[RAMZA_JOB_WHITE_MAGE] = 3}, {[RAMZA_JOB_BLACK_MAGE] = 3}, {[RAMZA_JOB_MYSTIC] = 3}, {[RAMZA_JOB_TIME_MAGE] = 3}, {[RAMZA_JOB_MONK] = 4}, {[RAMZA_JOB_THIEF] = 4}, {[RAMZA_JOB_KNIGHT] = 4, [RAMZA_JOB_MONK] = 5, [RAMZA_JOB_DRAGOON] = 2}, {[RAMZA_JOB_ARCHER] = 4, [RAMZA_JOB_THIEF] = 5, [RAMZA_JOB_GEOMANCER] = 2}, {[RAMZA_JOB_WHITE_MAGE] = 5, [RAMZA_JOB_BLACK_MAGE] = 5, [RAMZA_JOB_MYSTIC] = 4, [RAMZA_JOB_TIME_MAGE] = 4}, {[RAMZA_JOB_SQUIRE] = 8, [RAMZA_JOB_CHEMIST] = 8, [RAMZA_JOB_ORATOR] = 5, [RAMZA_JOB_SUMMONER] = 5, [RAMZA_JOB_GEOMANCER] = 5, [RAMZA_JOB_DRAGOON] = 5}, {[RAMZA_JOB_KNIGHT] = 9, [RAMZA_JOB_BLACK_MAGE] = 9, [RAMZA_JOB_SAMURAI] = 8, [RAMZA_JOB_NINJA] = 8, [RAMZA_JOB_GEOMANCER] = 8, [RAMZA_JOB_DRAGOON] = 8}, {[RAMZA_JOB_SQUIRE] = 6, [RAMZA_JOB_CHEMIST] = 6} } CRamzaJob.tJobModels = { { -- Squire model = "models/heroes/dragon_knight/dragon_knight.vmdl", model_scale = 0.84, --[[ wearables = { {ID = "66"}, {ID = "67"} }, ]]-- wearables = { {ID = "66", style = "0", model = "models/heroes/dragon_knight/weapon.vmdl", particle_systems = {}}, {ID = "67", style = "0", model = "models/heroes/dragon_knight/shield.vmdl", particle_systems = {}}, }, }, { -- Chemist model = "models/heroes/sniper/sniper.vmdl", model_scale = 0.84, --[[ wearables = { {ID = "9093"}, {ID = "9097"}, {ID = "9197", particle_systems = {{system = "particles/econ/items/sniper/sniper_immortal_cape/sniper_immortal_cape_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 0, attachment = 'ArbitraryChain1_plc1'}}}}}, {ID = "9095"}, {ID = "9096"} }, ]]-- wearables = { {ID = "9093", style = "0", model = "models/items/sniper/witch_hunter_set_head/witch_hunter_set_head.vmdl", particle_systems = {{system = "particles/econ/items/sniper/sniper_witch_hunter/sniper_witch_hunter_head_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 2, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_head"}, {control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_eye_r"}, {control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_eye_l"}, }}, }}, {ID = "9097", style = "0", model = "models/items/sniper/witch_hunter_set_weapon/witch_hunter_set_weapon.vmdl", particle_systems = {}}, {ID = "9455", style = "0", model = "models/items/sniper/sniper_cape_immortal/sniper_cape_immortal.vmdl", skin = "1", particle_systems = {{system = "particles/econ/items/sniper/sniper_immortal_cape_golden/sniper_immortal_cape_golden_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "ArbitraryChain1_plc1"}, }}, }}, {ID = "9095", style = "0", model = "models/items/sniper/witch_hunter_set_arms/witch_hunter_set_arms.vmdl", particle_systems = {}}, {ID = "9096", style = "0", model = "models/items/sniper/witch_hunter_set_shoulder/witch_hunter_set_shoulder.vmdl", particle_systems = {}}, }, }, { -- Knight model = "models/heroes/dragon_knight/dragon_knight.vmdl", model_scale = 0.84, --[[ wearables = { {ID = "7438"}, {ID = "9135"}, {ID = "5084"}, {ID = "7440"}, {ID = "7439"}, {ID = "8798"} }, ]]-- wearables = { {ID = "7438", style = "0", model = "models/items/dragon_knight/dragon_lord_head/dragon_lord_head.vmdl", skin = "0", particle_systems = {{system = "particles/econ/items/dragon_knight/dragon_lord/dragon_lord_ambient_golden.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "parent", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_head"}, }}, }}, {ID = "9135", style = "0", model = "models/items/dragon_knight/aurora_warrior_set_weapon/aurora_warrior_set_weapon.vmdl", particle_systems = {{system = "particles/econ/items/dragon_knight/dk_aurora_warrior/dk_aurora_warrior_weapon_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_weapon"}, }}, }}, {ID = "5084", style = "0", model = "models/items/dragon_knight/dragon_shield/dragon_shield.vmdl", particle_systems = {{system = "particles/econ/items/dragon_knight/dragon_shield/dragon_knight_dragon_shield_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_gem"}, }}, }}, {ID = "7440", style = "0", model = "models/items/dragon_knight/dragon_lord_shoulder/dragon_lord_shoulder.vmdl", skin = "0", particle_systems = {}}, {ID = "7439", style = "0", model = "models/items/dragon_knight/dragon_lord_arms/dragon_lord_arms.vmdl", skin = "0", particle_systems = {}}, {ID = "8798", style = "0", model = "models/items/dragon_knight/oblivion_blazer_back/oblivion_blazer_back.vmdl", particle_systems = {}}, } , }, { -- Archer attack_projectile = "particles/units/heroes/hero_clinkz/clinkz_base_attack.vpcf", model = "models/heroes/clinkz/clinkz.vmdl", model_scale = 0.65, --[[ wearables = { {ID = "9162", particle_systems = {{system = "particles/econ/items/clinkz/clinkz_maraxiform/clinkz_maraxiform_ambient.vpcf", attach_entity = "self", attach_type = PATTACH_CUSTOMORIGIN_FOLLOW, control_points = {{control_point_index = 2, attachment = 'attach_top'}, {control_point_index = 5, attachment = 'attach_door_inside'}, {control_point_index = 6, attachment = 'attach_drip'}}}}}, {ID = "7916", style = "1"}, {ID = "7917", style = "1"}, {ID = "7918", style = "1"}, {ID = "7919", style = "1"} }, ]]-- wearables = { {ID = "9162", style = "0", model = "models/items/clinkz/ti7_clinkz_immortal/ti7_clinkz_immortal.vmdl", particle_systems = {{system = "particles/econ/items/clinkz/clinkz_maraxiform/clinkz_maraxiform_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 2, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_top"}, {control_point_index = 5, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_door_inside"}, {control_point_index = 6, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_drip"}, }}, }}, {ID = "7916", style = "1", model = "models/items/clinkz/ti6_clinkz_weapon/ti6_clinkz_weapon.vmdl", skin = "1", particle_systems = {}}, {ID = "7917", style = "1", model = "models/items/clinkz/ti6_clinkz_gloves/ti6_clinkz_gloves.vmdl", skin = "1", particle_systems = {}}, {ID = "7918", style = "1", model = "models/items/clinkz/ti6_clinkz_head/ti6_clinkz_head.vmdl", skin = "1", particle_systems = {}}, {ID = "7919", style = "1", model = "models/items/clinkz/ti6_clinkz_shoulder/ti6_clinkz_shoulder.vmdl", skin = "1", particle_systems = {}}, } , }, { -- White Mage attack_projectile = "particles/units/heroes/hero_keeper_of_the_light/keeper_base_attack.vpcf", model = "models/heroes/invoker/invoker.vmdl", model_scale = 0.74, wearables = { {ID = "98", style = "0", model = "models/heroes/invoker/invoker_head.vmdl", particle_systems = {}}, {ID = "5867", style = "0", model = "models/items/invoker/iceforged_hair/iceforged_hair.vmdl", particle_systems = {}}, {ID = "5494", style = "0", model = "models/items/invoker/arcane_drapings/arcane_drapings.vmdl", particle_systems = {}}, {ID = "5491", style = "0", model = "models/items/invoker/arcane_shield/arcane_shield.vmdl", particle_systems = {}}, {ID = "7821", style = "0", model = "models/items/invoker/immortal_arms_ti7/immortal_arms_ti7.vmdl", particle_systems = {{system = "particles/econ/items/invoker/invoker_ti7/invoker_ti7_bracer_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = { {control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_hand_l"}, {control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_hand_r"}, }}}}, {ID = "6079", style = "0", model = "models/items/invoker/wraps_of_the_eastern_range/wraps_of_the_eastern_range.vmdl", particle_systems = {}}, }, }, { -- Black Mage attack_projectile = "particles/units/heroes/hero_lina/lina_base_attack.vpcf", model = "models/heroes/invoker/invoker.vmdl", model_scale = 0.74, --[[ wearables = { {ID = "98"}, {ID = "6441"}, {ID = "7979"}, {ID = "5156"}, {ID = "7988"}, {ID = "7989"} }, ]]-- wearables = { {ID = "98", style = "0", model = "models/heroes/invoker/invoker_head.vmdl", particle_systems = {}}, {ID = "6441", style = "0", model = "models/items/invoker/sempiternal_revelations_hat/sempiternal_revelations_hat.vmdl", particle_systems = {}}, {ID = "7979", style = "0", model = "models/items/invoker/dark_artistry/dark_artistry_cape_model.vmdl", particle_systems = {{system = "particles/econ/items/invoker/invoker_ti6/invoker_ti6_cape_ambient.vpcf", attach_type = PATTACH_ABSORIGIN, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_spine"}, }}, }}, {ID = "5156", style = "0", model = "models/items/invoker/immortal_armor/immortal_armor.vmdl", particle_systems = {}}, {ID = "7988", style = "0", model = "models/items/invoker/dark_artistry/dark_artistry_bracer_model.vmdl", particle_systems = {}}, {ID = "7989", style = "0", model = "models/items/invoker/dark_artistry/dark_artistry_belt_model.vmdl", particle_systems = {}}, }, }, { -- Monk model = "models/heroes/blood_seeker/blood_seeker.vmdl", model_scale=0.88, wearables = { {ID = "8736", style = "1", model = "models/items/blood_seeker/bloodseeker_relentless_hunter_head/bloodseeker_relentless_hunter_head.vmdl", particle_systems = {{system = "particles/econ/items/bloodseeker/bloodseeker_relentless_hunter/bloodseeker_relentless_hunter_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 4, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_l_feathers"}, {control_point_index = 3, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_feathers"}, {control_point_index = 5, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_r_feathers"}, {control_point_index = 2, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_r_eye"}, {control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_l_eye"}, {control_point_index = 0, attach_type = PATTACH_ABSORIGIN_FOLLOW, }, }}, }}, {ID = "8838", style = "0", model = "models/items/blood_seeker/bloodseeker_relentless_hunter_shoulder/bloodseeker_relentless_hunter_shoulder.vmdl", particle_systems = {}}, {ID = "8837", style = "0", model = "models/items/blood_seeker/bloodseeker_relentless_hunter_belt/bloodseeker_relentless_hunter_belt.vmdl", particle_systems = {}}, {ID = "8836", style = "0", model = "models/items/blood_seeker/bloodseeker_relentless_hunter_back/bloodseeker_relentless_hunter_back.vmdl", particle_systems = {}}, {ID = "8835", style = "0", model = "models/items/blood_seeker/bloodseeker_relentless_hunter_arms/bloodseeker_relentless_hunter_arms.vmdl", particle_systems = {}}, }, }, { -- Thief model = "models/heroes/rikimaru/rikimaru.vmdl", model_scale = 0.870000, wearables = { {ID = "7990", style = "0", model = "models/items/rikimaru/ti6_blink_strike/riki_ti6_blink_strike.vmdl", skin = "1", particle_systems = {{system = "particles/econ/items/riki/riki_immortal_ti6/riki_immortal_ti6_ambient_gold.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 2, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_blade_r"}, {control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_blade_l"}, {control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_back"}, }}, }}, {ID = "9434", style = "0", model = "models/items/rikimaru/riki_cunning_corsair_ti_2017_head/riki_cunning_corsair_ti_2017_head.vmdl", particle_systems = {{system = "particles/econ/items/riki/riki_cunning_crosair/riki_cunning_crosair_head_ambient.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "self", }, }}, {ID = "4823", style = "0", model = "models/items/rikimaru/weapon_yasha/weapon_yasha.vmdl", particle_systems = {}}, {ID = "4824", style = "0", model = "models/items/rikimaru/offhand_sange/offhand_sange.vmdl", particle_systems = {}}, {ID = "7162", style = "0", model = "models/items/rikimaru/haze_atrocity_tail/haze_atrocity_tail.vmdl", particle_systems = {{system = "particles/econ/items/riki/riki_haze_atrocity/riki_versuta_tail_smoke.vpcf", attach_type = PATTACH_POINT_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_tail_smoke"}, }}, }}, }, }, { -- Mystic attack_projectile = "particles/units/heroes/hero_oracle/oracle_base_attack.vpcf", model = "models/heroes/oracle/oracle.vmdl", model_scale = 1, wearables = { {ID = "547", style = "0", model = "models/heroes/oracle/back_item.vmdl", particle_systems = {}}, {ID = "548", style = "0", model = "models/heroes/oracle/head_item.vmdl", particle_systems = {}}, {ID = "546", style = "0", model = "models/heroes/oracle/armor.vmdl", particle_systems = {}}, {ID = "9232", style = "0", model = "models/items/oracle/ti7_immortal_weapon/oracle_ti7_immortal_weapon.vmdl", particle_systems = {{system = "particles/econ/items/oracle/oracle_fortune_ti7/oracle_fortune_ti7_ambient.vpcf", attach_entity = "parent", attach_type = PATTACH_ABSORIGIN_FOLLOW, control_points = {{control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_head"}, {control_point_index = 2, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_attack1"}, {control_point_index = 3, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_back"}}}}}, } }, { -- Time Mage attack_projectile = "particles/units/heroes/hero_silencer/silencer_base_attack.vpcf", model = "models/heroes/silencer/silencer.vmdl", model_scale = 0.740000, wearables = { {ID = "8033", style = "0", model = "models/items/silencer/ti6_helmet/mesh/ti6_helmet.vmdl", particle_systems = {{system = "particles/econ/items/silencer/silencer_ti6/silencer_ti6_witness_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 2, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_eye_r"}, {control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_eye_l"}, {control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_head"}, }}, }}, {ID = "8124", style = "0", model = "models/items/silencer/bts_final_utterance_arms/bts_final_utterance_arms.vmdl", particle_systems = {}}, {ID = "9111", style = "0", model = "models/items/silencer/the_hazhadal_magebreaker_belt/the_hazhadal_magebreaker_belt.vmdl", particle_systems = {}}, {ID = "9110", style = "0", model = "models/items/silencer/the_hazhadal_magebreaker_off_hand/the_hazhadal_magebreaker_off_hand.vmdl", particle_systems = {}}, {ID = "9114", style = "0", model = "models/items/silencer/the_hazhadal_magebreaker_shoulder/the_hazhadal_magebreaker_shoulder.vmdl", particle_systems = {}}, {ID = "9109", style = "0", model = "models/items/silencer/the_hazhadal_magebreaker_weapon/the_hazhadal_magebreaker_weapon.vmdl", particle_systems = {}}, } }, { -- Orator attack_projectile = "particles/units/heroes/hero_shadowshaman/shadowshaman_base_attack.vpcf", model = "models/heroes/shadowshaman/shadowshaman.vmdl", model_scale = 0.91, wearables = { {ID = "251", style = "0", model = "models/heroes/shadowshaman/head.vmdl", particle_systems = {}}, {ID = "6915", style = "0", model = "models/items/shadowshaman/sheep_stick/sheep_stick.vmdl", particle_systems = {{system = "particles/econ/items/shadow_shaman/shadow_shaman_sheepstick/shadowshaman_stick_sheepstick.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "parent", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_attack1"}, }}, }}, {ID = "9885", style = "0", model = "models/items/shadowshaman/eyedancer_wrath_arms/eyedancer_wrath_arms.vmdl", particle_systems = {}}, {ID = "9886", style = "0", model = "models/items/shadowshaman/eyedancer_wrath_belt/eyedancer_wrath_belt.vmdl", particle_systems = {}}, {ID = "9887", style = "0", model = "models/items/shadowshaman/eyedancer_wrath_offhand/eyedancer_wrath_offhand.vmdl", particle_systems = {{system = "particles/econ/items/shadow_shaman/shadow_shaman_spiteful/shadowshaman_stick_spite_l.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_attack2"}, }}, }}, {ID = "8341", style = "1", model = "models/items/shadowshaman/eyedancer_wrath_head/eyedancer_wrath_head.vmdl", particle_systems = {{system = "particles/econ/items/shadow_shaman/shadow_shaman_spiteful/shadowshaman_stick_spite_head.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_head"}, }}, }}, }, }, { -- Summoner attack_projectile = "particles/units/heroes/hero_keeper_of_the_light/keeper_base_attack.vpcf", model = "models/heroes/keeper_of_the_light/keeper_of_the_light.vmdl", model_scale = 0.8, wearables = { {ID = "9198", style = "0", model = "models/items/keeper_of_the_light/ti7_immortal_mount/kotl_ti7_immortal_horse.vmdl", particle_systems = {{system = "particles/econ/items/keeper_of_the_light/kotl_ti7_illuminate/kotl_ti7_immortal_ambient.vpcf", attach_entity = "self", attach_type = PATTACH_ABSORIGIN_FOLLOW}, {system = "particles/econ/items/keeper_of_the_light/kotl_ti7_illuminate/kotl_ti7_immortal_footsteps.vpcf", attach_entity = "self", attach_type = PATTACH_ABSORIGIN_FOLLOW}}}, {ID = "9125", style = "0", model = "models/items/keeper_of_the_light/keeper_of_the_light_light_messenger_weapon/keeper_of_the_light_light_messenger_weapon.vmdl", particle_systems = {}}, {ID = "9127", style = "0", model = "models/items/keeper_of_the_light/keeper_of_the_light_light_messenger_head/keeper_of_the_light_light_messenger_head.vmdl", particle_systems = {}}, {ID = "9128", style = "0", model = "models/items/keeper_of_the_light/keeper_of_the_light_light_messenger_belt/keeper_of_the_light_light_messenger_belt.vmdl", particle_systems = {}}, } }, { -- Geomancer attack_projectile = "particles/units/heroes/hero_warlock/warlock_base_attack.vpcf", model = "models/heroes/warlock/warlock.vmdl", model_scale = 0.930000, wearables = { {ID = "8947", style = "0", model = "models/items/warlock/mystery_of_the_lost_ores_off_hand/mystery_of_the_lost_ores_off_hand.vmdl", particle_systems = {{system = "particles/econ/items/warlock/warlock_lost_ores/warlock_lost_ores_offhand_glow.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "parent", control_points = {{control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_hitloc"}, {control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_attack2"}, }}, }}, {ID = "8946", style = "0", model = "models/items/warlock/mystery_of_the_lost_ores_belt/mystery_of_the_lost_ores_belt.vmdl", particle_systems = {}}, {ID = "8944", style = "0", model = "models/items/warlock/mystery_of_the_lost_ores_shoulder/mystery_of_the_lost_ores_shoulder.vmdl", particle_systems = {}}, {ID = "8943", style = "0", model = "models/items/warlock/mystery_of_the_lost_ores_back/mystery_of_the_lost_ores_back.vmdl", particle_systems = {}}, {ID = "8942", style = "0", model = "models/items/warlock/mystery_of_the_lost_ores_arms/mystery_of_the_lost_ores_arms.vmdl", particle_systems = {}}, {ID = "8941", style = "0", model = "models/items/warlock/mystery_of_the_lost_ores_head/mystery_of_the_lost_ores_head.vmdl", particle_systems = {}}, {ID = "7886", style = "0", model = "models/items/warlock/ceaseless/ceaseless.vmdl", particle_systems = {{system = "particles/econ/items/warlock/warlock_staff_ceaseless_ambient/warlock_ceaseless_ambient_glow.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_core"}, }}, }}, } }, { -- Dragoon model = "models/heroes/phantom_lancer/phantom_lancer.vmdl", model_scale = 0.84, --[[ wearables = { {ID = "7557"}, {ID = "127"}, {ID = "7749"}, {ID = "7746"}, {ID = "7747"}, }, ]]-- wearables = { {ID = "7557", style = "0", model = "models/items/phantom_lancer/immortal_ti6/mesh/phantom_lancer_immortal_spear_mdoel.vmdl", particle_systems = {{system = "particles/econ/items/phantom_lancer/phantom_lancer_immortal_ti6/phantom_lancer_immortal_ti6.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_weapon"}, }}, }}, {ID = "127", style = "0", model = "models/heroes/phantom_lancer/phantom_lancer_head.vmdl", particle_systems = {}}, {ID = "7817", style = "0", model = "models/items/phantom_lancer/phantom_lancer_ti7_immortal_shoulder/phantom_lancer_ti7_immortal_shoulder.vmdl", particle_systems = {{system = "particles/econ/items/phantom_lancer/ti7_immortal_shoulder/pl_ti7_immortal_ambient.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "self"}}}, {ID = "7746", style = "0", model = "models/items/phantom_lancer/vagabond_arms/vagabond_arms.vmdl", particle_systems = {}}, {ID = "7747", style = "0", model = "models/items/phantom_lancer/vagabond_pants/vagabond_pants.vmdl", particle_systems = {}}, }, }, { -- Samurai model = "models/heroes/juggernaut/juggernaut_arcana.vmdl", model_scale = 0.85, --[[ wearables = { {ID = "4401"}, {ID = "4101"}, {ID = "8983"}, {ID = "8982"}, {ID = "9059", style = "1", particle_systems = {{system = "particles/econ/items/juggernaut/jugg_arcana/juggernaut_arcana_v2_ambient.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 0, attachment = "attach_hitloc"}}}, {system = "particles/econ/items/juggernaut/jugg_arcana/juggernaut_arcana_v2_body_ambient.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "parent"}}} }, ]]-- wearables = { {ID = "4401", style = "0", model = "models/items/juggernaut/thousand_faces_hakama/thousand_faces_hakama.vmdl", particle_systems = {}}, {ID = "4101", style = "0", model = "models/items/juggernaut/generic_wep_broadsword.vmdl", particle_systems = {{system = "particles/econ/items/juggernaut/jugg_sword_script/jugg_weapon_glow_variation_script.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "parent", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_sword"}, }}, }}, {ID = "8983", style = "0", model = "models/items/juggernaut/armor_for_the_favorite_back/armor_for_the_favorite_back.vmdl", particle_systems = {{system = "particles/econ/items/juggernaut/armor_of_the_favorite/juggernaut_favorite_shoulder_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "parent", control_points = {{control_point_index = 0, attach_type = PATTACH_ABSORIGIN_FOLLOW, }, }}, }}, {ID = "8982", style = "0", model = "models/items/juggernaut/armor_for_the_favorite_arms/armor_for_the_favorite_arms.vmdl", particle_systems = {}}, {ID = "9059", style = "1", model = "models/items/juggernaut/arcana/juggernaut_arcana_mask.vmdl", skin = "1", particle_systems = {{system = "particles/econ/items/juggernaut/jugg_arcana/juggernaut_arcana_v2_ambient.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_hitloc"}, }}, {system = "particles/econ/items/juggernaut/jugg_arcana/juggernaut_arcana_v2_body_ambient.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "parent", }, }}, }, model_material_group = 1, }, { -- Ninja model = "models/heroes/bounty_hunter/bounty_hunter.vmdl", model_scale = 0.84, --[[ wearables = { {ID = "8424"}, {ID = "8433"}, {ID = "8439"}, {ID = "8458"}, {ID = "8461"}, {ID = "8464"}, }, ]]-- wearables = { {ID = "8424", style = "0", model = "models/items/bounty_hunter/bounty_scout_offhand/bounty_scout_offhand.vmdl", particle_systems = {}}, {ID = "8433", style = "0", model = "models/items/bounty_hunter/bounty_scout_shoulder/bounty_scout_shoulder.vmdl", particle_systems = {}}, {ID = "8439", style = "0", model = "models/items/bounty_hunter/bounty_scout_back/bounty_scout_back.vmdl", particle_systems = {}}, {ID = "8458", style = "0", model = "models/items/bounty_hunter/bounty_scout_weapon/bounty_scout_weapon.vmdl", particle_systems = {}}, {ID = "8461", style = "0", model = "models/items/bounty_hunter/bounty_scout_armor/bounty_scout_armor.vmdl", particle_systems = {}}, {ID = "8464", style = "0", model = "models/items/bounty_hunter/bounty_scout_head/bounty_scout_head.vmdl", particle_systems = {}}, }, }, { -- Arithmetician attack_projectile = "particles/econ/items/rubick/rubick_staff_wandering/rubick_base_attack_whset.vpcf", model = "models/heroes/rubick/rubick.vmdl", model_scale = 0.7, --[[ wearables = { {ID = "7026"}, {ID = "7507"}, {ID = "8108"}, {ID = "8592"}, {ID = "8393"} }, ]]-- wearables = { {ID = "7026", style = "0", model = "models/items/rubick/harlequin_head_black/harlequin_head_black.vmdl", particle_systems = {}}, {ID = "7507", style = "0", model = "models/items/rubick/force_staff/force_staff.vmdl", particle_systems = {{system = "particles/econ/items/rubick/rubick_force_gold_ambient/rubick_force_ambient_gold.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_staff_ambient"}, }}, }}, {ID = "8108", style = "0", model = "models/items/rubick/golden_ornithomancer_mantle/golden_ornithomancer_mantle.vmdl", particle_systems = {{system = "particles/econ/items/rubick/rubick_ornithomancer_gold/rubick_ornithomancer_gold_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "parent", control_points = {{control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_thorax"}, {control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_hitloc"}, }}, }}, {ID = "8592", style = "0", model = "models/items/rubick/puppet_master_doll/puppet_master_doll.vmdl", particle_systems = {{system = "particles/econ/items/rubick/rubick_puppet_master/rubick_doll_puppet_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 2, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_doll_mouth"}, {control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_doll_eye_r"}, {control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_doll_eye_l"}, }}, }}, {ID = "8393", style = "0", model = "models/items/rubick/gemini_juggler_shoulder/gemini_juggler_shoulder.vmdl", particle_systems = {}}, }, }, { -- Mime attack_projectile = "particles/units/heroes/hero_bane/bane_projectile.vpcf", model = "models/heroes/bane/bane.vmdl", model_scale = 0.93, --[[ wearables = { {ID = "7941"}, {ID = "7942"}, {ID = "7943"}, {ID = "7692"} }, ]]-- wearables = { {ID = "7941", style = "0", model = "models/items/bane/heir_of_terror_bane_head/heir_of_terror_bane_head.vmdl", particle_systems = {}}, {ID = "7942", style = "0", model = "models/items/bane/heir_of_terror_bane_arms/heir_of_terror_bane_arms.vmdl", particle_systems = {}}, {ID = "7943", style = "0", model = "models/items/bane/heir_of_terror_bane_back/heir_of_terror_bane_back.vmdl", particle_systems = {}}, {ID = "7692", style = "0", model = "models/items/bane/slumbering_terror/slumbering_terror.vmdl", particle_systems = {{system = "particles/econ/items/bane/slumbering_terror/bane_slumbering_terror_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_ABSORIGIN_FOLLOW, }, {control_point_index = 2, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_elbow_l"}, {control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_elbow_r"}, }}, }}, }, }, { -- Dark Knight model = "models/heroes/abaddon/abaddon.vmdl", model_scale = 0.78, --[[ wearables = { {ID = "5561"}, {ID = "6408"}, {ID = "6409"}, {ID = "6410", particle_systems = {{system = "particles/units/heroes/hero_abaddon/abaddon_ambient.vpcf", attach_entity = "parent", attach_type = PATTACH_ABSORIGIN_FOLLOW}}}, {ID = "6411"}, },]]-- wearables = { {ID = "5561", style = "0", model = "models/items/abaddon/phantoms_reaper/phantoms_reaper.vmdl", particle_systems = {{system = "particles/units/heroes/hero_abaddon/abaddon_blade.vpcf", attach_type = PATTACH_CUSTOMORIGIN, attach_entity = "parent", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_attack1"}, }}, }}, {ID = "6408", style = "0", model = "models/items/abaddon/alliance_abba_back/alliance_abba_back.vmdl", particle_systems = {}}, {ID = "6409", style = "0", model = "models/items/abaddon/alliance_abba_head/alliance_abba_head.vmdl", particle_systems = {}}, {ID = "6410", style = "0", model = "models/items/abaddon/alliance_abba_mount/alliance_abba_mount.vmdl", particle_systems = {{system = "particles/units/heroes/hero_abaddon/abaddon_ambient.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "parent", }, }}, {ID = "6411", style = "0", model = "models/items/abaddon/alliance_abba_shoulder/alliance_abba_shoulder.vmdl", particle_systems = {}}, }, }, { -- Onion knight model = "models/heroes/kunkka/kunkka.vmdl", model_scale = 0.84, --[[ wearables = { {ID = "5670"}, {ID = "5321", particle_systems = {{system = "particles/econ/items/kunkka/kunkka_weapon_shadow/kunkka_weapon_tidebringer_shadow.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "parent", control_points = {{control_point_index = 2, attachment = "attach_sword"}, {control_point_index = 0, attachment = "attach_tidebringer"}, {control_point_index = 1, attachment = "attach_tidebringer_2"}}}}}, {ID = "5373"}, {ID = "9115", particle_systems = {{system = "particles/econ/items/kunkka/kunkka_immortal/kunkka_immortal_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 0, attachment = "attach_shark"}, {control_point_index = 3, attachment = "attach_shark_eye_l"}, {control_point_index = 6, attachment = "attach_shark_eye_r"}}}}}, {ID = "5669"}, {ID = "4500"}, {ID = "5385"}, {ID = "5661"} }, ]]-- wearables = { {ID = "5670", style = "0", model = "models/items/kunkka/singsingkunkkaset_head/singsingkunkkaset_head.vmdl", particle_systems = {}}, {ID = "5321", style = "0", model = "models/items/kunkka/kunkka_shadow_blade/kunkka_shadow_blade.vmdl", particle_systems = {{system = "particles/econ/items/kunkka/kunkka_weapon_shadow/kunkka_weapon_tidebringer_shadow.vpcf", attach_type = PATTACH_ABSORIGIN_FOLLOW, attach_entity = "parent", control_points = {{control_point_index = 2, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_sword"}, {control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_tidebringer"}, {control_point_index = 1, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_tidebringer_2"}, }}, }}, {ID = "5373", style = "0", model = "models/items/kunkka/singkunkkabackfinal/singkunkkabackfinal.vmdl", particle_systems = {}}, {ID = "9115", style = "0", model = "models/items/kunkka/kunkka_immortal/kunkka_shoulder_immortal.vmdl", skin = "0", particle_systems = {{system = "particles/econ/items/kunkka/kunkka_immortal/kunkka_immortal_ambient.vpcf", attach_type = PATTACH_CUSTOMORIGIN_FOLLOW, attach_entity = "self", control_points = {{control_point_index = 0, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_shark"}, {control_point_index = 3, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_shark_eye_l"}, {control_point_index = 6, attach_type = PATTACH_POINT_FOLLOW, attachment = "attach_shark_eye_r"}, }}, }}, {ID = "5669", style = "0", model = "models/items/kunkka/singsingkunkkaset_gloves/singsingkunkkaset_gloves.vmdl", particle_systems = {}}, {ID = "4500", style = "0", model = "models/items/kunkka/singkunkabelt_final/singkunkabelt_final.vmdl", particle_systems = {}}, {ID = "5385", style = "0", model = "models/items/kunkka/singsingkunkkaset__cannon/singsingkunkkaset__cannon.vmdl", particle_systems = {}}, {ID = "5661", style = "0", model = "models/items/kunkka/singsingkunkkaset_boots/singsingkunkkaset_boots.vmdl", particle_systems = {}}, }, }, } CRamzaJob.tJobStats = { { --Squire primary_attribute = DOTA_ATTRIBUTE_STRENGTH, base_str = 19, base_agi = 19, base_int = 19, gain_str = 2.5, gain_agi = 2.5, gain_int = 2.5, armor = 1, attack_range = 150, attack_point = 0.39, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, move_speed = 300, }, { --Chemist primary_attribute = DOTA_ATTRIBUTE_INTELLECT, base_str = 15, base_agi = 17, base_int = 23, gain_str = 2.2, gain_agi = 1.7, gain_int = 2.7, armor = 0, attack_range = 600, attack_point = 0.17, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, move_speed = 280, }, { --Knight primary_attribute = DOTA_ATTRIBUTE_STRENGTH, base_str = 27, base_agi = 16, base_int = 12, gain_str = 3.4, gain_agi = 2.1, gain_int = 1.1, armor = 0, attack_range = 150, attack_point = 0.5, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, move_speed = 300, }, { --Archer primary_attribute = DOTA_ATTRIBUTE_AGILITY, base_str = 11, base_agi = 30, base_int = 14, gain_str = 1.5, gain_agi = 3.6, gain_int = 1.5, armor = 0, attack_range = 625, attack_point = 0.72, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 305, }, { -- White Mage primary_attribute = DOTA_ATTRIBUTE_INTELLECT, base_str = 11, base_agi = 11, base_int = 33, gain_str = 1.6, gain_agi = 1.3, gain_int = 3.7, armor = 1, attack_range = 550, attack_point = 0.59, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 290, }, { -- Black Mage primary_attribute = DOTA_ATTRIBUTE_INTELLECT, base_str = 13, base_agi = 11, base_int = 31, gain_str = 2.3, gain_agi = 1.1, gain_int = 3.2, armor = 1, attack_range = 500, attack_point = 0.59, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 300, }, { --Monk primary_attribute = DOTA_ATTRIBUTE_STRENGTH, base_str = 23, base_agi = 23, base_int = 9, gain_str = 2.9, gain_agi = 2.6, gain_int = 1.1, armor = 0, attack_range = 150, attack_point = 0.43, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, move_speed = 300, }, { --Thief primary_attribute = DOTA_ATTRIBUTE_AGILITY, base_str = 10, base_agi = 33, base_int = 12, gain_str = 1.6, gain_agi = 3.6, gain_int = 1.4, armor = 1, attack_range = 150, attack_point = 0.3, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, move_speed = 305, }, { --Mystic primary_attribute = DOTA_ATTRIBUTE_INTELLECT, base_str = 15, base_agi = 13, base_int = 27, gain_str = 1.9, gain_agi = 1.3, gain_int = 3.4, armor = 1, attack_range = 575, attack_point = 0.3, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 285, }, { --Time Mage primary_attribute = DOTA_ATTRIBUTE_INTELLECT, base_str = 12, base_agi = 19, base_int = 24, gain_str = 1.4, gain_agi = 2.3, gain_int = 2.9, armor = 1, attack_range = 500, attack_point = 0.5, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 295, }, { --Orator primary_attribute = DOTA_ATTRIBUTE_INTELLECT, base_str = 17, base_agi = 18, base_int = 20, gain_str = 2.1, gain_agi = 1.7, gain_int = 2.8, armor = 1, attack_range = 400, attack_point = 0.2, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 305, }, { --Summoner primary_attribute = DOTA_ATTRIBUTE_INTELLECT, base_str = 13, base_agi = 17, base_int = 25, gain_str = 1.6, gain_agi = 1.7, gain_int = 3.3, armor = 0, attack_range = 600, attack_point = 0.55, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 300, }, { --Geomancer primary_attribute = DOTA_ATTRIBUTE_STRENGTH, base_str = 24, base_agi = 13, base_int = 18, gain_str = 2.8, gain_agi = 1.7, gain_int = 1.8, armor = 1, attack_range = 500, attack_point = 0.55, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 310, }, { --Dragoon primary_attribute = DOTA_ATTRIBUTE_AGILITY, base_str = 22, base_agi = 22, base_int = 11, gain_str = 2.8, gain_agi = 2.5, gain_int = 1.0, armor = 0, attack_range = 150, attack_point = 0.3, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, move_speed = 315, }, { --Samurai primary_attribute = DOTA_ATTRIBUTE_STRENGTH, base_str = 23, base_agi = 18, base_int = 14, gain_str = 3.3, gain_agi = 2.0, gain_int = 1.0, armor = 0, attack_range = 150, attack_point = 0.33, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, move_speed = 315, }, { --Ninja primary_attribute = DOTA_ATTRIBUTE_AGILITY, base_str = 15, base_agi = 28, base_int = 12, gain_str = 1.7, gain_agi = 3.6, gain_int = 1.0, armor = 0, attack_range = 150, attack_point = 0.3, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, move_speed = 320, }, { -- Arithmetician primary_attribute = DOTA_ATTRIBUTE_INTELLECT, base_str = 8, base_agi = 7, base_int = 40, gain_str = 1.3, gain_agi = 1, gain_int = 4, armor = 0, attack_range = 700, attack_point = 0.4, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 295, }, { --Mime primary_attribute = DOTA_ATTRIBUTE_INTELLECT, base_str = 18, base_agi = 18, base_int = 18, gain_str = 2.4, gain_agi = 2.4, gain_int = 2.4, armor = 1, attack_range = 600, attack_point = 0.3, attack_cap = DOTA_UNIT_CAP_RANGED_ATTACK, move_speed = 300, }, { --Dark Knight primary_attribute = DOTA_ATTRIBUTE_STRENGTH, base_str = 30, base_agi = 30, base_int = 30, gain_str = 3.3, gain_agi = 3.3, gain_int = 3.3, armor = 0, attack_range = 150, attack_point = 0.433, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, move_speed = 300, }, { --Onion knight primary_attribute = DOTA_ATTRIBUTE_AGILITY, base_str = 40, base_agi = 40, base_int = 40, gain_str = 5.3, gain_agi = 5.3, gain_int = 5.3, armor = 1, attack_range = 150, attack_cap = DOTA_UNIT_CAP_MELEE_ATTACK, attack_point = 0.433, move_speed = 345, } } CRamzaJob.tJobCommands = { { -- Squire: Fundaments Lvl 1 - Stone, Rush|nLvl 2 - Focus|nLvl 3 - Counter Tackle|nLvl 4 - Tailwind|nLvl 5 - Defend|nLvl 6 - Chant|nLvl 7 - Move +1|nLvl 8 - Shout|nMastered - |c00ff8000Ultima {"ramza_squire_fundamental_stone", "ramza_squire_fundamental_rush"}, {"ramza_squire_fundamental_focus"}, {}, {"ramza_squire_fundamental_tailwind"}, {}, {"ramza_squire_fundamental_chant"}, {}, {"ramza_squire_fundamental_shout"}, {"ramza_squire_fundamental_ultima"} }, { -- Chemist: Items|r|nLvl 1 - Potion, Ether|nLvl 2 - Hi-Potion|nLvl 3 - Auto-Potion|nLvl 4 - Hi-Ether|nLvl 5 - Treasure Hunter|nLvl 6 - Remedy|nLvl 7 - Throw Items|nLvl 8 - Phoenix Down|nMastered - |c00ff8000Elixir {"ramza_chemist_items_potion", "ramza_chemist_items_ether"}, {"ramza_chemist_items_hipotion"}, {}, {"ramza_chemist_items_hiether"}, {}, {"ramza_chemist_items_remedy"}, {}, {"ramza_chemist_items_phoenix_down"}, {"ramza_chemist_items_elixir"} }, { -- Knight: Arts of War|r|nLvl 1 - Rend Power, Rend Magick|nLvl 2 - Rend Speed|nLvl 3 - Parry|nLvl 4 - Rend MP|nLvl 5 - Heavy Armor|nLvl 6 - Rend Armor|nLvl 7 - Knight Sword|nLvl 8 - Rend Weapon|nMastered - |c00ff8000Rend Helm {"ramza_knight_aow_rend_power", "ramza_knight_aow_rend_magick"}, {"ramza_knight_aow_rend_speed"}, {}, {"ramza_knight_aow_rend_mp"}, {}, {"ramza_knight_aow_rend_armor"}, {}, {"ramza_knight_aow_rend_weapon"}, {"ramza_knight_aow_rend_helm"} }, { -- Archer: Aim|r|nLvl 1 - Aim +2|nLvl 2 - Aim +4|nLvl 3 - Adrenaline Rush|nLvl 4 - Aim +6|nLvl 5 - Archer's Bane|nLvl 6 - Aim +7|nLvl 7 - Concentration|nLvl 8 - Aim +10|nMastered - |c00ff8000Aim +20 {"ramza_archer_aim_2"}, {"ramza_archer_aim_4"}, {}, {"ramza_archer_aim_6"}, {}, {"ramza_archer_aim_7"}, {}, {"ramza_archer_aim_10"}, {"ramza_archer_aim_20"} }, { -- White Mage: White Magicks|r|nLvl 1 - Cure, Regen|nLvl 2 - Protect, Shell|nLvl 3 - Regenerate|nLvl 4 - Cura|nLvl 5 - Arcane Defense|nLvl 6 - Wall|nLvl 7 - Reraise|nLvl 8 - Curaga|nMastered - |c00ff8000Holy {"ramza_white_mage_white_magicks_cure", "ramza_white_mage_white_magicks_regen"}, {"ramza_white_mage_white_magicks_protect", "ramza_white_mage_white_magicks_shell"}, {}, {"ramza_white_mage_white_magicks_cura"}, {}, {"ramza_white_mage_white_magicks_wall"}, {}, {"ramza_white_mage_white_magicks_curaga"}, {"ramza_white_mage_white_magicks_holy"} }, { -- Black Mage: Black Magicks|r|nLvl 1 - Fire, Blizzard|nLvl 2 - Thunder|nLvl 3 - Arcane Strength|nLvl 4 - Poison|nLvl 5 - Magick Counter|nLvl 6 - Toad|nLvl 7 - Death|nLvl 8 - Firaga, Blizzaga, Thundaga|nMastered - |c00ff8000Flare {"ramza_black_mage_black_magicks_fire", "ramza_black_mage_black_magicks_blizzard"}, {"ramza_black_mage_black_magicks_thunder"}, {}, {"ramza_black_mage_black_magicks_poison"}, {}, {"ramza_black_mage_black_magicks_toad"}, {}, {"ramza_black_mage_black_magicks_firaga", "ramza_black_mage_black_magicks_blizzaga", "ramza_black_mage_black_magicks_thundaga"}, {"ramza_black_mage_black_magicks_flare"}, }, { -- Monk: Martial Arts|r|nLvl 1 - Pummel|nLvl 2 - Purification|nLvl 3 - Brawler|nLvl 4 - Aurablast|nLvl 5 - Lifefont|nLvl 6 - Chakra|nLvl 7 - Critical: Recover HP|nLvl 8 - Shockwave|nMastered - |c00ff8000Doom Fist {"ramza_monk_martial_arts_pummel"}, {"ramza_monk_martial_arts_purification"}, {}, {"ramza_monk_martial_arts_aurablast"}, {}, {"ramza_monk_martial_arts_chakra"}, {}, {"ramza_monk_martial_arts_shockwave"}, {"ramza_monk_martial_arts_doom_fist"}, }, { -- Thief: Steal|r|nLvl 1 - Steal Gil|nLvl 2 - Steal Heart|nLvl 3 - Move +2|nLvl 4 - Steal EXP|nLvl 5 - Vigilance|nLvl 6 - Steal Armor|nLvl 7 - Gil Snapper|nLvl 8 - Steal Weapon|nMastered - |c00ff8000Steal Accessory {"ramza_thief_steal_gil"}, {"ramza_thief_steal_heart"}, {}, {"ramza_thief_steal_exp"}, {}, {"ramza_thief_steal_armor"}, {}, {"ramza_thief_steal_weapon"}, {"ramza_thief_steal_accessory"}, }, { -- Mystic: Mystic Arts|r|nLvl 1 - Umbra|nLvl 2 - Empowerment|nLvl 3 - Defense Boost|nLvl 4 - Disbelief|nLvl 5 - Manafont|nLvl 6 - Hesitation|nLvl 7 - Absorb MP|nLvl 8 - Quiescence|nMastered - |c00ff8000Invigoration {"ramza_mystic_mystic_arts_umbra"}, {"ramza_mystic_mystic_arts_empowerment"}, {}, {"ramza_mystic_mystic_arts_disbelief"}, {}, {"ramza_mystic_mystic_arts_hesitation"}, {}, {"ramza_mystic_mystic_arts_quiescence"}, {"ramza_mystic_mystic_arts_invigoration"}, }, { -- Time Mage: Time Magicks|r|nLvl 1 - Haste, Slow|nLvl 2 - Immobilize|nLvl 3 - Mana Shield|nLvl 4 - Gravity|nLvl 5 - Teleport|nLvl 6 - Quick|nLvl 7 - Swiftness|nLvl 8 - Stop|nMastered - |c00ff8000Meteor {"ramza_time_mage_time_magicks_haste", "ramza_time_mage_time_magicks_slow"}, {"ramza_time_mage_time_magicks_immobilize"}, {}, {"ramza_time_mage_time_magicks_gravity"}, {}, {"ramza_time_mage_time_magicks_quick"}, {}, {"ramza_time_mage_time_magicks_stop"}, {"ramza_time_mage_time_magicks_meteor"}, }, { -- Orator: Speechcraft|r|nLvl 1 - Praise, Preach|nLvl 2 - Mimic Darlavon|nLvl 3 - Enlighten|nLvl 4 - Entice|nLvl 5 - Intimidate|nLvl 6 - Beg|nLvl 7 - Beast Tongue|nLvl 8 - Stall|nMastered - |c00ff8000Condemn {"ramza_orator_speechcraft_praise", "ramza_orator_speechcraft_preach"}, {"ramza_orator_speechcraft_mimic_darlavon"}, {}, {"ramza_orator_speechcraft_entice"}, {}, {"ramza_orator_speechcraft_beg"}, {}, {"ramza_orator_speechcraft_stall"}, {"ramza_orator_speechcraft_condemn"}, }, { -- Summoner: Summon|r|nLvl 1 - Moogle|nLvl 2 - Shiva, Ifrit|nLvl 3 - Critical: Recover MP|nLvl 4 - Ramuh|nLvl 5 - Lich|nLvl 6 - Golem|nLvl 7 - Odin|nLvl 8 - Bahamut|nMastered - |c00ff8000Zodiark {"ramza_summoner_summon_moogle"}, {"ramza_summoner_summon_shiva", "ramza_summoner_summon_ifrit"}, {}, {"ramza_summoner_summon_ramuh"}, {}, {"ramza_summoner_summon_golem"}, {}, {"ramza_summoner_summon_bahamut"}, {"ramza_summoner_summon_zodiark"}, }, { -- Geomancer: Geomancy|r|nLvl 1 - Sinkhole|nLvl 2 - Torrent|nLvl 3 - Contortion|nLvl 4 - Will-o'-the-Wisp|nLvl 5 - Attack Boost|nLvl 6 - Sandstorm|nLvl 7 - Wind Blast|nLvl 8 - Tanglevine|nMastered - |c00ff8000Magma Surge {"ramza_geomancer_geomancy_sinkhole"}, {"ramza_geomancer_geomancy_torrent"}, {}, {"ramza_geomancer_geomancy_willothewisp"}, {}, {"ramza_geomancer_geomancy_sand_storm"}, {}, {"ramza_geomancer_geomancy_tanglevine"}, {"ramza_geomancer_geomancy_magma_surge"}, }, { -- Dragoon: Jump|r|nLvl 1 - Jump|nLvl 2 - Jump 2|nLvl 3 - Polearm|nLvl 4 - Jump 3|nLvl 5 - Ignore Elevation|nLvl 6 - Jump 4|nLvl 7 - Dragonheart|nLvl 8 - Jump 5|nMastered - |c00ff8000Jump 8 {"ramza_dragoon_jump1"}, {"ramza_dragoon_jump2"}, {}, {"ramza_dragoon_jump3"}, {}, {"ramza_dragoon_jump4"}, {}, {"ramza_dragoon_jump5"}, {"ramza_dragoon_jump8"}, }, { -- Samurai: Iaido|r|nLvl 1 - Ashura|nLvl 2 - Osafune|nLvl 3 - Doublehand|nLvl 4 - Murasame|nLvl 5 - Shirahadori|nLvl 6 - Kiku-ichimonji|nLvl 7 - Bonecrusher|nLvl 8 - Masamune|nMastered - |c00ff8000Chirijiraden {"ramza_samurai_iaido_ashura"}, {"ramza_samurai_iaido_osafune"}, {}, {"ramza_samurai_iaido_murasame"}, {}, {"ramza_samurai_iaido_kikuichimonji"}, {}, {"ramza_samurai_iaido_masamune"}, {"ramza_samurai_iaido_chirijiraden"}, }, { -- Ninja: Throw|r|nLvl 1 - Shuriken|nLvl 2 - Axe|nLvl 3 - Reflexes|nLvl 4 - Book|nLvl 5 - Vanish|nLvl 6 - Polearm|nLvl 7 - Dual Wield|nLvl 8 - Bomb|nMastered - |c00ff8000Ninja Blade {"ramza_ninja_throw_shuriken"}, {"ramza_ninja_throw_axe"}, {}, {"ramza_ninja_throw_book"}, {}, {"ramza_ninja_throw_polearm"}, {}, {"ramza_ninja_throw_bomb"}, {"ramza_ninja_throw_ninja_blade"}, }, { -- arithmetician: Arithmeticks|r|nLvl 1 - CT|nLvl 2 - Multiple of 5|nLvl 3 - Accrue EXP|nLvl 4 - Level|nLvl 5 - Soulbind|nLvl 6 - Multiple of 4|nLvl 7 - EXP Boost|nLvl 8 - Multiple of 3|nMastered - |c00ff8000EXP {"ramza_arithmetician_arithmeticks_CT"}, {"ramza_arithmetician_arithmeticks_multiple_of_5"}, {}, {"ramza_arithmetician_arithmeticks_level"}, {}, {"ramza_arithmetician_arithmeticks_multiple_of_4"}, {}, {"ramza_arithmetician_arithmeticks_multiple_of_3"}, {"ramza_arithmetician_arithmeticks_exp"}, }, { -- Mime: Mimic|r|nLvl 1 - 100% Mana Cost|nLvl 2 - 90% Mana Cost|nLvl 3 - 80% Mana Cost|nLvl 4 - 70% Mana Cost|nLvl 5 - 60% Mana Cost|nLvl 6 - 50% Mana Cost|nLvl 7 - 40% Mana Cost|nLvl 8 - 20% Mana Cost|nMastered - |c00ff80000% Mana Cost {"ramza_mime_mimic_100_mana_cost"}, {"ramza_mime_mimic_90_mana_cost"}, {"ramza_mime_mimic_80_mana_cost"}, {"ramza_mime_mimic_70_mana_cost"}, {"ramza_mime_mimic_60_mana_cost"}, {"ramza_mime_mimic_50_mana_cost"}, {"ramza_mime_mimic_40_mana_cost"}, {"ramza_mime_mimic_20_mana_cost"}, {"ramza_mime_mimic_0_mana_cost"}, }, { -- Dark Knight: Darkness|r|nLvl 1 - Sanguine Sword|nLvl 2 - Infernal Strike|nLvl 3 - HP Boost|nLvl 4 - Crushing Blow|nLvl 5 - Vehemence|nLvl 6 - Abyssal Blade|nLvl 7 - Move +3|nLvl 8 - Unholy Sacrifice|nMastered - |c00ff8000Shadowblade {"ramza_dark_knight_darkness_sanguine_sword"}, {"ramza_dark_knight_darkness_infernal_strike"}, {}, {"ramza_dark_knight_darkness_crushing_blow"}, {}, {"ramza_dark_knight_darkness_abyssal_blade"}, {}, {"ramza_dark_knight_darkness_unholy_sacrifice"}, {"ramza_dark_knight_darkness_shadowblade"}, }, { -- Onion Knight: None|r|nLvl 1 - +5 Stats|nLvl 2 - +10 Stats|nLvl 3 - +15 Stats|nLvl 4 - +20 Stats|nLvl 5 - +25 Stats|nLvl 6 - +30 Stats|nLvl 7 - +35 Stats|nLvl 8 - +50 Stats|nMastered - |c00ff8000+75 Stats {"ramza_onion_knight_stat5"}, {"ramza_onion_knight_stat10"}, {"ramza_onion_knight_stat15"}, {"ramza_onion_knight_stat20"}, {"ramza_onion_knight_stat25"}, {"ramza_onion_knight_stat30"}, {"ramza_onion_knight_stat35"}, {"ramza_onion_knight_stat50"}, {"ramza_onion_knight_stat75"}, } } CRamzaJob.tOtherAbilities = { { -- Squire {}, {}, {"ramza_squire_counter_tackle"}, {}, {"ramza_squire_defend"}, {}, {"ramza_squire_move1"}, {}, {} }, { -- Chemist {}, {}, {"ramza_chemist_autopotion"}, {}, {"ramza_chemist_treasure_hunter"}, {}, {"ramza_chemist_throw_items"}, {}, {} }, { -- Knight {}, {}, {"ramza_knight_parry"}, {}, {"ramza_knight_heavy_armor"}, {}, {"ramza_knight_knight_sword"}, {}, {} }, { -- Archer {}, {}, {"ramza_archer_adrenaline_rush"}, {}, {"ramza_archer_archers_bane"}, {}, {"ramza_archer_concentration"}, {}, {} }, { -- White Mage {}, {}, {"ramza_white_mage_regenerate"}, {}, {"ramza_white_mage_arcane_defense"}, {}, {"ramza_white_mage_reraise"}, {}, {} }, { -- Black Mage: {}, {}, {"ramza_black_mage_magick_counter"}, {}, {"ramza_black_mage_death"}, {}, {"ramza_black_mage_arcane_strength"}, {}, {} }, { -- Monk {}, {}, {"ramza_monk_brawler"}, {}, {"ramza_monk_lifefont"}, {}, {"ramza_monk_critical_recover_hp"}, {}, {} }, { -- Thief {}, {}, {"ramza_thief_move2"}, {}, {"ramza_thief_vigilance"}, {}, {"ramza_thief_gil_snapper"}, {}, {} }, { -- Mystic {}, {}, {"ramza_mystic_defense_boost"}, {}, {"ramza_mystic_manafont"}, {}, {"ramza_mystic_absorb_mp"}, {}, {} }, { -- Time Mage {}, {}, {"ramza_time_mage_mana_shield"}, {}, {"ramza_time_mage_teleport"}, {}, {"ramza_time_mage_swiftness"}, {}, {} }, { -- Orator {}, {}, {"ramza_orator_enlighten"}, {}, {"ramza_orator_intimidate"}, {}, {"ramza_orator_beast_tongue"}, {}, {} }, { -- Summoner {}, {}, {"ramza_summoner_critical_recover_mp"}, {}, {"ramza_summoner_lich"}, {}, {"ramza_summoner_odin"}, {}, {} }, { -- Geomancer {}, {}, {"ramza_geomancer_contortion"}, {}, {"ramza_geomancer_attack_boost"}, {}, {"ramza_geomancer_wind_blast"}, {}, {} }, { -- Dragoon {}, {}, {"ramza_dragoon_polearm"}, {}, {"ramza_dragoon_ignore_elevation"}, {}, {"ramza_dragoon_dragonheart"}, {}, {} }, { -- Samurai {}, {}, {"ramza_samurai_doublehand"}, {}, {"ramza_samurai_shirahadori"}, {}, {"ramza_samurai_bonecrusher"}, {}, {} }, { -- Ninja {}, {}, {"ramza_ninja_reflexes"}, {}, {"ramza_ninja_vanish"}, {}, {"ramza_ninja_dual_wield"}, {}, {} }, { -- arithmetician {}, {}, {"ramza_arithmetician_accrue_exp"}, {}, {"ramza_arithmetician_soulbind"}, {}, {"ramza_arithmetician_exp_boost"}, {}, {} }, { -- Mime {}, {}, {}, {}, {}, {}, {}, {}, {} }, { -- Dark Knight {}, {}, {"ramza_dark_knight_hp_boost"}, {}, {"ramza_dark_knight_vehemence"}, {}, {"ramza_dark_knight_move3"}, {}, {} }, { -- Onion Knight {}, {}, {}, {}, {}, {}, {}, {}, {} } } CRamzaJob.tOtherAbilityCastable = { ramza_chemist_treasure_hunter = true, ramza_white_mage_reraise = true, ramza_black_mage_death = true, ramza_time_mage_teleport = true, ramza_orator_enlighten = true, ramza_orator_intimidate = true, ramza_summoner_lich = true, ramza_summoner_odin = true, ramza_geomancer_contortion = true, ramza_geomancer_wind_blast = true } CRamzaJob.tOtherAbilityHasToggleModifiers = { ramza_squire_defend = true, ramza_chemist_autopotion = true, ramza_time_mage_mana_shield = true, ramza_ninja_vanish = true, ramza_dark_knight_vehemence = true }
function love.conf(t) t.window.identity = "." t.window.version = "0.7.0" t.window.width = 640 t.window.height = 480 t.window.x = -1 t.window.y = -1 t.window.window = true t.window.vsync = true t.window.resizable = false t.window.title = "No title in conf.lua" t.window.stats = true end
local steelPlate if mods["IndustrialRevolution"] then steelPlate = "iron-beam" else steelPlate = "steel-plate" end data:extend({ { type = "recipe", name = "logicarts-paint", category = "crafting-with-fluid", subgroup = "logicarts-subgroup", enabled = false, icon = "__logicarts2__/graphics/paint-icon.png", icon_size = 128, ingredients = { { type = "item", name = "stone", amount = 1 }, { type = "item", name = "coal", amount = 1 }, { type = "fluid", name = "water", amount = 11 }, }, results = { { type = "item", name = "logicarts-paint", amount = 1 }, }, hidden = false, energy_required = 5.0, order = "logicarts-a", }, { type = "recipe", name = "logicarts-car", category = "crafting", subgroup = "logicarts-subgroup", enabled = false, icon = "__logicarts2__/graphics/cart-ico.png", icon_size = 32, ingredients = { { type = "item", name = "engine-unit", amount = 2 }, { type = "item", name = steelPlate, amount = 4 }, { type = "item", name = "electronic-circuit", amount = 4 }, }, results = { { type = "item", name = "logicarts-car", amount = 1 }, }, hidden = false, energy_required = 5.0, order = "logicarts-b", }, { type = "recipe", name = "logicarts-car-electric", category = "crafting", subgroup = "logicarts-subgroup", enabled = false, icon = "__logicarts2__/graphics/e-cart-ico.png", icon_size = 32, ingredients = { { type = "item", name = "electric-engine-unit", amount = 2 }, { type = "item", name = steelPlate, amount = 4 }, { type = "item", name = "advanced-circuit", amount = 4 }, }, results = { { type = "item", name = "logicarts-car-electric", amount = 1 }, }, hidden = false, energy_required = 5.0, order = "logicarts-c", }, { type = "recipe", name = "logicarts-sticker", category = "crafting", subgroup = "logicarts-subgroup", enabled = false, icon = "__logicarts2__/graphics/sticker-icon.png", icon_size = 32, ingredients = { { type = "item", name = "logicarts-paint", amount = 1 }, { type = "item", name = "constant-combinator", amount = 1 }, }, results = { { type = "item", name = "logicarts-sticker", amount = 1 }, }, hidden = false, energy_required = 5.0, order = "logicarts-d", }, { type = "recipe", name = "logicarts-stop", category = "crafting", subgroup = "logicarts-subgroup-path", enabled = false, icon = "__logicarts2__/graphics/stop-icon.png", icon_size = 128, ingredients = { { type = "item", name = "copper-ore", amount = 1 }, { type = "item", name = "logicarts-paint", amount = 1 }, }, results = { { type = "item", name = "logicarts-stop", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-a", }, { type = "recipe", name = "logicarts-path", category = "crafting", subgroup = "logicarts-subgroup-path", enabled = false, icon = "__logicarts2__/graphics/path-icon.png", icon_size = 128, ingredients = { { type = "item", name = "copper-ore", amount = 1 }, { type = "item", name = "logicarts-paint", amount = 1 }, }, results = { { type = "item", name = "logicarts-path", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-b", }, { type = "recipe", name = "logicarts-continue", category = "crafting", subgroup = "logicarts-subgroup-path", enabled = false, icon = "__logicarts2__/graphics/continue-icon.png", icon_size = 128, ingredients = { { type = "item", name = "copper-ore", amount = 1 }, { type = "item", name = "logicarts-paint", amount = 1 }, }, results = { { type = "item", name = "logicarts-continue", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-c", }, { type = "recipe", name = "logicarts-turn", category = "crafting", subgroup = "logicarts-subgroup-path", enabled = false, icon = "__logicarts2__/graphics/turn-icon.png", icon_size = 128, ingredients = { { type = "item", name = "iron-ore", amount = 1 }, { type = "item", name = "logicarts-paint", amount = 1 }, }, results = { { type = "item", name = "logicarts-turn", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-d", }, { type = "recipe", name = "logicarts-turn-blocked", category = "crafting", subgroup = "logicarts-subgroup-path", enabled = false, icon = "__logicarts2__/graphics/turn-blocked-icon.png", icon_size = 128, ingredients = { { type = "item", name = "iron-ore", amount = 1 }, { type = "item", name = "logicarts-paint", amount = 1 }, }, results = { { type = "item", name = "logicarts-turn-blocked", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-e", }, { type = "recipe", name = "logicarts-turn-fuel", category = "crafting", subgroup = "logicarts-subgroup-path", enabled = false, icon = "__logicarts2__/graphics/turn-fuel-icon.png", icon_size = 128, ingredients = { { type = "item", name = "iron-ore", amount = 1 }, { type = "item", name = "logicarts-paint", amount = 1 }, }, results = { { type = "item", name = "logicarts-turn-fuel", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-f", }, { type = "recipe", name = "logicarts-yield", category = "crafting", subgroup = "logicarts-subgroup-path", enabled = false, icon = "__logicarts2__/graphics/yield-icon.png", icon_size = 128, ingredients = { { type = "item", name = "iron-ore", amount = 1 }, { type = "item", name = "logicarts-paint", amount = 1 }, }, results = { { type = "item", name = "logicarts-yield", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-g", }, { type = "recipe", name = "logicarts-stop-load", category = "crafting", subgroup = "logicarts-subgroup-stop", enabled = false, icon = "__logicarts2__/graphics/stop-load-icon.png", icon_size = 128, ingredients = { { type = "item", name = "iron-plate", amount = 1 }, { type = "item", name = "logicarts-stop", amount = 1 }, }, results = { { type = "item", name = "logicarts-stop-load", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-a-b", }, { type = "recipe", name = "logicarts-stop-unload", category = "crafting", subgroup = "logicarts-subgroup-stop", enabled = false, icon = "__logicarts2__/graphics/stop-unload-icon.png", icon_size = 128, ingredients = { { type = "item", name = "copper-plate", amount = 1 }, { type = "item", name = "logicarts-stop", amount = 1 }, }, results = { { type = "item", name = "logicarts-stop-unload", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-a-c", }, { type = "recipe", name = "logicarts-stop-supply", category = "crafting", subgroup = "logicarts-subgroup-stop", enabled = false, icon = "__logicarts2__/graphics/stop-supply-icon.png", icon_size = 128, ingredients = { { type = "item", name = "iron-plate", amount = 1 }, { type = "item", name = "logicarts-stop", amount = 1 }, }, results = { { type = "item", name = "logicarts-stop-supply", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-a-d", }, { type = "recipe", name = "logicarts-stop-dump", category = "crafting", subgroup = "logicarts-subgroup-stop", enabled = false, icon = "__logicarts2__/graphics/stop-dump-icon.png", icon_size = 128, ingredients = { { type = "item", name = "copper-plate", amount = 1 }, { type = "item", name = "logicarts-stop", amount = 1 }, }, results = { { type = "item", name = "logicarts-stop-dump", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-a-d", }, { type = "recipe", name = "logicarts-stop-accept", category = "crafting", subgroup = "logicarts-subgroup-stop", enabled = false, icon = "__logicarts2__/graphics/stop-accept-icon.png", icon_size = 128, ingredients = { { type = "item", name = "iron-plate", amount = 1 }, { type = "item", name = "logicarts-stop", amount = 1 }, }, results = { { type = "item", name = "logicarts-stop-accept", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-a-e", }, { type = "recipe", name = "logicarts-stop-deploy", category = "crafting", subgroup = "logicarts-subgroup-stop", enabled = false, icon = "__logicarts2__/graphics/stop-deploy-icon.png", icon_size = 128, ingredients = { { type = "item", name = steelPlate, amount = 1 }, { type = "item", name = "logicarts-stop", amount = 1 }, }, results = { { type = "item", name = "logicarts-stop-deploy", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-a-f", }, { type = "recipe", name = "logicarts-stop-retire", category = "crafting", subgroup = "logicarts-subgroup-stop", enabled = false, icon = "__logicarts2__/graphics/stop-retire-icon.png", icon_size = 128, ingredients = { { type = "item", name = steelPlate, amount = 1 }, { type = "item", name = "logicarts-stop", amount = 1 }, }, results = { { type = "item", name = "logicarts-stop-retire", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-a-g", }, { type = "recipe", name = "logicarts-path-dual-straight", category = "crafting", subgroup = "logicarts-subgroup-dual", enabled = false, icon = "__logicarts2__/graphics/path-dual-straight-icon.png", icon_size = 128, ingredients = { { type = "item", name = "logicarts-path", amount = 2 }, }, results = { { type = "item", name = "logicarts-path-dual-straight", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-a", }, { type = "recipe", name = "logicarts-path-dual-turn", category = "crafting", subgroup = "logicarts-subgroup-dual", enabled = false, icon = "__logicarts2__/graphics/path-dual-turn-icon.png", icon_size = 128, ingredients = { { type = "item", name = "logicarts-path", amount = 2 }, }, results = { { type = "item", name = "logicarts-path-dual-turn", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-b", }, { type = "recipe", name = "logicarts-continue-dual-straight", category = "crafting", subgroup = "logicarts-subgroup-dual", enabled = false, icon = "__logicarts2__/graphics/continue-dual-straight-icon.png", icon_size = 128, ingredients = { { type = "item", name = "logicarts-continue", amount = 2 }, }, results = { { type = "item", name = "logicarts-continue-dual-straight", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-c", }, { type = "recipe", name = "logicarts-continue-dual-turn", category = "crafting", subgroup = "logicarts-subgroup-dual", enabled = false, icon = "__logicarts2__/graphics/continue-dual-turn-icon.png", icon_size = 128, ingredients = { { type = "item", name = "logicarts-continue", amount = 2 }, }, results = { { type = "item", name = "logicarts-continue-dual-turn", amount = 1 }, }, hidden = false, energy_required = 1.0, order = "logicarts-e", }, })
local media_type local id = param.get_id() if id then media_type = MediaType:by_id(id) else media_type = MediaType:new() end if param.get("delete", atom.boolean) then local name = media_type.name media_type:destroy() slot.put_into("notice", _("Media type '#{name}' deleted", {name = name})) return end param.update(media_type, "name", "description") media_type:save() if id then slot.put_into("notice", _("Media type '#{name}' updated", {name = media_type.name})) else slot.put_into("notice", _("Media type '#{name}' created", {name = media_type.name})) end
if battle == 1 then character_4:UseSkill(1) character_4:UseSkill(3) end if battle == 2 then character_3:UseSkill(1) character_3:UseSkill(2) end if battle == 3 then EnableChargeAttack() character_1:UseSkill(2) character_1:UseSkill(3) character_1:UseSkill(4) character_1:UseSkill(1) character_2:UseSkill(1) character_2:UseSkill(3) character_2:UseSkill(2) end
local meta = FindMetaTable( "Player" ); function meta:AddMoney( amt ) if( !self.Money ) then -- ? self.Money = amt; return; end self.Money = self.Money + amt; sql.Query( "UPDATE coi_players SET Money = " .. self.Money .. " WHERE ID = " .. self.ID .. ";" ); net.Start( "nSetMoney" ); net.WriteUInt( self.Money, 32 ); net.Send( self ); end function GM:SendStateMoney() for k, v in pairs( self.Teams ) do local amtTotal = team.GetScore( v ); local nPlayers = 0; for _, n in pairs( team.GetPlayers( v ) ) do if( n.Safe ) then nPlayers = nPlayers + 1; end end local amt = math.floor( amtTotal / nPlayers ); for _, n in pairs( team.GetPlayers( v ) ) do if( n.Safe ) then n:AddMoney( amt ); end end end end function meta:AddInventory( item ) self:CheckInventory(); local x, y = self:FindInvInsertPos( item ); if( x and y ) then local id = self:SQLAddItem( item, x, y ); self.Inventory[id] = { ItemClass = item, X = x, Y = y }; net.Start( "nAddInventory" ); net.WriteUInt( id, 16 ); net.WriteString( item ); net.WriteUInt( x, 6 ); net.WriteUInt( y, 6 ); net.Send( self ); end end util.AddNetworkString( "nAddInventory" ); local function nBuyItem( len, ply ) if( GAMEMODE:GetState() != STATE_PREGAME ) then return end local item = net.ReadString(); ply:CheckInventory(); if( !GAMEMODE.Items[item] ) then return end if( ply:HasItem( item ) ) then return end local i = GAMEMODE.Items[item]; if( ply.Money >= i.Price ) then ply:AddMoney( -i.Price ); ply:AddInventory( item ); end end net.Receive( "nBuyItem", nBuyItem ); util.AddNetworkString( "nBuyItem" ); local function nDeleteItem( len, ply ) if( GAMEMODE:GetState() != STATE_PREGAME ) then return end local item = net.ReadUInt( 16 ); ply:CheckInventory(); if( !ply.Inventory[item] ) then return end ply.Inventory[item] = nil; ply:SQLDeleteItem( item ); end net.Receive( "nDeleteItem", nDeleteItem ); util.AddNetworkString( "nDeleteItem" ); local function nInvMove( len, ply ) ply:CheckInventory(); local id = net.ReadUInt( 16 ); if( !ply.Inventory[id] ) then return end local x = net.ReadUInt( 6 ); local y = net.ReadUInt( 6 ); if( !ply:CanPutItemInSlot( id, x, y ) ) then return end ply.Inventory[id].X = x; ply.Inventory[id].Y = y; ply:SQLMoveInventory( id, x, y ); end net.Receive( "nInvMove", nInvMove ); util.AddNetworkString( "nInvMove" );
--[[ * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. ]]-- -- Allows to display colors. -- Modified code from https://github.com/hoelzro/ansicolors . local colormt = {} function colormt:__tostring() return self.value end function colormt:__concat(other) return tostring(self) .. tostring(other) end function colormt:__call(s) return self .. s .. _M.reset end colormt.__metatable = {} local function makecolor(value) return setmetatable({ value = string.char(27) .. '[' .. tostring(value) .. 'm' }, colormt) end local colors = { -- attributes reset = 0, clear = 0, bright = 1, dim = 2, underscore = 4, blink = 5, reverse = 7, hidden = 8, -- foreground black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, white = 37, -- background onblack = 40, onred = 41, ongreen = 42, onyellow = 43, onblue = 44, onmagenta = 45, oncyan = 46, onwhite = 47, } for c, v in pairs(colors) do _G[c] = makecolor(v) end
local cURL = require "cURL" -- open output file f = io.open("example_homepage", "w") cURL.easy{ url = "http://www.example.com/", writefunction = f } :perform() :close() -- close output file f:close() print("Done")
local bin = require "bin" local http = require "http" local nmap = require "nmap" local os = require "os" local stdnse = require "stdnse" local tab = require "tab" local table = require "table" _ENV = stdnse.module("ipp", stdnse.seeall) --- -- -- A small CUPS ipp (Internet Printing Protocol) library implementation -- -- @author Patrik Karlsson -- -- The IPP layer IPP = { StatusCode = { OK = 0, }, State = { IPP_JOB_PENDING = 3, IPP_JOB_HELD = 4, IPP_JOB_PROCESSING = 5, IPP_JOB_STOPPED = 6, IPP_JOB_CANCELED = 7, IPP_JOB_ABORTED = 8, IPP_JOB_COMPLETED = 9, }, StateName = { [3] = "Pending", [4] = "Held", [5] = "Processing", [6] = "Stopped", [7] = "Canceled", [8] = "Aborted", [9] = "Completed", }, OperationID = { IPP_CANCEL_JOB = 0x0008, IPP_GET_JOB_ATTRIBUTES = 0x0009, IPP_GET_JOBS = 0x000a, CUPS_GET_PRINTERS = 0x4002, CUPS_GET_DOCUMENT = 0x4027 }, PrinterState = { IPP_PRINTER_IDLE = 3, IPP_PRINTER_PROCESSING = 4, IPP_PRINTER_STOPPED = 5, }, Attribute = { IPP_TAG_OPERATION = 0x01, IPP_TAG_JOB = 0x02, IPP_TAG_END = 0x03, IPP_TAG_PRINTER = 0x04, IPP_TAG_INTEGER = 0x21, IPP_TAG_ENUM = 0x23, IPP_TAG_NAME = 0x42, IPP_TAG_KEYWORD = 0x44, IPP_TAG_URI = 0x45, IPP_TAG_CHARSET = 0x47, IPP_TAG_LANGUAGE = 0x48, new = function(self, tag, name, value) local o = { tag = tag, name = name, value = value } setmetatable(o, self) self.__index = self return o end, parse = function(data, pos) local attrib = IPP.Attribute:new() local val pos, attrib.tag, attrib.name, val = bin.unpack(">CPP", data, pos) -- print(attrib.name, stdnse.tohex(val)) attrib.value = {} table.insert(attrib.value, { tag = attrib.tag, val = val }) repeat local tag, name_len, val if ( #data < pos + 3 ) then break end pos, tag, name_len = bin.unpack(">CS", data, pos) if ( name_len == 0 ) then pos, val = bin.unpack(">P", data, pos) table.insert(attrib.value, { tag = tag, val = val }) else pos = pos - 3 end until( name_len ~= 0 ) -- do minimal decoding for i=1, #attrib.value do if ( attrib.value[i].tag == IPP.Attribute.IPP_TAG_INTEGER ) then attrib.value[i].val = select(2, bin.unpack(">I", attrib.value[i].val)) elseif ( attrib.value[i].tag == IPP.Attribute.IPP_TAG_ENUM ) then attrib.value[i].val = select(2, bin.unpack(">I", attrib.value[i].val)) end end if ( 1 == #attrib.value ) then attrib.value = attrib.value[1].val end --print(attrib.name, attrib.value, stdnse.tohex(val)) return pos, attrib end, __tostring = function(self) if ( "string" == type(self.value) ) then return bin.pack(">CSASA", self.tag, #self.name, self.name, #self.value, self.value) else local data = bin.pack(">CSASA", self.tag, #self.name, self.name, #self.value[1].val, self.value[1].val) for i=2, #self.value do data = data .. bin.pack(">CSP", self.value[i].tag, 0, self.value[i].val) end return data end end }, -- An attribute group, groups several attributes AttributeGroup = { new = function(self, tag, attribs) local o = { tag = tag, attribs = attribs or {} } setmetatable(o, self) self.__index = self return o end, addAttribute = function(self, attrib) table.insert(self.attribs, attrib) end, -- -- Gets the first attribute matching name and optionally tag from the -- attribute group. -- -- @param name string containing the attribute name -- @param tag number containing the attribute tag getAttribute = function(self, name, tag) for _, attrib in ipairs(self.attribs) do if ( attrib.name == name ) then if ( not(tag) ) then return attrib elseif ( tag and attrib.tag == tag ) then return attrib end end end end, getAttributeValue = function(self, name, tag) for _, attrib in ipairs(self.attribs) do if ( attrib.name == name ) then if ( not(tag) ) then return attrib.value elseif ( tag and attrib.tag == tag ) then return attrib.value end end end end, __tostring = function(self) local data = bin.pack("C", self.tag) for _, attrib in ipairs(self.attribs) do data = data .. tostring(attrib) end return data end }, -- The IPP request Request = { new = function(self, opid, reqid) local o = { version = 0x0101, opid = opid, reqid = reqid, attrib_groups = {}, } setmetatable(o, self) self.__index = self return o end, addAttributeGroup = function(self, group) table.insert( self.attrib_groups, group ) end, __tostring = function(self) local data = bin.pack(">SSI", self.version, self.opid, self.reqid ) for _, group in ipairs(self.attrib_groups) do data = data .. tostring(group) end data = data .. bin.pack("C", IPP.Attribute.IPP_TAG_END) return data end, }, -- A class to handle responses from the server Response = { -- Creates a new instance of response new = function(self) local o = {} setmetatable(o, self) self.__index = self return o end, getAttributeGroups = function(self, tag) local groups = {} for _, v in ipairs(self.attrib_groups or {}) do if ( v.tag == tag ) then table.insert(groups, v) end end return groups end, parse = function(data) local resp = IPP.Response:new() local pos pos, resp.version, resp.status, resp.reqid = bin.unpack(">SSI", data) resp.attrib_groups = {} local group repeat local tag, attrib pos, tag = bin.unpack(">C", data, pos) if ( tag == IPP.Attribute.IPP_TAG_OPERATION or tag == IPP.Attribute.IPP_TAG_JOB or tag == IPP.Attribute.IPP_TAG_PRINTER or tag == IPP.Attribute.IPP_TAG_END ) then if ( group ) then table.insert(resp.attrib_groups, group) group = IPP.AttributeGroup:new(tag) else group = IPP.AttributeGroup:new(tag) end else pos = pos - 1 end if ( not(group) ) then stdnse.debug2("Unexpected tag: %d", tag) return end pos, attrib = IPP.Attribute.parse(data, pos) group:addAttribute(attrib) until( pos == #data + 1) return resp end, }, } HTTP = { Request = function(host, port, request) local headers = { ['Content-Type'] = 'application/ipp', ['User-Agent'] = 'CUPS/1.5.1', } port.version.service_tunnel = "ssl" local http_resp = http.post(host, port, '/', { header = headers }, nil, tostring(request)) if ( http_resp.status ~= 200 ) then return false, "Unexpected response from server" end local response = IPP.Response.parse(http_resp.body) if ( not(response) ) then return false, "Failed to parse response" end return true, response end, } Helper = { new = function(self, host, port, options) local o = { host = host, port = port, options = options or {} } setmetatable(o, self) self.__index = self return o end, connect = function(self) self.socket = nmap.new_socket() self.socket:set_timeout(self.options.timeout or 10000) return self.socket:connect(self.host, self.port) end, getPrinters = function(self) local attribs = { IPP.Attribute:new(IPP.Attribute.IPP_TAG_CHARSET, "attributes-charset", "utf-8" ), IPP.Attribute:new(IPP.Attribute.IPP_TAG_LANGUAGE, "attributes-natural-language", "en"), } local ag = IPP.AttributeGroup:new(IPP.Attribute.IPP_TAG_OPERATION, attribs) local request = IPP.Request:new(IPP.OperationID.CUPS_GET_PRINTERS, 1) request:addAttributeGroup(ag) local status, response = HTTP.Request( self.host, self.port, tostring(request) ) if ( not(response) ) then return status, response end local printers = {} for _, ag in ipairs(response:getAttributeGroups(IPP.Attribute.IPP_TAG_PRINTER)) do local attrib = { ["printer-name"] = "name", ["printer-location"] = "location", ["printer-make-and-model"] = "model", ["printer-state"] = "state", ["queued-job-count"] = "queue_count", ["printer-dns-sd-name"] = "dns_sd_name", } local printer = {} for k, v in pairs(attrib) do if ( ag:getAttributeValue(k) ) then printer[v] = ag:getAttributeValue(k) end end table.insert(printers, printer) end return true, printers end, getQueueInfo = function(self, uri) local uri = uri or ("ipp://%s/"):format(self.host.ip) local attribs = { IPP.Attribute:new(IPP.Attribute.IPP_TAG_CHARSET, "attributes-charset", "utf-8" ), IPP.Attribute:new(IPP.Attribute.IPP_TAG_LANGUAGE, "attributes-natural-language", "en-us"), IPP.Attribute:new(IPP.Attribute.IPP_TAG_URI, "printer-uri", uri), IPP.Attribute:new(IPP.Attribute.IPP_TAG_KEYWORD, "requested-attributes", { -- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-originating-host-name"}, { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "com.apple.print.JobInfo.PMJobName"}, { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "com.apple.print.JobInfo.PMJobOwner"}, { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-id" }, { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-k-octets" }, { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-name" }, { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-state" }, { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "printer-uri" }, -- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-originating-user-name" }, -- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-printer-state-message" }, -- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-printer-uri" }, { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "time-at-creation" } } ), IPP.Attribute:new(IPP.Attribute.IPP_TAG_KEYWORD, "which-jobs", "not-completed" ) } local ag = IPP.AttributeGroup:new(IPP.Attribute.IPP_TAG_OPERATION, attribs) local request = IPP.Request:new(IPP.OperationID.IPP_GET_JOBS, 1) request:addAttributeGroup(ag) local status, response = HTTP.Request( self.host, self.port, tostring(request) ) if ( not(response) ) then return status, response end local results = {} for _, ag in ipairs(response:getAttributeGroups(IPP.Attribute.IPP_TAG_JOB)) do local uri = ag:getAttributeValue("printer-uri") local printer = uri:match(".*/(.*)$") or "Unknown" -- some jobs have multiple state attributes, so far the ENUM ones have been correct local state = ag:getAttributeValue("job-state", IPP.Attribute.IPP_TAG_ENUM) or ag:getAttributeValue("job-state") -- some jobs have multiple id tag, so far the INTEGER type have shown the correct ID local id = ag:getAttributeValue("job-id", IPP.Attribute.IPP_TAG_INTEGER) or ag:getAttributeValue("job-id") local attr = ag:getAttribute("time-at-creation") local tm = ag:getAttributeValue("time-at-creation") local size = ag:getAttributeValue("job-k-octets") .. "k" local jobname = ag:getAttributeValue("com.apple.print.JobInfo.PMJobName") or "Unknown" local owner = ag:getAttributeValue("com.apple.print.JobInfo.PMJobOwner") or "Unknown" results[printer] = results[printer] or {} table.insert(results[printer], { id = id, time = os.date("%Y-%m-%d %H:%M:%S", tm), state = ( IPP.StateName[tonumber(state)] or "Unknown" ), size = size, owner = owner, jobname = jobname }) end local output = {} for name, entries in pairs(results) do local t = tab.new(5) tab.addrow(t, "id", "time", "state", "size (kb)", "owner", "jobname") for _, entry in ipairs(entries) do tab.addrow(t, entry.id, entry.time, entry.state, entry.size, entry.owner, entry.jobname) end if ( 1<#t ) then table.insert(output, { name = name, tab.dump(t) }) end end return output end, close = function(self) return self.socket:close() end, } return _ENV;
local function parse_args() local cmd = torch.CmdLine() cmd:option("-gpu_index", 1, "the index of GPU to use") cmd:option("-NBest", false, "output N-best list or just a simple output") cmd:option("-beam_size", 7, "beam_size") cmd:option("-batch_size", 128, "decoding batch_size") cmd:option("-params_file", "", "input parameter files for a pre-trained Seq2Seq model") cmd:option("-model_file", "", "path for loading a pre-trained Seq2Seq model") cmd:option("-dictPath", "data/movie_25000", "dictionary file") cmd:option("-InputFile", "data/t_given_s_test.txt", "the input file for decoding") cmd:option("-OutputFile", "output.txt", "the output file to store the generated responses") cmd:option('-save_params_file', '', 'if not empty, save the decoder params to this file') cmd:option("-setting", "BS", "setting for decoding. Choose from sampling, BS, DiverseBS, StochasticGreedy") -- sotchastic greedy sampling is a decoding technique proposed -- in Distill to bring in randomness and improve diversity (specificity). -- The model samples from the few words with the highest probability. -- This option controls the highest N words to sample. -- It is a trade-off of between sampling and greedy. -- The larger the value is, the more sampling is taken in. -- When it is 1 (default), it degrades to pure greedy. cmd:option("-StochasticGreedyNum", 1, "The words with the highest Num probability to sample") cmd:option("-max_length", 20, "the maximum length of a decoded response") cmd:option("-min_length", 0, "the minimum length of a decoded response") cmd:option("-max_decoded_num", 0, "the maximum number of instances to Decode. Decode the entire input set if the value is set to 0") cmd:option("-target_length", 0, "force the length of the generated target, 0 means there is no such constraints") cmd:option("-MMI", false, "whether to perform the mutual information reranking after decoding") cmd:option("-MMI_params_file", "", "the input parameter file for training the backward model p(s|t)") cmd:option("-MMI_model_file", "", "path for loading the backward model p(s|t)") -- Method introduced in A simple fast diverse decode algorithm. cmd:option("-DiverseRate", 0, "The diverse-decoding rate for penalizing intra-sibling hypotheses in the diverse decoding model") cmd:option("-output_source_target_side_by_side", true, "output input sources and decoded targets side by side") cmd:option("-PrintOutIllustrationSample", false, "print illustration sample while decoding") cmd:option("-allowUNK", false, "whether allowing to generate UNK") cmd:option("-onlyPred", true, "") -- Not found in readme. local params = cmd:parse(arg) print(params) return params end return parse_args
object_intangible_pet_beast_master_bm_mutated_narglatch = object_intangible_pet_beast_master_shared_bm_mutated_narglatch:new { } ObjectTemplates:addTemplate(object_intangible_pet_beast_master_bm_mutated_narglatch, "object/intangible/pet/beast_master/bm_mutated_narglatch.iff")
local md5 = require"md5" local soap = require"soap" local crypto = require"crypto" sanitize = require"npssdk.sanitize" version = require"npssdk.version" services = require"npssdk.services" local Utils = {} Utils.__index = Utils function Utils.build_parameters(params, service) local finalParams = build_inner_parameters(params, service) finalParams.tag="Requerimiento" return finalParams end function build_inner_parameters(params, service) local finalParams = {} local i = 1 for k,v in pairs(params) do local tempTable = {} if ((type(v)) == "string") or ((type(v)) == "number") then tempTable.tag = k tempTable[1] = v else tempTable = build_table_parameter(v, service) tempTable.tag = k end finalParams[i] = tempTable i = i + 1 end return finalParams end function build_table_parameter(params, service) if (is_assoc(params)) then resp = build_inner_parameters(params) else resp = build_array_parameter(params, service) end return resp end function build_array_parameter(params, service) local inner_array = {} for k, v in pairs(params) do inner_array[k] = build_inner_parameters(v) inner_array[k].tag = "Item" end inner_array.attr = { "ns2:arrayType", ["ns2:arrayType"]="" } return inner_array end function is_assoc(tbl) local numKeys = 0 for _, _ in pairs(tbl) do numKeys = numKeys+1 end local numIndices = 0 for _, _ in ipairs(tbl) do numIndices = numIndices+1 end return numKeys ~= numIndices end function Utils.wrap_response(response) if (response[1]) == nil then return response end local wrapped_response = normalize_table(response[1]) return wrapped_response end function normalize_table(response) local wrapped_response = {} for k, v in ipairs(response) do if (type(v[1]) == "table") then wrapped_response[v.tag] = normalize_array(v) else wrapped_response[v.tag] = v[1] end end return wrapped_response end function normalize_array(params) local resp = "" if params.attr["SOAP-ENC:arrayType"] == null then resp = normalize_table(params) else resp = normalize_array_items(params) end return resp end function normalize_array_items(params) local inner_array={} for k, v in ipairs(params) do inner_array[k] = normalize_table(params) end return inner_array end function Utils.add_secure_hash(params, thekey) local tempTable = {} tempTable.tag = "psp_SecureHash" local secure_hash = create_hmac_sha256(concat_params(params, ""), thekey) tempTable[1] = secure_hash params[#params+1] = tempTable return params end function build_secure_hash(params, thekey) local concatenated_params = concat_params(params, thekey) return md5.sumhexa(concatenated_params) end function create_hmac_sha256(message, key) return crypto.hmac.digest('sha256', message, key, false) end function create_hmac_sha512(message, key) return crypto.hmac.digest('sha512', message, key, false) end function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 local iter = function () i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end function concat_params(params, thekey) local concatenated_params = "" local tempTable = {} for k, v in ipairs(params) do if not(type(v[1]) == "table") then tempTable[v.tag] = v[1] end end for name, line in pairsByKeys(tempTable) do concatenated_params = concatenated_params .. line end concatenated_params = concatenated_params .. thekey return concatenated_params end function Utils.log(t, log_level, log_file) local xml = soap.serialize(t) if (log_level == "INFO") then xml = ofuscate(xml) end if (log_file) then file = io.open (file_path, "a") io.output(file) io.write(xml) io.close() else print(xml) end end function ofuscate(xml) xml = ofuscate_card_number(xml) xml = ofuscate_exp_date(xml) xml = ofuscate_cvc(xml) return xml end function ofuscate_card_number(xml) xml = string.gsub(xml,"([0-9]*</psp_CardNumber>)", inner_card_number_ofuscate) xml = string.gsub(xml,"([0-9]*</Number>)", inner_card_number_ofuscate) return xml end function inner_card_number_ofuscate(xml) xml = string.gsub(xml,"([0-9]*)", wrap_card_number) return xml end function wrap_card_number(number) b = string.sub(number, 0, 6) f = string.sub(number, string.len(number)-4, string.len(number)) number = b .. string.rep("*",string.len(number)-10) .. f return number end function ofuscate_exp_date(xml) xml = string.gsub(xml,"([0-9]*</psp_CardExpDate>)", inner_exp_date_ofuscate) xml = string.gsub(xml,"([0-9]*</ExpirationDate>)", inner_exp_date_ofuscate) return xml end function inner_exp_date_ofuscate(number) xml = string.gsub(number,"([0-9]*)", function(xml)return string.rep("*", string.len(xml))end) return xml end function ofuscate_cvc(xml) xml = string.gsub(xml,"([0-9]*</psp_CardSecurityCode>)", inner_cvc_ofuscate) xml = string.gsub(xml,"([0-9]*</SecurityCode>)", inner_cvc_ofuscate) return xml end function inner_cvc_ofuscate(number) xml = string.gsub(number,"([0-9]*)", function(xml)return string.rep("*", string.len(xml))end) return xml end function Utils.check_sanitize(params, is_root, nodo) return sanitize_me(params) end function sanitize_me(params, is_root, nodo) local result_params = {} if (is_root == nil) or (is_root == false) then result_params = {} else result_params = params end for k, v in pairs(params) do if (type(v) == "table") then if is_assoc(v) then result_params[k] = sanitize_me(v, false, k) else result_params[k] = check_sanitize_array(v, k) end else result_params[k] = validate_size(v, k, nodo) end end return result_params end function check_sanitize_array(params, nodo) local resul_params = {} for k, v in ipairs(params) do resul_params[#resul_params+1] = sanitize_me(v, false, nodo) end return resul_params end function validate_size(value, k, nodo) local key_name = "" if (nodo) then key_name = nodo .. k .. ".max_length" else key_name = k .. ".max_length" end local size = sanitize[key_name] if (size) then value = string.sub( value, 0, size) end return value end function Utils.add_add_details(params) local add_details = {} if (params["psp_MerchantAdditionalDetails"]) then add_details = params["psp_MerchantAdditionalDetails"] end add_details["SdkInfo"] = "Lua SDK Version: " .. version params["psp_MerchantAdditionalDetails"] = add_details return params end function Utils.is_value_in_array (valor, array) for i, name in ipairs(array) do if name == valor then return true end end return false end function Utils.is_client_session_in_params (params) for i, name in ipairs(params) do for key, value in pairs(name) do if (value == 'psp_ClientSession') then return true end end end return false end return Utils
local json = require( "json" ) local emittersManager = {} emittersManager.init = function(filename, varianceScale, ifStart) local group = display.newGroup() local scale = display.contentScaleX -- Read the exported Particle Designer file (JSON) into a string local filePath = system.pathForFile( "assets/particles/" .. filename) local f = io.open( filePath, "r" ) local fileData = f:read( "*a" ) f:close() -- Decode the string local emitterParams = json.decode( fileData ) -- Create the emitter with the decoded parameters local emitter = display.newEmitter( emitterParams) group:insert(1, emitter) group.xScale = scale; group.yScale = scale; emitter.startParticleSize = emitterParams.startParticleSize*scale; emitter.finishParticleSize = emitterParams.finishParticleSize*scale; emitter.startParticleSizeVariance = varianceScale*emitterParams.startParticleSizeVariance*scale; emitter.startParticleSizeVariance = varianceScale*emitterParams.finishParticleSizeVariance*scale; if not ifStart then emitter:stop() end return group end emittersManager.setPosition = function (opts) local scale = display.contentScaleX opts.emitterGroup[1].x = opts.x/scale opts.emitterGroup[1].y = opts.y/scale end return emittersManager
--- -- xcode/xcode4_scheme.lua -- Generate a shared scheme for an Xcode C/C++ project. -- Copyright (c) 2009-2016 Jason Perkins and the Premake project --- local p = premake local m = p.modules.xcode_alt local project = p.project local config = p.config local fileconfig = p.fileconfig local tree = p.tree m.scheme = {} local scheme = m.scheme function scheme.Header(prj) p.w('<?xml version="1.0" encoding="UTF-8"?>') p.push('<Scheme') p.w('LastUpgradeVersion = "0500"') p.w('version = "1.3">') end function scheme.Footer(prj) p.pop('</Scheme>') end function scheme.buildablereference(prj) local tr = project.getsourcetree(prj) for _, node in ipairs(tr.products.children) do p.push('<BuildableReference') p.w('BuildableIdentifier = "primary"') p.w('BlueprintIdentifier = "%s"', node.targetid) p.w('BuildableName = "%s"', node.name) p.w('BlueprintName = "%s"', tr.name) p.w('ReferencedContainer = "container:%s.xcodeproj">', tr.name) p.pop('</BuildableReference>') end end function scheme.build(prj) p.push('<BuildAction') p.w('parallelizeBuildables = "YES"') p.w('buildImplicitDependencies = "YES">') p.push('<BuildActionEntries>') p.push('<BuildActionEntry') p.w('buildForTesting = "YES"') p.w('buildForRunning = "YES"') p.w('buildForProfiling = "YES"') p.w('buildForArchiving = "YES"') p.w('buildForAnalyzing = "YES">') scheme.buildablereference(prj) p.pop('</BuildActionEntry>') p.pop('</BuildActionEntries>') p.pop('</BuildAction>') end function scheme.test(prj) p.push('<TestAction') p.w('selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"') p.w('selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"') p.w('shouldUseLaunchSchemeArgsEnv = "YES"') p.w('buildConfiguration = "Debug">') p.push('<Testables>') p.pop('</Testables>') p.push('<MacroExpansion>') scheme.buildablereference(prj) p.pop('</MacroExpansion>') p.pop('</TestAction>') end function scheme.launch(prj) p.push('<LaunchAction') p.w('selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"') p.w('selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"') p.w('launchStyle = "0"') p.w('useCustomWorkingDirectory = "NO"') p.w('buildConfiguration = "Debug"') p.w('ignoresPersistentStateOnLaunch = "NO"') p.w('debugDocumentVersioning = "NO"') p.w('allowLocationSimulation = "YES">') p.push('<BuildableProductRunnable>') scheme.buildablereference(prj) p.pop('</BuildableProductRunnable>') p.push('<AdditionalOptions>') p.pop('</AdditionalOptions>') p.pop('</LaunchAction>') end function scheme.profile(prj) p.push('<ProfileAction') p.w('shouldUseLaunchSchemeArgsEnv = "YES"') p.w('savedToolIdentifier = ""') p.w('useCustomWorkingDirectory = "NO"') p.w('buildConfiguration = "Release"') p.w('debugDocumentVersioning = "NO">') p.push('<BuildableProductRunnable>') scheme.buildablereference(prj) p.pop('</BuildableProductRunnable>') p.pop('</ProfileAction>') end function scheme.analyze(prj) p.push('<AnalyzeAction') p.w('buildConfiguration = "Debug">') p.pop('</AnalyzeAction>') end function scheme.archive(prj) p.push('<ArchiveAction') p.w('buildConfiguration = "Release"') p.w('revealArchiveInOrganizer = "YES">') p.pop('</ArchiveAction>') end -- -- Generate the shared data scheme for an xcode project -- -- @param prj -- The Premake project to generate. -- m.scheme.project = function(prj) return { scheme.Header, scheme.build, scheme.test, scheme.launch, scheme.profile, scheme.analyze, scheme.archive, scheme.Footer, } end function m.scheme.generate(prj) p.callArray(m.scheme.project, prj) end
--- === hs.canvas.turtle === --- --- Creates a view which can be assigned to an `hs.canvas` object of type "canvas" which displays graphical images rendered in a style similar to that of the Logo language, sometimes referred to as "Turtle Graphics". --- --- Briefly, turtle graphics are vector graphics using a relative cursor (the "turtle") upon a Cartesian plane. The view created by this module has its origin in the center of the display area. The Y axis grows positively as you move up and negatively as you move down from this origin (this is the opposite of the internal coordinates of other `hs.canvas` objects); similarly, movement left is positive movement along the X axis, while movement right is negative. --- --- The turtle is initially visible with a heading of 0 degrees (pointing straight up), and the pen (the drawing element of the turtle) is down with a black color in paint mode. All of these can be adjusted by methods within this module. --- --- --- Some of the code included in this module was influenced by or written to mimic behaviors described at: --- * https://people.eecs.berkeley.edu/~bh/docs/html/usermanual_6.html#GRAPHICS --- * https://www.calormen.com/jslogo/# --- * https://github.com/inexorabletash/jslogo local USERDATA_TAG = "hs.canvas.turtle" local module = require(USERDATA_TAG..".internal") local turtleMT = hs.getObjectMetatable(USERDATA_TAG) local color = require("hs.drawing.color") local inspect = require("hs.inspect") local fnutils = require("hs.fnutils") local canvas = require("hs.canvas") local screen = require("hs.screen") local eventtap = require("hs.eventtap") local mouse = require("hs.mouse") -- don't need these directly, just their helpers require("hs.image") local basePath = package.searchpath(USERDATA_TAG, package.path) if basePath then basePath = basePath:match("^(.+)/init.lua$") if require"hs.fs".attributes(basePath .. "/docs.json") then require"hs.doc".registerJSONFile(basePath .. "/docs.json") end end local log = require("hs.logger").new(USERDATA_TAG, require"hs.settings".get(USERDATA_TAG .. ".logLevel") or "warning") -- private variables and methods ----------------------------------------- -- borrowed and (very) slightly modified from https://www.calormen.com/jslogo/#; specifically -- https://github.com/inexorabletash/jslogo/blob/02482525925e399020f23339a0991d98c4f088ff/turtle.js#L129-L152 local betterTurtle = canvas.new{ x = 100, y = 100, h = 45, w = 45 }:appendElements{ { type = "segments", action = "strokeAndFill", strokeColor = { green = 1 }, fillColor = { green = .75, alpha = .25 }, frame = { x = 0, y = 0, h = 40, w = 40 }, strokeWidth = 2, transformation = canvas.matrix.translate(22.5, 24.5), coordinates = { { x = 0, y = -20 }, { x = 2.5, y = -17 }, { x = 3, y = -12 }, { x = 6, y = -10 }, { x = 9, y = -13 }, { x = 13, y = -12 }, { x = 18, y = -4 }, { x = 18, y = 0 }, { x = 14, y = -1 }, { x = 10, y = -7 }, { x = 8, y = -6 }, { x = 10, y = -2 }, { x = 9, y = 3 }, { x = 6, y = 10 }, { x = 9, y = 13 }, { x = 6, y = 15 }, { x = 3, y = 12 }, { x = 0, y = 13 }, { x = -3, y = 12 }, { x = -6, y = 15 }, { x = -9, y = 13 }, { x = -6, y = 10 }, { x = -9, y = 3 }, { x = -10, y = -2 }, { x = -8, y = -6 }, { x = -10, y = -7 }, { x = -14, y = -1 }, { x = -18, y = 0 }, { x = -18, y = -4 }, { x = -13, y = -12 }, { x = -9, y = -13 }, { x = -6, y = -10 }, { x = -3, y = -12 }, { x = -2.5, y = -17 }, { x = 0, y = -20 }, }, }, }:imageFromCanvas() -- Hide the internals from accidental usage local _wrappedCommands = module._wrappedCommands -- module._wrappedCommands = nil local _unwrappedSynonyms = { clearscreen = { "cs" }, showturtle = { "st" }, hideturtle = { "ht" }, background = { "bg" }, textscreen = { "ts" }, fullscreen = { "fs" }, splitscreen = { "ss" }, pencolor = { "pc" }, -- shownp = { "shown?" }, -- not a legal lua method name, so will need to catch when converter written -- pendownp = { "pendown?" }, } -- in case I ever write something to import turtle code directly, don't want these to cause it to break immediately local _nops = { wrap = false, -- boolean indicates whether or not warning has been issued; don't want to spam console window = false, fence = false, textscreen = false, fullscreen = false, splitscreen = false, refresh = false, norefresh = false, setpenpattern = true, -- used in setpen, in case I ever actually implement it, so skip warning } local defaultPalette = { { "black", { __luaSkinType = "NSColor", list = "Apple", name = "Black" }}, { "blue", { __luaSkinType = "NSColor", list = "Apple", name = "Blue" }}, { "green", { __luaSkinType = "NSColor", list = "Apple", name = "Green" }}, { "cyan", { __luaSkinType = "NSColor", list = "Apple", name = "Cyan" }}, { "red", { __luaSkinType = "NSColor", list = "Apple", name = "Red" }}, { "magenta", { __luaSkinType = "NSColor", list = "Apple", name = "Magenta" }}, { "yellow", { __luaSkinType = "NSColor", list = "Apple", name = "Yellow" }}, { "white", { __luaSkinType = "NSColor", list = "Apple", name = "White" }}, { "brown", { __luaSkinType = "NSColor", list = "Apple", name = "Brown" }}, { "tan", { __luaSkinType = "NSColor", list = "x11", name = "tan" }}, { "forest", { __luaSkinType = "NSColor", list = "x11", name = "forestgreen" }}, { "aqua", { __luaSkinType = "NSColor", list = "Crayons", name = "Aqua" }}, { "salmon", { __luaSkinType = "NSColor", list = "Crayons", name = "Salmon" }}, { "purple", { __luaSkinType = "NSColor", list = "Apple", name = "Purple" }}, { "orange", { __luaSkinType = "NSColor", list = "Apple", name = "Orange" }}, { "gray", { __luaSkinType = "NSColor", list = "x11", name = "gray" }}, } -- pulled from webkit/Source/WebKit/Shared/WebPreferencesDefaultValues.h 2020-05-17 module._fontMap = { serif = "Times", ["sans-serif"] = "Helvetica", cursive = "Apple Chancery", fantasy = "Papyrus", monospace = "Courier", -- pictograph = "Apple Color Emoji", } module._registerDefaultPalette(defaultPalette) module._registerDefaultPalette = nil module._registerFontMap(module._fontMap) module._registerFontMap = nil local finspect = function(obj) return inspect(obj, { newline = " ", indent = "" }) end local _backgroundQueues = setmetatable({}, { __mode = "k", -- work around for the fact that we're using selfRefCount to allow for auto-clean on __gc -- relies on the fact that these are only called if the key *doesn't* exist already in the -- table -- the following assume [<userdata>] = { table } in weak-key table; if you're not -- saving a table of values keyed to the userdata, all bets are off and you'll -- need to write something else __index = function(self, key) for k,v in pairs(self) do if k == key then -- put *this* key in with the same table so changes to the table affect all -- "keys" pointing to this table rawset(self, key, v) return v end end return nil end, __newindex = function(self, key, value) local haslogged = false -- only called for a complete re-assignment of the table if __index wasn't -- invoked first... for k,v in pairs(self) do if k == key then if type(value) == "table" and type(v) == "table" then -- do this to keep the target table for existing useradata the same -- because it may have multiple other userdatas pointing to it for k2, v2 in pairs(v) do v[k2] = nil end -- shallow copy -- can't have everything or this will get insane for k2, v2 in pairs(value) do v[k2] = v2 end rawset(self, key, v) return else -- we'll try... replace *all* existing matches (i.e. don't return after 1st) -- but since this will never get called if __index was invoked first, log -- warning anyways because this *isn't* what these additions are for... if not haslogged then hs.luaSkinLog.wf("%s - weak table indexing only works when value is a table; behavior is undefined for value type %s", USERDATA_TAG, type(value)) haslogged = true end rawset(self, k, value) end end end rawset(self, key, value) end, }) -- Public interface ------------------------------------------------------ local _new = module.new module.new = function(...) return _new(...):_turtleImage(betterTurtle) end module.turtleCanvas = function(...) local decorateSize = 16 local recalcDecorations = function(nC, decorate) if decorate then local frame = nC:frame() nC.moveBar.frame = { x = 0, y = 0, h = decorateSize, w = frame.w } nC.resizeX.frame = { x = frame.w - decorateSize, y = decorateSize, h = frame.h - decorateSize * 2, w = decorateSize } nC.resizeY.frame = { x = 0, y = frame.h - decorateSize, h = decorateSize, w = frame.w - decorateSize, } nC.resizeXY.frame = { x = frame.w - decorateSize, y = frame.h - decorateSize, h = decorateSize, w = decorateSize } nC.turtleView.frame = { x = 0, y = decorateSize, h = frame.h - decorateSize * 2, w = frame.w - decorateSize, } end end local args = table.pack(...) local frame, decorate = {}, true local decorateIdx = 2 if type(args[1]) == "table" then frame, decorateIdx = args[1], 2 end if args.n >= decorateIdx then decorate = args[decorateIdx] end frame = frame or {} local screenFrame = screen.mainScreen():fullFrame() local defaultFrame = { x = screenFrame.x + screenFrame.w / 4, y = screenFrame.y + screenFrame.h / 4, h = screenFrame.h / 2, w = screenFrame.w / 2, } frame.x = frame.x or defaultFrame.x frame.y = frame.y or defaultFrame.y frame.w = frame.w or defaultFrame.w frame.h = frame.h or defaultFrame.h local _cMouseAction -- make local here so it's an upvalue in mouseCallback local nC = canvas.new(frame):show() if decorate then nC[#nC + 1] = { id = "moveBar", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 0 }, fillColor = { white = 1 }, strokeWidth = 1, } nC[#nC + 1] = { id = "resizeX", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 0 }, fillColor = { white = 1 }, strokeWidth = 1, } nC[#nC + 1] = { id = "resizeY", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 0 }, fillColor = { white = 1 }, strokeWidth = 1, } nC[#nC + 1] = { id = "resizeXY", type = "rectangle", action = "strokeAndFill", strokeColor = { white = 0 }, fillColor = { white = 1 }, strokeWidth = 1, } nC[#nC + 1] = { id = "label", type = "text", action = "strokeAndFill", textSize = decorateSize - 2, textAlignment = "center", text = "TurtleCanvas", textColor = { white = 0 }, frame = { x = 0, y = 0, h = decorateSize, w = "100%" }, } end local turtleViewObject = module.new() nC[#nC + 1] = { id = "turtleView", type = "canvas", canvas = turtleViewObject, } recalcDecorations(nC, decorate) if decorate ~= nil then nC:clickActivating(false) :canvasMouseEvents(true, true) :mouseCallback(function(_c, _m, _i, _x, _y) if _i == "_canvas_" then if _m == "mouseDown" then local buttons = eventtap.checkMouseButtons() if buttons.left then local cframe = _c:frame() local inMoveArea = (_y < decorateSize) local inResizeX = (_x > (cframe.w - decorateSize)) local inResizeY = (_y > (cframe.h - decorateSize)) if inMoveArea then _cMouseAction = coroutine.wrap(function() while _cMouseAction do local pos = mouse.absolutePosition() local frame = _c:frame() frame.x = pos.x - _x frame.y = pos.y - _y _c:frame(frame) recalcDecorations(_c, decorate) coroutine.applicationYield() end end) _cMouseAction() elseif inResizeX or inResizeY then _cMouseAction = coroutine.wrap(function() while _cMouseAction do local pos = mouse.absolutePosition() local frame = _c:frame() if inResizeX then local newW = pos.x + cframe.w - _x - frame.x if newW < decorateSize then newW = decorateSize end frame.w = newW end if inResizeY then local newY = pos.y + cframe.h - _y - frame.y if newY < (decorateSize * 2) then newY = (decorateSize * 2) end frame.h = newY end _c:frame(frame) recalcDecorations(_c, decorate) coroutine.applicationYield() end end) _cMouseAction() end elseif buttons.right then local modifiers = eventtap.checkKeyboardModifiers() if modifiers.shift then _c:hide() end end elseif _m == "mouseUp" then _cMouseAction = nil end end end) end return turtleViewObject end -- methods with visual impact call this to allow for yields when we're running in a coroutine local coroutineFriendlyCheck = function(self) -- don't get tripped up by other coroutines if _backgroundQueues[self] and _backgroundQueues[self].ourCoroutine then if not self:_neverYield() then local thread, isMain = coroutine.running() if not isMain and (self:_cmdCount() % self:_yieldRatio()) == 0 then coroutine.applicationYield() end end end end --- hs.canvas.turtle:pos() -> table --- Method --- Returns the turtle’s current position, as a table containing two numbers, the X and Y coordinates. --- --- Parameters: --- * None --- --- Returns: --- * a table containing the X and Y coordinates of the turtle. local _pos = turtleMT.pos turtleMT.pos = function(...) local result = _pos(...) return setmetatable(result, { __tostring = function(_) return string.format("{ %.2f, %.2f }", _[1], _[2]) end }) end --- hs.canvas.turtle:pensize() -> turtleViewObject --- Method --- Returns a table of two positive integers, specifying the horizontal and vertical thickness of the turtle pen. --- --- Parameters: --- * None --- --- Returns: --- * a table specifying the horizontal and vertical thickness of the turtle pen. --- --- Notes: --- * in this implementation the two numbers will always be equal as the macOS uses a single width for determining stroke size. local _pensize = turtleMT.pensize turtleMT.pensize = function(...) local result = _pensize(...) return setmetatable(result, { __tostring = function(_) return string.format("{ %.2f, %.2f }", _[1], _[2]) end }) end --- hs.canvas.turtle:scrunch() -> table --- Method --- Returns a table containing the current X and Y scrunch factors. --- --- Parameters: --- * None --- --- Returns: --- * a table containing the X and Y scrunch factors for the turtle view local _scrunch = turtleMT.scrunch turtleMT.scrunch = function(...) local result = _scrunch(...) return setmetatable(result, { __tostring = function(_) return string.format("{ %.2f, %.2f }", _[1], _[2]) end }) end --- hs.canvas.turtle:labelsize() -> table --- Method --- Returns a table containing the height and width of characters rendered by [hs.canvas.turtle:label](#label). --- --- Parameters: --- * None --- --- Returns: --- * A table containing the width and height of characters. --- --- Notes: --- * On most modern machines, font widths are variable for most fonts; as this is not easily calculated unless the specific text to be rendered is known, the height, as specified with [hs.canvas.turtle:setlabelheight](#setlabelheight) is returned for both values by this method. local _labelsize = turtleMT.labelsize turtleMT.labelsize = function(...) local result = _labelsize(...) return setmetatable(result, { __tostring = function(_) return string.format("{ %.2f, %.2f }", _[1], _[2]) end }) end local __visibleAxes = turtleMT._visibleAxes turtleMT._visibleAxes = function(...) local result = __visibleAxes(...) return setmetatable(result, { __tostring = function(_) return string.format("{ { %.2f, %.2f }, { %.2f, %.2f } }", _[1][1], _[1][2], _[2][1], _[2][2]) end }) end --- hs.canvas.turtle:pencolor() -> int | table --- Method --- Get the current pen color, either as a palette index number or as an RGB(A) list, whichever way it was most recently set. --- --- Parameters: --- * None --- --- Returns: --- * if the background color was most recently set by palette index, returns the integer specifying the index; if it was set as a 3 or 4 value table representing RGB(A) values, the table is returned; otherwise returns a color table as defined in `hs.drawing.color`. --- --- Notes: --- * Synonym: `hs.canvas.turtle:pc()` local _pencolor = turtleMT.pencolor turtleMT.pencolor = function(...) local result = _pencolor(...) if type(result) == "number" then return result end local defaultToString = finspect(result) return setmetatable(result, { __tostring = function(_) if #_ == 3 then return string.format("{ %.2f, %.2f, %.2f }", _[1], _[2], _[3]) elseif #_ == 4 then return string.format("{ %.2f, %.2f, %.2f, %.2f }", _[1], _[2], _[3], _[4]) else return defaultToString end end }) end --- hs.canvas.turtle:background() -> int | table --- Method --- Get the background color, either as a palette index number or as an RGB(A) list, whichever way it was most recently set. --- --- Parameters: --- * None --- --- Returns: --- * if the background color was most recently set by palette index, returns the integer specifying the index; if it was set as a 3 or 4 value table representing RGB(A) values, the table is returned; otherwise returns a color table as defined in `hs.drawing.color`. --- --- Notes: --- * Synonym: `hs.canvas.turtle:bg()` local _background = turtleMT.background turtleMT.background = function(...) local result = _background(...) if type(result) == "number" then return result end local defaultToString = finspect(result) return setmetatable(result, { __tostring = function(_) if #_ == 3 then return string.format("{ %.2f, %.2f, %.2f }", _[1], _[2], _[3]) elseif #_ == 4 then return string.format("{ %.2f, %.2f, %.2f, %.2f }", _[1], _[2], _[3], _[4]) else return defaultToString end end }) end --- hs.canvas.turtle:palette(index) -> table --- Method --- Returns the color defined at the specified palette index. --- --- Parameters: --- * `index` - an integer between 0 and 255 specifying the index in the palette of the desired coloe --- --- Returns: --- * a table specifying the color as a list of 3 or 4 numbers representing the intensity of the red, green, blue, and optionally alpha channels as a number between 0.0 and 100.0. If the color cannot be represented in RGB(A) format, then a table as described in `hs.drawing.color` is returned. local _palette = turtleMT.palette turtleMT.palette = function(...) local result = _palette(...) local defaultToString = finspect(result) return setmetatable(result, { __tostring = function(_) if #_ == 3 then return string.format("{ %.2f, %.2f, %.2f }", _[1], _[2], _[3]) elseif #_ == 4 then return string.format("{ %.2f, %.2f, %.2f, %.2f }", _[1], _[2], _[3], _[4]) else return defaultToString end end }) end --- hs.canvas.turtle:towards(pos) -> number --- Method --- Returns the heading at which the turtle should be facing so that it would point from its current position to the position specified. --- --- Parameters: --- * `pos` - a position table containing the x and y coordinates as described in [hs.canvas.turtle:pos](#pos) of the point the turtle should face. --- --- Returns: --- * a number representing the heading the turtle should face to point to the position specified in degrees clockwise from the positive Y axis. turtleMT.towards = function(self, pos) local x, y = pos[1], pos[2] assert(type(x) == "number", "expected a number for the x coordinate") assert(type(y) == "number", "expected a number for the y coordinate") local cpos = self:pos() return (90 - math.atan(y - cpos[2],x - cpos[1]) * 180 / math.pi) % 360 end --- hs.canvas.turtle:screenmode() -> string --- Method --- Returns a string describing the current screen mode for the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * "FULLSCREEN" --- --- Notes: --- * This method always returns "FULLSCREEN" for compatibility with translated Logo code; since this module only implements `textscreen`, `fullscreen`, and `splitscreen` as no-op methods to simplify conversion, no other return value is possible. turtleMT.screenmode = function(self, ...) return "FULLSCREEN" end --- hs.canvas.turtle:turtlemode() -> string --- Method --- Returns a string describing the current turtle mode for the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * "WINDOW" --- --- Notes: --- * This method always returns "WINDOW" for compatibility with translated Logo code; since this module only implements `window`, `wrap`, and `fence` as no-op methods to simplify conversion, no other return value is possible. turtleMT.turtlemode = function(self, ...) return "WINDOW" end --- hs.canvas.turtle:pen() -> table --- Method --- Returns a table containing the pen’s position, mode, thickness, and hardware-specific characteristics. --- --- Parameters: --- * None --- --- Returns: --- * a table containing the contents of the following as entries: --- * [hs.canvas.turtle:pendownp()](#pendownp) --- * [hs.canvas.turtle:penmode()](#penmode) --- * [hs.canvas.turtle:pensize()](#pensize) --- * [hs.canvas.turtle:pencolor()](#pencolor) --- * [hs.canvas.turtle:penpattern()](#penpattern) --- --- Notes: --- * the resulting table is suitable to be used as input to [hs.canvas.turtle:setpen](#setpen). turtleMT.pen = function(self, ...) local pendown = self:pendownp() and "PENDOWN" or "PENUP" local penmode = self:penmode() local pensize = self:pensize() local pencolor = self:pencolor() local penpattern = self:penpattern() return setmetatable({ pendown, penmode, pensize, pencolor, penpattern }, { __tostring = function(_) return string.format("{ %s, %s, %s, %s, %s }", pendown, penmode, tostring(pensize), tostring(pencolor), tostring(penpattern) ) end }) end turtleMT.penpattern = function(self, ...) return nil end --- hs.canvas.turtle:setpen(state) -> turtleViewObject --- Method --- Sets the pen’s position, mode, thickness, and hardware-dependent characteristics. --- --- Parameters: --- * `state` - a table containing the results of a previous invocation of [hs.canvas.turtle:pen](#pen). --- --- Returns: --- * the turtleViewObject turtleMT.setpen = function(self, ...) local args = table.pack(...) assert(args.n == 1, "setpen: expected only one argument") assert(type(args[1]) == "table", "setpen: expected table of pen state values") local details = args[1] assert(({ penup = true, pendown = true })[details[1]:lower()], "setpen: invalid penup/down state at index 1") assert(({ paint = true, erase = true, reverse = true })[details[2]:lower()], "setpen: invalid penmode state at index 2") assert((type(details[3]) == "table") and (#details[3] == 2) and (type(details[3][1]) == "number") and (type(details[3][2]) == "number"), "setpen: invalid pensize table at index 3") assert(({ string = true, number = true, table = true })[type(details[4])], "setpen: invalid pencolor at index 4") assert(true, "setpen: invalid penpattern at index 5") -- in case I add it turtleMT["pen" .. details[2]:lower()](self) -- penpaint, penerase, or penreverse turtleMT[details[1]:lower()](self) -- penup or pendown (has to come after mode since mode sets pendown) self:setpensize(details[3]) self:setpencolor(details[4]) self:setpenpattern(details[5]) -- its a nop currently, but we're supressing it's output message return self end --- hs.canvas.turtle:_background(func, ...) -> turtleViewObject --- Method --- Perform the specified function asynchronously as coroutine that yields after a certain number of turtle commands have been executed. This gives turtle drawing which involves many steps the appearance of being run in the background, allowing other functions within Hammerspoon the opportunity to handle callbacks, etc. --- --- Parameters: --- * `func` - the function which contains the turtle commands to be executed asynchronously. This function should expect at least 1 argument -- `self`, which will be the turtleViewObject itself, and any other arguments passed to this method. --- * `...` - optional additional arguments to be passed to `func` when it is invoked. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * If a background function is already being run on the turtle view, this method will queue the new function to be executed when the currently running function, and any previously queued functions, have completed. --- --- * Backgrounding like this may take a little longer to complete the function, but will not block Hammerspoon from completing other tasks and will make your system significantly more responsive during long running tasks. --- * See [hs.canvas.turtle:_yieldRatio](#_yieldRatio) to adjust how many turtle commands are executed before each yield. This can have an impact on the total time a function takes to complete by trading Hammerspoon responsiveness for function speed. --- * See [hs.canvas.turtle:_neverYield](#_neverYield) to prevent this behavior and cause the queued function(s) to run to completion before returning. If a function has already been backgrounded, once it resumes, the function will continue (followed by any additionally queued background functions) without further yielding. --- --- * As an example, consider this function which generates a fern frond: --- --- ``` --- fern = function(self, size, sign) --- print(size, sign) --- if (size >= 1) then --- self:forward(size):right(70 * sign) --- fern(self, size * 0.5, sign * -1) --- self:left(70 * sign):forward(size):left(70 * sign) --- fern(self, size * 0.5, sign) --- self:right(70 * sign):right(7 * sign) --- fern(self, size - 1, sign) --- self:left(7 * sign):back(size * 2) --- end --- end --- --- tc = require("hs.canvas.turtle") --- --- -- drawing the two fronds without backgrounding: --- t = os.time() --- tc1 = tc.turtleCanvas() --- tc1:penup():back(150):pendown() --- fern(tc1, 25, 1) --- fern(tc1, 25, -1) --- print("Blocked for", os.time() - t) -- 4 seconds on my machine --- --- -- drawing the two fronds with backgrounding --- -- note that if we don't hide this while its drawing, it will take significantly longer --- -- as Hammerspoon has to update the view as it's being built. With the hiding, this --- -- also took 4 seconds on my machine to complete; without, it took 24. In both cases, --- -- however, it didn't block Hammerspoon and allowed for a more responsive experience. --- t = os.time() --- tc2 = tc.turtleCanvas() --- tc2:hide():penup() --- :back(150) --- :pendown() --- :_background(fern, 25, 1) --- :_background(fern, 25, -1) --- :_background(function(self) --- self:show() --- print("Completed in", os.time() - t) --- end) --- print("Blocked for", os.time() - t) --- ``` turtleMT._background = function(self, func, ...) if not (type(func) == "function" or (getmetatable(func) or {}).__call) then error("expected function for argument 1", 2) end local runner = _backgroundQueues[self] or { queue = {} } table.insert(runner.queue, fnutils.partial(func, self, ...)) if not runner.ourCoroutine then _backgroundQueues[self] = runner runner.ourCoroutine = coroutine.wrap(function() while #runner.queue ~= 0 do table.remove(runner.queue, 1)() end runner.ourCoroutine = nil end) runner.ourCoroutine() end return self end turtleMT.bye = function(self, doItNoMatterWhat) local c = self:_canvas() if c then doItNoMatterWhat = doItNoMatterWhat or (c[#c].canvas == self and c[#c].id == "turtleView") if doItNoMatterWhat then if c[#c].canvas == self then c[#c].canvas = nil else for i = 1, #c, 1 do if c[i].canvas == self then c[i].canvas = nil break end end end c:delete() else log.f("bye - not a known turtle only canvas; apply delete method to parent canvas, or pass in `true` as argument to this method") end else log.f("bye - not attached to a canvas") end end turtleMT.show = function(self, doItNoMatterWhat) local c = self:_canvas() if c then doItNoMatterWhat = doItNoMatterWhat or (c[#c].canvas == self and c[#c].id == "turtleView") if doItNoMatterWhat then c:show() else log.f("show - not a known turtle only canvas; apply show method to parent canvas, or pass in `true` as argument to this method") end else log.f("show - not attached to a canvas") end return self end turtleMT.hide = function(self, doItNoMatterWhat) local c = self:_canvas() if c then doItNoMatterWhat = doItNoMatterWhat or (c[#c].canvas == self and c[#c].id == "turtleView") if doItNoMatterWhat then c:hide() else log.f("hide - not a known turtle only canvas; apply hide method to parent canvas, or pass in `true` as argument to this method") end else log.f("hide - not attached to a canvas") end return self end -- 6.1 Turtle Motion --- hs.canvas.turtle:forward(dist) -> turtleViewObject --- Method --- Moves the turtle forward in the direction that it’s facing, by the specified distance. The heading of the turtle does not change. --- --- Parameters: --- * `dist` - the distance the turtle should move forwards. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:fd(dist)` --- hs.canvas.turtle:back(dist) -> turtleViewObject --- Method --- Move the turtle backward, (i.e. opposite to the direction that it's facing) by the specified distance. The heading of the turtle does not change. --- --- Parameters: --- * `dist` - the distance the turtle should move backwards. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:bk(dist)` --- hs.canvas.turtle:left(angle) -> turtleViewObject --- Method --- Turns the turtle counterclockwise by the specified angle, measured in degrees --- --- Parameters: --- * `angle` - the number of degrees to adjust the turtle's heading counterclockwise. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:lt(angle)` --- hs.canvas.turtle:right(angle) -> turtleViewObject --- Method --- Turns the turtle clockwise by the specified angle, measured in degrees --- --- Parameters: --- * `angle` - the number of degrees to adjust the turtle's heading clockwise. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:rt(angle)` --- hs.canvas.turtle:setpos(pos) -> turtleViewObject --- Method --- Moves the turtle to an absolute position in the graphics window. Does not change the turtle's heading. --- --- Parameters: --- * `pos` - a table containing two numbers specifying the `x` and the `y` position within the turtle view to move the turtle to. (Note that this is *not* a point table with key-value pairs). --- --- Returns: --- * the turtleViewObject --- hs.canvas.turtle:setxy(x, y) -> turtleViewObject --- Method --- Moves the turtle to an absolute position in the graphics window. Does not change the turtle's heading. --- --- Parameters: --- * `x` - the x coordinate of the turtle's new position within the turtle view --- * `y` - the y coordinate of the turtle's new position within the turtle view --- --- Returns: --- * the turtleViewObject --- hs.canvas.turtle:setx(x) -> turtleViewObject --- Method --- Moves the turtle horizontally from its old position to a new absolute horizontal coordinate. Does not change the turtle's heading. --- --- Parameters: --- * `x` - the x coordinate of the turtle's new position within the turtle view --- --- Returns: --- * the turtleViewObject --- hs.canvas.turtle:sety(y) -> turtleViewObject --- Method --- Moves the turtle vertically from its old position to a new absolute vertical coordinate. Does not change the turtle's heading. --- --- Parameters: --- * `y` - the y coordinate of the turtle's new position within the turtle view --- --- Returns: --- * the turtleViewObject --- hs.canvas.turtle:setheading(angle) -> turtleViewObject --- Method --- Sets the heading of the turtle to a new absolute heading. --- --- Parameters: --- * `angle` - The heading, in degrees clockwise from the positive Y axis, of the new turtle heading. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:seth(angle)` --- hs.canvas.turtle:home() -> turtleViewObject --- Method --- Moves the turtle to the center of the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * this is equivalent to `hs.canvas.turtle:setxy(0, 0):setheading(0)`. --- * this does not change the pen state, so if the pen is currently down, a line may be drawn from the previous position to the home position. --- hs.canvas.turtle:arc(angle, radius) -> turtleViewObject --- Method --- Draws an arc of a circle, with the turtle at the center, with the specified radius, starting at the turtle’s heading and extending clockwise through the specified angle. The turtle does not move. --- --- Parameters: --- * `angle` - the number of degrees the arc should extend from the turtle's current heading. Positive numbers indicate that the arc should extend in a clockwise direction, negative numbers extend in a counter-clockwise direction. --- * `radius` - the distance from the turtle's current position that the arc should be drawn. --- --- Returns: --- * the turtleViewObject -- 6.2 Turtle Motion Queries -- pos - documented where defined -- xcor - documented where defined -- ycor - documented where defined -- heading - documented where defined -- towards - documented where defined -- scrunch - documented where defined -- 6.3 Turtle and Window Control -- showturtle - documented where defined -- hideturtle - documented where defined -- clean - documented where defined -- clearscreen - documented where defined -- wrap - no-op -- implemented, but does nothing to simplify conversion to/from logo -- window - no-op -- implemented, but does nothing to simplify conversion to/from logo -- fence - no-op -- implemented, but does nothing to simplify conversion to/from logo -- fill - not implemented at present -- filled - not implemented at present; a similar effect can be had with `:fillStart()` and `:fillEnd()` --- hs.canvas.turtle:label(text) -> turtleViewObject --- Method --- Displays a string at the turtle’s position current position in the current pen mode and color. --- --- Parameters: --- * `text` - --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * does not move the turtle --- hs.canvas.turtle:setlabelheight(height) -> turtleViewObject --- Method --- Sets the font size for text displayed with the [hs.canvas.turtle:label](#label) method. --- --- Parameters: --- * `height` - a number specifying the font size --- --- Returns: --- * the turtleViewObject -- textscreen - no-op -- implemented, but does nothing to simplify conversion to/from logo -- fullscreen - no-op -- implemented, but does nothing to simplify conversion to/from logo -- splitscreen - no-op -- implemented, but does nothing to simplify conversion to/from logo --- hs.canvas.turtle:setscrunch(xscale, yscale) -> turtleViewObject --- Method --- Adjusts the aspect ratio and scaling within the turtle view. Further turtle motion will be adjusted by multiplying the horizontal and vertical extent of the motion by the two numbers given as inputs. --- --- Parameters: --- * `xscale` - a number specifying the horizontal scaling applied to the turtle position --- * `yscale` - a number specifying the vertical scaling applied to the turtle position --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * On old CRT monitors, it was common that pixels were not exactly square and this method could be used to compensate. Now it is more commonly used to create scaling effects. -- refresh - no-op -- implemented, but does nothing to simplify conversion to/from logo -- norefresh - no-op -- implemented, but does nothing to simplify conversion to/from logo -- 6.4 Turtle and Window Queries -- shownp - documented where defined -- screenmode - documented where defined -- turtlemode - documented where defined -- labelsize - documented where defined -- 6.5 Pen and Background Control --- hs.canvas.turtle:pendown() -> turtleViewObject --- Method --- Sets the pen’s position to down so that movement methods will draw lines in the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:pd()` --- hs.canvas.turtle:penup() -> turtleViewObject --- Method --- Sets the pen’s position to up so that movement methods do not draw lines in the turtle view. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:pu()` --- hs.canvas.turtle:penpaint() -> turtleViewObject --- Method --- Sets the pen’s position to DOWN and mode to PAINT. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:ppt()` --- --- * this mode is equivalent to `hs.canvas.compositeTypes.sourceOver` --- hs.canvas.turtle:penerase() -> turtleViewObject --- Method --- Sets the pen’s position to DOWN and mode to ERASE. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:pe()` --- --- * this mode is equivalent to `hs.canvas.compositeTypes.destinationOut` --- hs.canvas.turtle:penreverse() -> turtleViewObject --- Method --- Sets the pen’s position to DOWN and mode to REVERSE. --- --- Parameters: --- * None --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:px()` --- --- * this mode is equivalent to `hs.canvas.compositeTypes.XOR` --- hs.canvas.turtle:setpencolor(color) -> turtleViewObject --- Method --- Sets the pen color (the color the turtle draws when it moves and the pen is down). --- --- Parameters: --- * `color` - one of the following types: --- * an integer greater than or equal to 0 specifying an entry in the color palette (see [hs.canvas.turtle:setpalette](#setpalette)). If the index is outside of the defined palette, defaults to black (index entry 0). --- * a string matching one of the names of the predefined colors as described in [hs.canvas.turtle:setpalette](#setpalette). --- * a string starting with "#" followed by 6 hexadecimal digits specifying a color in the HTML style. --- * a table of 3 or 4 numbers between 0.0 and 100.0 specifying the percent saturation of red, green, blue, and optionally the alpha channel. --- * a color as defined in `hs.drawing.color` --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:setpc(color)` --- hs.canvas.turtle:setpalette(index, color) -> turtleViewObject --- Method --- Assigns the color to the palette at the given index. --- --- Parameters: --- * `index` - an integer between 8 and 255 inclusive specifying the slot within the palette to assign the specified color. --- * `color` - one of the following types: --- * an integer greater than or equal to 0 specifying an entry in the color palette (see Notes). If the index is outside the range of the defined palette, defaults to black (index entry 0). --- * a string matching one of the names of the predefined colors as described in the Notes. --- * a string starting with "#" followed by 6 hexadecimal digits specifying a color in the HTML style. --- * a table of 3 or 4 numbers between 0.0 and 100.0 specifying the percent saturation of red, green, blue, and optionally the alpha channel. --- * a color as defined in `hs.drawing.color` --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Attempting to modify color with an index of 0-7 are silently ignored. --- --- * An assigned color has no label for use when doing a string match with [hs.canvas.turtle:setpencolor](#setpencolor) or [hs.canvas.turtle:setbackground](#setbackground). Changing the assigned color to indexes 8-15 will clear the default label. --- --- * The initial palette is defined as follows: --- * 0 - "black" 1 - "blue" 2 - "green" 3 - "cyan" --- * 4 - "red" 5 - "magenta" 6 - "yellow" 7 - "white" --- * 8 - "brown" 9 - "tan" 10 - "forest" 11 - "aqua" --- * 12 - "salmon" 13 - "purple" 14 - "orange" 15 - "gray" --- hs.canvas.turtle:setpensize(size) -> turtleViewObject --- Method --- Sets the thickness of the pen. --- --- Parameters: --- * `size` - a number or table of two numbers (for horizontal and vertical thickness) specifying the size of the turtle's pen. --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * this method accepts two numbers for compatibility reasons - macOS uses a square pen for drawing. -- setpenpattern - no-op -- implemented, but does nothing to simplify conversion to/from logo -- setpen - documented where defined --- hs.canvas.turtle:setbackground(color) -> turtleViewObject --- Method --- Sets the turtle view background color. --- --- Parameters: --- * `color` - one of the following types: --- * an integer greater than or equal to 0 specifying an entry in the color palette (see [hs.canvas.turtle:setpalette](#setpalette)). If the index is outside of the defined palette, defaults to black (index entry 0). --- * a string matching one of the names of the predefined colors as described in [hs.canvas.turtle:setpalette](#setpalette). --- * a string starting with "#" followed by 6 hexadecimal digits specifying a color in the HTML style. --- * a table of 3 or 4 numbers between 0.0 and 100.0 specifying the percent saturation of red, green, blue, and optionally the alpha channel. --- * a color as defined in `hs.drawing.color` --- --- Returns: --- * the turtleViewObject --- --- Notes: --- * Synonym: `hs.canvas.turtle:setbg(...)` -- 6.6 Pen Queries -- pendownp - documented where defined -- penmode - documented where defined -- pencolor - documented where defined -- palette - documented where defined -- pensize - documented where defined -- penpattern - no-op -- implemented to simplify pen and setpen, but returns nil -- pen - documented where defined -- background - documented where defined -- 6.7 Saving and Loading Pictures -- savepict - not implemented at present -- loadpict - not implemented at present -- epspict - not implemented at present; a similar function can be found with `:_image()` -- 6.8 Mouse Queries -- mousepos - not implemented at present -- clickpos - not implemented at present -- buttonp - not implemented at present -- button - not implemented at present -- Others (unique to this module) -- _background - documented where defined -- _neverYield - not implemented at present -- _yieldRatio - not implemented at present -- _pause - -- _image -- _translate -- _visibleAxes -- _turtleImage -- _turtleSize -- bye -- fillend -- fillstart -- hide -- labelfont -- setlabelfont -- show -- Internal use only, no need to fully document at present -- _appendCommand -- _canvas -- _cmdCount -- _commands -- _palette -- _fontMap = {...}, -- new -- turtleCanvas for i, v in ipairs(_wrappedCommands) do local cmdLabel, cmdNumber = v[1], i - 1 -- local synonyms = v[2] or {} if not cmdLabel:match("^_") then if not turtleMT[cmdLabel] then -- this needs "special" help not worth changing the validation code in internal.m for if cmdLabel == "setpensize" then turtleMT[cmdLabel] = function(self, ...) local args = table.pack(...) if type(args[1]) ~= "table" then args[1] = { args[1], args[1] } end local result = self:_appendCommand(cmdNumber, table.unpack(args)) if type(result) == "string" then error(result, 2) ; end coroutineFriendlyCheck(self) return result end else turtleMT[cmdLabel] = function(self, ...) local result = self:_appendCommand(cmdNumber, ...) if type(result) == "string" then error(result, 2) ; end coroutineFriendlyCheck(self) return result end end else log.wf("%s - method already defined; can't wrap", cmdLabel) end end end for k, v in pairs(_nops) do if not turtleMT[k] then turtleMT[k] = function(self, ...) if not _nops[k] then log.f("%s - method is a nop and has no effect for this implemntation", k) _nops[k] = true end return self end else log.wf("%s - method already defined; can't assign as nop", k) end end -- Return Module Object -------------------------------------------------- turtleMT.__indexLookup = turtleMT.__index turtleMT.__index = function(self, key) -- handle the methods as they are defined if turtleMT.__indexLookup[key] then return turtleMT.__indexLookup[key] end -- no "logo like" command will start with an underscore if key:match("^_") then return nil end -- all logo commands are defined as lowercase, so convert the passed in key to lower case and... local lcKey = key:lower() -- check against the defined logo methods again if turtleMT.__indexLookup[lcKey] then return turtleMT.__indexLookup[lcKey] end -- check against the synonyms for the defined logo methods that wrap _appendCommand for i,v in ipairs(_wrappedCommands) do if lcKey == v[1] then return turtleMT.__indexLookup[v[1]] end for i2, v2 in ipairs(v[2]) do if lcKey == v2 then return turtleMT.__indexLookup[v[1]] end end end -- check against the synonyms for the defined logo methods that are defined explicitly for k,v in pairs(_unwrappedSynonyms) do for i2, v2 in ipairs(v) do if lcKey == v2 then return turtleMT.__indexLookup[k] end end end return nil -- not really necessary as none is interpreted as nil, but I like to be explicit end return module
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0173-Read-Generic-Network-Signal-data.md -- -- Description: SDL applies since, until parameters for custom VehicleData -- Precondition: -- 1. Preloaded file contains VehicleDataItems for all RPC spec VD -- 2. App1 is registered with majorVersion = 3.0 -- 3. App2 is registered with majorVersion = 5.9 -- 4. PTU is performed, the update contains single VehicleDataItems with since, until parameters -- 5. Custom VD is allowed -- Sequence: -- 1. SubscribeVD/GetVD/UnsubscribeVD with custom VD is requested from mobile app --   a. SDL applies since, until parameters -- b. SDL processes the requests according to defined since, until parameters in update --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/API/VehicleData/GenericNetworkSignalData/commonGenericNetSignalData') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false config.application1.registerAppInterfaceParams.syncMsgVersion.majorVersion = 3 config.application1.registerAppInterfaceParams.syncMsgVersion.minorVersion = 0 config.application2.registerAppInterfaceParams.syncMsgVersion.majorVersion = 5 config.application2.registerAppInterfaceParams.syncMsgVersion.minorVersion = 9 --[[ Local Variables ]] local itemInteger local vehicleDataName = "custom_vd_item1_integer" local validVDvalueForApp1 = 50 local validVDvalueForApp2 = 150 for VDkey, VDitem in pairs (common.customDataTypeSample)do if VDitem.name == vehicleDataName then itemInteger = common.cloneTable(common.customDataTypeSample[VDkey]) common.customDataTypeSample[VDkey]["since"] = "1.0" common.customDataTypeSample[VDkey]["until"] = "5.0" itemInteger.minvalue = 101 itemInteger.maxvalue = 1000 itemInteger.since = "5.0" end end table.insert(common.customDataTypeSample, itemInteger) common.writeCustomDataToGeneralArray(common.customDataTypeSample) common.setDefaultValuesForCustomData() local appSessionId1 = 1 local appSessionId2 = 2 local function setNewParams() common.VehicleDataItemsWithData[vehicleDataName].value = validVDvalueForApp2 end local function getVehicleDataGenericError(pAppId, pData) local mobRequestData = { [common.VehicleDataItemsWithData[pData].name] = true } local hmiRequestData = common.getHMIrequestData(pData) local hmiResponseData = common.getVehicleDataResponse(pData) local cid = common.getMobileSession(pAppId):SendRPC("GetVehicleData", mobRequestData) common.getHMIConnection():ExpectRequest("VehicleInfo.GetVehicleData", hmiRequestData) :Do(function(_, data) common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", hmiResponseData) end) common.getMobileSession(pAppId):ExpectResponse(cid, { success = false, resultCode = "GENERIC_ERROR" }) end local function onVD2AppsWithDifferentValues() common.VehicleDataItemsWithData[vehicleDataName].value = validVDvalueForApp1 local HMInotifData1 = common.getVehicleDataResponse(vehicleDataName) common.VehicleDataItemsWithData[vehicleDataName].value = validVDvalueForApp2 local HMInotifData2, mobileNotifData2 = common.getVehicleDataResponse(vehicleDataName) common.getHMIConnection():SendNotification("VehicleInfo.OnVehicleData", HMInotifData1) common.getHMIConnection():SendNotification("VehicleInfo.OnVehicleData", HMInotifData2) common.getMobileSession(1):ExpectNotification("OnVehicleData", mobileNotifData2) common.getMobileSession(2):ExpectNotification("OnVehicleData", mobileNotifData2) common.wait(500) end local function subscriptionFor2Apps() local vehicleData = common.VehicleDataItemsWithData[vehicleDataName] local mobileRequest = { [vehicleDataName] = true } local hmiRequestData = common.getHMIrequestData(vehicleDataName) local hmiResponseData = { [vehicleData.key] = { dataType = common.CUSTOM_DATA_TYPE, resultCode = "SUCCESS" } } local cid1 = common.getMobileSession(1):SendRPC("SubscribeVehicleData", mobileRequest) common.getHMIConnection():ExpectRequest("VehicleInfo.SubscribeVehicleData", hmiRequestData) :Do(function(_, data) common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", hmiResponseData) end) local mobileResponseData = { [vehicleDataName] = common.cloneTable(hmiResponseData[vehicleData.key]) } mobileResponseData[vehicleDataName].oemCustomDataType = vehicleData.type mobileResponseData.success = true mobileResponseData.resultCode = "SUCCESS" common.getMobileSession(1):ExpectResponse(cid1, mobileResponseData) :ValidIf(function(_,data) return common.validation(data.payload, mobileResponseData, "SubscribeVehicleData response") end) :Do(function() local cid2 = common.getMobileSession(2):SendRPC("SubscribeVehicleData", mobileRequest) common.getMobileSession(2):ExpectResponse(cid2, mobileResponseData) :ValidIf(function(_,data) return common.validation(data.payload, mobileResponseData, "SubscribeVehicleData response") end) end) common.getMobileSession(1):ExpectNotification("OnHashChange") common.getMobileSession(2):ExpectNotification("OnHashChange") end -- [[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Set ApplicationListUpdateTimeout=4000", common.setSDLIniParameter, { "ApplicationListUpdateTimeout", 4000 }) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("App1 registration", common.registerAppWOPTU, { appSessionId1 }) runner.Step("App2 registration", common.registerAppWOPTU, { appSessionId2 }) runner.Step("App1 activation", common.activateApp, { appSessionId1 }) runner.Step("PTU with VehicleDataItems", common.ptuWithPolicyUpdateReq, { common.ptuFuncWithCustomData2Apps }) runner.Step("App2 activation", common.activateApp, { appSessionId2 }) runner.Title("Test") runner.Step("App1 SubscribeVehicleData " .. vehicleDataName, common.VDsubscription, { appSessionId1, vehicleDataName, "SubscribeVehicleData" }) runner.Step("App1 OnVehicleData " .. vehicleDataName, common.onVD, { appSessionId1, vehicleDataName, common.VD.NOT_EXPECTED }) runner.Step("App1 UnsubscribeVehicleData " .. vehicleDataName, common.VDsubscription, { appSessionId1, vehicleDataName, "UnsubscribeVehicleData" }) runner.Step("App1 GetVehicleData " .. vehicleDataName, getVehicleDataGenericError, { appSessionId1, vehicleDataName }) runner.Step("App2 SubscribeVehicleData " .. vehicleDataName, common.VDsubscription, { appSessionId2, vehicleDataName, "SubscribeVehicleData" }) runner.Step("App2 OnVehicleData " .. vehicleDataName, common.onVD, { appSessionId2, vehicleDataName, common.VD.NOT_EXPECTED }) runner.Step("App2 UnsubscribeVehicleData " .. vehicleDataName, common.VDsubscription, { appSessionId2, vehicleDataName, "UnsubscribeVehicleData" }) runner.Step("App2 GetVehicleData " .. vehicleDataName, getVehicleDataGenericError, { appSessionId2, vehicleDataName }) runner.Step("Update parameter values according to since and until values", setNewParams) runner.Step("App2 SubscribeVehicleData " .. vehicleDataName .. " with updated values", common.VDsubscription, { appSessionId2, vehicleDataName, "SubscribeVehicleData" }) runner.Step("App2 OnVehicleData " .. vehicleDataName, common.onVD, { appSessionId2, vehicleDataName, common.VD.EXPECTED }) runner.Step("App2 UnsubscribeVehicleData " .. vehicleDataName .. " with updated values", common.VDsubscription, { appSessionId2, vehicleDataName, "UnsubscribeVehicleData" }) runner.Step("App2 GetVehicleData " .. vehicleDataName .. " with updated values", common.GetVD, { appSessionId2, vehicleDataName }) runner.Step("App1 SubscribeVehicleData " .. vehicleDataName .. " with updated values", common.VDsubscription, { appSessionId1, vehicleDataName, "SubscribeVehicleData" }) runner.Step("App1 OnVehicleData " .. vehicleDataName .. " with updated values", common.onVD, { appSessionId1, vehicleDataName, common.VD.EXPECTED }) runner.Step("App1 UnsubscribeVehicleData " .. vehicleDataName .. " with updated values", common.VDsubscription, { appSessionId1, vehicleDataName, "UnsubscribeVehicleData" }) runner.Step("App1 GetVehicleData " .. vehicleDataName .. " with updated values", common.GetVD, { appSessionId1, vehicleDataName }) runner.Step("SubscribeVehicleData for 2 apps " .. vehicleDataName, subscriptionFor2Apps) runner.Step("Two apps onVehicleData " .. vehicleDataName, onVD2AppsWithDifferentValues) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
-- Theme: zephyr -- Author: Glepnir -- License: MIT -- Source: http://github.com/glepnir/zephyr-nvim local zephyr = { base0 = "#1B2229", base1 = "#1c1f24", base2 = "#202328", base3 = "#23272e", base4 = "#3f444a", base5 = "#5B6268", base6 = "#73797e", base7 = "#9ca0a4", base8 = "#b1b1b1", base99 = "#293238", bg = "#282a36", bg1 = "#504945", dark = "#5c6370", dark2 = "#373d48", bg_popup = "#3e4556", bg_highlight = "#2E323C", bg_highlight2 = "#4E525C", bg_visual = "#b3deef", fg = "#bbc2cf", fg_alt = "#5B6268", light_red = "#3d3c3c", -- light_red = '#4d3e3f', light_yellow = "#3d3d3c", -- light_yellow = '#4d3f2a', light_blue = "#42424c", light_teal = "#1f4d3e", light_green = "#abcf84", pale_red = "#e06c75", dark_orange = "#ff922b", red = "#e95678", redwine = "#d16d9e", orange = "#D98E48", yellow = "#f0c674", yellowgreen = "#aed75f", pink = "#c678dd", green = "#afd700", dark_green = "#98be65", cyan = "#14ffff", cyan2 = "#65a7c5", blue = "#51afef", blue2 = "#7ec0ee", blue3 = "#9cd0fa", blue4 = "#7685b1", blue5 = "#5486c0", violet = "#b294bb", magenta = "#c678dd", -- teal = "#1abc9c", teal = "#15aabf", grey = "#928374", brown = "#c78665", black = "#000000", bracket = "#80a0c2", cursor_bg = "#4f5b66", none = "NONE", } function zephyr.terminal_color() vim.g.terminal_color_0 = zephyr.bg vim.g.terminal_color_1 = zephyr.red vim.g.terminal_color_2 = zephyr.green vim.g.terminal_color_3 = zephyr.yellow vim.g.terminal_color_4 = zephyr.blue vim.g.terminal_color_5 = zephyr.violet vim.g.terminal_color_6 = zephyr.cyan vim.g.terminal_color_7 = zephyr.bg_visual vim.g.terminal_color_8 = zephyr.brown vim.g.terminal_color_9 = zephyr.red vim.g.terminal_color_10 = zephyr.green vim.g.terminal_color_11 = zephyr.yellow vim.g.terminal_color_12 = zephyr.blue vim.g.terminal_color_13 = zephyr.violet vim.g.terminal_color_14 = zephyr.cyan vim.g.terminal_color_15 = zephyr.fg end function zephyr.highlight(group, color) local style = color.style and "gui=" .. color.style or "gui=NONE" local fg = color.fg and "guifg=" .. color.fg or "guifg=NONE" local bg = color.bg and "guibg=" .. color.bg or "guibg=NONE" local sp = color.sp and "guisp=" .. color.sp or "" vim.api.nvim_command("highlight " .. group .. " " .. style .. " " .. fg .. " " .. bg .. " " .. sp) end function zephyr.load_syntax() local syntax = { Normal = { fg = zephyr.fg, bg = zephyr.bg }, Terminal = { fg = zephyr.fg, bg = zephyr.bg }, SignColumn = { fg = zephyr.fg, bg = zephyr.bg }, FoldColumn = { fg = zephyr.fg_alt, bg = zephyr.black }, VertSplit = { fg = zephyr.black, bg = zephyr.bg }, Folded = { fg = zephyr.grey, bg = zephyr.bg_highlight2 }, EndOfBuffer = { fg = zephyr.bg, bg = zephyr.none }, IncSearch = { fg = zephyr.bg1, bg = zephyr.orange, style = zephyr.none }, Search = { fg = zephyr.bg, bg = zephyr.orange }, Conceal = { fg = zephyr.grey, bg = zephyr.none }, Cursor = { fg = zephyr.none, bg = zephyr.none, style = "reverse" }, vCursor = { fg = zephyr.none, bg = zephyr.none, style = "reverse" }, iCursor = { fg = zephyr.none, bg = zephyr.none, style = "reverse" }, lCursor = { fg = zephyr.none, bg = zephyr.none, style = "reverse" }, ColorColumn = { fg = zephyr.none, bg = zephyr.dark2 }, CursorIM = { fg = zephyr.none, bg = zephyr.none, style = "reverse" }, CursorColumn = { fg = zephyr.none, bg = zephyr.dark2 }, CursorLine = { fg = zephyr.none, bg = zephyr.dark2 }, LineNr = { fg = zephyr.base5, bg = zephyr.none }, qfLineNr = { fg = zephyr.cyan }, CursorLineNr = { fg = zephyr.pink, style = "bold" }, netrwDir = { fg = zephyr.pink }, qfFileName = { fg = zephyr.yellowgreen }, DiffAdd = { fg = zephyr.black, bg = zephyr.dark_green }, DiffChange = { fg = zephyr.black, bg = zephyr.yellow }, DiffDelete = { fg = zephyr.black, bg = zephyr.red }, DiffText = { fg = zephyr.black, bg = zephyr.fg }, Directory = { fg = zephyr.blue, bg = zephyr.none }, ErrorMsg = { fg = zephyr.red, bg = zephyr.none, style = "bold" }, WarningMsg = { fg = zephyr.yellow, bg = zephyr.none, style = "bold" }, ModeMsg = { fg = zephyr.fg, bg = zephyr.none, style = "bold" }, MatchParen = { fg = zephyr.red, bg = zephyr.none }, NonText = { fg = zephyr.bg1 }, Whitespace = { fg = zephyr.base4 }, SpecialKey = { fg = zephyr.bg1 }, Pmenu = { fg = zephyr.fg, bg = zephyr.bg_popup }, PmenuSel = { fg = zephyr.base0, bg = zephyr.blue }, PmenuSelBold = { fg = zephyr.base0, g = zephyr.blue }, PmenuSbar = { fg = zephyr.none, bg = zephyr.base4 }, PmenuThumb = { fg = zephyr.violet, bg = zephyr.light_green }, WildMenu = { fg = zephyr.fg, bg = zephyr.green }, Question = { fg = zephyr.yellow }, NormalFloat = { fg = zephyr.base8, bg = zephyr.bg_highlight }, TabLineFill = { style = zephyr.none }, TabLineSel = { bg = zephyr.blue }, StatusLine = { fg = zephyr.base8, bg = zephyr.base2, style = zephyr.none }, StatusLineNC = { fg = zephyr.grey, bg = zephyr.base2, style = zephyr.none }, SpellBad = { fg = zephyr.red, bg = zephyr.none, style = "undercurl" }, SpellCap = { fg = zephyr.blue, bg = zephyr.none, style = "undercurl" }, SpellLocal = { fg = zephyr.cyan, bg = zephyr.none, style = "undercurl" }, SpellRare = { fg = zephyr.violet, bg = zephyr.none, style = "undercurl" }, Visual = { fg = zephyr.black, bg = zephyr.bracket }, VisualNOS = { fg = zephyr.black, bg = zephyr.bracket }, QuickFixLine = { fg = zephyr.violet, style = "bold" }, Debug = { fg = zephyr.orange }, debugBreakpoint = { fg = zephyr.bg, bg = zephyr.red }, Boolean = { fg = zephyr.orange }, Number = { fg = zephyr.brown }, Float = { fg = zephyr.brown }, PreProc = { fg = zephyr.violet }, PreCondit = { fg = zephyr.violet }, Include = { fg = zephyr.violet }, Define = { fg = zephyr.violet }, Conditional = { fg = zephyr.magenta }, Repeat = { fg = zephyr.magenta }, Keyword = { fg = zephyr.green }, Typedef = { fg = zephyr.red }, Exception = { fg = zephyr.red }, Statement = { fg = zephyr.red }, Error = { fg = zephyr.red }, StorageClass = { fg = zephyr.orange }, Tag = { fg = zephyr.orange }, Label = { fg = zephyr.orange }, Structure = { fg = zephyr.orange }, Operator = { fg = zephyr.redwine }, Title = { fg = zephyr.orange, style = "bold" }, Special = { fg = zephyr.yellow }, SpecialChar = { fg = zephyr.yellow }, Type = { fg = zephyr.teal }, Function = { fg = zephyr.yellow }, String = { fg = zephyr.light_green }, Character = { fg = zephyr.green }, Constant = { fg = zephyr.cyan }, Macro = { fg = zephyr.cyan }, Identifier = { fg = zephyr.blue }, Comment = { fg = zephyr.base6 }, SpecialComment = { fg = zephyr.grey }, Todo = { fg = zephyr.orange, style = "italic" }, Delimiter = { fg = zephyr.fg }, Ignore = { fg = zephyr.grey }, Underlined = { fg = zephyr.none, style = "underline" }, } return syntax end function zephyr.load_plugin_syntax() local plugin_syntax = { TSFunction = { fg = zephyr.cyan }, TSComment = { fg = zephyr.dark }, TSMethod = { fg = zephyr.cyan }, TSKeywordFunction = { fg = zephyr.red }, TSProperty = { fg = zephyr.yellow }, TSType = { fg = zephyr.teal }, TSVariable = { fg = zephyr.blue }, TSPunctBracket = { fg = zephyr.bracket }, vimCommentTitle = { fg = zephyr.grey, style = "bold" }, vimLet = { fg = zephyr.orange }, vimVar = { fg = zephyr.cyan }, vimFunction = { fg = zephyr.redwine }, vimIsCommand = { fg = zephyr.fg }, vimCommand = { fg = zephyr.blue }, vimNotFunc = { fg = zephyr.violet, style = "bold" }, vimUserFunc = { fg = zephyr.yellow, style = "bold" }, vimFuncName = { fg = zephyr.yellow, style = "bold" }, diffAdded = { fg = zephyr.dark_green }, diffRemoved = { fg = zephyr.red }, diffChanged = { fg = zephyr.blue }, diffOldFile = { fg = zephyr.yellow }, diffNewFile = { fg = zephyr.orange }, diffFile = { fg = zephyr.aqua }, diffLine = { fg = zephyr.grey }, diffIndexLine = { fg = zephyr.violet }, gitcommitSummary = { fg = zephyr.red }, gitcommitUntracked = { fg = zephyr.grey }, gitcommitDiscarded = { fg = zephyr.grey }, gitcommitSelected = { fg = zephyr.grey }, gitcommitUnmerged = { fg = zephyr.grey }, gitcommitOnBranch = { fg = zephyr.grey }, gitcommitArrow = { fg = zephyr.grey }, gitcommitFile = { fg = zephyr.dark_green }, GitGutterAdd = { fg = zephyr.dark_green }, GitGutterChange = { fg = zephyr.blue }, GitGutterDelete = { fg = zephyr.red }, GitGutterChangeDelete = { fg = zephyr.violet }, GitSignsAdd = { fg = zephyr.dark_green }, GitSignsChange = { fg = zephyr.blue }, GitSignsDelete = { fg = zephyr.red }, GitSignsAddNr = { fg = zephyr.dark_green }, GitSignsChangeNr = { fg = zephyr.blue }, GitSignsDeleteNr = { fg = zephyr.red }, GitSignsAddLn = { bg = zephyr.bg_popup }, GitSignsChangeLn = { bg = zephyr.bg_highlight }, GitSignsDeleteLn = { bg = zephyr.bg1 }, SignifySignAdd = { fg = zephyr.dark_green }, SignifySignChange = { fg = zephyr.blue }, SignifySignDelete = { fg = zephyr.red }, dbui_tables = { fg = zephyr.blue }, LspDiagnosticsSignError = { fg = zephyr.pale_red }, LspDiagnosticsSignWarning = { fg = zephyr.dark_orange }, LspDiagnosticsSignInformation = { fg = zephyr.blue }, LspDiagnosticsSignHint = { fg = zephyr.teal }, LspDiagnosticsVirtualTextError = { fg = zephyr.pale_red, bg = zephyr.light_red }, LspDiagnosticsVirtualTextWarning = { fg = zephyr.dark_orange, bg = zephyr.light_yellow }, LspDiagnosticsVirtualTextInformation = { fg = zephyr.blue, bg = zephyr.light_blue }, LspDiagnosticsVirtualTextHint = { fg = zephyr.teal, bg = zephyr.light_teal }, LspDiagnosticsUnderlineError = { style = "undercurl", sp = zephyr.pale_red }, LspDiagnosticsUnderlineWarning = { style = "undercurl", sp = zephyr.dark_orange }, LspDiagnosticsUnderlineInformation = { style = "undercurl", sp = zephyr.blue }, LspDiagnosticsUnderlineHint = { style = "undercurl", sp = zephyr.teal }, LspReferenceRead = { bg = zephyr.base4 }, LspReferenceText = { bg = zephyr.base4 }, LspReferenceWrite = { bg = zephyr.base4 }, TroubleCount = { bg = zephyr.bg_highlight2, fg = zephyr.magenta }, TroubleFile = { fg = zephyr.blue, style = "bold" }, TroubleTextError = { fg = zephyr.red }, TroubleTextWarning = { fg = zephyr.yellow }, TroubleTextInformation = { fg = zephyr.blue }, TroubleTextHint = { fg = zephyr.teal }, BqfPreviewBorder = { fg = zephyr.blue }, BqfSign = { fg = zephyr.red }, BqfPreviewRange = "fg = zephyr.red", CursorWord0 = { bg = zephyr.cursor_bg }, CursorWord1 = { bg = zephyr.none }, CursorWord = { bg = zephyr.none }, NvimTreeFolderName = { fg = zephyr.blue }, NvimTreeRootFolder = { fg = zephyr.base5, style = "bold" }, NvimTreeEmptyFolderName = { fg = zephyr.base5 }, NvimTreeSpecialFile = { fg = zephyr.fg, bg = zephyr.none, style = "NONE" }, NvimTreeOpenedFolderName = { fg = zephyr.base5 }, TelescopeNormal = { fg = zephyr.fg }, TelescopeBorder = { fg = zephyr.blue2, bg = zephyr.bg }, TelescopeResultsBorder = { fg = zephyr.blue2, bg = zephyr.bg }, TelescopePromptBorder = { fg = zephyr.blue2, bg = zephyr.bg }, TelescopePreviewBorder = { fg = zephyr.magenta, bg = zephyr.bg }, TelescopeMatching = { fg = zephyr.yellowgreen, style = "bold" }, TelescopeSelection = { fg = zephyr.cyan, style = "bold" }, TelescopeSelectionCaret = { fg = zephyr.yellow }, TelescopeMultiSelection = { fg = zephyr.light_green }, TelescopePromptPrefix = { fg = zephyr.yellow }, FloatermBorder = { fg = zephyr.blue2, bg = zephyr.bg }, DashboardShortCut = { fg = zephyr.blue4 }, DashboardHeader = { fg = zephyr.blue2 }, DashboardCenter = { fg = zephyr.blue2 }, DashboardFooter = { fg = zephyr.cyan2, style = "bold" }, WhichKey = { fg = zephyr.blue2 }, WhichKeyName = { fg = zephyr.pink }, WhichKeyTrigger = { fg = zephyr.black }, WhichKeyFloating = { fg = zephyr.red }, WhichKeySeperator = { fg = zephyr.blue3 }, WhichKeyGroup = { fg = zephyr.blue2 }, WhichKeyDesc = { fg = zephyr.blue3 }, } return plugin_syntax end local async_load_plugin async_load_plugin = vim.loop.new_async(vim.schedule_wrap(function() zephyr.terminal_color() local syntax = zephyr.load_plugin_syntax() for group, colors in pairs(syntax) do zephyr.highlight(group, colors) end async_load_plugin:close() end)) function zephyr.colorscheme() vim.api.nvim_command("hi clear") if vim.fn.exists("syntax_on") then vim.api.nvim_command("syntax reset") end vim.o.background = "dark" vim.o.termguicolors = true vim.g.colors_name = "zephyr" local syntax = zephyr.load_syntax() for group, colors in pairs(syntax) do zephyr.highlight(group, colors) end async_load_plugin:send() end zephyr.colorscheme() return zephyr
local Camera = require(_G.enginedir .. "middleclass")('Camera') function Camera:initialize() self.config = { x = 0 } end function Camera:update(dt) self.config.x = 1 end function CameraUpdateValue (table) if type(table) ~= "table" then print("You should put a table as parameter[1]."); return false end end -- Prevent Multi/Instanciage -- local DefaultInstance = Camera:new(); -- End return { Camera = Camera, Default = DefaultInstance, Instances = {} }
--[[********************************** * * Multi Theft Auto - Admin Panel * * admin_screenshot.lua * * Original File by lil_Toady * **************************************]] local aScreenShots = { pending = {}, quality = { [SCREENSHOT_QLOW] = { w = 320, h = 240, q = 30, b = 2500, }, [SCREENSHOT_QMEDIUM] = { w = 640, h = 480, q = 50, b = 2000, }, [SCREENSHOT_QHIGH] = { w = 1024, h = 768, q = 70, b = 1500, } } } addEvent ( EVENT_SCREEN_SHOT, true ) addEventHandler ( EVENT_SCREEN_SHOT, _root, function ( action, id, ... ) if ( action == SCREENSHOT_SAVE ) then elseif ( action == SCREENSHOT_DELETE ) then end end ) function getPlayerScreen ( player, admin, q ) if ( not q ) then q = SCREENSHOT_QLOW end local quality = aScreenShots.quality[q] if ( not quality ) then quality = aScreenShots.quality[SCREENSHOT_QLOW] end local tag = "a"..math.random ( 1, 1000 ) while ( aScreenShots.pending[tag] ~= nil ) do tag = "a"..math.random ( 1, 1000 ) end takePlayerScreenShot( player, quality.w, quality.h, tag, quality.q, quality.b ) local timeout = getTickCount () + 1000 * 60 * 15 local account = 'Unknown' if ( admin and isElement ( admin ) ) then local acc = getPlayerAccount ( admin ) if ( isGuestAccount ( acc ) ) then account = string.gsub ( getPlayerName ( admin ), '#%x%x%x%x%x%x', '' ) else account = getAccountName ( acc ) end end aScreenShots.pending[tag] = { player = player, playername = getPlayerName ( player ), admin = admin, account = account, timeout = timeout } end local function collectTimedOutScreenShots () for tag, data in pairs ( aScreenShots.pending ) do local timeout = data.timeout if ( ( not timeout ) or ( getTickCount () > timeout ) ) then aScreenShots.pending[tag] = nil end end end local function removeTempScreenShots () local query = db.query ( "SELECT file FROM screenshots WHERE temp = 1" ) if ( query ) then for i, row in ipairs ( query ) do if ( fileExists ( "screenshots\\"..row.file ) ) then fileDelete ( "screenshots\\"..row.file ) end end end db.exec ( "DELETE FROM screenshots WHERE temp = 1" ) end local function getFileFriendlyName ( string ) if ( not string ) then return "" end local result = "" for s in string.gmatch ( string, "%a+" ) do result = result..s end return result end addEventHandler ( "onResourceStart", getResourceRootElement (), function () db.exec ( "CREATE TABLE IF NOT EXISTS screenshots ( file TEXT, player TEXT, admin TEXT, description TEXT, time INTEGER, temp BOOL )" ) removeTempScreenShots () end ) addEventHandler ( "onPlayerScreenShot", _root, function ( resource, status, jpeg, time, tag ) collectTimedOutScreenShots () if ( resource ~= getThisResource () ) then return end local data = aScreenShots.pending[tag] if ( not data ) then return end local id = 0 if ( status == "ok" ) then -- save a local copy local time = getRealTime () local file_time = string.format ( "%.2d-%.2d-%.2d_%.2d-%.2d-%.2d", time.year + 1900, time.month + 1, time.monthday, time.hour, time.minute, time.second ) local file_counter = 1 local file_player = getFileFriendlyName ( data.playername ) if ( file_player == "" ) then file_player = "screen" end local file_name = file_player..'_'..file_time..'.jpg' while ( fileExists ( "screenshots\\"..file_name ) ) do file_name = file_player..'_'..file_time..'_'..file_counter..'.jpg' file_counter = file_counter + 1 end local file = fileCreate ( "screenshots\\"..file_name ) if ( file ) then fileWrite ( file, jpeg ) fileClose ( file ) local query = "INSERT INTO screenshots (file,player,admin,description,time,temp) VALUES (?,?,?,?,?,?)" db.exec ( query, file_name, data.playername or 'Unknown', data.account or 'Unknown', "Toady's driving like a boss", time.timestamp, 0 ) id = db.last_insert_id () end else jpeg = nil end -- making sure the bastard didn't leave yet local admin = data.admin if ( ( not admin ) or ( not isElement ( admin ) ) or ( getElementType ( admin ) ~= 'player' ) ) then return end triggerClientEvent ( admin, EVENT_SCREEN_SHOT, admin, status, file_name, id, jpeg ) end )
local lu = require('luaunit') local ProcessBuilder = require('jls.lang.ProcessBuilder') local loader = require('jls.lang.loader') local Pipe = loader.tryRequire('jls.io.Pipe') local File = require('jls.io.File') local FileDescriptor = require('jls.io.FileDescriptor') local loop = require('jls.lang.loopWithTimeout') local logger = require('jls.lang.logger') local LUA_PATH = ProcessBuilder.getExecutablePath() logger:fine('Lua path is "'..tostring(LUA_PATH)..'"') function Test_pipe() --lu.runOnlyIf(Pipe) if not Pipe then lu.success() end local text = 'Hello world!' local pb = ProcessBuilder:new(LUA_PATH, '-e', 'print("'..text..'")') --pb:environment({'A_KEY=VALUE A', 'B_KEY=VALUE B'}) local p = Pipe:new() pb:redirectOutput(p) local ph = pb:start() --print('pid', ph:getPid()) local outputData p:readStart(function(err, data) if data then outputData = string.gsub(data, '%s*$', '') else p:close() end end) if not loop(function() p:close() end) then lu.fail('Timeout reached') end lu.assertEquals(outputData, text) lu.assertEquals(ph:isAlive(), false) end function Test_env() if not Pipe then lu.success() end local text = 'Hello world!' local pb = ProcessBuilder:new({LUA_PATH, '-e', 'print(os.getenv("A_KEY"))'}) pb:environment({'A_KEY='..text, 'B_KEY=VALUE B'}) local p = Pipe:new() pb:redirectOutput(p) local ph = pb:start() local outputData p:readStart(function(err, data) if data then outputData = string.gsub(data, '%s*$', '') else p:close() end end) if not loop(function() p:close() end) then lu.fail('Timeout reached') end lu.assertEquals(outputData, text) lu.assertEquals(ph:isAlive(), false) end function Test_exitCode() local code = 11 local pb = ProcessBuilder:new({LUA_PATH, '-e', 'os.exit('..tostring(code)..')'}) local exitCode local ph = pb:start(function(c) exitCode = c end) if not loop() then lu.fail('Timeout reached') end lu.assertEquals(exitCode, code) if ph then lu.assertEquals(ph:isAlive(), false) end end function Test_redirect() if not loader.getRequired('luv') then lu.success() end local tmpFile = File:new('test.tmp') if tmpFile:exists() then tmpFile:delete() end local fd = FileDescriptor.openSync(tmpFile, 'w') local pb = ProcessBuilder:new({LUA_PATH, '-e', 'io.write("Hello")'}) pb:redirectOutput(fd) local exitCode local ph = pb:start(function(c) fd:close() exitCode = c end) if not loop(function() ph:destroy() fd:close() tmpFile:delete() end) then lu.fail('Timeout reached') end local output = tmpFile:readAll() tmpFile:delete() lu.assertEquals(exitCode, 0) lu.assertEquals(output, 'Hello') end os.exit(lu.LuaUnit.run())
--!nocheck local function makeTests(try, BitBuffer) local writeTest = try("writeFloat16 tests") local readTest = try("readFloat16 tests") writeTest("Should require the argument be a number", function() local buffer = BitBuffer() buffer.writeFloat16({}) end).fail() writeTest("Should write positive integers to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(1337) assert(buffer.dumpBinary() == "01100101 00111001", "") end).pass() writeTest("Should write positive fractions to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(0.69420) assert(buffer.dumpBinary() == "00111001 10001110", "") end).pass() writeTest("Should write positive fractions to the stream properly after a bit", function() local buffer = BitBuffer() buffer.writeBits(1) buffer.writeFloat16(0.69420) assert(buffer.dumpBinary() == "10011100 11000111 0", "") end).pass() writeTest("Should write positive mixed numbers to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(19.85) assert(buffer.dumpBinary() == "01001100 11110110", "") end).pass() writeTest("Should write positive infinity to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(math.huge) assert(buffer.dumpBinary() == "01111100 00000000", "") end).pass() writeTest("Should write positive subnormal numbers to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(0.000041067600250244140625) assert(buffer.dumpBinary() == "00000010 10110001", "") end).pass() writeTest("Should write negative integers to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(-1337) assert(buffer.dumpBinary() == "11100101 00111001", "") end).pass() writeTest("Should write negative fractions to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(-0.69420) assert(buffer.dumpBinary() == "10111001 10001110", "") end).pass() writeTest("Should write negative fractions to the stream properly after a bit", function() local buffer = BitBuffer() buffer.writeBits(1) buffer.writeFloat16(-0.69420) assert(buffer.dumpBinary() == "11011100 11000111 0", "") end).pass() writeTest("Should write negative mixed numbers to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(-19.85) assert(buffer.dumpBinary() == "11001100 11110110", "") end).pass() writeTest("Should write negative infinity to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(-math.huge) assert(buffer.dumpBinary() == "11111100 00000000", "") end).pass() writeTest("Should write negative subnormal numbers to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(-0.000041067600250244140625) assert(buffer.dumpBinary() == "10000010 10110001", "") end).pass() writeTest("Should write NaN to the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(0/0) assert(buffer.dumpBinary() == "01111111 11111111", "") end).pass() writeTest("Should write a bit to the stream properly after a positive mixed number", function() local buffer = BitBuffer() buffer.writeFloat16(19.85) buffer.writeBits(1) assert(buffer.dumpBinary() == "01001100 11110110 1", "") end).pass() writeTest("Should write a bit to the stream properly after a negative mixed number", function() local buffer = BitBuffer() buffer.writeFloat16(-19.85) buffer.writeBits(1) assert(buffer.dumpBinary() == "11001100 11110110 1", "") end).pass() readTest("Should require no arguments", function() local buffer = BitBuffer() buffer.writeFloat16(10) buffer.readFloat16() end).pass() readTest("Should read positive integers from the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(1337) assert(buffer.readFloat16() == 1337, "") end).pass() readTest("Should read positive fractions from the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(0.69420) assert(buffer.readFloat16() == 0.6943359375, "") end).pass() readTest("Should read positive mixed numbers from the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(19.85) assert(buffer.readFloat16() == 19.84375, "") end).pass() readTest("Should read positive infinity from the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(math.huge) assert(buffer.readFloat16() == math.huge, "") end).pass() readTest("Should read negative integers from the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(-1337) assert(buffer.readFloat16() == -1337, "") end).pass() readTest("Should read negative fractions from the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(-0.69420) assert(buffer.readFloat16() == -0.6943359375, "") end).pass() readTest("Should read negative mixed numbers from the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(-19.85) assert(buffer.readFloat16() == -19.84375, "") end).pass() readTest("Should read negative infinity from the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(-math.huge) assert(buffer.readFloat16() == -math.huge, "") end).pass() readTest("Should read NaN from the stream properly", function() local buffer = BitBuffer() buffer.writeFloat16(0/0) local x = buffer.readFloat16() assert(x ~= x, "") end).pass() readTest("Should read a bit from the stream properly after a positive mixed number", function() local buffer = BitBuffer() buffer.writeFloat16(19.85) buffer.writeBits(1) buffer.readFloat16() assert(buffer.readBits(1)[1] == 1, "") end).pass() readTest("Should read a bit from the stream properly after a negative mixed number", function() local buffer = BitBuffer() buffer.writeFloat16(-19.85) buffer.writeBits(1) buffer.readFloat16() assert(buffer.readBits(1)[1] == 1, "") end).pass() readTest("Should not allow reading past the end of the stream", function() local buffer = BitBuffer() buffer.readFloat16() end).fail() local writeTestPassed = writeTest.run() local readTestPassed = readTest.run() return writeTestPassed and readTestPassed end return makeTests
local core = require "sys.core" local socket = require "sys.socket" local ssl = require "sys.netssl" local stream = require "http.stream" local dns = require "sys.dns" local assert = assert local tonumber = tonumber local format = string.format local match = string.match local insert = table.insert local concat = table.concat local client = {} local http_agent = format("User-Agent: Silly/%s", core.version) local function parseurl(url) local default = false local scheme, host, port, path= match(url, "(http[s]-)://([^:/]+):?(%d*)(.*)") if path == "" then path = "/" end if port == "" then if scheme == "https" then port = "443" elseif scheme == "http" then port = "80" else assert(false, "unsupport parse url scheme:" .. scheme) end default = true end return scheme, host, port, path, default end local function send_request(io_do, fd, method, host, abs, header, body) local tmp insert(header, 1, format("%s %s HTTP/1.1", method, abs)) insert(header, format("Host: %s", host)) insert(header, format("Content-Length: %d", #body)) insert(header, http_agent) insert(header, "Connection: keep-alive") insert(header, "") insert(header, body) tmp = concat(header, "\r\n") io_do.write(fd, tmp) end local function recv_response(io_do, fd) local readl = io_do.readline local readn = io_do.read local status, first, header, body = stream.readrequest(fd, readl, readn) if not status then --disconnected return nil end if status ~= 200 then return status end local ver, status= first:match("HTTP/([%d|.]+)%s+(%d+)") return tonumber(status), header, body, ver end local function process(uri, method, header, body) local ip, io_do local scheme, host, port, path, default = parseurl(uri) ip = dns.resolve(host, "A") assert(ip, host) if scheme == "https" then io_do = ssl elseif scheme == "http" then io_do = socket end if not default then host = format("%s:%s", host, port) end ip = format("%s:%s", ip, port) local fd = io_do.connect(ip) if not fd then return 599 end if not header then header = {} end body = body or "" send_request(io_do, fd, method, host, path, header, body) local status, header, body, ver = recv_response(io_do, fd) io_do.close(fd) return status, header, body, ver end function client.GET(uri, header) return process(uri, "GET", header) end function client.POST(uri, header, body) return process(uri, "POST", header, body) end return client
-- The sequence task is similar to an \"and\" operation. -- It will return failure as soon as one of its child tasks return failure. -- If a child task returns success then it will sequentially run the next task. -- If all child tasks return success then it will return success. local Status = require('bt.task.task_status') local Composite = require('bt.composite.composite') local mt = {} mt.__index = mt function mt.new(cls) local self = Composite.new(cls) self.cur_child = 0 self.run_status = Status.inactive return self end function mt:get_cur_child_idx() return self.cur_child end function mt:can_execute() return self.cur_idx < #self.children and self.run_status ~= Status.failure end function mt:on_child_executed(idx, status) self.cur_child = idx +1 self.run_status = status end function mt:on_contional_abort(idx) -- Set the current child index to the index that caused the abort self.cur_child = idx +1 self.run_status = Status.inactive end function mt:on_end() self.run_status = Status.inactive self.cur_child = 0 end return mt
local normalizer = require "kong.plugins.header-translator.normalize_header" describe("Normalizer", function() it("should lowercase the given input", function() assert.are.equal("x_suite_customer_id", normalizer("X_Suite_Customer_Id")) end) it("should change dash to underscore in the given input", function() assert.are.equal("x_suite_customer_id", normalizer("X-Suite-Customer-Id")) end) end)
local discordia = require("discordia") require("../discordia-interactions") -- [[ Patch Following Classes Into Discordia ]] require("client/Client") require("containers/abstract/Component") require("containers/abstract/TextChannel") require("containers/Message") -- [[ Patch Discordia's Enums to Add New Types ]] do local enums = require("enums") local discordiaEnums = discordia.enums local enum = discordiaEnums.enum for k, v in pairs(enums) do discordiaEnums[k] = enum(v) end end local module = { Button = require("components/Button"), SelectMenu = require("components/SelectMenu"), Components = require("containers/Components") } -- [[ Patch the Module into Discordia as a Shortcut]] do for k, v in pairs(module) do discordia[k] = v end end return module
--furnace-t1.lua local accumulatorFurnace = table.deepcopy(data.raw["furnace"]["stone-furnace"]) accumulatorFurnace.name = "furnace-mk1" accumulatorFurnace.icons = { { icon = accumulatorFurnace.icon, tint = {r=1,g=0,b=0} }, } accumulatorFurnace.crafting_speed = 2 accumulatorFurnace.energy_source = { type = "electric", energy_usage = "140kW", usage_priority = "secondary-input", drain = "100W", emissions_per_minute = 1 } accumulatorFurnace.minable.result = "furnace-mk1" accumulatorFurnace.animation = { layers = { { filename = "__base__/graphics/entity/stone-furnace/stone-furnace.png", tint = {r=1,g=0,b=0}, priority = "extra-high", width = 81, height = 64, frame_count = 1, shift = util.by_pixel(14.5, 2), hr_version = { filename = "__base__/graphics/entity/stone-furnace/hr-stone-furnace.png", tint = {r=1,g=0,b=0}, priority = "extra-high", width = 151, height = 146, frame_count = 1, shift = util.by_pixel(-0.25, 6), scale = 0.5 } }, { filename = "__base__/graphics/entity/stone-furnace/stone-furnace-shadow.png", tint = {r=1,g=0,b=0}, priority = "extra-high", width = 81, height = 64, frame_count = 1, draw_as_shadow = true, shift = util.by_pixel(14.5, 2), hr_version = { filename = "__base__/graphics/entity/stone-furnace/hr-stone-furnace-shadow.png", priority = "extra-high", width = 164, height = 74, frame_count = 1, draw_as_shadow = true, shift = util.by_pixel(14.5, 13), scale = 0.5 } } } } accumulatorFurnace.working_visualisations = { { north_position = {0.0, 0.0}, east_position = {0.0, 0.0}, south_position = {0.0, 0.0}, west_position = {0.0, 0.0}, animation = { filename = "__base__/graphics/entity/stone-furnace/stone-furnace-fire.png", tint = {r=1,g=0,b=0}, priority = "extra-high", line_length = 8, width = 20, height = 49, frame_count = 48, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(-0.5, 5.5), hr_version = { filename = "__base__/graphics/entity/stone-furnace/hr-stone-furnace-fire.png", tint = {r=1,g=0,b=0}, priority = "extra-high", line_length = 8, width = 41, height = 100, frame_count = 48, axially_symmetrical = false, direction_count = 1, shift = util.by_pixel(-0.75, 5.5), scale = 0.5 } }, light = {intensity = 1, size = 1, color = {r=1.0, g=1.0, b=1.0}} } } accumulatorFurnace.water_reflection = { pictures = { filename = "__base__/graphics/entity/steel-furnace/steel-furnace-reflection.png", priority = "extra-high", width = 20, height = 24, shift = util.by_pixel(0, 45), variation_count = 1, scale = 5, }, rotate = false, orientation_to_variation = false } data:extend{accumulatorFurnace} data:extend( { { type = "item", name = "furnace-mk1", icon = "__furnacesPlus__/graphics/icons/stone-furnace.png", icon_size = 64, icon_mipmaps = 4, subgroup = "smelting-machine", place_result = "furnace-mk1", stack_size = 5, order = "z+" }, { type = "recipe", enabled = false, energy_required = 30, name = "furnace-mk1", icon_size = 64, icon_mipmaps = 4, ingredients = {{"stone", 25}, {"electronic-circuit", 20}, {"iron-stick", 20}}, result = "furnace-mk1" }, { type = "technology", enabled = true, name = "furnace-mk1", icon_size = 64, icon = "__furnacesPlus__/graphics/icons/stone-furnace.png", prerequisites = {"electronics", "automation", "logistics"}, effects = { { type = "unlock-recipe", recipe = "furnace-mk1" } }, unit = { count = 250, ingredients = {{"automation-science-pack", 1}}, time = 20 }, order = "a-b-a" } } )
local PlaceID = game.PlaceID local Http = game:GetService("HttpService") local AllIDs = {} local foundAnything = "" local actualHour = os.date("!*t").hour local Deleted = false if isfile("NotSameServers.json") then Http:JSONDecode(readfile("NotSameServers.json")) else table.insert(AllIDs, actualHour) writefile("NotSameServers.json", Http:JSONEncode(AllIDs)) end function TPReturner() local Site if foundAnything == "" then Site = game.HttpService:JSONDecode( game:HttpGet("https://games.roblox.com/v1/games/" .. PlaceID .. "/servers/Public?sortOrder=Asc&limit=100") ) else Site = game.HttpService:JSONDecode( game:HttpGet( "https://games.roblox.com/v1/games/" .. PlaceID .. "/servers/Public?sortOrder=Asc&limit=100&cursor=" .. foundAnything ) ) end local ID = "" if Site.nextPageCursor and Site.nextPageCursor ~= "null" and Site.nextPageCursor ~= nil then foundAnything = Site.nextPageCursor end local num = 0 for i, v in pairs(Site.data) do local Possible = true ID = tostring(v.id) if tonumber(v.maxPlayers) > tonumber(v.playing) then for _, Existing in pairs(AllIDs) do if num ~= 0 then if ID == tostring(Existing) then Possible = false end else if tonumber(actualHour) ~= tonumber(Existing) then local delFile = pcall(function() delfile("NotSameServers.json") AllIDs = {} table.insert(AllIDs, actualHour) end) end end num = num + 1 end if Possible == true then table.insert(AllIDs, ID) task.wait() pcall(function() writefile("NotSameServers.json", game:GetService("HttpService"):JSONEncode(AllIDs)) task.wait() game:GetService("TeleportService"):TeleportToPlaceInstance(PlaceID, ID, game.Players.LocalPlayer) end) task.wait(4) end end end end function Teleport() while task.wait() do pcall(function() TPReturner() if foundAnything ~= "" then TPReturner() end end) end end
local SP = SmoothyPlates local Utils = SP.Utils local Trinket = SP.Addon:NewModule('Trinket', 'AceTimer-3.0', 'AceEvent-3.0') -- Stolen from Healers GladiatorlosSA2 local trinketspellIds = { [195901] = true, [214027] = true, [42292] = true, [208683] = true, -- Gladiator's Medallion Legion [195710] = true, -- Honorable Medallion Legion [336126] = true -- Gladiator's Medallion Shadowlands } local playerUsedTrinket = {} local TrinketTexture SP.hookOnClean( function() Trinket:CleanUp() end ) function Trinket:OnEnable() SP.SmoothyPlate.RegisterFrame('Arena Trinket', 'TRINKET') self:RegisterEvent('PLAYER_ENTERING_WORLD') TrinketTexture = GetSpellTexture(208683) SP.callbacks.RegisterCallback(self, 'AFTER_SP_CREATION', 'CreateElement_TrinketIcon') SP.callbacks.RegisterCallback(self, 'AFTER_SP_UNIT_ADDED', 'UNIT_ADDED') SP.callbacks.RegisterCallback(self, 'BEFORE_SP_UNIT_REMOVED', 'UNIT_REMOVED') end local inArena = false function Trinket:PLAYER_ENTERING_WORLD() if select(2, IsInInstance()) == 'arena' then inArena = true self:ARENA_STATE_CHANGED(true) else if inArena then inArena = false self:ARENA_STATE_CHANGED(false) end end end local timers = {} function Trinket:CleanUp() for _, v in pairs(timers) do self:CancelTimer(v) end timers = {} playerUsedTrinket = {} end function Trinket:ARENA_STATE_CHANGED(isInArena) if isInArena then self:RegisterEvent('COMBAT_LOG_EVENT_UNFILTERED') else self:UnregisterEvent('COMBAT_LOG_EVENT_UNFILTERED') end end function Trinket:CreateElement_TrinketIcon(_, plate) local sp = plate.SmoothyPlate.sp local w, h = SP.Layout.HW('TRINKET') local a, p, x, y = SP.Layout.APXY('TRINKET', sp) local TrinketIcon = CreateFrame('Frame', nil, sp) TrinketIcon:SetSize(w, h) TrinketIcon:SetPoint(a, p, x, y) Utils.createTextureFrame(TrinketIcon, w, h, a, x, y, SP.Layout.GET('TRINKET', 'opacity'), TrinketTexture) TrinketIcon.cd = CreateFrame('Cooldown', nil, TrinketIcon, 'CooldownFrameTemplate') TrinketIcon.cd:SetAllPoints() TrinketIcon.cd:SetHideCountdownNumbers(true) sp['TRINKET'] = TrinketIcon plate.SmoothyPlate:hookFrame('TRINKET') TrinketIcon:Hide() end local GetTime = GetTime local CombatLog_Object_IsA, COMBATLOG_FILTER_HOSTILE_PLAYERS = CombatLog_Object_IsA, COMBATLOG_FILTER_HOSTILE_PLAYERS function Trinket:COMBAT_LOG_EVENT_UNFILTERED() local _, _, _, sourceGUID, _, _, _, _, _, destFlags, _, spellId, _, _, _ = CombatLogGetCurrentEventInfo() if not CombatLog_Object_IsA(destFlags, COMBATLOG_FILTER_HOSTILE_PLAYERS) or not spellId or not sourceGUID then return end if playerUsedTrinket[sourceGUID] then return end if trinketspellIds[spellId] then playerUsedTrinket[sourceGUID] = GetTime() + 180 table.insert( timers, self:ScheduleTimer( function() if playerUsedTrinket[sourceGUID] then playerUsedTrinket[sourceGUID] = nil self:ApplyTrinket(sourceGUID) end end, 180 ) ) else return end self:ApplyTrinket(sourceGUID) end local getPlateByGUID = SP.Nameplates.getPlateByGUID function Trinket:ApplyTrinket(guid, plate, forceHide) if not plate then plate = getPlateByGUID(guid) if not plate then return end end local smp = plate.SmoothyPlate if not inArena or forceHide or not UnitIsPlayer(smp.unitid) then smp.sp.TRINKET:Hide() return end if playerUsedTrinket[guid] then smp.sp.TRINKET.cd:SetCooldown(GetTime() - playerUsedTrinket[guid], 180) smp.sp.TRINKET:Show() else smp.sp.TRINKET.cd:SetCooldown(0, 0) smp.sp.TRINKET:Show() end end function Trinket:UNIT_ADDED(_, plate) self:ApplyTrinket(plate.SmoothyPlate.guid, plate) end function Trinket:UNIT_REMOVED(_, plate) self:ApplyTrinket(plate.SmoothyPlate.guid, plate, true) end
local base = require('imgui.widgets.Window') ---@class xe.Debug:im.Window local M = class('xe.Debug', base) function M:ctor() base.ctor(self, 'Debug') end return M
local currentPlate = "" local currentType = 0 local job = "" local grade = 0 local unitCooldown = false local alertsToggled = true local unitBlipsToggled = true local callBlipsToggled = true local callBlips = {} local blips = {} Citizen.CreateThread(function() while QBCore == nil do TriggerEvent('QBCore:GetObject', function(obj) QBCore = obj end) citizen,Wait(0) end while QBCore.Functions.GetPlayerData().job == nil do Citizen.Wait(10) end job = QBCore.Functions.GetPlayerData().job.name grade = QBCore.Functions.GetPlayerData().job.grade Citizen.Wait(2000) local jobInfo = {} jobInfo[Config.JobOne.job] = { color = Config.JobOne.color, column = 1, label = Config.JobOne.label, canRequestLocalBackup = Config.JobOne.canRequestLocalBackup, canRequestOtherJobBackup = Config.JobOne.canRequestOtherJobBackup, forwardCall = Config.JobOne.forwardCall, canRemoveCall = Config.JobOne.canRemoveCall } jobInfo[Config.JobTwo.job] = { color = Config.JobTwo.color, column = 2, label = Config.JobTwo.label, canRequestLocalBackup = Config.JobTwo.canRequestLocalBackup, canRequestOtherJobBackup = Config.JobTwo.canRequestOtherJobBackup, forwardCall = Config.JobTwo.forwardCall, canRemoveCall = Config.JobTwo.canRemoveCall } jobInfo[Config.JobThree.job] = { color = Config.JobThree.color, column = 3, label = Config.JobThree.label, canRequestLocalBackup = Config.JobThree.canRequestLocalBackup, canRequestOtherJobBackup = Config.JobThree.canRequestOtherJobBackup, forwardCall = Config.JobThree.forwardCall, canRemoveCall = Config.JobThree.canRemoveCall } QBCore.Functions.TriggerCallback( "core_dispach:getPersonalInfo", function(firstname, lastname) SendNUIMessage( { type = "Init", firstname = firstname, lastname = lastname, jobInfo = jobInfo } ) end ) end ) RegisterNetEvent("QBCore:Client:OnJobUpdate") AddEventHandler( "QBCore:Client:OnJobUpdate", function(j) job = j.name grade = j.grade end ) RegisterKeyMapping(Config.OpenMenuCommand, "Open Dispach using " .. Config.OpenMenuKey, "keyboard", Config.OpenMenuKey) RegisterCommand( Config.OpenMenuCommand, function() openDispach() end, false ) RegisterCommand( Config.JobOne.callCommand, function(source, args, rawCommand) local msg = rawCommand:sub(5) local cord = GetEntityCoords(GetPlayerPed(-1)) TriggerServerEvent( "core_dispach:addMessage", msg, {cord[1], cord[2], cord[3]}, Config.JobOne.job, 5000, Config.callCommandSprite, Config.callCommandColor ) end, false ) RegisterCommand( Config.JobTwo.callCommand, function(source, args, rawCommand) local msg = rawCommand:sub(5) local cord = GetEntityCoords(GetPlayerPed(-1)) TriggerServerEvent( "core_dispach:addMessage", msg, {cord[1], cord[2], cord[3]}, Config.JobTwo.job, 5000, Config.callCommandSprite, Config.callCommandColor ) end, false ) RegisterCommand( Config.JobThree.callCommand, function(source, args, rawCommand) local msg = rawCommand:sub(5) local cord = GetEntityCoords(GetPlayerPed(-1)) TriggerServerEvent( "core_dispach:addMessage", msg, {cord[1], cord[2], cord[3]}, Config.JobThree.job, 5000, Config.callCommandSprite, Config.callCommandColor ) end, false ) function addBlipForCall(sprite, color, coords, text) local alpha = 250 local radius = AddBlipForRadius(coords, 40.0) local blip = AddBlipForCoord(coords) SetBlipSprite(blip, sprite) SetBlipDisplay(blip, 4) SetBlipScale(blip, 1.3) SetBlipColour(blip, color) SetBlipAsShortRange(blip, false) BeginTextCommandSetBlipName("STRING") AddTextComponentString(tostring(text)) EndTextCommandSetBlipName(blip) SetBlipHighDetail(radius, true) SetBlipColour(radius, color) SetBlipAlpha(radius, alpha) SetBlipAsShortRange(radius, true) table.insert(callBlips, blip) table.insert(callBlips, radius) while alpha ~= 0 do Citizen.Wait(Config.CallBlipDisappearInterval) alpha = alpha - 1 SetBlipAlpha(radius, alpha) if alpha == 0 then RemoveBlip(radius) RemoveBlip(blip) return end end end function addBlipsForUnits() QBCore.Functions.TriggerCallback( "core_dispach:getUnits", function(units) local id = GetPlayerServerId(PlayerId()) for _, z in pairs(blips) do RemoveBlip(z) end blips = {} for k, v in pairs(units) do if k ~= id and (Config.JobOne.job == v.job or Config.JobTwo.job == v.job or Config.JobThree.job == v.job) then local color = 0 local title = "" if Config.JobOne.job == v.job then color = Config.JobOne.blipColor title = Config.JobOne.label end if Config.JobTwo.job == v.job then color = Config.JobTwo.blipColor title = Config.JobTwo.label end if Config.JobThree.job == v.job then color = Config.JobThree.blipColor title = Config.JobThree.label end local new_blip = AddBlipForEntity(NetworkGetEntityFromNetworkId(v.netId)) SetBlipSprite(new_blip, Config.Sprite[v.type]) ShowHeadingIndicatorOnBlip(new_blip, true) HideNumberOnBlip(new_blip) SetBlipScale(new_blip, 0.7) SetBlipCategory(new_blip, 7) SetBlipColour(new_blip, color) SetBlipAsShortRange(new_blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString("(" .. title .. ") " .. v.firstname .. " " .. v.lastname) EndTextCommandSetBlipName(new_blip) blips[k] = new_blip end end end ) end function openDispach() if Config.JobOne.job == job or Config.JobTwo.job == job or Config.JobThree.job == job then SetNuiFocus(false, false) QBCore.Functions.TriggerCallback( "core_dispach:getInfo", function(units, calls, ustatus) SetNuiFocus(true, true) SendNUIMessage( { type = "open", units = units, calls = calls, ustatus = ustatus, job = job, id = GetPlayerServerId(PlayerId()) } ) end ) end end RegisterNetEvent("core_dispach:callAdded") AddEventHandler( "core_dispach:callAdded", function(id, call, j, cooldown, sprite, color) if job == j and alertsToggled then SendNUIMessage( { type = "call", id = id, call = call, cooldown = cooldown } ) if Config.AddCallBlips then addBlipForCall(sprite, color, vector3(call.coords[1], call.coords[2], call.coords[3]), id) end end end ) RegisterNUICallback( "dismissCall", function(data) local id = data["id"]:gsub("call_", "") TriggerServerEvent("core_dispach:unitDismissed", id) DeleteWaypoint() end ) RegisterNUICallback( "updatestatus", function(data) local id = data["id"] local status = data["status"] TriggerServerEvent("core_dispach:changeStatus", id, status) end ) RegisterNUICallback( "sendnotice", function(data) local caller = data["caller"] if Config.EnableUnitArrivalNotice then TriggerServerEvent("core_dispach:arrivalNotice", caller) end end ) RegisterNetEvent("core_dispach:arrivalNotice") AddEventHandler( "core_dispach:arrivalNotice", function() if not unitCooldown then SendTextMessage(Config.Text["someone_is_reacting"]) unitCooldown = true Citizen.Wait(20000) unitCooldown = false end end ) RegisterNUICallback( "reqbackup", function(data) local j = data["job"] local req = data["requester"] local firstname = data["firstname"] local lastname = data["lastname"] SendTextMessage(Config.Text["backup_requested"]) local cord = GetEntityCoords(GetPlayerPed(-1)) TriggerServerEvent( "core_dispach:addCall", "00-00", req .. " is requesting help", {{icon = "fa-user-friends", info = firstname .. " " .. lastname}}, {cord[1], cord[2], cord[3]}, j ) end ) RegisterNUICallback( "toggleoffduty", function(data) ToggleDuty() end ) RegisterNUICallback( "togglecallblips", function(data) callBlipsToggled = not callBlipsToggled if callBlipsToggled then for _, z in pairs(callBlips) do SetBlipDisplay(z, 4) end SendTextMessage(Config.Text["call_blips_turned_on"]) else for _, z in pairs(callBlips) do SetBlipDisplay(z, 0) end SendTextMessage(Config.Text["call_blips_turned_off"]) end end ) RegisterNUICallback( "toggleunitblips", function(data) unitBlipsToggled = not unitBlipsToggled if unitBlipsToggled then addBlipsForUnits() SendTextMessage(Config.Text["unit_blips_turned_on"]) else for _, z in pairs(blips) do RemoveBlip(z) end blips = {} SendTextMessage(Config.Text["unit_blips_turned_off"]) end end ) RegisterNUICallback( "togglealerts", function(data) alertsToggled = not alertsToggled if alertsToggled then SendTextMessage(Config.Text["alerts_turned_on"]) else SendTextMessage(Config.Text["alerts_turned_off"]) end end ) RegisterNUICallback( "copynumber", function(data) SendTextMessage(Config.Text["phone_number_copied"]) end ) RegisterNUICallback( "forwardCall", function(data) local id = data["id"]:gsub("call_", "") SendTextMessage(Config.Text["call_forwarded"]) TriggerServerEvent("core_dispach:forwardCall", id, data["job"]) end ) RegisterNUICallback( "acceptCall", function(data) local id = data["id"]:gsub("call_", "") SetNewWaypoint(tonumber(data["x"]), tonumber(data["y"])) TriggerServerEvent("core_dispach:unitResponding", id, job) end ) RegisterNUICallback( "removeCall", function(data) local id = data["id"]:gsub("call_", "") SendTextMessage(Config.Text["call_removed"]) TriggerServerEvent("core_dispach:removeCall", id) end ) RegisterNUICallback( "close", function(data) SetNuiFocus(false, false) end ) --Shots in area Citizen.CreateThread( function() while Config.EnableShootingAlerts do Citizen.Wait(10) local whithin = false local ped = PlayerPedId() local playerPos = GetEntityCoords(ped) for _, v in ipairs(Config.ShootingZones) do local distance = #(playerPos - v.coords) if distance < v.radius then whithin = true end end if whithin then if IsPedShooting(ped) and math.random(1, 2) == 1 then local gender = "unknown" local model = GetEntityModel(ped) if (model == GetHashKey("mp_f_freemode_01")) then gender = "female" end if (model == GetHashKey("mp_m_freemode_01")) then gender = "male" end TriggerServerEvent( "core_dispach:addCall", "10-71", "Shots in area", {{icon = "fa-venus-mars", info = gender}}, {playerPos[1], playerPos[2], playerPos[3]}, "police", 5000, 156, 1 ) Citizen.Wait(20000) end else Citizen.Wait(2000) end end end ) Citizen.CreateThread( function() while Config.EnableMapBlipsForUnits do if Config.JobOne.job == job or Config.JobTwo.job == job or Config.JobThree.job == job then if unitBlipsToggled then addBlipsForUnits() end end Citizen.Wait(5000) end end ) Citizen.CreateThread( function() while true do status = { carPlate = currentPlate, type = currentType, job = job, netId = NetworkGetNetworkIdFromEntity(GetPlayerPed(-1)) } TriggerServerEvent("core_dispach:playerStatus", status) Citizen.Wait(1000) end end ) Citizen.CreateThread( function() while true do local ped = PlayerPedId() local vehicle = GetVehiclePedIsIn(ped, false) if vehicle ~= nil then local plate = GetVehicleNumberPlateText(vehicle) if plate ~= nil then currentPlate = plate currentType = GetVehicleClass(vehicle) else currentPlate = "" end end Citizen.Wait(0) end end ) --EXPORTS exports( "addCall", function(code, title, extraInfo, coords, job, cooldown, sprite, color) TriggerServerEvent("core_dispach:addCall", code, title, extraInfo, coords, job, cooldown or 5000, sprite or 11, color or 5) end ) exports( "addMessage", function(message, coords, job, cooldown, sprite, color) TriggerServerEvent("core_dispach:addMessage", message, coords, job, sprite, cooldown or 5000, sprite or 11, color or 5) end )
-- ============================================================= -- b_mover_dpad.lua -- Mover Behavior - dpad Object (Self) -- Behavior Type: Instance -- ============================================================= -- -- ============================================================= --[[ FUNCTIONS IN THIS FILE --]] --behaviors = require("behaviors") public = {} public._behaviorName = "mover_dpad" function public:createInputObj( group, region, params ) --[[ w = display.contentWidth h = display.contentHeight centerX = w/2 centerY = h/2 --]] local region = region or "user" local params = params or {} local rgnParams = {} rgnParams.trans = params.rTrans or 64 if(region == "full") then rgnParams.w = w rgnParams.h = h rgnParams.x = centerX rgnParams.y = centerY elseif(region == "top") then rgnParams.w = w rgnParams.h = h/2 rgnParams.x = centerX rgnParams.y = centerY - h/4 elseif(region == "bot") then rgnParams.w = w rgnParams.h = h/2 rgnParams.x = centerX rgnParams.y = centerY + h/4 elseif(region == "left") then rgnParams.w = w/2 rgnParams.h = h rgnParams.x = centerX - w/4 rgnParams.y = centerY elseif(region == "right") then rgnParams.w = w/2 rgnParams.h = h rgnParams.x = centerX + w/4 rgnParams.y = centerY elseif(region == "ul") then rgnParams.w = w/2 rgnParams.h = h/2 rgnParams.x = centerX - w/4 rgnParams.y = centerY - h/4 elseif(region == "ur") then rgnParams.w = w/2 rgnParams.h = h/2 rgnParams.x = centerX + w/4 rgnParams.y = centerY - h/4 elseif(region == "ll") then rgnParams.w = w/2 rgnParams.h = h/2 rgnParams.x = centerX - w/4 rgnParams.y = centerY + h/4 elseif(region == "lr") then rgnParams.w = w/2 rgnParams.h = h/2 rgnParams.x = centerX + w/4 rgnParams.y = centerY + h/4 elseif(region == "llsquare") then if(h > w) then rgnParams.w = w/2 rgnParams.h = w/2 rgnParams.x = w/4 rgnParams.y = h - w/4 else rgnParams.w = h/2 rgnParams.h = h/2 rgnParams.x = h/4 rgnParams.y = h - h/4 end elseif(region == "lrsquare") then if(h > w) then rgnParams.w = w/2 rgnParams.h = w/2 rgnParams.x = centerX + w/4 rgnParams.y = h - w/4 else rgnParams.w = h/2 rgnParams.h = h/2 rgnParams.x = w - h/4 rgnParams.y = h - h/4 end else rgnParams.w = params.rWidth or w rgnParams.h = params.rHeight or h rgnParams.x = params.rX or centerX rgnParams.y = params.rY or centerY end local inputObj = display.newRect(0, 0, rgnParams.w, rgnParams.h) group:insert(inputObj) inputObj.x = rgnParams.x inputObj.y = rgnParams.y inputObj:setFillColor(128, rgnParams.trans) local dPadSize = params.dPadSize or 80 --local imgPath = params.imgPath or imagesDir .. "dpad.png" local imgPath = imagesDir .. "dpad.png" print(imgPath) --local theDPad = display.newImageRect( group, imgPath, dPadSize, dPadSize ) local theDPad = display.newImageRect( group, imgPath, 100, 100 ) theDPad.x = inputObj.x theDPad.y = inputObj.y inputObj.theDPad = theDPad return inputObj end function public:onAttach( obj, params ) print("Attached Behavior: " .. self._behaviorName) local behaviorInstance = {} behaviorInstance._behaviorName = self._behaviorName -- This method is required (even if it does no work) ==> function behaviorInstance:onDetach( obj ) print("Detached behavior:" .. self._behaviorName) -- ========= ADD YOUR DETACH CODE HERE ======= self.inputObj:removeEventListener( "touch", behaviorInstance ) -- ========= ADD YOUR DETACH CODE HERE ======= end -- ========= ADD YOUR ATTACH CODE HERE ======= if( not params ) then params = {} end -- do initialization work here (like adding functions, fields, etc.) behaviorInstance.inputObj = params.inputObj or obj -- Default to this object as input obj behaviorInstance.moveObj = params.moveObj or obj -- Object to move -- Enable "touch" listener for for the 'inputObj' and pass these events to the 'behaviorInstance' behaviorInstance.inputObj:addEventListener( "touch", behaviorInstance ) -- Event listener for touches on 'inputObj' function behaviorInstance:touch( event ) local target = event.target if(event.phase == "began") then self.lastX = event.x self.lastY = event.y display.getCurrentStage():setFocus( target ) target.isFocus = true elseif(target.isFocus) then if(event.phase == "ended") then self.lastX = nil self.lastY = nil display.getCurrentStage():setFocus( nil ) target.isFocus = false elseif(event.phase == "moved") then if(not self.lastX) then return end local deltaX = event.x - self.lastX local deltaY = event.y - self.lastY self.lastX = event.x self.lastY = event.y self.moveObj.x = self.moveObj.x + deltaX self.moveObj.y = self.moveObj.y + deltaY end end end -- ========= ADD YOUR ATTACH CODE HERE ======= return behaviorInstance end ssk.behaviors:registerBehavior( public._behaviorName, public ) return public
local actor = require "actor" local ACTOR = actor.create() ACTOR:set_name("紫") ACTOR:set_wait(900,800,700,300) return ACTOR
local plugin = script:FindFirstAncestorWhichIsA("Plugin") local UI = {} --- Creates a new UI state for the plugin. -- @param request_spawn A function that when called spawns a character. -- @return state The UI state. It should be passed to other UI functions. function UI.init(request_spawn) -- create and configure our widget local widget = plugin:CreateDockWidgetPluginGui("SuperCharacterLoader", DockWidgetPluginGuiInfo.new( Enum.InitialDockState.Left, -- initial state false, -- whether visible on start true, -- whether it overrides previous visible state 150, -- init width when float 210, -- init height when float 100, -- min width 100 -- min height ) ) widget.Title = "Super Character Loader" -- instantiate our UI (currently template-based) local ui = plugin.CharacterLoader.Frame:Clone() ui.Parent = widget -- create our state object local state = { active = false, current_id = nil, first_load = false, spawn_at_origin = false, input_valid = false, widget = widget, ui = ui, request_spawn = request_spawn } -- voila return state end --- Destroys and clears an UI state, making it invalid. -- @param state The UI state to be cleared. function UI.clear(state) UI.toggle(state, false) state.ui:Destroy() state.ui = nil state.widget:Destroy() state.widget = nil end --- Connects any necessary events to an UI state. -- @param state The UI state to be connected. function UI.hook(state) local contents = state.ui.Contents -- UI element events contents.Buttons.LoadR6.Activated:Connect(function() if not (state.current_id and state.input_valid and state.active) then if not (state.current_id and state.input_valid) then warn("[ERROR] Super Character Loader: please input a valid player name or ID.") end return end state.request_spawn(state.current_id, true, state.spawn_at_origin) end) contents.Buttons.LoadR15.Activated:Connect(function() if not (state.current_id and state.input_valid and state.active) then if not (state.current_id and state.input_valid) then warn("[ERROR] Super Character Loader: please input a valid player name or ID.") end return end state.request_spawn(state.current_id, false, state.spawn_at_origin) end) contents.AtOrigin.Check.Checkmark.Activated:Connect(function() UI._toggle_at_origin(state) end) contents.PlrName.Field.FocusLost:Connect(function() UI._on_input_focus_lost(state) end) contents.PlrName.Field:GetPropertyChangedSignal("AbsoluteSize"):Connect(function() -- keeps the input text under a fixed proportion (TextScaled makes it shrink when it gets long) local plr_field = contents.PlrName.Field plr_field.TextSize = 17/22 * plr_field.AbsoluteSize.Y end) -- widget events state.widget:BindToClose(function() UI.toggle(state, false) end) -- initial state UI._sync_theme(state) UI._update_origin_check(state) settings().Studio.ThemeChanged:Connect(function() UI._sync_theme(state) end) end --- Toggles visibility of a state or sets it to a supplied argument. -- @param state The UI state to toggle visibility. -- @param force_visible If supplied, sets the UI state's visibility to it. -- @return visible The new visible state. function UI.toggle(state, force_visible: boolean?): boolean if force_visible ~= nil then state.active = state.force else state.active = not state.active end if state.active and not state.first_load then -- we do this for the courtesy of not doing web requests at boot state.first_load = true UI._on_input_focus_lost(state) end state.widget.Enabled = state.active return state.active end -- Synchronizes a UI state to studio's theme. function UI._sync_theme(state) local ui = state.ui local theme = settings().Studio.Theme -- we unfortunately have to update everything manually local bg = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground) local text = theme:GetColor(Enum.StudioStyleGuideColor.MainText) local dim_text = theme:GetColor(Enum.StudioStyleGuideColor.DimmedText) local border = theme:GetColor(Enum.StudioStyleGuideColor.Border) local input_bg = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBackground) local button = theme:GetColor(Enum.StudioStyleGuideColor.DialogMainButton) local button_border = theme:GetColor(Enum.StudioStyleGuideColor.DialogButtonBorder) local button_text = theme:GetColor(Enum.StudioStyleGuideColor.DialogMainButtonText) local input_border = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBorder) ui.BackgroundColor3 = bg ui.Contents.Title.TextColor3 = text ui.Contents.Preview.Icon.BorderColor3 = border ui.Contents.Preview.Icon.BackgroundColor3 = bg UI._update_name_field_border(state) ui.Contents.PlrName.Field.BackgroundColor3 = input_bg ui.Contents.PlrName.Field.TextColor3 = text ui.Contents.PlrName.Field.PlaceholderColor3 = dim_text ui.Contents.AtOrigin.Check.Checkmark.BackgroundColor3 = input_bg ui.Contents.AtOrigin.Check.Checkmark.BorderColor3 = input_border ui.Contents.Buttons.LoadR6.BackgroundColor3 = button ui.Contents.Buttons.LoadR6.BorderColor3 = button_border ui.Contents.Buttons.LoadR6.TextLabel.TextColor3 = button_text ui.Contents.Buttons.LoadR15.BackgroundColor3 = button ui.Contents.Buttons.LoadR15.BorderColor3 = button_border ui.Contents.Buttons.LoadR15.TextLabel.TextColor3 = button_text ui.Contents.AtOrigin.Text.Label.TextColor3 = text end -- Updates the player preview. function UI._update_preview_thumbnail(state) if state.current_id then state.ui.Contents.Preview.Icon.Image = "rbxthumb://type=AvatarHeadShot&w=150&h=150&id="..state.current_id end end -- Updates the name input field's border depending on whether the input is valid or not. function UI._update_name_field_border(state) local theme = settings().Studio.Theme if state.input_valid then state.ui.Contents.PlrName.Field.BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.InputFieldBorder) else state.ui.Contents.PlrName.Field.BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.ErrorText) end end -- Updates the "Spawn at (0,0,0)" checkmark. function UI._update_origin_check(state) local button = state.ui.Contents.AtOrigin.Check.Checkmark button.ImageTransparency = state.spawn_at_origin and 0 or 1 end -- Toggles the spawn at origin checkmark. function UI._toggle_at_origin(state) state.spawn_at_origin = not state.spawn_at_origin UI._update_origin_check(state) end -- Fires when the name field is changed by the user. function UI._on_input_focus_lost(state) local Fetcher = require(script.Parent.Fetcher) local id = Fetcher.get_id(state.ui.Contents.PlrName.Field.Text) if id then state.current_id = id state.input_valid = true UI._update_name_field_border(state) UI._update_preview_thumbnail(state) else state.input_valid = false UI._update_name_field_border(state) end end return UI
-- check if within map limits (-30911 to 30927) function within_limits(pos, radius) if (pos.x - radius) > -30913 and (pos.x + radius) < 30928 and (pos.y - radius) > -30913 and (pos.y + radius) < 30928 and (pos.z - radius) > -30913 and (pos.z + radius) < 30928 then return true -- within limits end return false -- beyond limits end set_velocity = function(self, v) self.jumping = false local x = 0 local z = 0 if v and v ~= 0 then local yaw = (self.object:getyaw() + self.rotate) or 0 x = math.sin(yaw) * -v z = math.cos(yaw) * v end self.object:setvelocity({ x = x, y = self.object:getvelocity().y, z = z }) end set_velocity2 = function(self, v, up) local x = 0 local z = 0 if v and v ~= 0 then local yaw = (self.object:getyaw() + self.rotate) or 0 x = math.sin(yaw) * -v z = math.cos(yaw) * v end local y if up then y = up else y = self.object:getvelocity().y end self.object:setvelocity({ x = x, y = y, z = z }) end set_animation = function(self, type) if not self.animation then print("no animation") return end self.animation.current = self.animation.current or "" if type == "stand" then if self.animation.stand_start and self.animation.stand_end and self.animation.speed_normal then self.object:set_animation({ x = self.animation.stand_start, y = self.animation.stand_end}, self.animation.speed_normal, 0) self.animation.current = "stand" end elseif type == "walk" then if self.animation.walk_start and self.animation.walk_end and self.animation.speed_normal then self.object:set_animation({ x = self.animation.walk_start, y = self.animation.walk_end}, self.animation.speed_normal, 0) self.animation.current = "walk" end elseif type == "run" then if self.animation.run_start and self.animation.run_end and self.animation.speed_run then self.object:set_animation({ x = self.animation.run_start, y = self.animation.run_end}, self.animation.speed_run, 0) self.animation.current = "run" end elseif type == "punch" then if self.animation.punch_start and self.animation.punch_end and self.animation.speed_normal then self.object:set_animation({ x = self.animation.punch_start, y = self.animation.punch_end}, self.animation.speed_normal, 0) self.animation.current = "punch" end else print("invalid animation ".. self.inv_id) end end local function animal_step(self, dtime) local btdata = self.btData -- print('newstep') local pos = self.object:getpos() local yaw = self.object:getyaw() or 0 self.bt_timer = self.bt_timer + dtime -- run the behavior tree every two seconds if self.bt_timer > 2 then btdata.pos = pos btdata.yaw = yaw btdata.mob = self -- print("\n<<< start >>> ("..math.floor(pos.x)..","..math.floor(pos.z)..")") -- inventories cannot be serialized and cause the game to crash if -- placed in the entity's table local inv = minetest.get_inventory({type="detached", name=self.inv_id}) btdata.inv = inv bt.tick(self.bt, btdata) -- print("<<< end >>>\n") -- so clear it out after running the behavior trees btdata.inv = nil -- the inventory exists on its own self.bt_timer = 0 end local rpos = vector.round(pos) if not self.node_here or not self.node_below or not vector.equals(self.last_rpos, rpos) then local here = minetest.get_node({x=rpos.x, y=rpos.y, z=rpos.z}) local below = minetest.get_node({x=rpos.x, y=rpos.y-2, z=rpos.z}) self.node_here = here.name self.node_below = below.name -- print("below: ".. self.node_below) self.last_rpos = rpos end -- handle movement local v = self.object:getvelocity() -- TODO: floating local bdef = minetest.registered_nodes[self.node_below] if minetest.registered_nodes[self.node_here].drawtype == "liquid" then -- print("in liquid") self.object:setacceleration({ -- float x = 0, y = 1, z = 0 }) elseif bdef.climbable or bdef.drawtype == "liquid" then self.object:setacceleration({ x = 0, y = 0, z = 0 }) local v = self.object:getvelocity() self.object:setvelocity({x=v.x, y=0, z=v.z}) else self.object:setacceleration({ x = 0, y = self.fall_speed, z = 0 }) end -- TODO: fall damage self.jump_timer = self.jump_timer + dtime if self.destination ~= nil then self.walk_timer = self.walk_timer + dtime --print("destination ") local tdist = distance3(pos, btdata.lastpos) local dist2 = distance(pos, self.destination) -- print("walk dist ".. dist) local s = self.destination local vec = { x = pos.x - s.x, y = pos.y - s.y, z = pos.z - s.z } if tdist < self.walk_velocity * dtime * .9 and self.walk_timer > 1 then if self.jump_timer > 4 then local v = self.object:getvelocity() v.y = self.jump_height + 1 v.x = v.x * 2.2 v.z = v.z * 2.2 self.object:setvelocity(v) self.jump_timer = 0 end end yaw = (math.atan2(vec.z, vec.x) + math.pi / 2) - self.rotate self.object:setyaw(yaw) if dist2 < (self.approachDistance or .1) then -- we have arrived self.destination = nil self.walk_timer = 0 -- TODO: make sure this doesn't lead to infinite loops -- bump bttimer to get new directions self.bt_timer = 99 set_velocity(self, 0) set_animation(self, "stand") else -- TODO look at dy/dxz and see if we need to try to go up if dist2 < (self.approachDistance or .1) then set_velocity(self, 0, self.walk_velocity) else set_velocity(self, self.walk_velocity) set_animation(self, "walk") end end end btdata.lastpos = pos end --[[ moveresult = { touching_ground = boolean, collides = boolean, standing_on_object = boolean, collisions = { { type = string, -- "node" or "object", axis = string, -- "x", "y" or "z" node_pos = vector, -- if type is "node" object = ObjectRef, -- if type is "object" old_velocity = vector, new_velocity = vector, }, ... } } ]] local function walk_dest(self, pos) local s = self.next_wp local vec = { x = pos.x - s.x, y = pos.y - s.y, z = pos.z - s.z } local yaw = (math.atan2(vec.z, vec.x) + math.pi / 2) - self.rotate self.object:set_yaw(yaw) set_velocity(self, self.walk_velocity) set_animation(self, "walk") end local function npc_step(self, dtime, mr) local btdata = self.btData -- print('newstep') local pos = self.object:get_pos() local rpos = { x = math.floor(pos.x + 0.5), y = math.floor(pos.y - 0.4), z = math.floor(pos.z + 0.5) } local bpos = {x = rpos.x, y = rpos.y-1, z= rpos.z} local pos_yr = {x = pos.x, y = rpos.y, z = pos.z} --print(minetest.pos_to_string(pos1) .. " -> " ..minetest.pos_to_string(pos)) local yaw = self.object:get_yaw() or 0 local standing_on_node = nil local standing_on_pos = nil local collisions = {} if mr.standing_on_object == true or mr.touching_ground == true then self.jumping = false end --print(dump(mr)) --print("p.y " .. pos.y..", rp "..minetest.pos_to_string(rpos)) if type(mr.collisions) == "table" then for k,v in pairs(mr.collisions) do if v.type == "node" then local n = minetest.get_node(v.node_pos) if bpos.y == v.node_pos.y then -- print("standing on "..n.name) standing_on_node = n standing_on_pos = v.node_pos else -- print("coll: "..n.name.." at " .. minetest.pos_to_string(v.node_pos)) table.insert(collisions, {p = v.node_pos, n = n}) end end end end self.bt_timer = self.bt_timer + dtime --set_animation(self, "walk") -- run the behavior tree every two seconds if self.run_bt == true and self.bt_timer > 2 then btdata.pos = pos btdata.yaw = yaw btdata.mob = self --print("\n<<< start >>> ("..math.floor(pos.x)..","..math.floor(pos.z)..")") -- inventories cannot be serialized and cause the game to crash if -- placed in the entity's table local inv = minetest.get_inventory({type="detached", name=self.inv_id}) btdata.inv = inv bt.tick(self.bt, btdata) --print("<<< end >>>\n") -- so clear it out after running the behavior trees btdata.inv = nil -- the inventory exists on its own self.bt_timer = 0 self.arrived = false self.walk_aborted = false end -- process new node being stood on if not vector.equals(self.last_rpos, rpos) then if standing_on_node then self.node_below = standing_on_node.name else self.node_below = "air" end --print("below: ".. self.node_below) self.last_rpos = rpos -- don't fall while on ladders if minetest.registered_nodes[self.node_below].climbable then self.object:setacceleration({ x = 0, y = 0, z = 0 }) else self.object:setacceleration({ x = 0, y = self.fall_speed, z = 0 }) end end -- handle movement local v = self.object:get_velocity() -- TODO: floating -- TODO: fall damage self.jump_timer = self.jump_timer + dtime -- handle new destinations if self.internal_dest ~= self.destination then self.internal_dest = self.destination self.last_tdist = nil self.arrived = false self.run_bt = false self.wp_list = {} table.insert(self.wp_list, self.destination) self.next_wp = self.destination --print("new destination: ".. minetest.pos_to_string(self.destination)) walk_dest(self, pos) end if self.next_wp ~= nil then -- target (current waypoint) distance local tdist = distance3(pos, self.next_wp) if self.last_tdist == nil then self.last_tdist = tdist end -- moved distance, since last tick local mdist = distance3(pos, self.last_pos) --print("tdist "..tdist) -- reset the stall timer if we moved if mdist > (dtime * self.walk_velocity * 0.9) then self.stall_timer = 0 end if self.jumping == true then -- collisions stop velocity, so keep pushing forward while jumping local v = self.object:getvelocity() v.x = -math.sin(yaw) * 2.2 v.z = math.cos(yaw) * 2.2 self.object:set_velocity(v) elseif tdist < (self.approachDistance or 0.1) and #self.wp_list <= 1 then -- check arrival if #self.wp_list <= 1 then -- arrived at final destination -- print("final arrival") self.destination = nil self.internal_dest = nil self.wp_list = {} self.next_wp = nil self.arrived = true self.run_bt = true set_velocity(self, 0) set_animation(self, "stand") --[[ elseif tdist <= 0.1 then -- arrived at a waypoint print("arrived at waypoint") table.remove(self.wp_list, 1) self.next_wp = self.wp_list[1] print(" a:next wp: ".. minetest.pos_to_string(self.next_wp)) walk_dest(self, pos)]] else -- print("unhandled arrival case (#wp_list == ".. #self.wp_list..")" -- .. " .. tdist = "..tdist -- ) end elseif self.last_tdist < tdist then -- moving away from the current waypoint -- effectively arrived there, but must find the next best one -- print("passed waypoint") -- TODO: check for final arrival if #self.wp_list == 1 then -- arrived -- bug: gets stuf f you arrive too far away and the btree does not -- run the next cycle. tall stairs with falling near the dest. -- print("a:final arrival, ".. (tdist - (self.approachDistance or 0.1)) .. " too far") --self.jumping = false self.destination = nil self.internal_dest = nil self.wp_list = {} self.next_wp = nil self.arrived = true self.run_bt = true set_velocity(self, 0) set_animation(self, "stand") else table.remove(self.wp_list, 1) self.next_wp = self.wp_list[1] -- print(" b:next wp: ".. minetest.pos_to_string(self.next_wp)) walk_dest(self, pos) end elseif mdist < (dtime * self.walk_velocity * 0.9) then self.stall_timer = self.stall_timer + dtime if self.stall_timer > 0.1 then -- stalled on something -- look for a way around --print("stalled") self.stall_timer = 0 -- check to see if we can just jump over it local should_jump = false local vel = self.object:get_velocity() local fpos = vector.add(pos, {x = -math.sin(yaw), y = .5, z = math.cos(yaw)}) local fnode = minetest.get_node(fpos) if fnode and fnode.name == "air" then should_jump = true end --print("fnode: "..(fnode.name) .. " "..dump(fpos)) if should_jump == true then if self.jump_timer > 2.0 then local v = self.object:getvelocity() v.y = self.jump_height v.x = v.x * 2.2 v.z = v.z * 2.2 self.object:set_velocity(v) self.jump_timer = 0 self.stall_timer = 0 self.jumping = true -- print("jumping") else -- print("waiting to jump") end else -- use the pathfinder local points = minetest.find_path( rpos, self.internal_dest, 10, 1.45, 3, "A*") if points == nil then -- print("failed to find path") self.walk_aborted = true self.wp_list = {} self.next_wp = nil self.run_bt = true set_velocity(self, 0) set_animation(self, "stand") else -- print("found path ".. minetest.pos_to_string(pos)) self.wp_list = {} for k,v in ipairs(points) do v.y = v.y + .5 if k > 1 and not ( v.x == points[k-1].x and v.z == points[k-1].z and v.y ~= points[k-1].y ) then table.insert(self.wp_list, v) --[[ print(k.. " - "..minetest.pos_to_string(v)); minetest.add_particlespawner({ amount = #points, time = .9 * (#points-3), minpos = v, maxpos = v, minvel = {x=-.1, y=-.1, z=-.1}, maxvel = {x=.1, y=.1, z=.1}, minacc = {x=0, y=0, z=0}, maxacc = {x=0, y=0, z=0}, minexptime = 1.05, maxexptime = 1.05, minsize = 4.1, maxsize = 4.1, collisiondetection = false, vertical = false, texture = "tnt_smoke.png^[colorize:#00ff00:300", playername = "singleplayer" }) else if k > 1 then print(" bad wp: ".. minetest.pos_to_string(v) .. " == " .. minetest.pos_to_string(points[k-1])) end ]] end -- minetest.set_node(v, {name="fire:basic_flame"}) end if #self.wp_list == 0 then -- print("failed to find acceptable path") self.walk_aborted = true self.wp_list = {} self.next_wp = nil self.run_bt = true set_velocity(self, 0) set_animation(self, "stand") else self.next_wp = self.wp_list[1] -- print("c:next wp: ".. minetest.pos_to_string(self.next_wp)) walk_dest(self, pos) end end -- found points end -- should_jump else -- stall timer --print("stall timer: ".. self.stall_timer) --set_animation(self, "stand") end -- stall timer end if self.next_wp then --print("setting last_tdist") self.last_tdist = distance3(pos, self.next_wp) else --print("last_tdist = nil") self.last_tdist = nil end else --print("standing debug") set_animation(self, "stand") end self.last_pos = pos btdata.lastpos = pos end function mobehavior:register_mob_fast(name, def) local step if def.climbs_ladders then step = npc_step else step = animal_step end local mdef = { hp = 14, rotate = 0, reach = 3, physical = true, weight = 5, jump_height = 6, collisionbox = {-0.5,-0.5,-0.5, 0.5,0.5,0.5}, visual = "mesh", visual_size = {x=1, y=1}, mesh = "model", fall_speed = -9.81, textures = {}, -- number of required textures depends on visual colors = {}, -- number of required colors depends on visual spritediv = {x=1, y=1}, initial_sprite_basepos = {x=0, y=0}, is_visible = true, makes_footstep_sound = false, automatic_rotate = 0, bt_timer = 0, bt = nil, btData = nil, last_rpos = {x=99999999, y=9999999999, z=99999999}, node_below = "air", jump_timer = 0, walk_timer = 0, on_death = function(self, killer) print("died") local p = self local obj = self.object if not p then return end local drops = p.drops if not drops then return end local pos = obj:get_pos() if type(drops) == "string" then minetest.add_item(pos, drops) return end local total = 0 for _,d in ipairs(drops) do if type(d) == string then minetest.add_item(pos, d) else if 1 == math.random(d.chance or 1) then minetest.add_item(pos, {name=d.name, count=d.min + math.random(d.max-d.min)}) end end end end, on_punch = function(self, puncher, time_from_last_punch, tool_capabilities, dir) print("punched") end, on_step = step, on_activate = function(self, staticdata, dtime_s) self.btData = { groupID = "default", waypoints= {}, paths= {}, counters={}, history={}, history_queue={}, history_depth=20, posStack={}, } local btdata = self.btData self.inv_id= name..":"..math.random(1, 2000000000) btdata.lastpos = self.object:get_pos() btdata.last_rpos = vector.round(self.object:get_pos()) self.walk_timer = 0 self.stall_timer = 0 self.destination = nil self.internal_dest = nil self.wp_list = {} self.next_wp = nil self.last_pos = btdata.lastpos self.last_tdist = nil self.arrived = false self.walk_aborted = false self.run_bt = true if type(def.pre_activate) == "function" then def.pre_activate(self, static_data, dtime_s) end -- load entity variables if staticdata then local tmp = minetest.deserialize(staticdata) if tmp then for _,stat in pairs(tmp) do self[_] = stat end end else self.object:remove() return end local inventory = minetest.create_detached_inventory(self.inv_id, {}) inventory:set_size("main", 9) -- select random texture, set model and size if not self.base_texture then self.base_texture = def.textures[math.random(1, #def.textures)] self.base_mesh = def.mesh self.base_size = self.visual_size self.base_colbox = self.collisionbox end -- set texture, model and size local textures = self.base_texture local mesh = self.base_mesh local vis_size = self.base_size local colbox = self.base_colbox -- specific texture if gotten if self.gotten == true and def.gotten_texture then textures = def.gotten_texture end -- specific mesh if gotten if self.gotten == true and def.gotten_mesh then mesh = def.gotten_mesh end -- set child objects to half size if self.child == true then vis_size = { x = self.base_size.x / 2, y = self.base_size.y / 2 } if def.child_texture then textures = def.child_texture[1] end colbox = { self.base_colbox[1] / 2, self.base_colbox[2] / 2, self.base_colbox[3] / 2, self.base_colbox[4] / 2, self.base_colbox[5] / 2, self.base_colbox[6] / 2 } end if not self.health or self.health == 0 then self.health = math.random(self.hp_min, self.hp_max) end self.object:set_hp(self.health) if type(self.armor) == "table" then self.object:set_armor_groups(self.armor) else self.object:set_armor_groups({fleshy = self.armor}) end if self._velocity ~= nil then self.object:set_velocity(self._velocity) end if self._animation ~= nil then set_animation(self, self._animation) end if self._rotation ~= nil then self.object:set_rotation(self._rotation) else self.object:set_yaw(math.random(1, 360) / 180 * math.pi) end self.old_y = self.object:get_pos().y -- self.sounds.distance = (self.sounds.distance or 10) self.textures = textures self.mesh = mesh self.collisionbox = colbox self.visual_size = vis_size -- set anything changed above self.object:set_properties(self) -- update_tag(self) if type(def.post_activate) == "function" then def.post_activate(self, static_data, dtime_s) end end, get_staticdata = function(self) if self.btData ~= nil then self.btData.inv = nil -- just in case self.btData.mob = nil -- just in case self.btData.targetEntity = nil -- just in case end local tmp = {} for _,stat in pairs(self) do local t = type(stat) if t ~= 'function' and t ~= 'nil' and t ~= 'userdata' then tmp[_] = self[_] end end tmp._velocity = self.object:get_velocity() tmp._rotation = self.object:get_rotation() tmp._animation = self.animation.name -- print('===== '..self.name..'\n'.. dump(tmp)..'\n=====\n') return minetest.serialize(tmp) end, } for k,v in pairs(def) do mdef[k] = v end minetest.register_entity(name, mdef) end
AddCSLuaFile() DEFINE_BASECLASS("player_basezm") local PLAYER = {} PLAYER.WalkSpeed = 170 PLAYER.RunSpeed = 170 PLAYER.CrouchedWalkSpeed = 0.65 PLAYER.AvoidPlayers = false PLAYER.TeammateNoCollide = false function PLAYER:Spawn() BaseClass.Spawn(self) self.Player:CrosshairEnable() self.Player:SetMoveType(MOVETYPE_WALK) self.Player:SetCollisionGroup(COLLISION_GROUP_PLAYER) self.Player:SetSolid(SOLID_BBOX) self.Player:SetSolidFlags(0) self.Player:ResetHull() self.Player:UnSpectate() self.Player:SetNoTarget(false) self.Player:DrawShadow(true) self.Player:GodDisable() self.Player:StripWeapons() self.Player:SetColor(color_white) if self.Player:GetMaterial() ~= "" then self.Player:SetMaterial("") end if GetConVar("zm_disableplayercollision"):GetBool() then self.Player:SetCustomCollisionCheck(true) end self.Player:SendLua([[ gamemode.Call("RemoveZMPanels") local ply = LocalPlayer() if not IsValid(ply.QuickInfo) then ply.QuickInfo = vgui.Create("CHudQuickInfo") ply.QuickInfo:Center() end if cvars.Number("zm_hudtype", 0) == HUD_ZMR and not IsValid(GAMEMODE.HumanHealthHUD) then GAMEMODE.HumanHealthHUD = vgui.Create("CHudHealthInfo") end if cvars.Bool("zm_cl_enablehints") and IsValid(GAMEMODE.ZM_Center_Hints) then GAMEMODE.ZM_Center_Hints:SetHint(translate.Get("zm_hint_intro_s")) GAMEMODE.ZM_Center_Hints:SetActive(true, 2) timer.Simple(8, function() if not IsValid(GAMEMODE.ZM_Center_Hints) then return end GAMEMODE.ZM_Center_Hints:SetHint(translate.Get("zm_hint_weapons")) GAMEMODE.ZM_Center_Hints:SetActive(true, 2) timer.Simple(8, function() if not IsValid(GAMEMODE.ZM_Center_Hints) then return end GAMEMODE.ZM_Center_Hints:SetHint(translate.Format("zm_hint_dropping", input.GetKeyName(cvars.Number("zm_dropweaponkey", 0)), input.GetKeyName(cvars.Number("zm_dropammokey", 0)))) GAMEMODE.ZM_Center_Hints:SetActive(true, 2) end) end) end ]]) end function PLAYER:Loadout() self.Player:Give("weapon_zm_fists") self.Player:Give("weapon_zm_carry") end function PLAYER:Think() BaseClass.Think(self) if SERVER then GAMEMODE:CheckIfPlayerStuck(self.Player) if self.Player:WaterLevel() == 3 then if self.Player:IsOnFire() then self.Player:Extinguish() end if self.Player.Drowning then if self.Player.Drowning < CurTime() then local dmginfo = DamageInfo() dmginfo:SetDamage(15) dmginfo:SetDamageType(DMG_DROWN) dmginfo:SetAttacker(game.GetWorld()) self.Player:TakeDamageInfo(dmginfo) self.Player.Drowning = CurTime() + 1 end else self.Player.Drowning = CurTime() + 15 end else if self.Player.DrownDamage then local timername = "zm_playerdrown_regen."..self.Player:EntIndex() if timer.Exists(timername) then return end timer.Create(timername, 2, 0, function() if not IsValid(self.Player) or self.Player:Health() == self.Player:GetMaxHealth() then self.Player.DrownDamage = nil timer.Remove(timername) return end local d = DamageInfo() d:SetAttacker(self.Player) d:SetInflictor(self.Player) d:SetDamageType(DMG_DROWNRECOVER) self.Player:TakeDamageInfo(d) self.Player:SetHealth(self.Player:Health() + 5) self.Player.DrownDamage = self.Player.DrownDamage - 5 if self.Player.DrownDamage <= 0 then self.Player.DrownDamage = nil timer.Remove(timername) end end) end self.Player.Drowning = nil end else if cvars.Number("zm_hudtype", 0) == HUD_ZMR and not IsValid(GAMEMODE.HumanHealthHUD) then GAMEMODE.HumanHealthHUD = vgui.Create("CHudHealthInfo") end end end function PLAYER:AllowPickup(ent) if not ent:IsValid() or ent:IsPlayerHolding() or not self.Player:Alive() then return false end local phys = ent:GetPhysicsObject() local objectMass = 0 if IsValid(phys) then objectMass = phys:GetMass() if phys:HasGameFlag(FVPHYSICS_NO_PLAYER_PICKUP) or not phys:IsMotionEnabled() then return false end else return false end if ent.AllowPickup and not ent:AllowPickup(self.Player) then return false end if CARRY_MASS > 0 and objectMass > CARRY_MASS then return false end --[[ if sizeLimit > 0 then local size = ent:OBBMaxs() - ent:OBBMins() if size.x > sizeLimit or size.y > sizeLimit or size.z > sizeLimit then return false end end --]] return true end function PLAYER:CanPickupWeapon(ent) if SERVER and self.Player.DelayPickup and self.Player.DelayPickup > CurTime() then self.Player.DelayPickup = 0 return false end if self.Player:Alive() then if ent.ThrowTime and ent.ThrowTime > CurTime() then return false end if self.Player:HasWeapon(ent:GetClass()) then if ent.WeaponIsAmmo then return hook.Call("PlayerCanPickupItem", GAMEMODE, self.Player, ent) end return false end local weps = self.Player:GetWeapons() for index, wep in pairs(weps) do local slot = wep:GetSlot() if slot == 0 then continue end if slot == ent:GetSlot() then return false end end if SERVER and (ent:CreatedByMap() or ent.Dropped) then local class = ent:GetClass() self.Player:Give(class) local wep = self.Player:GetWeapon(class) if not wep.IsMelee and wep:GetClass() == class then wep:SetClip1(ent:Clip1()) wep:SetClip2(ent:Clip2()) end ent:Remove() return false end return true end self.Player.DelayPickup = CurTime() + 0.2 return false end function PLAYER:CanPickupItem(item) if self.Player.DelayItemPickup and self.Player.DelayItemPickup > CurTime() then self.Player.DelayItemPickup = 0 return false end if self.Player:Alive() and item:GetClassName() ~= nil then if item.ThrowTime and item.ThrowTime > CurTime() then return false end for _, wep in pairs(self.Player:GetWeapons()) do local primaryammo = wep.Primary and wep.Primary.Ammo or "" local secondaryammo = wep.Secondary and wep.Secondary.Ammo or "" local ammotype = GAMEMODE.AmmoClass[item:GetClassName()] or "" if string.lower(primaryammo) == string.lower(ammotype) or string.lower(secondaryammo) == string.lower(ammotype) then local ammovar = GetConVar("zm_maxammo_"..primaryammo or secondaryammo) if ammovar == nil then return end if self.Player:GetAmmoCount(ammotype) < ammovar:GetInt() then if item:IsWeapon() then self.Player:GiveAmmo(GAMEMODE.AmmoCache[ammotype], ammotype, false) item:Remove() return false end return true end end end return false end self.Player.DelayItemPickup = CurTime() + 0.2 return false end function PLAYER:SetupMove(mv, cmd) if IsValid(self.Player.HeldObject) and bit.band(cmd:GetButtons(), IN_ATTACK) ~= 0 then local ent = self.Player.HeldObject if ent:IsPlayerHolding() then DropEntityIfHeld(ent) local ang = Angle(util.SharedRandom("physpax", 0.2, 1.0), util.SharedRandom("physpay", -0.5, 0.5), 0.0) self.Player:ViewPunch(ang) local phys = ent:GetPhysicsObject() if IsValid(phys) then local massFactor = math.Remap(math.Clamp(phys:GetMass(), 0.5, 15), 0.5, 15, 0.5, 4) phys:ApplyForceCenter(self.Player:GetAimVector() * (2000 * massFactor)) ent:SetPhysicsAttacker(self.Player) end return true end end end function PLAYER:ButtonDown(button) if SERVER then return end if button == cvars.Number("zm_dropweaponkey", 0) then RunConsoleCommand("zm_dropweapon") elseif button == cvars.Number("zm_dropammokey", 0) then RunConsoleCommand("zm_dropammo") end end local healthBG = Material("zmr_effects/hud_bg_hp") function PLAYER:DrawHUD() if cvars.Number("zm_hudtype", 0) == HUD_ZMR then return end local wid, hei = ScreenScale(75), ScreenScale(24) local x, y = ScrW() * 0.035, ScrH() * 0.9 draw.RoundedBox(ScreenScale(5), x + 2, y + 2, wid, hei, Color(60, 0, 0, 200)) local health = self.Player:Health() if self.Player.CurrentHP ~= health then self.Player.CurrentHP = health self.Player.LastHurtTime = CurTime() self.Player.HurtTimer = CurTime() + 5 end local healthCol = health <= 10 and Color(185, 0, 0, 255) or health <= 30 and Color(150, 50, 0) or health <= 60 and Color(255, 200, 0) or color_white if health <= 10 then local sinScale = math.floor(math.abs(math.sin(CurTime() * 8)) * 128) healthCol.a = math.Clamp(sinScale, 90, 230) end draw.SimpleTextBlurry(health, "zm_hud_font_big", x + wid * 0.72, y + hei * 0.5, healthCol, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, self.Player.LastHurtTime, self.Player.HurtTimer) draw.SimpleTextBlurry(language.GetPhrase("Valve_Hud_HEALTH"), "zm_hud_font_small", x + wid * 0.25, y + hei * 0.7, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) end function PLAYER:PreDeath(inflictor, attacker) BaseClass.PreDeath(self, inflictor, attacker) self.Player:SendLua([[ if IsValid(LocalPlayer().QuickInfo) then LocalPlayer().QuickInfo:Remove() end if IsValid(GAMEMODE.HumanHealthHUD) then GAMEMODE.HumanHealthHUD:Remove() end ]]) for _, wep in pairs(self.Player:GetWeapons()) do if IsValid(wep) and not wep.Undroppable then self.Player:DropWeapon(wep) end end end function PLAYER:OnDeath(attacker, dmginfo) self.Player:Freeze(false) self.Player:DropAllAmmo() GAMEMODE.DeadPlayers[self.Player:SteamID()] = true if IsValid(attacker) and attacker:IsPlayer() then if attacker == self.Player then attacker:AddFrags(-1) else attacker:AddFrags(1) end end if self.Player:Health() <= -70 and not dmginfo:IsDamageType(DMG_DISSOLVE) then self.Player:Gib(dmginfo) else self.Player:CreateRagdoll() end local hands = self.Player:GetHands() if IsValid(hands) then hands:Remove() end self.Player:PlayDeathSound() local pZM = GAMEMODE:FindZM() if IsValid(pZM) then local income = math.random(GetConVar("zm_resourcegainperplayerdeathmin"):GetInt(), GetConVar("zm_resourcegainperplayerdeathmax"):GetInt()) pZM:AddZMPoints(income) pZM:SetZMPointIncome(pZM:GetZMPointIncome() - 5) end self.Player:Flashlight(false) self.Player:RemoveEffects(EF_DIMLIGHT) timer.Simple(0.1, function() if not IsValid(self.Player) then return end hook.Call("PlayerSpawnAsSpectator", GAMEMODE, self.Player) end) end function PLAYER:PostOnDeath(inflictor, attacker) self.Player:Spectate(OBS_MODE_CHASE) self.Player:SpectateEntity(self.Player:GetRagdollEntity()) self.Player.AllowKeyPress = false timer.Simple(3.15, function() if not IsValid(self.Player) or self.Player:Team() ~= TEAM_SPECTATOR then return end self.Player.AllowKeyPress = true self.Player:Spectate(OBS_MODE_ROAMING) self.Player:SpectateEntity(NULL) if IsValid(self.Player:GetRagdollEntity()) then self.Player:SetPos(self.Player:GetRagdollEntity():WorldSpaceCenter()) end end) if player.GetCount() == 1 then return end timer.Simple(0.15, function() if team.NumPlayers(TEAM_SURVIVOR) == 0 then hook.Call("TeamVictorious", GAMEMODE, false, "undead_has_won") end end) end function PLAYER:OnTakeDamage(attacker, dmginfo) local inflictor = dmginfo:GetInflictor() if IsValid(attacker) and attacker:GetClass() == "projectile_molotov" then return true end if IsValid(inflictor) and inflictor:GetClass() == "projectile_molotov" then return true end if attacker:GetClass() == "env_fire" and attacker:GetOwner() == self.Player then dmginfo:ScaleDamage(0.25) end if bit.band(dmginfo:GetDamageType(), DMG_DROWN) ~= 0 and dmginfo:GetDamage() > 0 then self.Player.DrownDamage = (self.Player.DrownDamage or 0) + dmginfo:GetDamage() end if dmginfo:GetDamage() > 0 and self.Player:Health() > 0 and bit.band(dmginfo:GetDamageType(), DMG_DROWN) == 0 and self:ShouldTakeDamage(attacker) and not self.Player:HasGodMode() then self.Player:PlayPainSound() end end function PLAYER:ShouldTakeDamage(attacker) if attacker.PBAttacker and attacker.PBAttacker:IsValid() and CurTime() < attacker.NPBAttacker then -- Protection against prop_physbox team killing. physboxes don't respond to SetPhysicsAttacker() attacker = attacker.PBAttacker end if IsValid(attacker) then local entteam = attacker.OwnerTeam if attacker:GetClass() == "env_fire" and entteam == self.Player:Team() and attacker:GetOwner() ~= self.Player then return false elseif attacker:GetClass() == "env_delayed_physexplosion" then return false end end if attacker:IsPlayer() and attacker ~= self.Player and not attacker.AllowTeamDamage and not self.Player.AllowTeamDamage and attacker:Team() == self.Player:Team() then return false end local entclass = attacker:GetClass() if string.find(entclass, "item_") then return false end return true end player_manager.RegisterClass("player_survivor", PLAYER, "player_basezm")
s=[[io.write('s=[','[',s,']','];',s)]];io.write('s=[','[',s,']','];',s)
local vars = { description = "Scythe library v3 (developer tools)", filename = "Lokasenna_Scythe library v3 (developer tools)", folder = "development", about = [[ Examples and utilities for developing scripts with Scythe v3. This package requires "Scythe library v3" to be installed as well.]], } local path = debug.getinfo(1, "S").source:match("@(.*/)[^/]+$") local file, err = loadfile(path .. "generate-metapackage.lua") if err then reaper.ShowConsoleMsg(err) return end file()(vars)
-- TableauxProver -- Copyright: Laborat'orio de Tecnologia em M'etodos Formais (TecMF) -- Pontif'icia Universidade Cat'olica do Rio de Janeiro (PUC-Rio) -- Author: Bruno Lopes ([email protected] -- Edward Hermann ([email protected])) -- TableauxProver is licensed under a Creative Commons Attribution 3.0 Unported License function selectLanguage(lang) if lang == "en" then stepButtonName = "Step" tableauButtonName = "All" latexButtonName = "LaTeX" dotButtonName = "Dot" undoButtonName = "Undo" readFileButtonName = "Read" disposeButtonName = "Adjust" trueLabel = "T" falseLabel = "F" tableauClosedLabel = "Tableau Closed!" fileDisclaimer = "Generated by TableauxProver" inputFail = "File not found" elseif lang == "pt-br" then stepButtonName = "Passo" tableauButtonName = "Tableau" latexButtonName = "LaTeX" dotButtonName = "Dot" undoButtonName = "Desfazer" readFileButtonName = "Arquivo" disposeButtonName = "Ajustar" trueLabel = "V" falseLabel = "F" tableauClosedLabel = "Tableau Fechado!" fileDisclaimer = "Gerado pelo TableauxProver" inputFail = "Arquivo inexistente" end end
--RAM Utilities. --Variabes. local sw,sh = screenSize() --The API local RamUtils = {} RamUtils.VRAM = 0 --The start address of the VRAM RamUtils.LIMG = RamUtils.VRAM + (sw/2)*sh --The start address of the LabelImage. RamUtils.FRAM = RamUtils.LIMG + (sw/2)*sh --The start address of the Floppy RAM. --Make the ramutils a global _G["RamUtils"] = RamUtils
local _M = { _VERSION = "0.1" } local cjson = require "cjson" local job = require "job" local common = require "resty.cache.common" local redis = require "resty.cache.redis.wrapper" local log_server = require "resty.cache.log_server" local system = require "resty.cache.redis.system" -- import types local ftype = common.ftype local tconcat, tinsert, tremove, tsort = common.concat, table.insert, table.remove, table.sort local tostring, tonumber = tostring, tonumber local pairs, ipairs, next = pairs, ipairs, next local assert, type, unpack, pcall = assert, type, unpack, pcall local setmetatable = setmetatable local max, min, floor = math.max, math.min, math.floor local crc32 = ngx.crc32_short local update_time = ngx.update_time local ngx_now, ngx_time = ngx.now, ngx.time local ngx_var = ngx.var local ngx_log = ngx.log local ngx_null = ngx.null local sleep = ngx.sleep local worker_exiting = ngx.worker.exiting local DEBUG, INFO, WARN, ERR = ngx.DEBUG, ngx.INFO, ngx.WARN, ngx.ERR local thread_spawn, thread_wait = ngx.thread.spawn, ngx.thread.wait local json_encode, json_decode = cjson.encode, cjson.decode local loadstring = loadstring local safe_call = common.safe_call local pipeline = redis.pipeline local transaction = redis.transaction local check_pipeline = redis.check_pipeline local SEP = "\x1d" local function escape_sep(s) return s:gsub(SEP, ":") end local events = { SET = "set", UPDATE = "update", DELETE = "delete", PURGE = "purge" } local ok, new_tab = pcall(require, "table.new") if not ok or type(new_tab) ~= "function" then new_tab = function (narr, nrec) return {} end end local function fake_fun(...) return ... end -- int64 suport local Int64 local UInt64 local int64_loaded, int64 = pcall(require, "int64") if int64_loaded then Int64 = int64.signed UInt64 = int64.unsigned else int64 = nil end -- ZLIB support for fields local zlib_loaded, zlib = pcall(require, "ffi-zlib") local inflate = zlib_loaded and function(input) local decompressed = {} local offset = 1 local length = #input local ok, err = zlib.inflateGzip(function(sz) if offset > length then return end local chunk = input:sub(offset, min(offset + sz - 1, length)) offset = offset + sz return chunk end, function(chunk) tinsert(decompressed, chunk) end, 16384) return tconcat(decompressed, "") end or fake_fun local deflate = zlib_loaded and function(input) local compressed = {} local offset = 1 local length = #input local ok, err = zlib.deflateGzip(function(sz) if offset > length then return end local chunk = input:sub(offset, min(offset + sz - 1, length)) offset = offset + sz return chunk end, function(chunk) tinsert(compressed, chunk) end, 16384, { strategy = zlib.Z_HUFFMAN_ONLY, level = zlib.Z_BEST_COMPRESSION }) return tconcat(compressed, "") end or fake_fun -- time helpers local function now() update_time() return ngx_now() end local function time() update_time() return ngx_time() end local foreachi, foreach, find_if, find_if_i = common.foreachi, common.foreach, common.find_if, common.find_if_i -- helpers local function check_number(n) local tp = type(n) return tp == "number" and n or ( tp == "userdata" and n:tonumber() or tonumber(n) ) end local function check_boolean(v) if type(v) == "boolean" then return v end if not v or type(v) == "number" then return v and v ~= 0 end v = v:lower() return v == "true" or v == "y" or v == "yes" or v == "ok" or v == "1" end local function compare(old, new) if not pcall(foreach, new, function(k,nv) local ov = old[k] if type(nv) ~= "table" then assert((ov and ov == nv) or (not ov and nv == "nil"), "not matched") return end -- table value tsort(ov,function(l,r) return l < r end) tsort(nv,function(l,r) return l < r end) assert(compare(ov, nv), "not matched") end) then return false end return true end local function equals(old, new) return compare(old, new) and compare(new, old) end -- update cache description local function cache_desc_fixup(cache) if cache.fields[#cache.fields].dbfield then return end local update = function(red) local cache_key = "cache:" .. cache.cache_name local old = assert(red:hgetall(cache_key)) local desc = old == ngx_null and { fields = {} } or red:array_to_hash(old) desc.fields = desc.fields and json_decode(desc.fields) or {} desc.indexes = desc.indexes and json_decode(desc.indexes) or {} local function dbfield(name) local field, i = unpack(find_if_i(desc.fields, function(field) return field.name == name end) or { { dbfield = tostring(assert(red:hincrby(cache_key, "f_index", 1))) }, -1 }) return field.dbfield end local indexes_changed local function dbindex(hash) local index, i = unpack(find_if_i(desc.indexes, function(idx) return idx.hash == hash end) or { { id = tostring(assert(red:hincrby(cache_key, "i_index", 1))) }, -1 }) if i == -1 then -- new index desc.i_index = index.id else tremove(desc.indexes, i) end return index.id, hash end cache.fields_indexed = {} foreachi(cache.fields, function(field) field.dbfield = dbfield(field.name) if field.indexed then tinsert(cache.fields_indexed, field.dbfield) end end) foreachi(cache.indexes, function(index) local hash = ngx.encode_base64(tconcat(index.fields, ":"), true) index.id, index.hash = dbindex(hash) end) foreachi(desc.indexes, function(index) index.obsolete = true tinsert(cache.indexes, index) end) cache.i_crc32 = tostring(crc32(json_encode(cache.indexes))) assert(red:hmset(cache_key, { fields = json_encode(cache.fields), indexes = json_encode(cache.indexes), ttl = cache.ttl, cache_id = cache.cache_id, i_crc32 = cache.i_crc32 })) foreachi(cache.fields, function(field) local default = field.default assert(type(default) ~= "function", "default can't de a function type") if default then field.default = (type(default) == "string" and default:match("^return")) and assert(loadstring(default)) or function() return default end end end) end return system:handle(update) end local function check_pk(fields, pk) local pk_tab = (type(pk) == "table" and pk[1]) and pk or { pk } for _, pk in ipairs(pk_tab) do local tmp = {} foreach(pk, function(k,v) tmp[k:lower()] = v pk[k] = nil end) foreach(tmp, function(k,v) pk[k] = v end) for i=1,#fields do local field = fields[i] local v = pk[field.name] if field.pk and (not v or v == "" or type(v) == "table") then return nil, "bad args: " .. field.name .. " required and must be a scalar" end end end return true end local function check_simple_types_out(fields, data) foreachi(fields, function(field) local name = field.name local value = data[name] if value then if value == "null" or value == ngx_null then data[name] = ngx_null elseif value == "nil" then data[name] = nil elseif field.ftype == ftype.NUM then data[name] = check_number(value) elseif field.ftype == ftype.INT64 then data[name] = Int64(value) elseif field.ftype == ftype.UINT64 then data[name] = UInt64(value) elseif field.ftype == ftype.STR then data[name] = tostring(value) elseif field.ftype == ftype.BOOL then data[name] = check_boolean(value) end end end) return data end local function check_in(cache, data, update) local fields = cache.fields local tmp = {} foreach(data, function(k,v) tmp[k:lower()] = v data[k] = nil end) foreach(tmp, function(k,v) data[k] = v end) for i=1,#fields do local field = fields[i] local name = field.name local value = data[name] if value then if value == ngx_null then data[name] = ngx_null elseif value == "nil" then if field.mandatory then return nil, "bad args: mandatory field can't be nil" end if field.indexed then return nil, "bad args: indexed field can't be nil" end elseif type(value) == "table" and value.type and value.action then -- skip elseif field.ftype == ftype.NUM then data[name] = check_number(value) elseif field.ftype == ftype.INT64 then data[name] = Int64(value) elseif field.ftype == ftype.UINT64 then data[name] = UInt64(value) elseif field.ftype == ftype.STR then data[name] = tostring(value) elseif field.ftype == ftype.BOOL then data[name] = check_boolean(value) elseif field.ftype == ftype.OBJECT then -- skip elseif field.ftype == ftype.SET then -- skip elseif field.ftype == ftype.LIST then -- skip end elseif field.partof and data[field.partof] then -- skip elseif field.skip and not field.partof then -- skip else if field.pk or (field.mandatory and not update) then return nil, "bad args: " .. field.name .. " required" end end end return true end local function defaults(fields, data) foreachi(fields, function(field) local name = field.name local value, default = data[name], field.default if not value and default then data[name] = default() end end) end local function to_db(cache, data) local set, funcs, del = { ["#i"] = cache.i_crc32 }, {}, {} local fields = cache.fields for i=1,#fields do local field = fields[i] local name, dbfield = field.name, field.dbfield if not field.skip then local value = data[name] if value == "nil" then -- special value for remove field tinsert(del, { dbfield, field.ftype == ftype.SET or field.ftype == ftype.LIST } ) elseif type(value) == "table" and value.type and value.action then funcs[name] = value elseif field.ftype == ftype.SET or field.ftype == ftype.LIST then local object if not value then -- composing from source fields object = {} local source_fields = type(field.source) == "table" and field.source or { field.source } foreachi(source_fields, function(source) local val = data[source] if val then object[#object + 1] = val ~= ngx_null and val or "null" end end) if #object == #source_fields then set[dbfield] = tconcat(object, "|") end else -- get from value set[dbfield] = {} foreachi(type(value) == "table" and value or { value }, function(v) object = {} local source_fields = type(field.source) == "table" and field.source or { field.source } foreachi(source_fields, function(source) local val = v[source] if val then object[#object + 1] = val ~= ngx_null and val or "null" end end) if #object == #source_fields then tinsert(set[dbfield], tconcat(object, "|")) end end) end elseif value then if field.ftype == ftype.OBJECT then local x = json_encode(value) set[dbfield] = field.gzip and deflate(x) or x elseif field.ftype == ftype.STR then set[dbfield] = value == ngx_null and "null" or (field.gzip and deflate(value) or value) else set[dbfield] = value == ngx_null and "null" or value end end end end return set, funcs, del end local function from_db(fields, data) local out = {} for i=1,#fields do local field = fields[i] local name, dbfield = field.name, field.dbfield local value = data[dbfield] if value then if field.ftype == ftype.SET or field.ftype == ftype.LIST then local source = type(field.source) == "table" and field.source or { field.source } if type(value) == "table" then out[name] = {} for j=1,#value do local object = {} local k = 1 for f in value[j]:gmatch("([^|]+)") do if f ~= "nil" then object[source[k]] = f end k = k + 1 end check_simple_types_out(fields, object) out[name][j] = type(field.source) == "table" and object or object[source[1]] end end elseif field.ftype == ftype.OBJECT then out[name] = value == "null" and ngx_null or json_decode( field.gzip and inflate(value) or value ) elseif field.ftype == ftype.STR then out[name] = value == "null" and ngx_null or (field.gzip and inflate(value) or value) elseif field.ftype == ftype.INT64 then out[name] = value == "null" and ngx_null or Int64(value) elseif field.ftype == ftype.UINT64 then out[name] = value == "null" and ngx_null or UInt64(value) else out[name] = value == "null" and ngx_null or value end end end return out end local cache_class = {} local function pstxid() local ok, id = pcall(function() return ngx_var.pstxid or ngx_var.request_id end) return ok and id or "job" end function cache_class:debug(f, fun) if self.debug_enabled then ngx_log(DEBUG, "[", pstxid() , "] ", self.cache_name, "_", f, " ", fun()) end end function cache_class:info(f, fun) ngx_log(INFO, "[", pstxid() , "] ", self.cache_name, "_", f, " ", fun()) end function cache_class:warn(f, fun) ngx_log(WARN, "[", pstxid() , "] ", self.cache_name, "_", f, " ", fun()) end function cache_class:err(f, fun) ngx_log(ERR, "[", pstxid() , "] ", self.cache_name, "_", f, " ", fun()) end function cache_class:make_pk(data) local is_multi = type(data) == "table" and data[1] local data_tab = is_multi and data or { data } local result = {} for _, data in ipairs(data_tab) do local key, pk = { self.cache_id }, {} foreachi(self.fields, function(field) if field.pk then local name = field.name local value = data[name] or "*" pk[name] = value tinsert(key, value ~= ngx_null and value or "null") end end) if not is_multi then return pk, tconcat(key, SEP) end tinsert(result, { pk, tconcat(key, SEP) }) end return result end function cache_class:key2pk(key) local fields = self.fields local pk = key:match("^" .. self.cache_id) and key:match("^" .. self.cache_id .. SEP .. "(.+)$") or key local t, i = {}, 1 for v in pk:gmatch("([^" .. SEP .. "]+)") do while i <= #fields and not fields[i].pk do i = i + 1 end assert(i <= #fields, "invalid key") t[fields[i].name] = v ~= "null" and v or ngx_null i = i + 1 end return t end function cache_class:make_key(data) local pattern = "^" .. self.cache_id .. SEP .. "(.+)$" local tab, key = self:make_pk(data) if key then -- single key operation return key:match(pattern) end -- fix all keys for i,pair in ipairs(tab) do tab[i] = { key = pair[2]:match(pattern) } end return tab end function cache_class:keys(redis_xx) local keys = function(red) local keys = assert(self.redis:zscan(red, self.PK, "*")) local h = {} foreachi(keys, function(v) h[tostring(v.key)] = true end) return h, #keys end return self.redis:handle(keys, redis_xx or self.redis_rw) end function cache_class:exists_unsafe(pk, redis_xx) if not pk then return nil, "bad args: pk required" end local ok, err = check_pk(self.fields, pk) if not ok then return nil, err end pcall(cache_desc_fixup, self) local exists = function(red) local key_part = self:make_key(pk) local pk_exists, key_exists = unpack(pipeline(red, function() red:zscore(self.PK, key_part) red:exists(self.cache_id .. SEP .. key_part) end)) return pk_exists ~= ngx_null and key_exists == 1 end return self.redis:handle(exists, redis_xx or self.redis_rw) end function cache_class:exists(pk) return safe_call(self.exists_unsafe, self, pk, self.redis_ro) end function cache_class:get_unsafe(pk, redis_xx, getter) if not pk then return nil, "bad args: pk required" end local ok, err = check_pk(self.fields, pk) if not ok then return nil, err end pcall(cache_desc_fixup, self) local get = function(red) local response = {} local ok, err, data, expires local key = self:make_key(pk) -- if type(key) is a table we have a multikey operation local keys = type(key) == "table" and key or { { key = key } } local PK = self.PK if type(key) ~= "table" then if key:match("[%?%*%[]") then keys = assert(self.redis:zscan(red, PK, key)) end end getter = getter or function(data) tinsert(response, data) end local callback_on_get = self.callback_on_get or fake_fun local offset = 1 while offset <= #keys do local j = offset local r = pipeline(red, function() for i=1,100 do local k = keys[offset].key local key = self.cache_id .. SEP .. k red:hgetall(key) red:zscore(PK, k) foreachi(self.sets, function(field) red:smembers(key .. SEP .. field.dbfield) end) foreachi(self.lists, function(field) red:lrange(key .. SEP .. field.dbfield, 0, -1) end) offset = offset + 1 if offset > #keys then break end end end) for i=1,#r,2 + #self.sets + #self.lists do local key = keys[j].key j = j + 1 data, expires = r[i], r[i + 1] if expires ~= ngx_null then expires = expires ~= "inf" and tonumber(expires) or nil if #data ~= 0 and (not expires or expires > now()) then local object = red:array_to_hash(data) for k = 1,#self.sets do local members = assert(r[i + 1 + k]) object[self.sets[k].dbfield] = members end for k = 1,#self.lists do local members = assert(r[i + 1 + #self.sets + k]) object[self.lists[k].dbfield] = members end data = from_db(self.fields, object) check_simple_types_out(self.fields, data) self:debug("get()", function() return "pk=", json_encode(self:key2pk(key)), " data=", json_encode(data) end) foreach(check_simple_types_out(self.fields, self:key2pk(key)), function(k,v) data[k] = v end) callback_on_get(red, data) getter(data, key, expires and expires - time() or nil) end end end end return #response ~= 0 and response or ngx_null end return self.redis:handle(get, redis_xx or self.redis_rw) end function cache_class:get(pk, getter) return safe_call(self.get_unsafe, self, pk, self.redis_ro, getter) end function cache_class:get_master(pk, getter) return safe_call(self.get_unsafe, self, pk, self.redis_rw, getter) end -- search by indexes local function index_keys(self, data) local index_keys = {} foreachi(self.indexes, function(index) local index_key = { index.id } foreachi(index.fields, function(name) local val = data[name] if val then tinsert(index_key, val) end end) if #index_key - 1 == #index.fields then -- found tinsert(index_keys, tconcat(index_key, SEP)) end end) return #index_keys ~= 0 and index_keys or nil end function cache_class:search_unsafe(data, redis_xx, getter) if not data then return nil, "bad args: data required" end pcall(cache_desc_fixup, self) local ikeys = index_keys(self, data) if not ikeys then return nil, "bad args: not enough data for indexes" end redis_xx = redis_xx or self.redis_rw local search_pk = function(red, ikey) return assert(red:zrangebyscore(ikey, time(), "+inf")) end local pk = {} foreachi(ikeys, function(iikey) foreachi(self.redis:handle(search_pk, redis_xx, self.cache_id .. SEP .. iikey), function(ikey) tinsert(pk, self:key2pk(ikey)) end) end) if #pk == 0 then return self.redis:handle(function(red) local logid, err = red:get("L:" .. self.cache_name .. ":ID") return logid and {} or nil, err end, redis_xx) end return self:get_unsafe(pk, redis_xx, getter) end function cache_class:search(data, getter) return safe_call(self.search_unsafe, self, data, self.redis_ro, getter) end function cache_class:search_master(data, getter) return safe_call(self.search_unsafe, self, data, self.redis_rw, getter) end local function with_indexes(self, pk, new, old, fun) foreachi(self.indexes, function(index) local index_key, old_index_key = { index.id }, { index.id } foreachi(index.fields, function(name) tinsert(index_key, new[name] or pk[name] or old[name]) tinsert(old_index_key, old[name] or pk[name]) end) index_key = #index_key == #index.fields + 1 and tconcat(index_key, SEP) or ngx_null old_index_key = #old_index_key == #index.fields + 1 and tconcat(old_index_key, SEP) or ngx_null fun(index_key, old_index_key, index) end) end local function decode_indexes(self, db) local fields_indexed = self.fields_indexed local values = {} for i=1,#fields_indexed do local dbfield = fields_indexed[i] values[dbfield] = db[i] end return from_db(self.fields, values) end local function get_indexes_values(self, red, pk) local fields_indexed = self.fields_indexed if #fields_indexed == 0 then return end local pk, key = self:make_pk(pk) local key_part = self:make_key(pk) local expires, db = unpack(pipeline(red, function() red:zscore(self.PK, key_part) red:hmget(key, unpack(fields_indexed)) end)) if expires == ngx_null then return ngx_null end return decode_indexes(self, db) end function cache_class:set_unsafe(data, o) if not data then return nil, "bad args: data required" end local ok, err = check_pk(self.fields, data) if not ok then return nil, err end pcall(cache_desc_fixup, self) o = o or {} local ttl = o.ttl o.wait = o.wait or self.wait local set = function(red) local reason, old, old_ttl, old_expires local pk, key = self:make_pk(data) local key_part = self:make_key(pk) -- get exists data old, old_expires = unpack(pipeline(red, function() red:hgetall(key) red:zscore(self.PK, key_part) end)) if old_expires ~= ngx_null and old ~= ngx_null and #old ~= 0 then old_ttl = (old_expires ~= ngx_null and old_expires ~= "inf") and tonumber(old_expires) - time() or nil if old_ttl and old_ttl < 0 then -- expired old, old_ttl = nil, nil end else old, old_expires = nil, nil end if old then if not o.overwrite and not o.update and not o.upsert then return ngx_null, ngx_null end else if o.update then return ngx_null end end local overwrite = old and o.overwrite local ok, err = check_in(self, data, old and not overwrite) if not ok then return nil, err end -- remove pk fields foreachi(self.fields, function(field) if field.pk then data[field.name] = nil end end) local update_data local i_crc32 local on_new = o.on_new or fake_fun local on_nothing = o.on_nothing or fake_fun local on_update = o.on_update or fake_fun red:init_pipeline() red:multi() if old then old = red:array_to_hash(old) i_crc32 = old["#i"] old = from_db(self.fields, old) check_simple_types_out(self.fields, old) local eq = equals(old, data) update_data = (overwrite and not eq) or not eq or not compare(old, data) reason = update_data and { desc = overwrite and "overwrite()" or "update()", fun = overwrite and on_new or on_update } or { desc = "nothing()" } self:debug("set()", function() return "overwrite_data=", overwrite and "Y" or "N", " update_data=", update_data and "Y" or "N", " old=", json_encode(old), " new=", json_encode(data) end) overwrite = overwrite and not eq else reason = { desc = "set()", fun = on_new } defaults(self.fields, data) update_data = true end ttl = old_ttl or ttl or self.ttl -- update indexes if #self.indexes ~= 0 then if self.i_crc32 ~= i_crc32 then self:debug("update_index()", function() return "#i=", i_crc32, "->", self.i_crc32 end) end with_indexes(self, pk, data, old or {}, function(index_key, old_index_key, index) if not index.obsolete and index_key ~= ngx_null and index_key ~= old_index_key then -- new key or index field changed self:debug("update_index()", function() return "index=", cjson.encode(index), " add index_key=", escape_sep(index_key), " id=", escape_sep(key_part) end) red:zadd(self.cache_id .. SEP .. index_key, ttl and (time() + ttl) or "+inf", key_part) reason = not reason.fun and { desc = "update()", fun = on_update } or reason end if index.obsolete or index_key == ngx_null or index_key ~= old_index_key then if old_index_key ~= ngx_null then -- remove obsolete exists index red:zrem(self.cache_id .. SEP .. old_index_key, key_part) self:debug("update_index()", function() return "index=", cjson.encode(index), " remove index_key=", escape_sep(old_index_key), " id=", escape_sep(key_part) end) reason = not reason.fun and { desc = "update()", fun = on_update } or reason end end end) end local db_data_set, db_funcs, db_data_del = to_db(self, data) if overwrite then -- overwrite key data if any red:del(key) old = nil else -- delete fields foreachi(db_data_del, function(todel) local dbfield, complex = unpack(todel) if complex then -- list or set red:del(key .. SEP .. dbfield) end red:hdel(key, dbfield) end) -- funcs foreach(db_funcs, function(fname, v) v:callback(red, key) end) -- redefine skip_log o.skip_log = o.skip_log or o.skip_log_set end -- update sets & lists local function update_complex(field, fun) local value, key_f = db_data_set[field.dbfield], key .. SEP .. field.dbfield if not value then return end reason = not reason.fun and { desc = "update()", fun = on_update } or reason if type(value) == "table" then red:del(key_f) foreachi(value, function(v) fun(key_f, v) end) else fun(key_f, value) end if ttl and #self.indexes == 0 then red:expire(key_f, ttl) end db_data_set[field.dbfield] = "ref" end foreachi(self.sets, function(field) update_complex(field, function(k, v) red:sadd(k, v) end) end) foreachi(self.sets, function(field) update_complex(field, function(k, v) red:rpush(k, v) end) end) self:debug(reason.desc, function() return "pk=", json_encode(pk), " ttl=", ttl, " data=", json_encode(data) end) -- may be nothing ? if not reason.fun then red:cancel_pipeline() -- restore pk fields foreach(pk, function(k,v) data[k] = v end) on_nothing(pk) return true end -- update key if update_data then red:hmset(key, db_data_set) end if not old then -- update primary index and ttl if ttl then red:zadd(self.PK, time() + ttl, key_part) -- DO NOT setup ttl - need for remove indexes if #self.indexes == 0 then red:expire(key, ttl) end else red:zadd(self.PK, "+inf", key_part) end end -- guard from purge red:zrem(self.PURGE, key_part) red:exec() if o.wait then red:wait(o.wait.slaves or 1, o.wait.ms or 100) end ok, err = check_pipeline(assert(red:commit_pipeline())) if not ok then self:warn(reason.desc, function() return err end) end if ok and not o.skip_log then local log_data if self.log_data then log_data = {} foreachi(self.fields, function(field) if not field.nostore then log_data[field.name] = data[field.name] end end) end self:log_event(old and events.UPDATE or events.SET, pk, log_data, ttl) end if ok then reason.fun(pk, data, ttl) err = nil end -- restore pk fields foreach(pk, function(k,v) data[k] = v end) return ok, err end local start = now() ok, err = self.redis:handle(set, self.redis_rw) self:debug("set()", function() return "time=", now() - start end) return ok, err end function cache_class:set(data, o) return safe_call(self.set_unsafe, self, data, o) end function cache_class:incr_unsafe(data, o) if not data then return nil, "bad args: pk required" end local ok, err = check_pk(self.fields, data) if not ok then return nil, err end local fname, incr_by = data.field, data.incr_by or 1 if not fname then return nil, "bad args: field name required" end local field = self.fields_by_name[fname] if not field then return nil, "bad args: " .. field .. " is not found" end if field.ftype ~= ftype.NUM then return nil, "bad args: " .. field .. " type is not a number" end pcall(cache_desc_fixup, self) if field.indexed then return nil, "bad args: " .. field .. " is indexed and can't be INCR" end local update_data = self:make_pk(data) update_data[fname] = setmetatable({ type = "function()", action = "HINCRBY(" .. incr_by .. ")" }, { __index = { callback = function(self, red, key) red:hincrby(key, field.dbfield, incr_by) end } }) o = o or {} o.update = true return self:set_unsafe(update_data, o) end function cache_class:incr(data, o) return safe_call(self.incr_unsafe, self, data, o) end function cache_class:delete_unsafe(pk, data, skip_log) if not pk then return nil, "bad args: pk required" end local ok, err = check_pk(self.fields, pk) if not ok then return nil, err end pcall(cache_desc_fixup, self) local delete = function(red) self:debug("delete()", function() return "pk=", json_encode(pk) end) local key, key_part pk, key = self:make_pk(pk) key_part = self:make_key(pk) local exists = get_indexes_values(self, red, pk) or ( assert(red:zscore(self.PK, key_part)) ~= ngx_null and {} or ngx_null ) if exists == ngx_null then -- not found return ngx_null end transaction(red, function() red:del(key) if next(exists) then with_indexes(self, {}, exists, {}, function(index_key) if index_key ~= ngx_null then red:zrem(self.cache_id .. SEP .. index_key, key_part) end end) end red:zrem(self.PK, key_part) foreachi(self.sets, function(field) red:del(key .. SEP .. field.dbfield) end) foreachi(self.lists, function(field) red:del(key .. SEP .. field.dbfield) end) end, self.wait) if skip_log then return true end self:log_event(events.DELETE, pk) return true end return self.redis:handle(delete, self.redis_rw) end function cache_class:delete(pk, data) return safe_call(self.delete_unsafe, self, pk, data) end function cache_class:log_event(ev, pk, data, ttl) return self.log:log_event { ev = ev, pk = pk, data = self.log_data and data or nil, ttl = ttl } end -- memory index helpers -------------------------------------------------------- local function add_to_index(self, pk, data, ttl) local memory = self.memory local dict = memory.dict local idx_keys = {} for i,index in ipairs(memory.indexes or {}) do local idx_key = { "$i:" .. i } if pcall(foreachi, index, function(field) local p = data[field] assert(p, "break") tinsert(idx_key, p ~= ngx_null and p or "null") end) then idx_key = tconcat(idx_key, SEP) tinsert(idx_keys, idx_key) if not dict:object_fun(idx_key, function(idx_data, flags) idx_data = idx_data or {} for j,k in ipairs(idx_data) do if self:make_key(k) == self:make_key(pk) then -- already exists goto done end end tinsert(idx_data, pk) self:debug("add_to_index()", function() return "idx_key=", escape_sep(idx_key), " pk=", json_encode(pk), " data=", json_encode(data), " ttl=", ttl, " index=", json_encode(idx_data) end) :: done :: return idx_data, flags end, ttl) then -- cleanup foreachi(idx_keys, function(idx_key) dict:delete(idx_key) end) return nil, "no memory" end end end return idx_keys end local function delete_from_index(self, pk) local old, flags self.memory.dict:object_fun(self:make_key(pk), function(value, f) old, flags = value, f return nil, 0 end) if not old then return end for i,index in ipairs(self.memory.indexes or {}) do local idx_key = { "$i:" .. i } if pcall(foreachi, index, function(field) local p = old[field] assert(p, "break") tinsert(idx_key, p ~= ngx_null and p or "null") end) then idx_key = tconcat(idx_key, SEP) self.memory.dict:object_fun(idx_key, function(idx_data, flags) if idx_data then for j,k in ipairs(idx_data) do if self:make_key(k) == self:make_key(pk) then -- remove from index tremove(idx_data, j) self:debug("delete_from_index()", function() return "idx_key=", escape_sep(idx_key), " pk=", json_encode(pk), " index=", json_encode(idx_data) end) break end end return #idx_data ~= 0 and idx_data or nil, flags end return idx_data, flags end) end end return old, flags end -- memory index helpers end ---------------------------------------------------- local function memory_prefetch(self) local logid = self.log:log_id() if not self.memory.prefetch then self.memory.shm:set("logid", logid) return end local pk = self:make_pk { --[[ get all --]] } local on_set = self.memory.events.on_set local count = 0 local start = now() local resp, err = self:get_unsafe(pk, self.redis_rw, function(data, key, ttl) pk = self:key2pk(key) local ok, err = self.memory.dict:object_add(key, data, ttl) if ok then -- add indexes ok, err = add_to_index(self, pk, data, ttl) end if not ok then self:warn("memory_prefetch()", function() return "please increase dictionary size" end) error(err) end count = count + 1 on_set(pk, data, ttl) end) assert(resp, err) self.memory.shm:set("logid", logid) self:info("memory_prefetch()", function() return self.memory.name, " completed, count=", count, " at ", now() - start, " seconds" end) end local function do_memory_update(self, n) local logid_old = self.memory.shm:get("logid") or self.log:log_id() local log, err = self.log:get_events(logid_old, n) if not log then self:warn("memory_update()", function() return err end) return 0 end if #log.events == 0 then self.memory.shm:set("logid", log.logid) return 0 end self:debug("memory_update()", function() return "logid_old=", logid_old, ", logid=", log.logid end) local on_set, on_delete, on_purge = self.memory.events.on_set, self.memory.events.on_delete, self.memory.events.on_purge local start = now() local added, updated, deleted = 0, 0, 0 local dict = self.memory.dict local prefetch = self.memory.prefetch local tab_pk = {} local function flush_update() self:get_unsafe(tab_pk, self.redis_rw, function(data, key, ttl) local pk = self:key2pk(key) local old, flags = delete_from_index(self, pk) if old or prefetch then local nomemory local saved = prefetch and dict:object_safe_set(key, data, ttl, flags) or dict:object_set(key, data, ttl, flags) if saved then if add_to_index(self, pk, data, ttl) then on_set(pk, data, ttl) if old then updated = updated + 1 else added = added + 1 end else dict:delete(key) nomemory = true end else nomemory = true end if nomemory then self:warn("memory_update()", function() return "please increase dictionary size" end) end end end) tab_pk = {} end foreachi(log.events, function(event) self:debug("memory_update()", function() return "event: ", json_encode(event) end) if event.ev == events.SET or event.ev == events.UPDATE then tinsert(tab_pk, event.pk) elseif event.ev == events.DELETE then flush_update() local data = delete_from_index(self, event.pk) if data then on_delete(event.pk, data) deleted = deleted + 1 end elseif event.ev == events.PURGE then tab_pk = {} dict:flush_all() dict:flush_expired() on_purge() end self.memory.shm:set("logid", event.logid) end) flush_update() self:info("memory_update()", function() return "completed, added=", added, ", updated=", updated, ", deleted=", deleted, " at ", now() - start, " seconds" end) return #log.events end local function memory_update(self) repeat local count = do_memory_update(self, 1000) until count ~= 1000 or worker_exiting() end local function memory_cleanup(self) local start = now() local count = self.memory.dict:flush_expired() if count ~= 0 then self:info("memory_cleanup()", function() return "count=", count, " at ", now() - start, " seconds" end) end end local DDOS_FLAG = (0xFFFFFFFF - 1) / 2 local function save_hot(self, pk, key, data, ttl, callback) local memory = self.memory local dict = memory.dict ttl = ttl and min(ttl, memory.ttl or ttl) or nil local val, flags = dict:object_fun(key, function(_, flags) return unpack( callback and { callback(data, flags) } or { data, flags } ) end, ttl) if val and add_to_index(self, pk, data, ttl) then self:debug("save_hot()", function() return "pk=", json_encode(pk), " data=", json_encode(data), " ttl=", ttl end) return val, flags end dict:delete(key) self:warn("save_hot()", function() return "please increase dictionary size" end) return data, 0 end local function get_memory(self, red, pk, callback_fn) local memory = self.memory if not memory then return nil, nil, "only for in-memory caches" end local ok, err = check_pk(self.fields, pk) if not ok then return nil, nil, err end local callback = function(val, flags) local nval, nflags = callback_fn(val, flags) return nval or val, nflags or flags end local memory_ttl = memory.ttl local dict = memory.dict local key = self:make_key(pk) local val, flags if not memory_ttl or memory_ttl > 0 then val, flags = unpack( callback_fn and { dict:object_fun(key, function(val, flags) return unpack( val and { callback(val, flags) } or { nil, 0 } ) end) } or { dict:object_get(key) } ) self:debug("get_memory()", function() return "lookup hot: pk=", json_encode(pk), " data=", (val and val ~= ngx_null) and json_encode(val) or "NOT_FOUND" end) end local minute = floor(time() / 60) if val then dict:incr("$h:" .. minute, 1, 0) else dict:incr("$m:" .. minute, 1, 0) self:get_unsafe(pk, red, function(data, key, ttl) val, flags = unpack( (not memory_ttl or memory_ttl > 0) and { save_hot(self, pk, key, data, ttl, callback_fn and callback or nil) } or ( callback_fn and { callback(data, 0) } or { data, 0 } ) ) end) end if not val then if red == self.redis_rw then dict:object_safe_set(key, ngx_null, memory.ddos_timeout or 1, DDOS_FLAG) flags = DDOS_FLAG end val = ngx_null end return val, flags end function cache_class:get_memory_slave(pk, callback) local data, flags, err = get_memory(self, self.redis_ro, pk, callback) if not data then return nil, err end if data ~= ngx_null or flags == DDOS_FLAG then return data, flags end -- failover on master node data, flags, err = get_memory(self, self.redis_rw, pk, callback) return data, data and flags or err end function cache_class:get_memory_master(pk, callback) local data, flags, err = get_memory(self, self.redis_rw, pk, callback) return data, data and flags or err end function cache_class:memory_exists(pk) local exists self:get_memory_slave(pk, function(val, flags) exists = val return val, flags end) return exists and exists ~= ngx_null end function cache_class:hits(backward, m) if not self.memory then return nil, "no in-memory data" end backward, m = backward or 1, m or 1 local hits, miss = 0, 0 local minute = floor(time() / 60) - backward for t = minute, minute + m do hits = hits + (self.memory.dict:get("$h:" .. t) or 0) miss = miss + (self.memory.dict:get("$m:" .. t) or 0) end return hits, miss end function cache_class:memory_scan(fun) foreachi(self.memory.dict:get_keys(0), function(key) if not key:match("^%$") then local data = self.memory.dict:object_get(key) if type(data) == "table" then fun(self:key2pk(key), data) end end end) end function cache_class:get_by_index(data, o) assert(self.memory and self.memory.prefetch, "index operation is possible only with in-memory caches with prefetch") o = o or {} local callback, filter = o.callback, o.filter or function() return true end local pk, flags local dict = self.memory.dict for i,index in ipairs(self.memory.indexes or {}) do local idx_key = { "$i:" .. i } if pcall(foreachi, index, function(field) local p = data[field] assert(p, "break") tinsert(idx_key, p ~= ngx_null and p or "null") end) then pk = dict:object_get(tconcat(idx_key, SEP)) if pk then break end end end if not pk then return ngx_null end local items = {} foreachi(pk, function(k) local key = self:make_key(k) local data, flags = unpack(callback and { dict:object_fun(key, function(value, flags) callback(k, value, flags) return value, flags end) } or { dict:object_get(key) }) local pk = self:key2pk(key) if filter(pk, data, flags) then tinsert(items, { pk, data, flags }) end end) return #items ~= 0 and items or ngx_null end local function purge_bulk(self, index, next_keys_fn, prepare_fn) pcall(cache_desc_fixup, self) prepare_fn = prepare_fn or function() end local function purge_chunk(red, bulk) local start = now() for j, key_part in ipairs(bulk) do bulk[j] = { key = self.cache_id .. SEP .. key_part, key_part = key_part } end local purged repeat prepare_fn(red, bulk) if #self.fields_indexed ~= 0 and not bulk[1].index_keys then local r = pipeline(red, function() foreachi(bulk, function(b) if not b.skip then red:hmget(b.key, unpack(self.fields_indexed)) else -- skip this key (replaced) red:ping() end end) end) for j, index_values in ipairs(r) do local index_keys_k = {} if type(index_values) == "table" and index_values[1] ~= ngx_null then -- found with_indexes(self, {}, decode_indexes(self, index_values), {}, function(index_key) if index_key ~= ngx_null then tinsert(index_keys_k, index_key) end end) end bulk[j].index_keys = index_keys_k end end -- flush data purged = 0 if transaction(red, function() foreachi(bulk, function(b) if b.skip then return end local key, key_part = b.key, b.key_part -- remove from XX:keys red:zrem(index, key_part) -- remove from XX:key:N set foreachi(self.sets, function(field) red:del(key .. SEP .. field.dbfield) end) -- remove from XX:key:N list foreachi(self.lists, function(field) red:del(key .. SEP .. field.dbfield) end) -- remove indexes foreachi(b.index_keys or {}, function(index_key) red:zrem(self.cache_id .. SEP .. index_key, key_part) end) red:del(key) purged = purged + 1 end) end, self.wait) == ngx_null then -- transaction fails self:warn("purge_chunk()", function() return "some of the keys have been changed while purging, try again ..." end) purged = nil end until purged ~= nil self:debug("purge_chunk()", function() return "count=", #bulk, " purged=", purged, " at ", now() - start, " seconds" end) return #bulk, purged end local total_count, total_purged = 0, 0 while not worker_exiting() do local start = now() local keys = next_keys_fn() if not next(keys) then break end local threads = {} local count, purged = 0, 0 local ok, err = pcall(function() local function spawn_thread(chunk) local thr = thread_spawn(function() return self.redis:handle(function(red) return purge_chunk(red, chunk) end, self.redis_rw) end) assert(thr, "failed to create corutine") return thr end local chunk = {} foreach(keys, function(key) tinsert(chunk, key) if #chunk == 100 then tinsert(threads, spawn_thread(chunk)) chunk = {} end end) if #chunk ~= 0 then tinsert(threads, spawn_thread(chunk)) end end) foreachi(threads, function(thr) local r = { thread_wait(thr) } if tremove(r, 1) then local chunk_count, chunk_purged = unpack(r) count, purged = count + chunk_count, purged + chunk_purged end end) self:info("purge_bulk()", function() return "count=", count, " purged=", purged, " at ", now() - start, " seconds" end) assert(ok, err) total_count, total_purged = total_count + count, total_purged + purged end return total_count, total_purged end local function watch(self, red, bulk) local watched = new_tab(#bulk, 0) foreachi(bulk, function(e) tinsert(watched, e.key) end) assert(red:watch(unpack(watched))) -- check for exists in the XX:keys for j, expire_at in ipairs(pipeline(red, function() foreachi(bulk, function(b) -- get expire at red:zscore(self.PK, b.key_part) b.skip = nil end) end)) do if expire_at ~= ngx_null then -- now added to XX:keys => skip local b = bulk[j] red:unwatch(b.key) b.skip = true end end end local function purge_keys(self, red) local lock = self.redis:create_lock(self.cache_id, 10) if not lock:aquire() then self:warn("purge()", function() return "can't aquire the lock ..." end) return nil, "locked" end local start = now() local count, purged local cursor = "0" -- purge XX:purge, XX:keys local ok, err = pcall(function() local renamed, err = red:renamenx(self.PK, self.PURGE) assert(renamed or err:match("no such key"), err) if renamed == 0 then self:warn("purge()", function() return "continue previous purge(): you need to call purge() again after the current process will be completed" end) end count, purged = purge_bulk(self, self.PURGE, function() local keys, err repeat local tmp = assert(red:zscan(self.PURGE, cursor, "count", 1000, "match", "*")) cursor, keys, err = unpack(tmp) assert(not err, err) lock:prolong() until cursor == "0" or #keys ~= 0 return red:array_to_hash(keys) end, function(red, bulk) -- setup watchers (prepare transaction) return watch(self, red, bulk) end) if cursor == "0" then -- full assert(red:del(self.PURGE)) end end) lock:release() assert(ok, err) if count ~= 0 then self:info("purge()", function() return "count=", count, " purged=", purged, " at ", now() - start, " seconds" end) end return true end local function cleanup_keys(self, red) local lock = self.redis:create_lock(self.cache_id, 10) if not lock:aquire() then return nil, "locked" end local start = now() local count = 0 local ok, err = pcall(function() count = purge_bulk(self, self.PK, function() local keys = assert(red:zrangebyscore(self.PK, 0, time(), "LIMIT", 0, 1000)) lock:prolong() local h = {} foreachi(keys, function(k) h[k] = true end) return h end) end) lock:release() assert(ok, err) if count ~= 0 then self:info("cleanup()", function() return "count=", count, " at ", now() - start, " seconds" end) end return true end function cache_class:gc() pcall(cache_desc_fixup, self) local cursor = "0" local count = 0 local function gc(red) local lock = self.redis:create_lock(self.cache_id .. ":gc", 10) if not lock:aquire() then return end local indexes local err repeat local part = 0 local start = now() repeat cursor, indexes, err = unpack(assert(red:scan(cursor, "count", 100, "match", self.cache_id .. SEP .. "*" .. SEP .. "*"))) assert(not err, err) self.redis:handle(function(red) local resp = pipeline(red, function() foreachi(indexes, function(index) red:zremrangebyscore(index, 0, time() - 60) end) end) foreachi(resp, function(n) part = part + n end) end, self.redis_rw) lock:prolong() until part >= 10000 or cursor == "0" if part ~= 0 then self:info("gc_part()", function() return "end, count=", part, " at ", now() - start, " seconds" end) end count = count + part until cursor == "0" lock:release() if count ~= 0 then self:info("gc()", function() return "end, count=", count end) end return count end local gc_job gc_job = job.new("gc " .. self.cache_name, function() local ok, ret = pcall(function() return self.redis:handle(function(red) return gc(red) end, self.redis_ro) end) if ok then if not ret then -- locked self:err("gc()", function() return "can't aquire the lock ..." end) elseif cursor == "0" then -- completed gc_job:stop() gc_job:clean() end return true end if ret:match("invalid cursor") then -- repeat all cursor = "0" return true end -- other error self:err("gc()", function() return err or ret end) return true end, 0.1) if gc_job:running() then return nil, "already in progress" end gc_job:run() return "async" end function cache_class:purge(max_wait) pcall(cache_desc_fixup, self) local function purge() return self.redis:handle(function(red) red:del("L:" .. self.cache_name .. ":last_modified") self:log_event(events.PURGE) return purge_keys(self, red) end, self.redis_rw) end local completed local purge_job purge_job = job.new("purge " .. self.cache_name, function() local ok, ret, err = pcall(purge) if ok and ret then purge_job:stop() purge_job:clean() completed = true elseif err ~= "locked" then self:err("purge()", function() return err or ret end) end return true end, 1) if purge_job:running() then return nil, "already in progress" end purge_job:run() local wait_to = now() + (max_wait or 0) while not completed and now() < wait_to and not worker_exiting() do sleep(0.1) end return completed and true or "async" end function cache_class:last_modified() local last_modified = function(red) return assert(red:get("L:" .. self.cache_name .. ":last_modified")) end return self.redis:handle(last_modified, self.redis_rw) end function cache_class:update_last_modified(lm) local update_last_modified = function(red) assert(red:set("L:" .. self.cache_name .. ":last_modified", lm)) self:info("update_last_modified()", function() return lm end) return true end return self.redis:handle(update_last_modified, self.redis_rw) end function cache_class:create_lock(name, period) return self.redis:create_lock(name, period) end local batch_class = {} function batch_class:add(f, ...) local fun = self.cache[f] if not fun then return nil, f .. " function is not found" end tinsert(self.batch, { function(...) assert(fun(...)) end, { ... } }) if #self.batch < self.size then return true end return self:flush() end function batch_class:flush() local threads = {} local ok, err = pcall(foreachi, self.batch, function(opts) local fun, args = unpack(opts) local thr = thread_spawn(fun, self.cache, unpack(args)) assert(thr, "failed to create corutine") tinsert(threads, thr) end) if not ok then self.cache:err("batch:flush()", function() return err end) end for i=1,#threads do local result = { thread_wait(threads[i]) } local ok = tremove(result, 1) self.ret[1 + #self.ret] = { ok, result, tremove(self.batch, 1)[2] } end return ok, err end function batch_class:results() return self.ret end function batch_class:cancel() self.batch = {} self.ret = {} end function cache_class:create_batch(size) return setmetatable({ size = size, threads = {}, batch = {}, ret = {}, cache = self }, { __index = batch_class }) end function cache_class:ro_socket() return self.redis_ro end function cache_class:rw_socket() return self.redis_rw end local function init_memory(self) if not self.memory then return end if self.memory.prefetch then self.memory.ttl = nil -- no ttl end self.memory.events = self.memory.events or {} self.memory.events.on_set = self.memory.events.on_set or fake_fun self.memory.events.on_delete = self.memory.events.on_delete or fake_fun self.memory.events.on_purge = self.memory.events.on_purge or fake_fun -- fix worker local ttl self.memory.L1 = self.memory.L1 or { ttl = 0, count = 0 } self.memory.L1.ttl = min(self.memory.L1.ttl or 0, self.memory.ttl or self.memory.L1.ttl or 0) local shdict = require "shdict" local shdict_ex = require "shdict_ex" local err self.memory.shm = shdict.new(self.memory.name) self.memory.dict, err = assert(shdict_ex.new(self.memory.name, self.memory.L1.ttl, self.memory.L1.ttl ~= 0 and self.memory.L1.count or 0)) end function cache_class:init() cache_desc_fixup(self) if self.ttl and not self.cleanup_off then job.new("cleanup " .. self.cache_name, function() self.redis:handle(function(red) local ok, err = pcall(cleanup_keys, self, red) if not ok and err ~= "locked" then self:err("cleanup_keys()", function() return err end) end end, self.redis_rw) return true end, 10):run() end if not self.memory then return end local update_job = job.new("memory update " .. self.cache_name, function() memory_update(self) return true end, 1) job.new("memory cleanup " .. self.cache_name, function() memory_cleanup(self) return true end, 60):run() if not self.memory.prefetch then job.new("memory hits " .. self.cache_name, function() local p = max(60, self.memory.ttl) / 60 local hits_avg, miss_avg = self:hits(p, p) local hits_1, miss_1 = self:hits(1, 1) if hits_1 + miss_1 == 0 then return end self:info("memory_hits()", function() return "avg: ", floor(100 * hits_avg / (hits_avg + miss_avg)), "%, ", "last: ", floor(100 * hits_1 / (hits_1 + miss_1)), "% ", "hits=", hits_1, " misses=", miss_1 end) return true end, 60):run() end local prefetch_job prefetch_job = job.new("memory prefetch " .. self.cache_name, function() local ok, err = pcall(memory_prefetch, self) if ok then prefetch_job:stop() else self:err("memory_prefetch()", function() return err end) end return true end, 1) update_job:wait_for(prefetch_job) prefetch_job:run() update_job:run() return prefetch_job end function cache_class:desc() pcall(cache_desc_fixup) local get_cache_desc = function(red) local cache_desc = assert(red:hgetall("cache:" .. self.cache_name)) if cache_desc == ngx_null then return end cache_desc = red:array_to_hash(cache_desc) cache_desc.fields = json_decode(cache_desc.fields) cache_desc.indexes = json_decode(cache_desc.indexes) cache_desc.f_index = nil cache_desc.i_index = nil return cache_desc end return system:handle(get_cache_desc) end -- public api function _M.new(opts, redis_opts) assert(opts.fields and type(opts.fields) == "table", "fields table required") assert(opts.cache_id, "cache_id required") assert(opts.cache_name, "cache_name required") opts.redis = redis.new(redis_opts) opts.redis_ro = opts.redis:ro_socket() opts.redis_rw = opts.redis:rw_socket() opts.sets = {} opts.lists = {} opts.indexes = opts.indexes or {} for i, index in ipairs(opts.indexes) do opts.indexes[i] = { fields = index } foreachi(index, function(name) local field = unpack(find_if_i(opts.fields, function(field) return field.name == name end) or {}) assert(field, "invalid index: field " .. name .. " is not found") field.indexed = true end) end opts.fields_by_name = {} foreachi(opts.fields, function(field) if field.ftype == ftype.INT64 or field.ftype == ftype.UINT64 then assert(int64, "Int64 unsupported") end field.name = field.name:lower() if field.ftype == ftype.SET then tinsert(opts.sets, field) end if field.ftype == ftype.LIST then tinsert(opts.lists, field) end if field.skip then field.nostore = true end opts.fields_by_name[field.name] = field end) local function setpartof(t) foreachi(t, function(field) foreachi(type(field.source) == "table" and field.source or { field.source }, function(source) for i=1,#opts.fields do if opts.fields[i].name == source then opts.fields[i].skip = true opts.fields[i].partof = field.name break end end end) end) end setpartof(opts.sets) setpartof(opts.lists) opts.PK = opts.cache_id .. ":keys" opts.PURGE = opts.cache_id .. ":purge" local CONFIG = ngx.shared.config local scope = redis_opts.scope or CONFIG:get("ngx.caches.scope") or "ngx" opts.debug_enabled = CONFIG:get(scope .. ".caches." .. opts.cache_name .. ".debug") local config_ttl = CONFIG:get(scope .. ".caches." .. opts.cache_name .. ".ttl") if not opts.ttl then opts.ttl = config_ttl end if opts.ttl then opts.ttl = opts.ttl * 60 end opts.cleanup_off = CONFIG:get(scope .. ".caches." .. opts.cache_name .. ".cleanup_off") local cache = assert(setmetatable(opts, { __index = cache_class })) opts.log = log_server.new(cache) init_memory(cache) return cache end do common.export_to(_M) _M.events = events end return _M
local shared = require("tevgit:workshop/controllers/shared.lua") local themer = require("tevgit:workshop/controllers/ui/core/themer.lua") local controller = {} function roundToMultiple(number, multiple) if multiple == 0 then return number end return ((number % multiple) > multiple/2) and number + multiple - number%multiple or number - number%multiple end -- Used to sort objects by ZIndex. -- This script uses the object's ZIndex to control the order in the dock function numSorter(a,b) return a < b end function zSorter(a,b) return a.zIndex < b.zIndex end -- Currently only supposed to be called once, -- it creates 'docks's that can hold other windows. -- currently docks themselves are static and invisible, -- this can easily be changed. controller.setupDocks = function () if controller.docks then -- delete old docks for _,dock in pairs(controller.docks) do for _,child in pairs(dock.children) do child.parent = dock.parent end dock:destroy() end end controller.docks = { engine.construct("guiFrame", shared.workshop.interface, { name = "_dockTop", size = guiCoord(1, -500, 0, 250 - 76), position = guiCoord(250, 0, 0, 76), backgroundAlpha = 0, handleEvents = false, cropChildren = false, }), engine.construct("guiFrame", shared.workshop.interface, { name = "_dockLeft", size = guiCoord(0, 250, 1, -76), position = guiCoord(0, 0, 0, 76), backgroundAlpha = 0, handleEvents = false, cropChildren = false, }), engine.construct("guiFrame", shared.workshop.interface, { name = "_dockBottom", size = guiCoord(1, -500, 0, 250), position = guiCoord(0, 250, 1, -250), backgroundAlpha = 0, handleEvents = false, cropChildren = false, }), engine.construct("guiFrame", shared.workshop.interface, { name = "_dockRight", size = guiCoord(0, 265, 1, -76), position = guiCoord(1, -265, 0, 76), backgroundAlpha = 0, handleEvents = false, cropChildren = false, }) } end controller.setupDocks() -- Store info about a window, -- such as their pre-docked size local windowDetails = {} -- Ran whenever a dock's contents is changed local function dockCallback(dock, isPreviewing) if dock.name == "_dockLeft" then shared.workshop.interface["_toolBar"].position = (#dock.children > 0 or isPreviewing) and guiCoord(0, 258, 0, 80) or guiCoord(0, 8, 0, 80) end end -- Adds a window to a dock local function pushToDock(window, dock, slot) local perWindow = 1 / (#dock.children + 1) local isVertical = dock.absoluteSize.y > dock.absoluteSize.x -- sort zIndexes local children = dock.children table.sort(children, zSorter) local ii = 0 for i,v in pairs(children) do if ii == slot then ii = ii + 1 end v.zIndex = ii v.size = guiCoord(isVertical and 1 or perWindow, 0, isVertical and perWindow or 1, 0) v.position = guiCoord(isVertical and 0 or (perWindow*(ii)), 0, isVertical and (perWindow*(ii)) or 0, 0) ii = ii + 1 end window.parent = dock window.size = guiCoord(isVertical and 1 or perWindow, 0, isVertical and perWindow or 1, 0) window.position = guiCoord(isVertical and 0 or (slot * perWindow), 0, isVertical and slot * perWindow or 0, 0) window.zIndex = slot dockCallback(dock) end -- Properly orders windows within a dock -- useful when a window is removed local function orderDock(dock) local perWindow = 1 / #dock.children local isVertical = dock.absoluteSize.y > dock.absoluteSize.x -- sort zIndexes local children = dock.children table.sort(children, zSorter) local ii = 0 for i,v in pairs(children) do v.zIndex = ii v.size = guiCoord(isVertical and 1 or perWindow, 0, isVertical and perWindow or 1, 0) v.position = guiCoord(isVertical and 0 or (perWindow*(ii)), 0, isVertical and (perWindow*(ii)) or 0, 0) ii = ii + 1 end dockCallback(dock) end -- returns the parent dock of a window if any local function isInDock(window) for _,v in pairs(controller.docks) do if window:isDescendantOf(v) then return v end end end controller.saveDockSettings = function() -- Save dock to workshop settings local settings = {} for _,v in pairs(controller.docks) do settings[v.name] = {} local children = v.children table.sort(children, zSorter) for _,vv in pairs(children) do settings[v.name][vv.name] = vv.zIndex end shared.workshop:setSettings("workshopDocks", settings) end end -- used if docks haven't been saved before: local defaultSettings = { ["_dockRight"] = { ["Hierarchy"] = 0, ["Properties"] = 1 } } controller.loadDockSettings = function() -- Load Dock from settings local settings = shared.workshop:getSettings("workshopDocks") if not settings then settings = defaultSettings end for dockName, windows in pairs(settings) do local dock = shared.workshop.interface:hasChild(dockName) if dock then for windowName, zIndex in pairs(windows) do local win = shared.workshop.interface:hasChild(windowName) if win then if not windowDetails[win] then windowDetails[win] = {zIndex = win.zIndex, size = win.size} end win.zIndex = zIndex win.parent = dock end end end end for _,v in pairs(controller.docks) do orderDock(v) end end controller.undock = function (window) local dock = isInDock(window) if dock then window.parent = dock.parent orderDock(dock) if windowDetails[window] then window.size = windowDetails[window].size end end end -- Invoked by a 3rd party script when user begins dragging window. controller.beginWindowDrag = function(window, dontDock) -- change window appeareance (mainly for debugging) to make it clear this window is on the move. if not windowDetails[window] then windowDetails[window] = {zIndex = window.zIndex, size = window.size} else window.size = windowDetails[window].size end window.zIndex = 99 -- offset used for dragging local offset = window.absolutePosition - engine.input.mousePosition -- undock window controller.undock(window) local previewer = engine.construct("guiFrame", shared.workshop.interface, { handleEvents = false, visible = false, backgroundAlpha = 0.75 }) themer.registerGui(previewer, "primary") local isOverDock, slot; local lastDock; -- yield until user releases window drag while engine.input:isMouseButtonDown(enums.mouseButton.left) do local mPos = engine.input.mousePosition local newpos = mPos + offset window.position = guiCoord(0, newpos.x, 0, newpos.y) isOverDock = false if not dontDock then for _,dock in pairs(controller.docks) do -- the user's cursor is in this dock. if mPos.x > dock.absolutePosition.x and mPos.x < dock.absolutePosition.x + dock.absoluteSize.x and mPos.y > dock.absolutePosition.y and mPos.y < dock.absolutePosition.y + dock.absoluteSize.y then local perWindow = 1 / (#dock.children + 1) local perWindowSize = perWindow * dock.absoluteSize local isVertical = dock.absoluteSize.y > dock.absoluteSize.x local pws = (isVertical and perWindowSize.y or perWindowSize.x) local m = (isVertical and mPos.y or mPos.x) local dockPosition = (isVertical and dock.absolutePosition.y or dock.absolutePosition.x) local dockSize = (isVertical and dock.absoluteSize.y or dock.absoluteSize.x) local mouseScaled = (m - dockPosition) / dockSize slot = math.clamp((roundToMultiple(mouseScaled, perWindow) / perWindow), 0, (#dock.children)) isOverDock = dock previewer.visible = true previewer.size = guiCoord(0, isVertical and dock.absoluteSize.x or pws, 0, isVertical and pws or dock.absoluteSize.y) previewer.position = guiCoord(0, isVertical and dock.absolutePosition.x or dock.absolutePosition.x + (slot * pws), 0, isVertical and dock.absolutePosition.y + (slot * pws) or dock.absolutePosition.y) local ii = 0 local children = dock.children table.sort(children, zSorter) for i,v in pairs(children) do if ii == slot then ii = ii + 1 end v.size = guiCoord(isVertical and 1 or perWindow, 0, isVertical and perWindow or 1, 0) v.position = guiCoord(isVertical and 0 or (perWindow*(ii)), 0, isVertical and (perWindow*(ii)) or 0, 0) ii = ii + 1 end dockCallback(dock, true) end end end if (lastDock ~= isOverDock) then if lastDock then orderDock(lastDock) -- reorder old dock we were hovering end lastDock = isOverDock end if not isOverDock and previewer.visible then previewer.visible = false end wait() end if (lastDock and lastDock ~= isOverDock) then orderDock(lastDock) -- reorder old dock we were hovering end previewer:destroy() -- reset Window appearance window.zIndex = windowDetails[window].zIndex if isOverDock then pushToDock(window, isOverDock, slot) else windowDetails[window] = nil end -- save dock controller.saveDockSettings() end return controller
--- 模块功能:阿里云功能测试. -- 支持数据传输和OTA功能 -- @author openLuat -- @module aLiYun.testALiYun -- @license MIT -- @copyright openLuat -- @release 2018.04.14 module(...,package.seeall) require"aLiYun" require"misc" require"pm" --采用一机一密认证方案时: --PRODUCT_KEY为阿里云华东2站点上创建的产品的ProductKey,用户根据实际值自行修改 local PRODUCT_KEY = "b0FMK1Ga5cp" --除了上面的PRODUCT_KEY外,还需要提供获取DeviceName的函数、获取DeviceSecret的函数 --设备名称使用函数getDeviceName的返回值,默认为设备的IMEI --设备密钥使用函数getDeviceSecret的返回值,默认为设备的SN --单体测试时,可以直接修改getDeviceName和getDeviceSecret的返回值 --批量量产时,使用设备的IMEI和SN;合宙生产的模块,都有唯一的IMEI,用户可以在自己的产线批量写入跟IMEI(设备名称)对应的SN(设备密钥) --或者用户自建一个服务器,设备上报IMEI给服务器,服务器返回对应的设备密钥,然后调用misc.setSn接口写到设备的SN中 --采用一型一密认证方案时: --PRODUCT_KEY和PRODUCE_SECRET为阿里云华东2站点上创建的产品的ProductKey和ProductSecret,用户根据实际值自行修改 --local PRODUCT_KEY = "b1KCi45LcCP" --local PRODUCE_SECRET = "VWll9fiYWKiwraBk" --除了上面的PRODUCT_KEY和PRODUCE_SECRET外,还需要提供获取DeviceName的函数、获取DeviceSecret的函数、设置DeviceSecret的函数 --设备第一次在某个product下使用时,会先去云端动态注册,获取到DeviceSecret后,调用设置DeviceSecret的函数保存DeviceSecret --[[ 函数名:getDeviceName 功能 :获取设备名称 参数 :无 返回值:设备名称 ]] local function getDeviceName() --默认使用设备的IMEI作为设备名称,用户可以根据项目需求自行修改 return misc.getImei() --用户单体测试时,可以在此处直接返回阿里云的iot控制台上注册的设备名称,例如return "862991419835241" --return "862991419835241" end --[[ 函数名:setDeviceSecret 功能 :修改设备密钥 参数 :设备密钥 返回值:无 ]] local function setDeviceSecret(s) --默认使用设备的SN作为设备密钥,用户可以根据项目需求自行修改 misc.setSn(s) end --[[ 函数名:getDeviceSecret 功能 :获取设备密钥 参数 :无 返回值:设备密钥 ]] local function getDeviceSecret() --默认使用设备的SN作为设备密钥,用户可以根据项目需求自行修改 return misc.getSn() --用户单体测试时,可以在此处直接返回阿里云的iot控制台上生成的设备密钥,例如return "y7MTCG6Gk33Ux26bbWSpANl4OaI0bg5Q" --return "y7MTCG6Gk33Ux26bbWSpANl4OaI0bg5Q" end --阿里云客户端是否处于连接状态 local sConnected local publishCnt = 1 --[[ 函数名:pubqos1testackcb 功能 :发布1条qos为1的消息后收到PUBACK的回调函数 参数 : usertag:调用mqttclient:publish时传入的usertag result:true表示发布成功,false或者nil表示失败 返回值:无 ]] local function publishTestCb(result,para) log.info("testALiYun.publishTestCb",result,para) sys.timerStart(publishTest,20000) publishCnt = publishCnt+1 end --发布一条QOS为1的消息 function publishTest() if sConnected then --注意:在此处自己去控制payload的内容编码,aLiYun库中不会对payload的内容做任何编码转换 aLiYun.publish("/"..PRODUCT_KEY.."/"..getDeviceName().."/update","qos1data",1,publishTestCb,"publishTest_"..publishCnt) end end ---数据接收的处理函数 -- @string topic,UTF8编码的消息主题 -- @number qos,消息质量等级 -- @string payload,原始编码的消息负载 local function rcvCbFnc(topic,qos,payload) log.info("testALiYun.rcvCbFnc",topic,qos,payload) end --- 连接结果的处理函数 -- @bool result,连接结果,true表示连接成功,false或者nil表示连接失败 local function connectCbFnc(result) log.info("testALiYun.connectCbFnc",result) sConnected = result if result then --订阅主题,不需要考虑订阅结果,如果订阅失败,aLiYun库中会自动重连 aLiYun.subscribe({["/"..PRODUCT_KEY.."/"..getDeviceName().."/get"]=0, ["/"..PRODUCT_KEY.."/"..getDeviceName().."/get"]=1}) --注册数据接收的处理函数 aLiYun.on("receive",rcvCbFnc) --PUBLISH消息测试 publishTest() end end -- 认证结果的处理函数 -- @bool result,认证结果,true表示认证成功,false或者nil表示认证失败 local function authCbFnc(result) log.info("testALiYun.authCbFnc",result) end --采用一机一密认证方案时: --配置:ProductKey、获取DeviceName的函数、获取DeviceSecret的函数;其中aLiYun.setup中的第二个参数必须传入nil aLiYun.setup(PRODUCT_KEY,nil,getDeviceName,getDeviceSecret) --采用一型一密认证方案时: --配置:ProductKey、ProductSecret、获取DeviceName的函数、获取DeviceSecret的函数、设置DeviceSecret的函数 --aLiYun.setup(PRODUCT_KEY,PRODUCE_SECRET,getDeviceName,getDeviceSecret,setDeviceSecret) --setMqtt接口不是必须的,aLiYun.lua中有这个接口设置的参数默认值,如果默认值满足不了需求,参考下面注释掉的代码,去设置参数 --aLiYun.setMqtt(0) aLiYun.on("auth",authCbFnc) aLiYun.on("connect",connectCbFnc) --要使用阿里云OTA功能,必须参考本文件124或者126行aLiYun.setup去配置参数 --然后加载阿里云OTA功能模块(打开下面的代码注释) require"aLiYunOta" --如果利用阿里云OTA功能去下载升级合宙模块的新固件,默认的固件版本号格式为:_G.PROJECT.."_".._G.VERSION.."_"..sys.getcorever(),下载结束后,直接重启,则到此为止,不需要再看下文说明 --如果下载升级合宙模块的新固件,下载结束后,自己控制是否重启 --如果利用阿里云OTA功能去下载其他升级包,例如模块外接的MCU升级包,则根据实际情况,打开下面的代码注释,调用设置接口进行配置和处理 --设置MCU当前运行的固件版本号 --aLiYunOta.setVer("MCU_VERSION_1.0.0") --设置新固件下载后保存的文件名 --aLiYunOta.setName("MCU_FIRMWARE.bin") --[[ 函数名:otaCb 功能 :新固件文件下载结束后的回调函数 通过uart1(115200,8,uart.PAR_NONE,uart.STOP_1)把下载成功的文件,发送到MCU,发送成功后,删除此文件 参数 : result:下载结果,true为成功,false为失败 filePath:新固件文件保存的完整路径,只有result为true时,此参数才有意义 返回值:无 ]] local function otaCb(result,filePath) log.info("testALiYun.otaCb",result,filePath) if result then local uartID = 1 sys.taskInit( function() local fileHandle = io.open(filePath,"rb") if not fileHandle then log.error("testALiYun.otaCb open file error") if filePath then os.remove(filePath) end return end pm.wake("UART_SENT2MCU") uart.on(uartID,"sent",function() sys.publish("UART_SENT2MCU_OK") end) uart.setup(uartID,115200,8,uart.PAR_NONE,uart.STOP_1,nil,1) while true do local data = fileHandle:read(1460) if not data then break end uart.write(uartID,data) sys.waitUntil("UART_SENT2MCU_OK") end --此处上报新固件版本号(仅供测试使用) --用户开发自己的程序时,根据下载下来的新固件,执行升级动作 --升级成功后,调用aLiYunOta.setVer上报新固件版本号 --如果升级失败,调用aLiYunOta.setVer上报旧固件版本号 aLiYunOta.setVer("MCU_VERSION_1.0.1") uart.close(uartID) pm.sleep("UART_SENT2MCU") fileHandle:close() if filePath then os.remove(filePath) end end ) else --文件使用完之后,如果以后不再需求,需要自行删除 if filePath then os.remove(filePath) end end end --设置新固件下载结果的回调函数 --aLiYunOta.setCb(otaCb)
-- Getting folder that contains our src local folderOfThisFile = (...):match("(.-)[^%/%.]+$") local HooECS = require(folderOfThisFile .. 'namespace') local Entity = HooECS.class("Entity") function Entity:initialize(parent, name, active) self.components = {} self.eventManager = nil self.active = active or true self.alive = false if parent then self:setParent(parent) else parent = nil end self.name = name self.children = {} end -- Sets the entities component of this type to the given component. -- An entity can only have one Component of each type. function Entity:add(component) local name = component.class.name if self.components[name] then HooECS.debug("Entity: Trying to add Component '" .. name .. "', but it's already existing. Please use Entity:set to overwrite a component in an entity.") else self.components[name] = component if self.eventManager then self.eventManager:fireEvent(HooECS.ComponentAdded(self, name)) end end if component.addedToEntity then component:addedToEntity(self) end return self end function Entity:set(component) local name = component.class.name if self.components[name] == nil then self:add(component) else if self.components[name].addedToEntity ~= component.addedToEntity and component.addedToEntity then component:addedToEntity(self) end self.components[name] = component end end function Entity:addMultiple(componentList) for _, component in pairs(componentList) do self:add(component) end end function Entity:setMultiple(componentList) for _, component in pairs(componentList) do self:set(component) end end -- Removes a component from the entity. function Entity:remove(name) if self.components[name] then if self.components[name].removedFromEntity then self.components[name]:removedFromEntity(self) end self.components[name] = nil else HooECS.debug("Entity: Trying to remove unexisting component " .. name .. " from Entity. Please fix this") end if self.eventManager then self.eventManager:fireEvent(HooECS.ComponentRemoved(self, name)) end return self end function Entity:setParent(parent) if self.parent then self.parent.children[self.id] = nil end self.parent = parent self:registerAsChild() end function Entity:getParent() return self.parent end function Entity:getChildren() if next(self.children) then return self.children end end function Entity:registerAsChild() if self.id then self.parent.children[self.id] = self end end function Entity:get(name) return self.components[name] end function Entity:has(name) return not not self.components[name] end function Entity:getComponents() return self.components end function Entity:getRootEntity() local entity = self while entity.getParent do local parent = entity:getParent() if parent.engine then return parent else entity = parent end end end function Entity:getEngine() return self:getRootEntity().engine end function Entity:activate() if not self.active then self.active = true self.eventManager:fireEvent(HooECS.EntityActivated(self)) end end function Entity:deactivate() if self.active then self.active = false self.eventManager:fireEvent(HooECS.EntityDeactivated(self)) end end function Entity:isActive() return self.active end function Entity:setUpdate(newUpdateFunction) if type(newUpdateFunction) == "function" then self.update = newUpdateFunction local engine = self:getEngine() if engine then engine:addUpdateEntity(self) end elseif type(newUpdateFunction) == "nil" then self.update = nil local engine = self:getEngine() if engine then engine:removeUpdateEntity(self) end end end -- Returns an entity with all components deeply copied. function Entity:copy(componentList) function deepCopy(obj, seen) -- Handle non-tables and previously-seen tables. if type(obj) ~= 'table' then return obj end if seen and seen[obj] then return seen[obj] end -- New table; mark it as seen an copy recursively. local s = seen or {} local res = setmetatable({}, getmetatable(obj)) s[obj] = res local k, v = next(obj) while k do res[deepCopy(k, s)] = deepCopy(v, s) k, v = next(obj, k) end return res end local newEntity = Entity() newEntity.components = deepCopy(self.components) if componentList then if type(componentList) == "table" then newEntity:setMultiple(componentList) else HooECS.debug("Entity:copy() componentList is not a table!") end end return newEntity end -- Returns an entity with references to the components. -- Modifying a component of the origin entity will result in the returned entity being modified too. function Entity:shallowCopy(componentList) function shallowCopy(obj) if type(obj) ~= 'table' then return obj end local res = setmetatable({}, getmetatable(obj)) local k, v = next(obj) while k do res[k] = v k, v = next(obj, k) end return res end local newEntity = Entity() newEntity.components = shallowCopy(self.components) if componentList then if type(componentList) == "table" then newEntity:setMultiple(componentList) else HooECS.debug("Entity:shallowCopy() componentList is not a table!") end end return newEntity end return Entity
local Log = luajava.bindClass "android.util.Log" local config = {} -- 添加要调试的函数 local func = {} local NIL = {} setmetatable(NIL, { __tostring = function() return "nil" end }) local function printstack(mask, line) local m = 2 local dbs = {} local info = debug.getinfo(m) if info == nil then return end if not line and func and func[info.name] == nil then return end dbs.info = info local func = info.func local nups = info.nups local ups = {} dbs.upvalues = ups for n = 1, nups do local n, v = debug.getupvalue(func, n) if v == nil then v = NIL end if string.byte(n) == 40 then if ups[n] == nil then ups[n] = {} end table.insert(ups[n], v) else ups[n] = v end end local lps = {} dbs.localvalues = lps lps.vararg = {} --lps.temporary={} for n = -1, -255, -1 do local k, v = debug.getlocal(m, n) if k == nil then break end if v == nil then v = NIL end table.insert(lps.vararg, v) end for n = 1, 255 do local n, v = debug.getlocal(m, n) if n == nil then break end if v == nil then v = NIL end if string.byte(n) == 40 then if lps[n] == nil then lps[n] = {} end table.insert(lps[n], v) else lps[n] = v end end Log.d("test", string.format("%s %s\n%s", mask, line or info.name, dump(dbs))) end --print(string.byte("(")) if pcall(loadfile(activity.LuaDir .. "/.test.lua", "bt", config)) then if config.line then debug.sethook(printstack, "crl", config.line) else debug.sethook(printstack, "cr") end func = {} for k, v in ipairs(config.func) do func[v] = true end end
local pickers = require('telescope.pickers') local finders = require('telescope.finders') local conf = require('telescope.config').values local actions = require('telescope.actions') local action_state = require "telescope.actions.state" local make_entry = function() return function(entry) local content = table.concat(entry[1], [[\n]]) return { valid = true, value = entry[1], ordinal = content, display = content, } end end return function() pickers.new({}, { prompt_title = 'miniyank', finder = finders.new_table { results = vim.fn['miniyank#read'](), entry_maker = make_entry(), }, sorter = conf.generic_sorter({}), attach_mappings = function(prompt_bufnr, map) local put = function() local entry = action_state.get_selected_entry() actions.close(prompt_bufnr) vim.fn['miniyank#drop'](entry.value, 'p') end -- local Put = function() -- local entry = actions.get_selected_entry() -- actions.close() -- vim.fn['miniyank#drop'](entry.value, 'P') -- end local yank = function() local entry = action_state.get_selected_entry() actions.close(prompt_bufnr) vim.fn.setreg(vim.v.register, entry.value) end actions.select_default:replace(yank) map('n', '<C-l>', put) map('i', '<C-l>', put) return true end, }):find() end
require("iupcdaux") -- utility module used in some samples w = 100 h = 100 image_rgb = cd.CreateImageRGB(w, h) size = w * h i = 0 while i < size do if i < size/2 then image_rgb.r[i] = 255 image_rgb.g[i] = 0 image_rgb.b[i] = 0 else image_rgb.r[i] = 0 image_rgb.g[i] = 0 image_rgb.b[i] = 255 end i = i + 1 end dlg = iupcdaux.new_dialog(w, h) cnv = dlg[1] -- retrieve the IUP canvas -- custom function used in action callback -- from the iupcdaux module function cnv:Draw(canvas) canvas:PutImageRectRGB(image_rgb, 0, 0, w, h, 0, 0, 0, 0) end dlg:show() iup.MainLoop()
-- Comparison information expected_u_l2norm = 1.4225 expected_v_l2norm = 0.2252 epsilon = 0.0001 main_mesh = { type = "box", elements = {x = 3, y = 1}, size = {x = 8., y = 1.}, -- serial and parallel refinement levels ser_ref_levels = 0, par_ref_levels = 0, } -- material property helper functions function linear_mu(E, nu) return 0.5 * E / (1. + nu); end function linear_bulk(E, nu) return E / ( 3. * (1. - 2.*nu)); end -- Problem parameters E = 17.e6; nu = 0.3; r = 1.; -- density g = -32.3; -- gravity i = 1./12 * main_mesh.size.y * main_mesh.size.y * main_mesh.size.y; m = main_mesh.size.y * r; omega = (1.875) * (1.875) * math.sqrt(E * i / (m * main_mesh.size.x * main_mesh.size.x * main_mesh.size.x * main_mesh.size.x)); period = 2. * math.pi / omega; -- Simulation time parameters t_final = 2. * period; nsteps = 40; dt = t_final / nsteps; print("t_final = " .. t_final); -- Solver parameters solid = { equation_solver = { linear = { type = "iterative", iterative_options = { rel_tol = 1.0e-8, abs_tol = 1.0e-12, max_iter = 500, print_level = 0, solver_type = "gmres", prec_type = "HypreAMG", }, }, nonlinear = { rel_tol = 1.0e-8, abs_tol = 1.0e-12, max_iter = 500, print_level = 1, }, }, dynamics = { timestepper = "NewmarkBeta", enforcement_method = "RateControl", }, -- polynomial interpolation order order = 1, -- neo-Hookean material parameters corresponding to lienar elasticity mu = linear_bulk(E, nu)/2.; K = linear_bulk(E, nu)/2.; -- initial conditions initial_displacement = { vector_constant = { x = 0.0, y = 0.0 } }, -- boundary condition parameters boundary_conds = { ['displacement'] = { -- boundary attribute 1 (index 0) is fixed (Dirichlet) in the x direction attrs = {2}, vector_constant = { x = 0.0, y = 0.0 } }, }, }
rotSpeed = 150.0 panSpeed = 150.0 zoomSpeed = 50 finalPos = float3.new(0, 0, 0) angle = 45.0 remainingAngle = 0.0 offset = float3.new(0, 200, 270) scrollspeed = 15.0 targetAngle = 0.0 newZoomedPos = float3.new(0, 0, 0) mosquitoAlive = false zPanning = 0.0 -- 1 to go front, -1 to go back xPanning = 0.0 -- 1 to go right, -1 to go left borderXNegative = -2000 borderXPositive = 2190 borderZNegative = -1900 borderZPositive = 1350 borderXNegative1 = -2000 borderXPositive1 = 2190 borderZNegative1 = -1900 borderZPositive1 = 1350 borderXNegative2 = -1900 borderXPositive2 = 1880 borderZNegative2 = -900 borderZPositive2 = 1075 cursorMargin = 25 mouseTopIn = true mouseBottomIn = true mouseLeftIn = true mouseRightIn = true isEagleView = false camSensitivity = 0.2 lastDeltaX = 0 -- resetOffset = 1; -- currentTarget = float3.new(0, 0, 0) closestY = -100.0 furthestY = 2000.0 rayCastCulling = {} local freePanningDebug isStarting = true -- use the fokin start function Float3Length(v) return math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z) end function Float3Normalized(v) len = Float3Length(v) return { x = v.x / len, y = v.y / len, z = v.z / len } end function Float3Difference(a, b) return { x = b.x - a.x, y = b.y - a.y, z = b.z - a.z } end function Float3Distance(a, b) diff = Float3Difference(a, b) return Float3Length(diff) end function Float3NormalizedDifference(a, b) v = Float3Difference(a, b) return Float3Normalized(v) end function Float3Dot(a, b) return a.x * b.x + a.y * b.y + a.z * b.z end function Float3Angle(a, b) lenA = Float3Length(a) lenB = Float3Length(b) return math.acos(Float3Dot(a, b) / (lenA * lenB)) end function Float3Cross(a, b) return float3.new(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x) end function Float3Mult(a, b) return float3.new(a.x * b, a.y * b, a.z * b) end function Float3Sum(a, b) return float3.new(a.x + b.x, a.y + b.y, a.z + b.z) end function Float3RotateAxisAngle(v, axis, angle) do anglecos = math.cos(angle) vbycos = float3.new(v.x * anglecos, v.y * anglecos, v.z * anglecos) anglesin = math.sin(angle) axisvectorcross = Float3Cross(axis, v) axisvectordot = Float3Dot(axis, v) ret = Float3Sum(Float3Sum(vbycos, Float3Mult(axisvectorcross, anglesin)), (Float3Mult(axis, axisvectordot * (1 - anglecos)))) do return ret end end end function Start() -- Put the position of the selected character inside variable target level = GetVariable("GameState.lua", "levelNumber", INSPECTOR_VARIABLE_TYPE.INSPECTOR_INT) if level == 1 then borderXNegative = borderXNegative1 borderXPositive = borderXPositive1 borderZNegative = borderZNegative1 borderZPositive = borderZPositive1 -- Log("Level 1") elseif level == 2 then borderXNegative = borderXNegative2 borderXPositive = borderXPositive2 borderZNegative = borderZNegative2 borderZPositive = borderZPositive2 -- Log("Level 2") end -- Log("Level xD") freePanningDebug = false GetSelectedCharacter() offset = float3.new(0, 240, 270) newZoomedPos = float3.new(0, 99, 112) end function Update(dt) if (GetMouseScreenPos().y < 0 or GetMouseScreenPos().y > GetLastViewportSize().y or GetMouseScreenPos().x < 0 or GetMouseScreenPos().x > GetLastViewportSize().x) then xPanning = 0.0 zPanning = 0.0 end -- str = "Position X: " .. tostring(gameObject:GetTransform():GetPosition().x) .. "Position Z: " .. tostring(gameObject:GetTransform():GetPosition().z) .. "\n" -- Log(str) local lastFinalPos = componentTransform:GetPosition() -- input: mouse wheel to zoom in and out -- local? if (GetMouseZ() > 0) then local deltaY = newZoomedPos.y + gameObject:GetCamera():GetFront().y * zoomSpeed Log(tostring(deltaY) .. "\n") if math.abs(deltaY) < 110 then newZoomedPos.y = newZoomedPos.y + gameObject:GetCamera():GetFront().y * zoomSpeed newZoomedPos.x = newZoomedPos.x + gameObject:GetCamera():GetFront().x * zoomSpeed newZoomedPos.z = newZoomedPos.z + gameObject:GetCamera():GetFront().z * zoomSpeed end elseif (GetMouseZ() < 0) then local deltaY = newZoomedPos.y - gameObject:GetCamera():GetFront().y * zoomSpeed Log(tostring(deltaY) .. "\n") if math.abs(deltaY) < 165 then newZoomedPos.y = newZoomedPos.y - gameObject:GetCamera():GetFront().y * zoomSpeed newZoomedPos.x = newZoomedPos.x - gameObject:GetCamera():GetFront().x * zoomSpeed newZoomedPos.z = newZoomedPos.z - gameObject:GetCamera():GetFront().z * zoomSpeed end end if (GetInput(16) == KEY_STATE.KEY_REPEAT) then -- W --HAY UN KEY REPEAT zPanning = -1.0 end if (GetInput(16) == KEY_STATE.KEY_UP) then -- W zPanning = 0.0 end if (GetInput(17) == KEY_STATE.KEY_REPEAT) then -- A xPanning = -1 end if (GetInput(17) == KEY_STATE.KEY_UP) then -- A xPanning = 0.0 end if (GetInput(18) == KEY_STATE.KEY_REPEAT) then -- S zPanning = 1.0 end if (GetInput(18) == KEY_STATE.KEY_UP) then -- S zPanning = 0.0 end if (GetInput(19) == KEY_STATE.KEY_REPEAT) then -- D xPanning = 1.0 end if (GetInput(19) == KEY_STATE.KEY_UP) then -- D xPanning = 0.0 end -- Mouse Movement if (GetMouseScreenPos().y < GetLastViewportSize().y and GetMouseScreenPos().y > (GetLastViewportSize().y - cursorMargin)) then -- W --HAY UN KEY REPEAT mouseTopIn = true zPanning = -1.0 end if ((GetMouseScreenPos().y < (GetLastViewportSize().y) - cursorMargin and GetMouseScreenPos().y > cursorMargin) and mouseTopIn == true) then -- W mouseTopIn = false zPanning = 0.0 end if ((GetMouseScreenPos().x > 0 and GetMouseScreenPos().x < cursorMargin)) then -- A mouseLeftIn = true xPanning = -1.0 end if (GetMouseScreenPos().x > cursorMargin and GetMouseScreenPos().x < (GetLastViewportSize().x - cursorMargin) and mouseLeftIn == true) then -- A mouseLeftIn = false xPanning = 0.0 end if (GetMouseScreenPos().y > 0 and GetMouseScreenPos().y < cursorMargin) then -- S mouseBottomIn = true zPanning = 1.0 end if (GetMouseScreenPos().y > cursorMargin and GetMouseScreenPos().y < (GetLastViewportSize().y - cursorMargin) and GetMouseScreenPos().y < 0 and mouseBottomIn == true) then -- S mouseBottomIn = false zPanning = 0.0 end if (GetMouseScreenPos().x < GetLastViewportSize().x and GetMouseScreenPos().x > (GetLastViewportSize().x - cursorMargin)) then -- D mouseRightIn = true xPanning = 1.0 end if (GetMouseScreenPos().x < (GetLastViewportSize().x) - cursorMargin and GetMouseScreenPos().x > 15 and mouseRightIn == true) then -- D mouseRightIn = false xPanning = 0.0 end -- go back to the selected character -- if (GetInput(10) == KEY_STATE.KEY_DOWN) then -- R -- GetSelectedCharacter() -- offset = float3.new(0, 240, 270) -- end -- if (GetInput(10) == KEY_STATE.KEY_DOWN) then -- H -- if freePanningDebug then -- freePanningDebug = false -- else -- freePanningDebug = true -- end -- end if (GetInput(43) == KEY_STATE.KEY_DOWN) then -- SPACE if (isEagleView == true) then return end freePanningDebug = not freePanningDebug if freePanningDebug == true then GetSelectedCharacter() offset = float3.new(0, 240, 270) newZoomedPos = float3.new(0, 99, 112) CleanCulling() end end if (GetInput(14) == KEY_STATE.KEY_REPEAT) then -- Q local newQuat = Quat.new(float3.new(0, 1, 0), -0.0174533) offset = MulQuat(newQuat, offset) newZoomedPos = MulQuat(newQuat, newZoomedPos) end if (GetInput(15) == KEY_STATE.KEY_REPEAT) then -- E local newQuat = Quat.new(float3.new(0, 1, 0), 0.0174533) offset = MulQuat(newQuat, offset) newZoomedPos = MulQuat(newQuat, newZoomedPos) end if (GetMouseMotionX() > 0 and GetInput(2) == KEY_STATE.KEY_REPEAT) then xMotion = GetMouseMotionX() newDeltaX = xMotion * camSensitivity -- camera sensitivity deltaX = newDeltaX + 0.8 * (lastDeltaX - newDeltaX) lastDeltaX = deltaX finalDelta = deltaX * dt local newQuat = Quat.new(float3.new(0, 1, 0), finalDelta) offset = MulQuat(newQuat, offset) newZoomedPos = MulQuat(newQuat, newZoomedPos) xMotion = 0 end if (GetMouseMotionX() < 0 and GetInput(2) == KEY_STATE.KEY_REPEAT) then xMotion = GetMouseMotionX() newDeltaX = xMotion * camSensitivity -- camera sensitivity deltaX = newDeltaX + 0.8 * (lastDeltaX - newDeltaX) lastDeltaX = deltaX finalDelta = deltaX * dt local newQuat = Quat.new(float3.new(0, 1, 0), finalDelta) offset = MulQuat(newQuat, offset) newZoomedPos = MulQuat(newQuat, newZoomedPos) xMotion = 0 end -- modify target with the camera panning if (freePanningDebug == true) then local currentPanSpeed = panSpeed * dt panning = float3.new(xPanning, 0, zPanning) front = componentTransform:GetGlobalFront() front.y = 0 front = Float3Normalized(front) right = componentTransform:GetGlobalRight() right.y = 0 right = Float3Normalized(right) panning = Float3Sum(Float3Mult(right, panning.x), Float3Mult(front, panning.z)) -- str = "Front Normalized: " .. tostring(panning) .. "\n" -- Log(str) if (target.z >= borderZPositive and panning.z > 0) then panning = float3.new(0, 0, 0) end if (target.z <= borderZNegative and panning.z < 0) then panning = float3.new(0, 0, 0) end if (target.x <= borderXNegative and panning.x < 0) then panning = float3.new(0, 0, 0) end if (target.x >= borderXPositive and panning.x > 0) then panning = float3.new(0, 0, 0) end target.z = target.z + (panning.z * currentPanSpeed) target.x = target.x + (panning.x * currentPanSpeed) else GetSelectedCharacter() end -- Log("current target " .. target.x .. " " .. target.z .. "\n") -- add offset to the target to set the current camera position local newPos = float3.new(0, 0, 0) newPos.x = target.x + offset.x newPos.y = target.y + offset.y newPos.z = target.z + offset.z -- --compute final position adding zoom finalPos.x = newPos.x + newZoomedPos.x finalPos.y = newPos.y + newZoomedPos.y finalPos.z = newPos.z + newZoomedPos.z if Float3Angle(Float3Difference(target, newPos), Float3Difference(target, finalPos)) > math.rad(90) then front = Float3Normalized(gameObject:GetCamera():GetFront()) finalPos = float3.new(finalPos.x - front.x * zoomSpeed, finalPos.y - front.y * zoomSpeed, finalPos.z - front.z * zoomSpeed) newZoomedPos.x = newZoomedPos.x - gameObject:GetCamera():GetFront().x * zoomSpeed newZoomedPos.y = newZoomedPos.y - gameObject:GetCamera():GetFront().y * zoomSpeed newZoomedPos.z = newZoomedPos.z - gameObject:GetCamera():GetFront().z * zoomSpeed end componentTransform:SetPosition(finalPos) gameObject:GetCamera():LookAt(target) if (freePanningDebug == false) then if componentTransform:GetPosition() ~= lastFinalPos then for i = 1, #rayCastCulling do rayCastCulling[i].active = true end if #rayCastCulling > 0 then rayCastCulling = {} end rayCastCulling = CustomRayCastList(finalPos, target, {Tag.UNTAGGED, Tag.WALL, Tag.DECORATIONFLOOR}) for j = 1, #rayCastCulling do rayCastCulling[j].active = false end end -- 1st iteration use look at to center at characters end end function EventHandler(key, fields) -- funcion virtual que recibe todos los eventos que se componen de una key y unos fields. la cosa esta en especificar la key (quees el evento) if (key == "Mosquito_Spawn") then mosquito = fields[1] elseif (key == "Mosquito_Death") then mosquito = nil elseif (key == "Eagle_View_Camera") then if isEagleView == false then isEagleView = true Log("eagle view!") offset = float3.new(0, 300, 10) CleanCulling() else isEagleView = false Log("off eagle view!") offset = float3.new(0, 240, 270) newZoomedPos = float3.new(0, 99, 112) CleanCulling() end end end function GetSelectedCharacter() -- get character selected. I keep it in order to center the camera arround a player in case needed id = GetVariable("GameState.lua", "characterSelected", INSPECTOR_VARIABLE_TYPE.INSPECTOR_INT) if (id == 1) then target = Find("Zhib"):GetTransform():GetPosition() lastTarget = id elseif (id == 2) then if (mosquito ~= nil) then target = mosquito:GetTransform():GetPosition() else target = Find("Nerala"):GetTransform():GetPosition() end lastTarget = id elseif (id == 3) then target = Find("Omozra"):GetTransform():GetPosition() lastTarget = id else if (lastTarget == 1) then target = Find("Zhib"):GetTransform():GetPosition() elseif (lastTarget == 2) then if (mosquitoAlive == true and mosquito ~= nil) then target = mosquito:GetTransform():GetPosition() else target = Find("Nerala"):GetTransform():GetPosition() end elseif (lastTarget == 3) then target = Find("Omozra"):GetTransform():GetPosition() end end end function CleanCulling() for j = 1, #rayCastCulling do rayCastCulling[j].active = true end rayCastCulling = {} end