content
stringlengths
5
1.05M
w = love.graphics.getWidth(); h = love.graphics.getHeight(); max_acc = 180 max_vel = 60 max_visible_dist = 60 damping = 0.0 min_dist = 18; mouse_flee_radius = 35 keep_distance = true; stay_centered = true adjust_velocity = true stay_on_display = true show_visible = false should_flee = false boids = {}; function love.mousereleased(x, y, button) if button == "l" then addBoid(x,y) end if button == "r" then remove_nearest_Boid(x,y) end end function love.keypressed( key, isrepeat ) if (key == "d") then keep_distance = not keep_distance end if (key == "c") then stay_centered = not stay_centered end if (key == "v") then adjust_velocity = not adjust_velocity end if (key == "s") then stay_on_display = not stay_on_display end if (key == "q") then show_visible = not show_visible end if (key == "t") then for i = 1, 10, 1 do addBoid(w*0.5, h*0.5); end end if (key == "f") then should_flee = not should_flee end end function addBoid(x,y) local b = { pos_x = x, pos_y = y, vel_x = math.random()*14-7, vel_y = math.random()*14-7, acc_x = 0, acc_y = 0, } table.insert(boids,b) end function remove_nearest_Boid(x,y) local distSQ = math.huge local i = 1 for index, value in ipairs(boids) do local temp = (value.pos_x-x)*(value.pos_x-x)+(value.pos_y-y)*(value.pos_y-y) if distSQ>temp then distSQ = temp i = index end end table.remove(boids,i) end function dir_move_to(boid,x,y) local dx, dy, l dx = x - boid.pos_x dy = y - boid.pos_y local l = math.sqrt(dx*dx+dy*dy) if (l>0.0) then return dx/l, dy/l else return 0,0 end end function boid_apply_acc(boid, dir_x, dir_y) local l = math.sqrt(dir_x*dir_x+dir_y*dir_y) if l<=0.0 then return end boid.acc_x = dir_x/l*max_acc; boid.acc_y = dir_y/l*max_acc; end function visible_boids(boid) local dsq = max_visible_dist*max_visible_dist local dx = 0; local dy = 0 local visibles = {} for index, value in ipairs(boids) do dx = value.pos_x - boid.pos_x dy = value.pos_y - boid.pos_y if dx*dx + dy*dy <= dsq then table.insert(visibles, value); end end return visibles end function dir_flee_mouse(boid) local mx, my = love.mouse.getPosition( ) if ((mx-boid.pos_x)*(mx-boid.pos_x)+(my-boid.pos_y)*(my-boid.pos_y)<mouse_flee_radius*mouse_flee_radius) then local dx, dy = dir_move_to(boid, mx, my) return -dx,-dy else return 0,0 end end function dir_keep_distance(boid, vis) local dir_x=0; local dir_y=0; local dx = 0; local dy = 0; local l = 0 for index, value in ipairs(vis) do dx = value.pos_x - boid.pos_x dy = value.pos_y - boid.pos_y l = math.sqrt(dx*dx+dy*dy) if l>0.0 and l <= min_dist then dir_x = dir_x-dx/l; dir_y = dir_y-dy/l end end l = math.sqrt(dir_x*dir_x+dir_y*dir_y) if l>0.0 then return dir_x/l, dir_y/l --return dx,dy else return 0, 0 end end function dir_center(boid, vis) local x = 0 local y = 0 local c = 0 for index, value in ipairs(vis) do x = x+value.pos_x y = y+value.pos_y c = c+1 end if c>0 then x=x/c; y=y/c else x=boid.pos_x; y = boid.pos_y end return dir_move_to(boid, x,y) end function dir_average_vel(boid, vis) local x = 0 local y = 0 local c = 0 for index, value in ipairs(vis) do x = x+value.vel_x y = y+value.vel_y c = c+1 end if c>0 then x=x/c; y=y/c else x=boid.vel_x; y = boid.vel_y end local l = math.sqrt(x*x+y*y) if l>0.0 then return x/l, y/l --return dx,dy else return 0, 0 end end function love.load() for i = 1, 50, 1 do addBoid(math.random()*w*0.4+w*0.3, math.random()*h*0.4+h*0.3); --addBoid(math.random()+w*0.5, math.random()+h*0.5); end end function love.update(dt) -- Physics for index, value in ipairs(boids) do value.vel_x = value.vel_x+dt*value.acc_x; value.vel_y = value.vel_y+dt*value.acc_y; value.vel_x = value.vel_x*(1.0-damping) value.vel_y = value.vel_y*(1.0-damping) local vel = math.sqrt(value.vel_x*value.vel_x+value.vel_y*value.vel_y) if(vel>max_vel) then local d = max_vel/vel; value.vel_x = value.vel_x* d value.vel_y = value.vel_y*d end value.pos_x = value.pos_x+dt*value.vel_x; value.pos_y = value.pos_y+dt*value.vel_y; end -- Boid's Mind for index, value in ipairs(boids) do --dx, dy = dir_move_to(value,w*0.5,h*0.5) local vis = visible_boids(value) local dx, dy = 0,0 if keep_distance then dx, dy = dir_keep_distance(value, vis) end local cx, cy = 0,0 if stay_centered then cx, cy = dir_center(value,vis) end local vx, vy = dir_average_vel(value,vis) if adjust_velocity then vx, vy = dir_average_vel(value,vis) end local wx=0 local wy = 0 if stay_on_display then local offset = 40 if (value.pos_x<offset) then wx = 1 end if (value.pos_y<offset) then wy = 1 end if (value.pos_x>w-offset) then wx = -1 end if (value.pos_y>h-offset) then wy = -1 end end local fx, fy = 0,0 if (should_flee) then fx, fy = dir_flee_mouse(value) end boid_apply_acc(value, (dx+wx)*2+cx+vx+8*fx,(dy+wy)*2+cy+vy+wy+8*fy) end end function love.draw() for index, value in ipairs(boids) do love.graphics.circle( "fill", value.pos_x, value.pos_y, 5, 10 ) if show_visible then love.graphics.circle( "line", value.pos_x, value.pos_y, max_visible_dist, 100 ) end end love.graphics.print(string.format("Keep distance[d]:%s, Stay centered[c]:%s, Adjust velocity[v]:%s, Stay on display[s]:%s",tostring(keep_distance),tostring(stay_centered),tostring(adjust_velocity),tostring(stay_on_display)), 0, 0) love.graphics.print(string.format("Left klick: create, Right click: kill, Show Visible[q]:%s, Flee[f]:%s, Create 10 Boids[t]",tostring(show_visible),tostring(should_flee)), 0, 20) end
-------------------------------------------------------------------------------- -- Vector support -- -------------------------------------------------------------------------------- local delta = wire_expression2_delta local random = math.random local Vector = Vector local sqrt = math.sqrt local floor = math.floor local ceil = math.ceil local pi = math.pi local atan2 = math.atan2 local asin = math.asin local rad2deg = 180 / pi local deg2rad = pi / 180 -- TODO: add reflect? -- TODO: add absdotproduct? -- TODO: add helper for angle and dotproduct? (just strange?) -------------------------------------------------------------------------------- registerType("vector", "v", { 0, 0, 0 }, nil, function(self, output) return Vector(output[1], output[2], output[3]) end, function(retval) if isvector(retval) then return end if not istable(retval) then error("Return value is neither a Vector nor a table, but a "..type(retval).."!",0) end if #retval ~= 3 then error("Return value does not have exactly 3 entries!",0) end end, function(v) return not isvector(v) and (not istable(v) or #v ~= 3) end ) -------------------------------------------------------------------------------- __e2setcost(1) -- approximated e2function vector vec() return { 0, 0, 0 } end __e2setcost(2) e2function vector vec(x) return { x, x, x } end e2function vector vec(x, y, z) return { x, y, z } end e2function vector vec(vector2 v2) return { v2[1], v2[2], 0 } end e2function vector vec(vector2 v2, z) return { v2[1], v2[2], z } end e2function vector vec(vector4 v4) return { v4[1], v4[2], v4[3] } end --- Convert Angle -> Vector e2function vector vec(angle ang) return { ang[1], ang[2], ang[3] } end -------------------------------------------------------------------------------- registerOperator("ass", "v", "v", function(self, args) local lhs, op2, scope = args[2], args[3], args[4] local rhs = op2[1](self, op2) local Scope = self.Scopes[scope] local lookup = Scope.lookup if !lookup then lookup = {} Scope.lookup = lookup end if lookup[rhs] then lookup[rhs][lhs] = true else lookup[rhs] = {[lhs] = true} end Scope[lhs] = rhs Scope.vclk[lhs] = true return rhs end) -------------------------------------------------------------------------------- e2function number vector:operator_is() if this[1] > delta or -this[1] > delta or this[2] > delta or -this[2] > delta or this[3] > delta or -this[3] > delta then return 1 else return 0 end end e2function number vector:operator==( vector other ) if this[1] - other[1] <= delta and other[1] - this[1] <= delta and this[2] - other[2] <= delta and other[2] - this[2] <= delta and this[3] - other[3] <= delta and other[3] - this[3] <= delta then return 1 else return 0 end end e2function number vector:operator!=( vector other ) if this[1] - other[1] > delta or other[1] - this[1] > delta or this[2] - other[2] > delta or other[2] - this[2] > delta or this[3] - other[3] > delta or other[3] - this[3] > delta then return 1 else return 0 end end -------------------------------------------------------------------------------- e2function vector vector:operator_neg() return { -this[1], -this[2], -this[3] } end e2function vector operator+(lhs, vector rhs) return { lhs + rhs[1], lhs + rhs[2], lhs + rhs[3] } end e2function vector operator+(vector lhs, rhs) return { lhs[1] + rhs, lhs[2] + rhs, lhs[3] + rhs } end e2function vector operator+(vector lhs, vector rhs) return { lhs[1] + rhs[1], lhs[2] + rhs[2], lhs[3] + rhs[3] } end e2function vector operator-(lhs, vector rhs) return { lhs - rhs[1], lhs - rhs[2], lhs - rhs[3] } end e2function vector operator-(vector lhs, rhs) return { lhs[1] - rhs, lhs[2] - rhs, lhs[3] - rhs } end e2function vector operator-(vector lhs, vector rhs) return { lhs[1] - rhs[1], lhs[2] - rhs[2], lhs[3] - rhs[3] } end e2function vector operator*(lhs, vector rhs) return { lhs * rhs[1], lhs * rhs[2], lhs * rhs[3] } end e2function vector operator*(vector lhs, rhs) return { lhs[1] * rhs, lhs[2] * rhs, lhs[3] * rhs } end e2function vector operator*(vector lhs, vector rhs) return { lhs[1] * rhs[1], lhs[2] * rhs[2], lhs[3] * rhs[3] } end e2function vector operator/(lhs, vector rhs) return { lhs / rhs[1], lhs / rhs[2], lhs / rhs[3] } end e2function vector operator/(vector lhs, rhs) return { lhs[1] / rhs, lhs[2] / rhs, lhs[3] / rhs } end e2function vector operator/(vector lhs, vector rhs) return { lhs[1] / rhs[1], lhs[2] / rhs[2], lhs[3] / rhs[3] } end e2function number vector:operator[](index) return this[floor(math.Clamp(index, 1, 3) + 0.5)] end e2function number vector:operator[](index, value) this[floor(math.Clamp(index, 1, 3) + 0.5)] = value self.GlobalScope.vclk[this] = true return value end -------------------------------------------------------------------------------- __e2setcost(10) -- temporary --- Returns a uniformly distributed, random, normalized direction vector. e2function vector randvec() local s,a, x,y --[[ This is a variant of the algorithm for computing a random point on the unit sphere; the algorithm is suggested in Knuth, v2, 3rd ed, p136; and attributed to Robert E Knop, CACM, 13 (1970), 326. ]] -- translated to lua from http://mhda.asiaa.sinica.edu.tw/mhda/apps/gsl-1.6/randist/sphere.c -- Begin with the polar method for getting x,y inside a unit circle repeat x = random() * 2 - 1 y = random() * 2 - 1 s = x*x + y*y until s <= 1.0 a = 2 * sqrt(1 - s) -- factor to adjust x,y so that x^2+y^2 is equal to 1-z^2 return Vector(x*a, y*a, s * 2 - 1) -- z uniformly distributed from -1 to 1 --[[ -- This variant saves 2 multiplications per loop, woo. But it's not readable and not verified, thus commented out. -- I will also not add a cheaper non-uniform variant, as that can easily be derived from the other randvec functions and V:normalize(). -- Begin with the polar method for getting x,y inside a (strangely skewed) unit circle repeat x = random() y = random() s = x*(x-1) + y*(y-1) until s <= -0.25 a = sqrt(-16 - s*64) -- factor to adjust x,y so that x^2+y^2 is equal to 1-z^2 return Vector((x-0.5)*a, (y-0.5)*a, s * 8 + 3) -- z uniformly distributed from -1 to 1 ]] end __e2setcost(5) --- Returns a random vector with its components between <min> and <max> e2function vector randvec( normal min, normal max) local range = max-min return Vector(min+random()*range, min+random()*range, min+random()*range) end --- Returns a random vector between <min> and <max> e2function vector randvec(vector min, vector max) local minx, miny, minz = min[1], min[2], min[3] return Vector(minx+random()*(max[1]-minx), miny+random()*(max[2]-miny), minz+random()*(max[3]-minz)) end -------------------------------------------------------------------------------- __e2setcost(5) e2function number vector:length() return (this[1] * this[1] + this[2] * this[2] + this[3] * this[3]) ^ 0.5 end e2function number vector:length2() return this[1] * this[1] + this[2] * this[2] + this[3] * this[3] end e2function number vector:distance(vector other) local dx, dy, dz = this[1] - other[1], this[2] - other[2], this[3] - other[3] return (dx * dx + dy * dy + dz * dz) ^ 0.5 end e2function number vector:distance2( vector other ) local dx, dy, dz = this[1] - other[1], this[2] - other[2], this[3] - other[3] return dx * dx + dy * dy + dz * dz end e2function vector vector:normalized() local len = (this[1] * this[1] + this[2] * this[2] + this[3] * this[3]) ^ 0.5 if len > delta then return { this[1] / len, this[2] / len, this[3] / len } else return { 0, 0, 0 } end end e2function number vector:dot( vector other ) return this[1] * other[1] + this[2] * other[2] + this[3] * other[3] end e2function vector vector:cross( vector other ) return { this[2] * other[3] - this[3] * other[2], this[3] * other[1] - this[1] * other[3], this[1] * other[2] - this[2] * other[1], } end __e2setcost(10) --- returns the outer product (tensor product) of two vectors e2function matrix vector:outerProduct( vector other ) return { this[1] * this[1], this[1] * other[2], this[1] * other[3], this[2] * this[1], this[2] * other[2], this[2] * other[3], this[3] * this[1], this[3] * other[2], this[3] * other[3], } end __e2setcost(15) e2function vector vector:rotateAroundAxis(vector axis, degrees) local ca, sa = math.cos(degrees*deg2rad), math.sin(degrees*deg2rad) local x,y,z = axis[1], axis[2], axis[3] local length = (x*x+y*y+z*z)^0.5 x,y,z = x/length, y/length, z/length return {(ca + (x^2)*(1-ca)) * this[1] + (x*y*(1-ca) - z*sa) * this[2] + (x*z*(1-ca) + y*sa) * this[3], (y*x*(1-ca) + z*sa) * this[1] + (ca + (y^2)*(1-ca)) * this[2] + (y*z*(1-ca) - x*sa) * this[3], (z*x*(1-ca) - y*sa) * this[1] + (z*y*(1-ca) + x*sa) * this[2] + (ca + (z^2)*(1-ca)) * this[3]} end __e2setcost(5) e2function vector vector:rotate( angle ang ) local v = Vector(this[1], this[2], this[3]) v:Rotate(Angle(ang[1], ang[2], ang[3])) return v end e2function vector vector:rotate( normal pitch, normal yaw, normal roll ) local v = Vector(this[1], this[2], this[3]) v:Rotate(Angle(pitch, yaw, roll)) return v end e2function vector2 vector:dehomogenized() local w = this[3] if w == 0 then return { this[1], this[2] } end return { this[1]/w, this[2]/w } end e2function vector positive(vector rv1) return { rv1[1] >= 0 and rv1[1] or -rv1[1], rv1[2] >= 0 and rv1[2] or -rv1[2], rv1[3] >= 0 and rv1[3] or -rv1[3], } end __e2setcost(3) --- Convert the magnitude of the vector to radians e2function vector toRad(vector rv1) return Vector(rv1[1] * deg2rad, rv1[2] * deg2rad, rv1[3] * deg2rad) end --- Convert the magnitude of the vector to degrees e2function vector toDeg(vector rv1) return Vector(rv1[1] * rad2deg, rv1[2] * rad2deg, rv1[3] * rad2deg) end -------------------------------------------------------------------------------- __e2setcost(5) --- Returns a vector in the same direction as <Input>, with a length clamped between <Min> (min) and <Max> (max) e2function vector clamp(vector Input, Min, Max) if Min < 0 then Min = 0 end local x,y,z = Input[1], Input[2], Input[3] local length = x*x+y*y+z*z if length < Min*Min then length = Min*(length ^ -0.5) -- Min*(length ^ -0.5) <=> Min/sqrt(length) elseif length > Max*Max then length = Max*(length ^ -0.5) -- Max*(length ^ -0.5) <=> Max/sqrt(length) else return Input end return { x*length, y*length, z*length } end -------------------------------------------------------------------------------- __e2setcost(1) e2function number vector:x() return this[1] end e2function number vector:y() return this[2] end e2function number vector:z() return this[3] end __e2setcost(2) --- SET method that returns a new vector with x replaced e2function vector vector:setX(x) return { x, this[2], this[3] } end --- SET method that returns a new vector with y replaced e2function vector vector:setY(y) return { this[1], y, this[3] } end --- SET method that returns a new vector with z replaced e2function vector vector:setZ(z) return { this[1], this[2], z } end -------------------------------------------------------------------------------- __e2setcost(6) e2function vector round(vector rv1) return { floor(rv1[1] + 0.5), floor(rv1[2] + 0.5), floor(rv1[3] + 0.5) } end e2function vector round(vector rv1, decimals) local shf = 10 ^ decimals return { floor(rv1[1] * shf + 0.5) / shf, floor(rv1[2] * shf + 0.5) / shf, floor(rv1[3] * shf + 0.5) / shf } end e2function vector ceil( vector rv1 ) return { ceil(rv1[1]), ceil(rv1[2]), ceil(rv1[3]) } end e2function vector ceil(vector rv1, decimals) local shf = 10 ^ decimals return { ceil(rv1[1] * shf) / shf, ceil(rv1[2] * shf) / shf, ceil(rv1[3] * shf) / shf } end e2function vector floor(vector rv1) return { floor(rv1[1]), floor(rv1[2]), floor(rv1[3]) } end e2function vector floor(vector rv1, decimals) local shf = 10 ^ decimals return { floor(rv1[1] * shf) / shf, floor(rv1[2] * shf) / shf, floor(rv1[3] * shf) / shf } end __e2setcost(10) --- min/max based on vector length - returns shortest/longest vector e2function vector min(vector rv1, vector rv2) local length1 = ( rv1[1] * rv1[1] + rv1[2] * rv1[2] + rv1[3] * rv1[3] ) ^ 0.5 local length2 = ( rv2[1] * rv2[1] + rv2[2] * rv2[2] + rv2[3] * rv2[3] ) ^ 0.5 if length1 < length2 then return rv1 else return rv2 end end e2function vector max(vector rv1, vector rv2) local length1 = ( rv1[1] * rv1[1] + rv1[2] * rv1[2] + rv1[3] * rv1[3] ) ^ 0.5 local length2 = ( rv2[1] * rv2[1] + rv2[2] * rv2[2] + rv2[3] * rv2[3] ) ^ 0.5 if length1 > length2 then return rv1 else return rv2 end end --- component-wise min/max e2function vector maxVec(vector rv1, vector rv2) return { rv1[1] > rv2[1] and rv1[1] or rv2[1], rv1[2] > rv2[2] and rv1[2] or rv2[2], rv1[3] > rv2[3] and rv1[3] or rv2[3], } end e2function vector minVec(vector rv1, vector rv2) return { rv1[1] < rv2[1] and rv1[1] or rv2[1], rv1[2] < rv2[2] and rv1[2] or rv2[2], rv1[3] < rv2[3] and rv1[3] or rv2[3], } end --- Performs modulo on x,y,z separately e2function vector mod(vector rv1, rv2) return { rv1[1] >= 0 and rv1[1] % rv2 or rv1[1] % -rv2, rv1[2] >= 0 and rv1[2] % rv2 or rv1[2] % -rv2, rv1[3] >= 0 and rv1[3] % rv2 or rv1[3] % -rv2, } end --- Modulo where divisors are defined as a vector e2function vector mod(vector rv1, vector rv2) return { rv1[1] >= 0 and rv1[1] % rv2[1] or rv1[1] % -rv2[1], rv1[2] >= 0 and rv1[2] % rv2[2] or rv1[2] % -rv2[2], rv1[3] >= 0 and rv1[3] % rv2[3] or rv1[3] % -rv2[3], } end --- Clamp according to limits defined by two min/max vectors e2function vector clamp(vector value, vector min, vector max) local x,y,z if value[1] < min[1] then x = min[1] elseif value[1] > max[1] then x = max[1] else x = value[1] end if value[2] < min[2] then y = min[2] elseif value[2] > max[2] then y = max[2] else y = value[2] end if value[3] < min[3] then z = min[3] elseif value[3] > max[3] then z = max[3] else z = value[3] end return {x, y, z} end --- Mix two vectors by a given proportion (between 0 and 1) e2function vector mix(vector vec1, vector vec2, ratio) return { vec1[1] * ratio + vec2[1] * (1-ratio), vec1[2] * ratio + vec2[2] * (1-ratio), vec1[3] * ratio + vec2[3] * (1-ratio) } end e2function vector bezier(vector startVec, vector control, vector endVec, ratio) return { (1-ratio)^2 * startVec[1] + (2 * (1-ratio) * ratio * control[1]) + ratio^2 * endVec[1], (1-ratio)^2 * startVec[2] + (2 * (1-ratio) * ratio * control[2]) + ratio^2 * endVec[2], (1-ratio)^2 * startVec[3] + (2 * (1-ratio) * ratio * control[3]) + ratio^2 * endVec[3] } end __e2setcost(2) --- Circular shift function: shiftR(vec(x,y,z)) = vec(z,x,y) e2function vector shiftR(vector vec) return { vec[3], vec[1], vec[2] } end --- Circular shift function: shiftL(vec(x,y,z)) = vec(y,z,x) e2function vector shiftL(vector vec) return { vec[2], vec[3], vec[1] } end __e2setcost(5) --- Returns 1 if the vector lies between (or is equal to) the min/max vectors e2function number inrange(vector vec, vector min, vector max) if vec[1] < min[1] then return 0 end if vec[2] < min[2] then return 0 end if vec[3] < min[3] then return 0 end if vec[1] > max[1] then return 0 end if vec[2] > max[2] then return 0 end if vec[3] > max[3] then return 0 end return 1 end -------------------------------------------------------------------------------- __e2setcost(3) e2function angle vector:toAngle() local angle = Vector(this[1], this[2], this[3]):Angle() return { angle.p, angle.y, angle.r } end e2function angle vector:toAngle(vector up) local angle = Vector(this[1], this[2], this[3]):AngleEx(Vector(up[1], up[2], up[3])) return { angle.p, angle.y, angle.r } end -------------------------------------------------------------------------------- local contents = {} for k,v in pairs(_G) do if (k:sub(1,9) == "CONTENTS_") then contents[v] = k:sub(10):lower() end end local cachemeta = {} local cache_parts_array = setmetatable({ [0] = {} }, cachemeta) local cache_lookup_table = setmetatable({ [0] = { empty = true } }, cachemeta) local cache_concatenated_parts = setmetatable({ [0] = "empty" }, cachemeta) local function generateContents( n ) local parts_array, lookup_table = {}, {} local ret = {} for i = 0,30 do if bit.band(n, (2^i)) ~= 0 then local name = contents[2^i] lookup_table[name] = true parts_array[#parts_array+1] = name end end concatenated_parts = table.concat(parts_array, ",") cache_parts_array[n] = parts_array cache_lookup_table[n] = lookup_table cache_concatenated_parts[n] = concatenated_parts return concatenated_parts end function cachemeta:__index(n) generateContents(n) return rawget(self, n) end __e2setcost( 20 ) e2function number pointHasContent( vector point, string has ) local cont = cache_lookup_table[util.PointContents(Vector(point[1], point[2], point[3]))] has = has:gsub(" ", "_"):lower() for m in has:gmatch("([^,]+),?") do if cont[m] then return 1 end end return 0 end __e2setcost( 15 ) e2function string pointContents( vector point ) return cache_concatenated_parts[util.PointContents( Vector(point[1],point[2],point[3]))] end e2function array pointContentsArray( vector point ) return cache_parts_array[util.PointContents( Vector(point[1],point[2],point[3]))] end -------------------------------------------------------------------------------- __e2setcost(15) --- Converts a local position/angle to a world position/angle and returns the position e2function vector toWorld( vector localpos, angle localang, vector worldpos, angle worldang ) local localpos = Vector(localpos[1],localpos[2],localpos[3]) local localang = Angle(localang[1],localang[2],localang[3]) local worldpos = Vector(worldpos[1],worldpos[2],worldpos[3]) local worldang = Angle(worldang[1],worldang[2],worldang[3]) return LocalToWorld(localpos,localang,worldpos,worldang) end --- Converts a local position/angle to a world position/angle and returns the angle e2function angle toWorldAng( vector localpos, angle localang, vector worldpos, angle worldang ) local localpos = Vector(localpos[1],localpos[2],localpos[3]) local localang = Angle(localang[1],localang[2],localang[3]) local worldpos = Vector(worldpos[1],worldpos[2],worldpos[3]) local worldang = Angle(worldang[1],worldang[2],worldang[3]) local pos, ang = LocalToWorld(localpos,localang,worldpos,worldang) return {ang.p,ang.y,ang.r} end --- Converts a local position/angle to a world position/angle and returns both in an array e2function array toWorldPosAng( vector localpos, angle localang, vector worldpos, angle worldang ) local localpos = Vector(localpos[1],localpos[2],localpos[3]) local localang = Angle(localang[1],localang[2],localang[3]) local worldpos = Vector(worldpos[1],worldpos[2],worldpos[3]) local worldang = Angle(worldang[1],worldang[2],worldang[3]) local pos, ang = LocalToWorld(localpos,localang,worldpos,worldang) return {pos, {ang.p,ang.y,ang.r}} end --- Converts a world position/angle to a local position/angle and returns the position e2function vector toLocal( vector localpos, angle localang, vector worldpos, angle worldang ) local localpos = Vector(localpos[1],localpos[2],localpos[3]) local localang = Angle(localang[1],localang[2],localang[3]) local worldpos = Vector(worldpos[1],worldpos[2],worldpos[3]) local worldang = Angle(worldang[1],worldang[2],worldang[3]) return WorldToLocal(localpos,localang,worldpos,worldang) end --- Converts a world position/angle to a local position/angle and returns the angle e2function angle toLocalAng( vector localpos, angle localang, vector worldpos, angle worldang ) local localpos = Vector(localpos[1],localpos[2],localpos[3]) local localang = Angle(localang[1],localang[2],localang[3]) local worldpos = Vector(worldpos[1],worldpos[2],worldpos[3]) local worldang = Angle(worldang[1],worldang[2],worldang[3]) local vec, ang = WorldToLocal(localpos,localang,worldpos,worldang) return {ang.p,ang.y,ang.r} end --- Converts a world position/angle to a local position/angle and returns both in an array e2function array toLocalPosAng( vector localpos, angle localang, vector worldpos, angle worldang ) local localpos = Vector(localpos[1],localpos[2],localpos[3]) local localang = Angle(localang[1],localang[2],localang[3]) local worldpos = Vector(worldpos[1],worldpos[2],worldpos[3]) local worldang = Angle(worldang[1],worldang[2],worldang[3]) local pos, ang = WorldToLocal(localpos,localang,worldpos,worldang) return {pos, {ang.p,ang.y,ang.r}} end -------------------------------------------------------------------------------- -- Credits to Wizard of Ass for bearing(v,a,v) and elevation(v,a,v) e2function number bearing(vector originpos,angle originangle, vector pos) pos = WorldToLocal(Vector(pos[1],pos[2],pos[3]),Angle(0,0,0),Vector(originpos[1],originpos[2],originpos[3]),Angle(originangle[1],originangle[2],originangle[3])) return rad2deg*-atan2(pos.y, pos.x) end e2function number elevation(vector originpos,angle originangle, vector pos) pos = WorldToLocal(Vector(pos[1],pos[2],pos[3]),Angle(0,0,0),Vector(originpos[1],originpos[2],originpos[3]),Angle(originangle[1],originangle[2],originangle[3])) local len = pos:Length() if (len < delta) then return 0 end return rad2deg*asin(pos.z / len) end e2function angle heading(vector originpos,angle originangle, vector pos) pos = WorldToLocal(Vector(pos[1],pos[2],pos[3]),Angle(0,0,0),Vector(originpos[1],originpos[2],originpos[3]),Angle(originangle[1],originangle[2],originangle[3])) local bearing = rad2deg*-atan2(pos.y, pos.x) local len = pos:Length() if (len < delta) then return { 0, bearing, 0 } end return { rad2deg*asin(pos.z / len), bearing, 0 } end -------------------------------------------------------------------------------- __e2setcost( 10 ) e2function number vector:isInWorld() if util.IsInWorld(Vector(this[1], this[2], this[3])) then return 1 else return 0 end end __e2setcost( 5 ) --- Gets the vector nicely formatted as a string "[X,Y,Z]" e2function string toString(vector v) return ("[%s,%s,%s]"):format(v[1],v[2],v[3]) end --- Gets the vector nicely formatted as a string "[X,Y,Z]" e2function string vector:toString() = e2function string toString(vector v)
if not pcall(require, 'FTerm') then print('Failed to call FTerm') return end require('FTerm').setup { dimensions = { height = 0.9, width = 0.9 }, border = 'double' } local option = {noremap = true, silent = true} vim.api.nvim_set_keymap('n', '<C-\\>', [[<CMD>lua require("FTerm").toggle()<CR>]], option) vim.api.nvim_set_keymap('t', '<C-\\>', [[<C-\><C-n><CMD>lua require("FTerm").toggle()<CR>]], option)
local args = ... local row = args[1] local col = args[2] local Input = args[3] local bg_color = {0,0,0,0.9} local divider_color = {1,1,1,0.75} local af = Def.ActorFrame{ InitCommand=function(self) self:diffusealpha(0) end, SwitchFocusToSongsMessageCommand=function(self) self:linear(0.1):diffusealpha(0) end, SwitchFocusToGroupsMessageCommand=function(self) self:linear(0.1):diffusealpha(0) end, SwitchFocusToSingleSongMessageCommand=function(self) self:sleep(0.3):linear(0.1):diffusealpha(1) end, Def.Quad{ Name="SongInfoBG", InitCommand=function(self) self:diffuse(bg_color):zoomto(_screen.w/WideScale(1.15,1.5), row.h) end, OnCommand=function(self) self:xy(_screen.cx, _screen.cy - row.h/1.6) end, }, Def.Quad{ Name="PlayerOptionsBG", InitCommand=function(self) self:diffuse(bg_color):zoomto(_screen.w/WideScale(1.15,1.5), row.h*1.5) end, OnCommand=function(self) self:xy(_screen.cx, _screen.cy + row.h/1.5) end, }, Def.Quad{ Name="PlayerOptionsDivider", InitCommand=function(self) self:diffuse(divider_color):zoomto(2, row.h*1.25) end, OnCommand=function(self) self:xy(_screen.cx, _screen.cy + row.h/1.5) end, }, } for player in ivalues( {PLAYER_1, PLAYER_2} ) do if not GAMESTATE:IsSideJoined(player) and Input.AllowLateJoin() then af[#af+1] = Def.BitmapText{ Font="_miso", Text=THEME:GetString("ScreenSelectMusicCasual", "PressStartToLateJoin"), InitCommand=function(self) self:xy( _screen.cx + 150 * (player==PLAYER_1 and -1 or 1), _screen.cy + 80 ) :diffuseshift():effectcolor1(1,1,1,1):effectcolor1(1,1,1,0.5) end, PlayerJoinedMessageCommand=function(self, params) if params.Player == player then self:smooth(0.15):zoom(1.4):smooth(0.15):zoom(0) end end } end end return af
-- This file is subject to copyright - contact swampservers@gmail.com for more information. -- INSTALL: CINEMA SS_Tab("Weapons", "bomb") SS_WeaponProduct({ name = 'Throatneck Slitter', description = "A deadly knife capable of killing one person before breaking.", price = 2000, model = 'models/weapons/w_knife_t.mdl', class = 'weapon_slitter' }) SS_WeaponAndAmmoProduct({ name = 'Peacekeeper', description = "Peacekeeper (Re-buy for more shots)", price = 5000, model = 'models/weapons/w_sawed-off.mdl', class = 'weapon_peacekeeper', ammotype = "peaceshot", amount = 2 }) SS_WeaponProduct({ name = 'Crossbow', description = "Kills players in one shot, and is capable of hitting distant targets. Also unfreezes props.", price = 5000, model = 'models/weapons/w_crossbow.mdl', class = 'weapon_crossbow' }) -- SS_WeaponProduct({ -- name = 'Submachine Gun', -- description = "Effective at killing players at close range, and the ammo is cheap.", -- price = 5000, -- model = 'models/weapons/w_smg1.mdl', -- class = 'weapon_smg1' -- }) -- SS_WeaponProduct({ -- name = 'Sniper', -- description = "This powerful rifle kills any player in one shot and has a scope for long distance assassinations. Also unfreezes props.", -- price = 8000, -- model = 'models/weapons/w_barrett_m98b.mdl', -- class = 'weapon_sniper' -- }) SS_WeaponProduct({ name = '357 Magnum', description = "This gun is convenient for shooting and removing props. It takes 2 bullets to kill a player.", price = 4000, model = 'models/weapons/w_357.mdl', class = 'weapon_357' }) -- SS_WeaponProduct({ -- name = 'Light Machine Gun', -- description = "Crouch for better control", -- price = 12000, -- model = 'models/weapons/w_mg42bu.mdl', -- class = 'weapon_spades_lmg' -- }) SS_WeaponAndAmmoProduct({ name = 'Big Frickin\' Gun', description = "Fires a slow-moving ball, deadly of plasma which kills players in a huge radius.", price = 20000, ammotype = "doom3_bfg", amount = 1, model = "models/weapons/doom3/w_bfg.mdl", class = 'weapon_doom3_bfg' }) SS_WeaponProduct({ name = 'Suicide Bombing', description = "A powerful suicide bomb attack capable of killing seated players.", price = 16000, model = 'models/dav0r/tnt/tnt.mdl', class = 'weapon_jihad' }) SS_WeaponProduct({ name = 'Big Bomb', description = "A large throwable bomb which kills everyone nearby, even seated players.", price = 25000, model = 'models/dynamite/dynamite.mdl', class = 'weapon_bigbomb' }) SS_WeaponAndAmmoProduct({ name = 'Infinity Gauntlet', description = '*snap*', price = 13000, model = 'models/swamp/v_infinitygauntlet.mdl', ammotype = "infinitygauntlet", amount = 1, class = 'weapon_gauntlet' }) -- SS_WeaponAndAmmoProduct({ -- name = 'Anti-Kleiner Rifle', -- description = "This specialty weapon is capable of massacring Kleiners, but is harmless to anyone else. Re-purchase for more ammo.", -- price = 2000, -- model = 'models/weapons/w_IRifle.mdl', -- class = 'weapon_ar2', -- ammotype = "AR2", -- amount = 30 -- }) SS_WeaponAndAmmoProduct({ name = 'S.L.A.M. x3', description = "Explosives that can be placed as mines or thrown and detonated.", price = 6000, model = 'models/weapons/w_slam.mdl', class = 'weapon_slam', ammotype = "slam", amount = 3, clip2 = true }) SS_WeaponAndAmmoProduct({ name = 'Rocket Launcher', description = "Two guided rocket-propelled grenades and a launcher. Re-purchase for more rockets.", price = 8000, model = 'models/weapons/w_rocket_launcher.mdl', class = 'weapon_rpg', ammotype = "RPG_Round", amount = 2 }) SS_WeaponProduct({ name = 'Crusader Sword', description = "A powerful melee weapon. Powers up after a rapid chain of kills.", price = 25000, model = 'models/aoc_weapon/w_longsword.mdl', class = 'weapon_crusadersword' }) if SERVER then language = language or {} language.GetPhrase = function(s) return s:gsub("#Cstrike_WPNHUD_", "") end end local weaponspecs = {"rating", "roll_rof", "roll_range", "roll_accuracy", "roll_control", "roll_handling", "roll_mobility"} SS_WeaponPerkData = { -- rating 1 min = { name = "Mexican", description = "It's just bad (min all stats)", minrating = 1, maxrating = 1, }, alwaysjam = { name = "Rusted", description = "Has to be cycled manually", -- the deploy animation for these looks like cycling a round weapons = { gun_p90 = true, gun_fiveseven = true, gun_usp = true, gun_m4a1 = true, gun_glock = true, gun_p228 = true, gun_mp5navy = true, gun_ak47 = true }, minrating = 1, maxrating = 1, }, crackedscope = { name = "Cracked", description = "Scope is cracked - Ooops!", weapons = { sniper = true, autosniper = true, gun_aug = true, gun_sg552 = true }, minrating = 1, maxrating = 1, }, airsoft = { name = "Airsoft", description = "Not a real gun", minrating = 1, maxrating = 3 }, lessdamage = { name = "Less-Lethal", description = "Fires less-lethal rubber bullets", minrating = 1, maxrating = 2 }, sometimesjam = { name = "Dirty", description = "Occasionally jams", weapons = { gun_p90 = true, gun_fiveseven = true, gun_usp = true, gun_m4a1 = true, gun_glock = true, gun_p228 = true, gun_mp5navy = true, gun_ak47 = true }, minrating = 1, maxrating = 3, }, unstable = { name = "Unstable", description = "May explode when fired", minrating = 1, maxrating = 3, }, smoothbore = { name = "Smoothbore", description = "Not very accurate", minrating = 1, maxrating = 3, }, chinese = { name = "Chinese", description = "Less accurate, but quite cheap", minrating = 1, maxrating = 4, }, compliant = { name = "Libtard-Compliant", description = "10 round magazine and semi-auto only", weapons = { ar = true }, minrating = 2, maxrating = 4 }, highimpact = { name = "High Impact", description = "Heavy bullets that hit hard (more camera punch to target)", minrating = 4, maxrating = 6 }, fullauto = { name = "Full-Auto", description = "Black market full-auto sear installed", weapons = { pistol = true, autosniper = true, autoshotgun = true }, minrating = 5, maxrating = 6 }, lightweight = { name = "Lightweight", description = "Easier to fire on the move", minrating = 5, maxrating = 6 }, compensated = { name = "Compensated", description = "Reduced recoil", weapons = { pistol = true, autosniper = true, ar = true, smg = true }, minrating = 5, maxrating = 6 }, extended = { name = "Extended", description = "Extended mags", minrating = 5, maxrating = 7 }, skullpiercing = { name = "Skullpiercing", description = "More damage to the head", weapons = { ar = true, pistol = true }, minrating = 5, maxrating = 7 }, slug = { name = "Slug", description = "Fires devastating slug ammunition", weapons = { shotgun = true, autoshotgun = true }, minrating = 5, maxrating = 7 }, antimaterial = { name = "Anti-Material", description = "Can damage any prop (AWP instaremoves)", minrating = 7, maxrating = 8 }, selfloading = { name = "Self-Loading", description = "Semi-automatic firepower", weapons = { sniper = true }, minrating = 7, maxrating = 8 }, boomstick = { name = "Boomstick", description = "Fires way more pellets, but in a wider cone", weapons = { shotgun = true, autoshotgun = true }, minrating = 7, maxrating = 8 }, moredamage = { name = "Armor-Piercing", description = "More damage", minrating = 7, maxrating = 8 }, antikleiner = { name = "Anti-Kleiner", description = "Kleiner Killer", minrating = 7, maxrating = 8 }, -- antipony = {name="Anti-pony", description="Pony blaster",minrating=7,maxrating=8}, -- antihuman = {name="Anti-human", description="Kleiner Killer",minrating=7,maxrating=8}, --rating 8 explosiveslug = { name = "Explosive Slug", description = "Fires explosive slug ammunition", weapons = { shotgun = true, autoshotgun = true }, minrating = 8, maxrating = 8 }, explosive = { name = "Hand Cannon", description = "Fires 20mm high explosive rounds", weapons = { gun_awp = true }, minrating = 8, maxrating = 8 }, bottomless = { name = "Bottomless", description = "Never needs to be reloaded (you still have to buy ammo though!)", minrating = 8, maxrating = 8 }, dragon = { name = "Dragon's Breath", description = "Ignites targets", minrating = 8, maxrating = 8 }, shothose = { name = "Death Machine", description = "Full auto buckshot hose", weapons = { autoshotgun = true, gun_mac10 = true }, minrating = 8, maxrating = 8 }, max = { name = "Golden", description = "Worthy of Trump (max all stats)", minrating = 8, maxrating = 8 } } SS_Item({ class = "weapon", background = true, value = 5000, GetDescription = function(self) local d = (weapons.GetStored(self.specs.class or "") or {}).Purpose or "" --self.description if (self.specs.perk or "") ~= "" then local pk = SS_WeaponPerkData[self.specs.perk] if pk then d = d .. "\nPerk: " .. pk.name .. ": " .. pk.description end end if self.specs.trophy_winner then local p = player.GetBySteamID64(self.specs.trophy_winner) local n = IsValid(p) and p:GetName() or util.SteamIDFrom64(self.specs.trophy_winner) n = self.specs.trophy_winner_name_cache or n d = d .. "\n\nGranted to " .. n .. " for their service (#" .. self.specs.trophy_rank .. ")" end return d end, GetName = function(self) local name = (weapons.GetStored(self.specs.class or "") or {}).PrintName or "Unknown" if (self.specs.perk or "") ~= "" then name = SS_WeaponPerkData[self.specs.perk].name .. " " .. name end if self.specs.trophy_tag then name = self.specs.trophy_tag .. " " .. name end return name end, GetModel = function(self) return (weapons.GetStored(self.specs.class or "") or {}).WorldModel or 'models/error.mdl' end, OutlineColor = function(self) return SS_GetRating(self.specs.rating).color end, SanitizeSpecs = function(self) local specs, ch = self.specs, false for i, spec in ipairs(weaponspecs) do if not specs[spec] then specs[spec] = math.random() ch = true end end local r = SS_GetRating(self.specs.rating) local cl = self.specs.class -- class may not be set yet, dont choose a perk til it is if cl then local ct = weapons.GetStored(cl) or {} local validperks = {} for k, v in pairs(SS_WeaponPerkData) do if v.minrating <= r.id and r.id <= v.maxrating then if v.weapons == nil or v.weapons[cl] or v.weapons[ct.GunType or ""] then validperks[k] = true end end end if specs.perk and specs.perk ~= "" and validperks[specs.perk] == nil then specs.perk = nil end -- specs.perk=nil if specs.perk == nil then local r_roll = (self.specs.rating - r.min) / (r.max - r.min) -- perks at rank <= 4 are "bad" if r.id <= 4 then r_roll = 1 - r_roll end if r_roll > (1 - SS_WeaponPerkChance[r.id]) then specs.perk = table.Random(table.GetKeys(validperks)) -- reroll if non specific perk (todo remove this after a while) if SS_WeaponPerkData[specs.perk].weapons == nil then specs.perk = table.Random(table.GetKeys(validperks)) end else specs.perk = "" end ch = true end end if specs.trophy_winner then local p = player.GetBySteamID64(specs.trophy_winner) local n = IsValid(p) and p:GetName() if n and n ~= specs.trophy_winner_name_cache then specs.trophy_winner_name_cache = n ch = true end end return ch end, actions = { spawnweapon = { Text = function(item) return "MAKE (-" .. tostring(item:SpawnPrice()) .. ")" end, primary = true, } }, SpawnPrice = function(self) local swep = weapons.GetStored(self.specs.class or "") or {} local perk = GunPerkOverrides(swep, self.specs.perk) local baseprice = swep.SpawnPrice or ({ pistol = 1000, heavypistol = 1500, smg = 2000, shotgun = 2000, autoshotgun = 3000, ar = 3000, autosniper = 4000, sniper = 4000, lmg = 3000, })[swep.GunType] or 10000 local ratingmod = 1.5 ^ (self.specs.rating - 0.5) -- it comes with ammo, add that to the price :^) return math.Round(baseprice * (perk.SpawnPriceMod or swep.SpawnPriceMod or 1) * ratingmod, -2) + SS_GunAmmoPrice(self) end, SellValue = function(self) return 1000 * 2 ^ SS_GetRating(self.specs.rating).id end, invcategory = "Weapons", never_equip = true }) -- also used to set ammo purchase options for non-item guns (TODO cleanup) GUNTYPE_BASE_REFILL_PRICE = { pistol = 500, heavypistol = 500, smg = 1500, shotgun = 1500, autoshotgun = 1500, ar = 2000, autosniper = 2500, sniper = 2500, lmg = 5000, } function SS_GunAmmoPrice(item) local swep = weapons.GetStored(item.specs.class or "") or {} local perk = GunPerkOverrides(swep, item.specs.perk) local baseprice = swep.AmmoPrice or GUNTYPE_BASE_REFILL_PRICE[swep.GunType] or 1000 local ratingmod = 1 --1.5 ^ (item.specs.rating - 0.5) return math.Round(baseprice * (perk.AmmoPriceMod or swep.AmmoPriceMod or 1) * ratingmod, -2) end --NOMINIFY -- for i, tm in ipairs({"CT", "TERRORIST"}) do SS_Product({ class = 'csslootbox', background = true, price = 100000, name = "Gun Blueprint", --tm == "CT" and "Thin Blue Line Box" or "Jihad Box", description = "Contains a blueprint for a random gun.\nToo expensive? Try the \"Auctions\" tab!", model = 'models/Items/ammocrate_smg1.mdl', Options = function(self) local options = {} for k, v in ipairs(weapons.GetList()) do if v.GunType then table.insert(options, v) end end return options end, GetModel = function(self) local options = self:Options() return options[(math.floor(SysTime() * 2.5) % #options) + 1].WorldModel end, OnBuy = function(self, ply) local options = self:Options() local others = {} for i = 1, 15 do table.insert(others, options[math.random(#options)].WorldModel) end local chosen = options[math.random(#options)] local rating local item = SS_GenerateItem(ply, "weapon") item.specs.class = chosen.ClassName item:Sanitize() rating = item.specs.rating ply:SS_GiveNewItem(item, function(item) net.Start("LootBoxAnimation") net.WriteUInt(item.id, 32) net.WriteTable(others) net.Send(ply) local w = chosen.ClassName timer.Simple(5, function() if not IsValid(ply) then return end GiveWeaponItem(ply, item) end) end) end }) -- end) -- end -- hook.Add("Initialize","ss css setup", function() -- for k, wep in ipairs(weapons.GetList()) do -- if wep.Base == "weapon_csbasegun" then -- end -- end -- end) SS_Heading("To buy ammo, press Undo (default Z)") -- SS_Product({ -- class = 'cssammo', -- price = 2000, --5000,3000 -- name = 'CS:S gun magazine', -- description = "1 mag for CSS gun from mystery box (Free ammo in the shooting range!!)", -- model = 'models/Items/sniper_round_box.mdl', -- OnBuy = function(self, ply) -- local w = ply:GetActiveWeapon() -- ply:GiveAmmo(w:GetMaxClip1(), w:GetPrimaryAmmoType()) -- end, -- CanBuyStatus = function(self, ply) -- local w = ply:GetActiveWeapon() -- if not IsValid(w) or w.Base ~= "weapon_csbasegun" then return "Equip a CS:S gun (from the lootbox)" end -- end -- }) -- SS_AmmoProduct({ -- name = 'Crossbow bolt x5', -- price = 1500, -- model = 'models/Items/CrossbowRounds.mdl', -- ammotype = "XBowBolt", -- amount = 5 -- }) -- SS_AmmoProduct({ -- name = 'SMG Magazine', -- description = "45 rounds", -- price = 1000, -- model = 'models/Items/BoxSRounds.mdl', -- ammotype = "SMG1", -- amount = 45 -- }) -- SS_AmmoProduct({ -- name = 'Sniper Ammo x 5', -- price = 2500, -- model = 'models/Items/sniper_round_box.mdl', -- ammotype = "sniper", -- amount = 5 -- }) -- SS_AmmoProduct({ -- name = '357 Ammo x 6', -- price = 500, -- model = 'models/Items/357ammo.mdl', -- ammotype = "357", -- amount = 6 -- }) -- SS_AmmoProduct({ -- name = 'LMG x 100', -- model = 'models/weapons/w_mg42bu.mdl', -- price = 5000, -- ammotype = "lmg", -- amount = 100 -- }) -- asdf
function readScript(file) local f = io.open(file, "rb") local content = f:read("*all") f:close() return content end load(readScript(LIB_PATH.."DivinePred.luac"), "Divine Prediction","bt",_ENV)()
local Message = {} Message.__index = Message Message.__metatable = false Message.Class = "Message" local _scanparam = require("../util/ScanParam") local _scanurl = require("../util/ScanURL") local _typeof = require("../util/TypeOf") local _log = require("../util/Log") function Message.new(data) _scanparam({"data", data}, {"nil", "table"}, false, true) local msg = {} msg.rawdata = data or {} _log(1, "Created message object.") return setmetatable(msg, Message) end function Message:SetContent(content) _scanparam({"content", content}, {"string"}, true, true, {1, 2000}) self.rawdata.content = content _log(1, "Setted message content") return self end function Message:SetUsername(username) _scanparam({"username", username}, {"string"}, true, true, {1, 80}) self.rawdata.username = username _log(1, "Setted message username") return self end function Message:SetAvatarURL(url) _scanparam({"url", url}, {"string"}, true, true) _scanurl(url) self.rawdata.avatar_url = url _log(1, "Setted message avatar URL") return self end function Message:AddEmbed(embed) _scanparam({"embed", embed}, {"table", "Embed"}, true, true) if not self.rawdata.embeds then self.rawdata.embeds = {} end assert((#self.rawdata.embeds + 1) <= 10, "You can only exceed 10 embed per message.") table.insert(self.rawdata.embeds, embed.rawdata or embed) _log(1, "Added embed. [Table Pos: %d]", #self.rawdata.embeds) return self end function Message:AddEmbeds(...) local embeds = {...} _scanparam({"embeds", embeds[1]}, {"array", "table", "Embed"}, true, true) if _typeof(embeds[1]) == "array" then embeds = embeds[1] end _log(1, "Adding "..#embeds.." embeds.") for _, embed in next, embeds do _scanparam({"embed", embed}, {"table", "Embed"}, false, true) self:AddEmbed(embed) end _log(1, "Added "..#embeds.." embeds.") return self end Message.__call = function(_, ...) return Message.new(...) end return setmetatable(Message, Message)
the.HexScale = 64 the.ActiveHex = nil the.ActiveHexColor = {255, 0, 0, 100} local function RoundHex(q, r) local x = q local z=r-.75--numeros magicos ftw local y=-x-z local rx=math.round(x) local rz=math.round(z) local ry=math.round(y) local x_diff = math.abs(rx - x) local y_diff = math.abs(ry - y) local z_diff = math.abs(rz - z) if rx + ry + rz == 0 then return rx, rz end if x_diff > y_diff and x_diff > z_diff then rx = -ry-rz elseif y_diff > z_diff then ry = -rx-rz else rz = -rx-ry end return rx, rz end local function RoundHexCube(x, y, z) local rx=math.round(x) local rz=math.round(z) local ry=math.round(y) local x_diff = math.abs(rx - x) local y_diff = math.abs(ry - y) local z_diff = math.abs(rz - z) if rx + ry + rz == 0 then return rx, rz end if x_diff > y_diff and x_diff > z_diff then rx = -ry-rz elseif y_diff > z_diff then ry = -rx-rz else rz = -rx-ry end return rx, rz end HexTile = Tile:extend { colored = true, weight = 0, width = the.HexScale, height = the.HexScale, image = 'images/hex.png', origcolor = {}, coords = {}, vertices = {}, SetAlpha = function(self, a) if not a then self.alpha = 1 return end self.alpha = a / 100 end, SetOrigColor = function(self, r, g, b, a) self.origcolor[1] = r self.origcolor[2] = g self.origcolor[3] = b self.origcolor[4] = a end, SetColor = function(self, r, g, b, a) if not r and not g and not b then self.colored = false self:SetAlpha() return end if a then self:SetAlpha(a) end self.colored = true self.tint[1] = r/255 self.tint[2] = g/255 self.tint[3] = b/255 end, GenerateVertices = function( self ) local angle for i=1, 6 do self.vertices[i] = {} angle = 2 * math.pi / 6 * (i + 0.5) self.vertices[i].x = self.x + the.HexScale/2 * math.cos(angle) self.vertices[i].y = self.y + the.HexScale/2 * math.sin(angle) end end, onNew = function( self ) self.coords.q = self.coords.q or 0 self.coords.r = self.coords.r or 0 self:GenerateVertices() self:SetColor(self.origcolor[1], self.origcolor[2],self.origcolor[3], self.origcolor[4]) end, OnMouseEnter = function(self) end, OnMouseHover = function(self) end, OnMouseExit = function(self) end, onUpdate = function(self) end } HexMap = Sprite:extend { alpha=100, visible=true, hexes = {}, hextiles = Group:new(), scale = 1, origcolor = {255,255,255,100}, BoundingBox = function(self) local minx = self.x+(the.HexScale/2)*math.sqrt(3)*(-self.scale)-the.HexScale local miny = self.y+(the.HexScale/2)*3/2*-self.scale-the.HexScale local maxx = self.x+(the.HexScale/2)*math.sqrt(3)*(self.scale)+the.HexScale local maxy = self.y+(the.HexScale/2)*3/2*self.scale+the.HexScale return minx, miny, maxx, maxy end, PixelToHex = function(self,x,y) x = x - self.x y = y - self.y local q = (1/3*math.sqrt(3) * x - 1/3 * y) / (the.HexScale/2) local r = 2/3 * y / (the.HexScale/2) q, r = RoundHex(q,r) if self.hexes[q] and self.hexes[q][r] then return self.hexes[q][r] else return false end end, FindNeighbors = function(self,q,r) local neighbors = {} if self.hexes[q] and self.hexes[q][r-1] and not self.hexes[q][r-1].disabled then table.insert(neighbors, self.hexes[q][r-1]) end if self.hexes[q] and self.hexes[q][r+1] and not self.hexes[q][r+1].disabled then table.insert(neighbors, self.hexes[q][r+1]) end if self.hexes[q-1] and self.hexes[q-1][r+1] and not self.hexes[q-1][r+1].disabled then table.insert(neighbors, self.hexes[q-1][r+1]) end if self.hexes[q+1] and self.hexes[q+1][r-1] and not self.hexes[q+1][r-1].disabled then table.insert(neighbors, self.hexes[q+1][r-1]) end if self.hexes[q+1] and self.hexes[q+1][r] and not self.hexes[q+1][r].disabled then table.insert(neighbors, self.hexes[q+1][r]) end if self.hexes[q-1] and self.hexes[q-1][r] and not self.hexes[q-1][r].disabled then table.insert(neighbors, self.hexes[q-1][r]) end return neighbors end, FindAllAdyacents = function(self, startq, startr, range) if not self.hexes[startq] or not self.hexes[startq][startr] then return {}, {}, {} end local results = {} local visited = {} local final = {} local origin = self.hexes[startq][startr] visited[tostring(startq) .. tostring(startr)] = true results[0] = {origin} table.insert(final, origin) local q, r for i=1, range do for _, hex in pairs(results[i-1] or {}) do for __, neighbor in pairs(self:FindNeighbors(hex.coords.q, hex.coords.r)) do if not visited[tostring(neighbor.coords.q) .. tostring(neighbor.coords.r)] and not neighbor.disabled then if not results[i] then results[i] = {} end table.insert(results[i], neighbor) visited[tostring(neighbor.coords.q) .. tostring(neighbor.coords.r)] = true table.insert(final, neighbor) end end end end return visited, final, results end, Distance = function( self, q1, r1, q2, r2 ) return (math.abs(q1 - q2) + math.abs(r1 - r2) + math.abs(q1 + r1 - q2 - r2)) / 2 end, FindInLine = function( self, q1, r1, q2, r2) local ax = q1 + 1e-6 local ay = -q1-r1 + 1e-6 local az = r1 + 1e-6 local bx = q2 local by = -q2-r2 local bz = r2 local difx = ax - bx local dify = ay - by local difz = az - bz local n = math.max(math.abs(difx-dify), math.abs(dify-difz), math.abs(difz-difx)) local prevq, prevr local p local hexes = {} local visited = {} for i=0, n do local pq, pr = RoundHexCube(ax*(1-i/n)+bx*i/n, ay*(1-i/n)+by*i/n, az*(1-i/n)+bz*i/n) if not (visited[pq] and visited[pq][pr]) and not (pq == prevq and pr == prevr) then if not visited[pq] then visited[pq] = {} end visited[pq][pr] = true table.insert(hexes, self.hexes[pq][pr]) prevq = pq prevr = pr end end return hexes, visited end, FindAllButAdyacents = function(self, startq, startr, range) if not self.hexes[startq] or not self.hexes[startq][startr] then return {}, {}, {} end local results = {} local visited = {} local final = {} local origin = self.hexes[startq][startr] visited[tostring(startq) .. tostring(startr)] = true results[0] = {origin} table.insert(final, origin) local q, r for i=2, range do for _, hex in pairs(results[i-1] or {}) do for __, neighbor in pairs(self:FindNeighbors(hex.coords.q, hex.coords.r)) do if not visited[tostring(neighbor.coords.q) .. tostring(neighbor.coords.r)] and not neighbor.disabled then if not results[i] then results[i] = {} end table.insert(results[i], neighbor) visited[tostring(neighbor.coords.q) .. tostring(neighbor.coords.r)] = true table.insert(final, neighbor) end end end end return visited, final, results end, FindAllInRange = function(self, startq, startr, range) if not self.hexes[startq] or not self.hexes[startq][startr] then return {}, {}, {} end local results = {} local visited = {} local final = {} local origin = self.hexes[startq][startr] visited[tostring(startq) .. tostring(startr)] = true results[0] = {origin} table.insert(final, origin) local q, r for i=1, range do for _, hex in pairs(results[i-1] or {}) do for __, neighbor in pairs(self:FindNeighbors(hex.coords.q, hex.coords.r)) do if i==1 or (not visited[tostring(neighbor.coords.q) .. tostring(neighbor.coords.r)] and not neighbor.disabled and i-1+neighbor.weight<=range) then if not results[i-1+neighbor.weight] then results[i-1+neighbor.weight] = {} end table.insert(results[i-1+neighbor.weight], neighbor) visited[tostring(neighbor.coords.q) .. tostring(neighbor.coords.r)] = true table.insert(final, self.hexes[neighbor.coords.q][neighbor.coords.r]) end end end end return visited, final, results end, onNew = function( self ) for i=-self.scale, self.scale do self.hexes[i] = {} for j=-self.scale, self.scale do if j+i<=self.scale and not (i*-1+j*-1>self.scale) then self.hexes[i][j] = HexTile:new{coords = {q=i, r=j}, x=self.x+(the.HexScale/2)*math.sqrt(3)*(i + j/2), y=self.y+(the.HexScale/2)*3/2*j} self.hextiles:add(self.hexes[i][j]) end end end end, draw = function (self, x, y) -- lock our x/y coordinates to integers -- to avoid gaps in the tiles x = math.floor(x or self.x) y = math.floor(y or self.y) -- draw each sprite in turn for i=-self.scale, self.scale do for j=-self.scale, self.scale do if j+i<=self.scale and not (i*-1+j*-1>self.scale) then self.hexes[i][j]:draw() end end end end, } DebugTestLine = View:extend { onNew = function (self) self.hexmap = HexMap:new{x=the.app.width/2-the.HexScale/2, y=the.app.height/2-the.HexScale/2, scale=8, alpha = 100} --self.minVisible.x, self.minVisible.y, self.maxVisible.x, self.maxVisible.y = self.hexmap:BoundingBox() self.hexmap.ClearColor = function(this) for i=-self.hexmap.scale, self.hexmap.scale do for j=-self.hexmap.scale, self.hexmap.scale do if j+i<=self.hexmap.scale and not (i*-1+j*-1>self.hexmap.scale) then if self.hexmap.hexes[i][j].disabled then self.hexmap.hexes[i][j]:SetOrigColor(0,0,0,0) self.hexmap.hexes[i][j]:SetColor(0,0,0,0) else self.hexmap.hexes[i][j]:SetOrigColor(255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,100) self.hexmap.hexes[i][j]:SetColor(255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,100) end end end end end for i=-self.hexmap.scale, self.hexmap.scale do for j=-self.hexmap.scale, self.hexmap.scale do if j+i<=self.hexmap.scale and not (i*-1+j*-1>self.hexmap.scale) then if self.hexmap.hexes[i][j].disabled then self.hexmap.hexes[i][j]:SetOrigColor(0,0,0,0) self.hexmap.hexes[i][j]:SetColor(0,0,0,0) else self.hexmap.hexes[i][j]:SetOrigColor(255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,100) self.hexmap.hexes[i][j]:SetColor(255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,100) end self.hexmap.hexes[i][j].OnMouseEnter = function(this) if this.disabled then return end the.ActiveHex = this end self.hexmap.hexes[i][j].OnMouseHover = function(this) if this.disabled then return end this:SetColor(math.abs(this.origcolor[1]-255), math.abs(this.origcolor[1]-255),math.abs(this.origcolor[1]-255), 255) if the.mouse:justPressed() then --self.translate.x = this.x --self.translate.y = this.y local hexes, visited = self.hexmap:FindInLine(0, 0, this.coords.q, this.coords.r, 2) self.hexmap:ClearColor() for _, hex in pairs(hexes) do hex:SetOrigColor(0,255,0,100) hex:SetColor(0,255,0,100) end end end self.hexmap.hexes[i][j].OnMouseExit = function(this) if this.disabled then return end this:SetColor(this.origcolor[1], this.origcolor[2],this.origcolor[3], this.origcolor[4]) end end end end self:add(self.hexmap) end, onUpdate = function(self) local hex = self.hexmap:PixelToHex(the.mouse.x, the.mouse.y) if hex then if not the.ActiveHex then hex:OnMouseEnter() the.app.view:panTo({100, 100},2) elseif the.ActiveHex ~= hex then the.ActiveHex:OnMouseExit() hex:OnMouseEnter() else hex:OnMouseHover() end else if the.ActiveHex then the.ActiveHex:OnMouseExit() the.ActiveHex = nil end end end } DebugPolygonView = View:extend { onNew = function (self) self.hexmap = HexMap:new{x=the.app.width/2-the.HexScale/2, y=the.app.height/2-the.HexScale/2, scale=8} --self.minVisible.x, self.minVisible.y, self.maxVisible.x, self.maxVisible.y = self.hexmap:BoundingBox() self.hexmap.ClearColor = function(this) for i=-self.hexmap.scale, self.hexmap.scale do for j=-self.hexmap.scale, self.hexmap.scale do if j+i<=self.hexmap.scale and not (i*-1+j*-1>self.hexmap.scale) then if self.hexmap.hexes[i][j].disabled then self.hexmap.hexes[i][j]:SetOrigColor(0,0,0,0) self.hexmap.hexes[i][j]:SetColor(0,0,0,0) else self.hexmap.hexes[i][j]:SetOrigColor(255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,100) self.hexmap.hexes[i][j]:SetColor(255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,100) end end end end end for i=-self.hexmap.scale, self.hexmap.scale do for j=-self.hexmap.scale, self.hexmap.scale do if j+i<=self.hexmap.scale and not (i*-1+j*-1>self.hexmap.scale) then self.hexmap.hexes[i][j].weight = math.random(1,3) if math.random(1, 16) == 16 then self.hexmap.hexes[i][j].disabled = true self.hexmap.hexes[i][j]:SetOrigColor(0,0,0,0) self.hexmap.hexes[i][j]:SetColor(0,0,0,0) else self.hexmap.hexes[i][j]:SetOrigColor(255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,100) self.hexmap.hexes[i][j]:SetColor(255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,255-(self.hexmap.hexes[i][j].weight-1)*20,100) end end end end self:add(self.hexmap) end, onUpdate = function(self) local hex = self.hexmap:PixelToHex(the.mouse.x, the.mouse.y) if hex then if not the.ActiveHex then hex:OnMouseEnter() the.app.view:panTo({100, 100},2) elseif the.ActiveHex ~= hex then the.ActiveHex:OnMouseExit() hex:OnMouseEnter() else hex:OnMouseHover() end else if the.ActiveHex then the.ActiveHex:OnMouseExit() the.ActiveHex = nil end end local curvisited = {} for i=-self.hexmap.scale, self.hexmap.scale do for j=-self.hexmap.scale, self.hexmap.scale do if j+i<=self.hexmap.scale and not (i*-1+j*-1>self.hexmap.scale) then self.hexmap.hexes[i][j].OnMouseEnter = function(this) if this.disabled then return end the.ActiveHex = this end self.hexmap.hexes[i][j].OnMouseHover = function(this) if this.disabled then return end if not curvisited[tostring(this.coords.q)..tostring(this.coords.r)] then this:SetColor(math.abs(this.origcolor[1]-255), math.abs(this.origcolor[1]-255),math.abs(this.origcolor[1]-255), 255) end if the.mouse:justPressed() then --self.translate.x = this.x --self.translate.y = this.y local visited,hexes,strata = self.hexmap:FindAllInRange(this.coords.q, this.coords.r, 2) self.hexmap:ClearColor() for _, hex in pairs(hexes) do hex:SetOrigColor(0,255,0,100) hex:SetColor(0,255,0,100) end end end self.hexmap.hexes[i][j].OnMouseExit = function(this) if this.disabled then return end this:SetColor(this.origcolor[1], this.origcolor[2],this.origcolor[3], this.origcolor[4]) end end end end end }
Player = Ship:extend() function Player:new(x_start, y_start) Player.super.new(self, x_start, y_start, dir_start) self:setColor(COLORS.red) self.max_speed_base = 160 self.max_speed = self.max_speed_base self.cruise_speed = 100 self.min_speed = 75 self.boost = 100 self.max_boost = 400 self.over_boosted = false self.radius = 10 self.current_speed = 0 self.roation_speed = 3 self.size = 20 self.team = Teams.blue self.shield_enabled = true self.shield_health = 100 self.shield_recharge_rate = 5 self.shield_max = 110 self.inventory = {Gun(2, 80)} -- currently a default gun, may want to change self.equipped_weapon = self.inventory[1] self.invincible = false self.sprite_image = Sprites.player_image self.timer = Timer.new() -- not sure if this is used self.damage_color = {1,0,0,0} -- not used end function Player:grow() -- not used print("in grow") self.timer:tween(1, self.damage_color, {1, 0, 0, 1}, 'in-out-quad', self:shrink()) end function Player:shrink() -- not used print("in shrink") self.timer:tween(1, self.damage_color, {1, 0, 0, 0}, 'in-out-quad') end function Player:setupBump(world) self.world = world world:add(self, self:getX(), self:getY(), self.size, self.size) end -- called before the player starts a new level and such function Player:reset() -- need to add info self.shield_health = 0 self.current_health = 100 print("Upgrade mods") print(upgrade_manager:getModifiers("speed")) self.max_speed = self.max_speed_base * upgrade_manager:getModifiers("speed") if upgrade_manager:isUnlocked("shotgun") then -- this should be handeled by an inventory system that tracks upgrade events self.inventory[3] = Shotgun() end end function Player:update(dt) Player.super.update(self, dt) self.timer:update(dt) self:updateBoost(dt) if outOfBounds(self.coord) then self:damage(dt*20) end -- Linear Speed if love.keyboard.isDown("up") and not self.over_boosted then self.boost = self.boost - 100*dt self.current_speed = math.min(self.current_speed + 500 * dt, self.max_speed) elseif love.keyboard.isDown("down") then self.current_speed = self.min_speed else self.current_speed = math.max(self.current_speed - 200*dt, self.cruise_speed) end -- Roation local rotation_speed_const = 1 if love.keyboard.isDown("right") then self.coord:rotate(dt * (self.roation_speed + rotation_speed_const * (self.cruise_speed - self.current_speed) / self.cruise_speed)) elseif love.keyboard.isDown("left") then self.coord:rotate(-dt * (self.roation_speed + rotation_speed_const * (self.cruise_speed - self.current_speed) / self.cruise_speed)) end -- Recharge Shield if self.shield_enabled then self.shield_health = math.min(self.shield_max, self.shield_health + self.shield_recharge_rate * dt) end -- Final movement + bump self.coord:moveForward(self.current_speed * dt) local actualX, actualY, cols, len = self.world:move(self, self:getX() - self.size / 2, self:getY() - self.size / 2, function() return "bounce"end) self:setXY(actualX + self.size / 2, actualY + self.size / 2) -- particle System self.pSystem:update(dt) self.pSystem:moveTo(self.coord.x, self.coord.y) self.pSystem:setDirection(self.coord:getT() + math.pi) if love.keyboard.isDown("space") and self.equipped_weapon:is(Machinegun) then print("Machine") self:fire() end end function Player:draw() Player.super.draw(self) love.graphics.setColor(self.damage_color) love.graphics.circle('fill', self.coord.x, self.coord.y, 200) end function Player:updateBoost(dt) if self.boost < 1 then self.over_boosted = true end -- if we need to refill if self.boost < self.max_boost then self.boost = math.min(self.max_boost, self.boost + dt * 25) else self.over_boosted = false end end function Player:damage(amount) -- take damage to shield first if self.invincible then return false end if self.shield_enabled then local shield_residual = self.shield_health - amount -- how much is left in the shield after a hit self.shield_health = math.max(0, shield_residual) if shield_residual < 0 then -- if the shield took too much damage self.current_health = self.current_health + shield_residual end else -- if we dont have a shield self.current_health = self.current_health - amount end if self.current_health <= 0 then return true else return false end end function Player:keypressed(key) if key == "space" and not love.keyboard.isDown("up") then self:fire() end if key == "u" then self.equipped_weapon:setUnlimitedAmmo(not self.equipped_weapon:getUnlimitedAmmo()) end if key == "i" then self.invincible = not self.invincible end if key == "1" then if self.inventory[1] ~= nil then self.equipped_weapon = self.inventory[1] end end if key == "2" then self.equipped_weapon = Machinegun() end if key == "3" then if self.inventory[3] ~= nil then self.equipped_weapon = self.inventory[3] print(self.equipped_weapon) end end end
local Stack = require 'scripts.make.stack' local Logs = require 'lib.logs' local Parser = {} local concat = table.concat local function apply_macro(macro, argv) return (macro:gsub("($+)(%d+)", function(esc, i) local v = argv[tonumber(i)] or "" if esc:len() % 2 == 1 then return esc:sub(1, -2) .. v end end)) end local function parse(macros, str) local stack = Stack.new() local function parse(macros, str, cursor, up_sep) local cursor, len = cursor or 1, str:len() local function char(i) i = i or 0 return str:sub(cursor + i, cursor + i) end local function step(n) cursor = cursor + (n or 1) end local function in_bounds() if up_sep then return cursor <= len and char() ~= up_sep else return cursor <= len end end local out, esc = "" local argi, argv, macro, sep = 0, {} while in_bounds() do if macro then if char() == "}" then local m = macros[macro] if m then Logs.assert(not stack:contains(macro), 1, macro, ": cyclic macro") stack:push(macro) out = out .. parse(macros, apply_macro(m, argv)) stack:pop() else out = out .. ("${%s%s%s}"):format(macro, sep or "", concat(argv, sep)) end macro = nil elseif char():match("[%w_-]") then macro = macro .. char() elseif char():match("[${]") then out = out .. "${" .. macro macro = nil step(-1) elseif not sep or char() == sep then argi = argi + 1 sep = sep or char() step() argv[argi], cursor = parse(macros, str, cursor, sep) step(-1) end elseif esc then if char() == "{" then macro = "" else out = out .. (up_sep and "$" or "") .. char() end esc = false elseif char() == "$" then esc = true elseif up_sep and char() == "}" then break else out = out .. char() end step() end return out, cursor end local out = parse(macros, str) stack:clear() return out end local function scan(macros, group) for _, entry in pairs(group) do for fname, field in pairs(entry) do if type(field) == 'string' then entry[fname] = parse(macros, field) end end end end function Parser.parse(data) local macros, cards, sets = data.macro or {}, data.card or {}, data.set or {} scan(macros, sets) scan(macros, cards) return sets, cards end return Parser
Menu.Spacing() Menu.Separator() Menu.Spacing() Menu.Text("KibbeWater - Grenade Helper") Menu.Spacing() Menu.Spacing() Menu.Spacing() Menu.Checkbox("Draw Line To Angle", "cHelperDrawLineAngle", true) Menu.SliderInt("Render Distance", "cHelperRenderDistance", 50, 2000, "", 500) Menu.Spacing() Menu.Spacing() Menu.Text("Publishing") Menu.Separator() Menu.InputText("Spot Name", "cSpotFName", "Not Named") Menu.Combo("Throw Type", "cSpotThrowType", {"Throw", "RunThrow", "JumpThrow", "Right Click"}, 0) Menu.Checkbox("Submit Spot", "cSubmitGrenadeSpot", false) Menu.Spacing() Menu.Text("You need to hold a smoke/molotov to submit") Menu.Text("Abuse of the API will lead to a ban") local viewAngle = QAngle.new(0, 0, 0) local displayedID = 0 local map = "" local loadedMap = "" --Global Vars local coords = {} --For version handling local ver = "v2.0" local notifNew = false local notifData = "" FileSys.CreateDirectory(GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\") FileSys.CreateDirectory(GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\kibbewater\\") FileSys.CreateDirectory(GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\kibbewater\\Grenade Helper\\") --Register Functions function Split (inputstr, sep) if sep == nil then sep = "%s" end local t={} for str in string.gmatch(inputstr, "([^"..sep.."]+)") do table.insert(t, str) end return t end function SplitLiteral(inputstr, sep) if sep == nil then sep = "%s" end local t={} for str in string.gmatch(inputstr, "("..sep..")") do table.insert(t, str) end return t end function SendNotif(ID, type, title, msg, clr, r, g, b, expire) local clrBool = "false" if clr then clrBool = "true" end if Menu.GetInt("NM_API_Enabled") > IGlobalVars.realtime then Menu.SetString("NM_API_Payload", ID .. "*" .. type .. "*" .. title .. "*" .. msg .. "*" .. clrBool .. "*" .. r .. "*" .. g .. "*" .. b .. "*" .. (IGlobalVars.realtime + expire)) Menu.SetBool("NM_API_Send", true) end end function Bool2String(boolz) if boolz then return "true" else return "false" end end --Set initial settings function Setup() Print("Downloading version file...") URLDownloadToFile("https://kibbewater.xyz/ver/gh.txt", GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\kibbewater\\gh.txt") Print("Download finished") if FileSys.FileIsExist(GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\kibbewater\\gh.txt") then local fileData = FileSys.GetTextFromFile(GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\kibbewater\\gh.txt") local data = Split(fileData, "\n") Print("Recieved data: " .. data[1]) if #data == 2 then if ver ~= data[1] and Menu.GetInt("NM_API_Enabled") > IGlobalVars.realtime and not Menu.GetBool("NM_API_Send") and Menu.GetString("NM_API_Payload") == "" then Menu.SetString("NM_API_Payload", "GHUpdates" .. "*" .. "1" .. "*" .. "Grenade Helper Update" .. "*" .. "Please download " .. data[1] .. ", check forums for the latest update" .. "*" .. "false" .. "*" .. "0" .. "*" .. "0" .. "*" .. "0" .. "*" .. (IGlobalVars.realtime + 7)) Menu.SetBool("NM_API_Send", true) elseif Menu.GetInt("NM_API_Enabled") < IGlobalVars.realtime or Menu.GetBool("NM_API_Send") or Menu.GetString("NM_API_Payload") ~= "" then notifData = "GHUpdates" .. "*" .. "1" .. "*" .. "Grenade Helper Update" .. "*" .. "Please download " .. data[1] .. ", check forums for the latest update" .. "*" .. "false" .. "*" .. "0" .. "*" .. "0" .. "*" .. "0" .. "*" notifNew = true end end else Print("File not recieved") SendNotif("GHUpdates", 1, "Movement Recorder Update", "Error occured while getting current version", false, 0, 0, 0, IGlobalVars.realtime + 7) end end Hack.RegisterCallback("PaintTraverse", function () if Menu.GetInt("NM_API_Enabled") > IGlobalVars.realtime and notifNew and not Menu.GetBool("NM_API_Send") and Menu.GetString("NM_API_Payload") == "" then Menu.SetString("NM_API_Payload", notifData .. (IGlobalVars.realtime + 7)) Menu.SetBool("NM_API_Send", true) notifNew = false end if (not Utils.IsLocalAlive()) then return end if not Utils.IsInGame() then return end local pLocal = IEntityList.GetPlayer(IEngine.GetLocalPlayer()) if (not pLocal) then return end local weapon = pLocal:GetActiveWeapon() if (not weapon) then return end local wInfo = weapon:GetWeaponData() if (not wInfo) then return end local localPos = pLocal:GetAbsOrigin() local wName = "" if wInfo.consoleName == "weapon_molotov" or wInfo.consoleName == "weapon_incgrenade" then wName = "molotov" elseif wInfo.consoleName == "weapon_smokegrenade" then wName = "smoke" else wName = "" end if wName ~= "" and map ~= "" and Menu.GetString("cSpotFName") ~= "" and Menu.GetBool("cSubmitGrenadeSpot") then local throwTypes = {"Throw", "RunThrow", "JumpThrow", "Right Click"} local pPos = pLocal:GetAbsOrigin() --FileSys.SaveTextToFile("https://kibbewater.xyz/interium/submitspot.php?username=" .. Hack.GetUserName() .. "&map=" .. map .. "&location=" .. Menu.GetString("cSpotFName") .. "&throwtype=" .. throwTypes[Menu.GetInt("cSpotThrowType")+1] .. "&grenadetype=" .. wName .. "&x=" .. tostring(pPos.x) .. "&y=" .. tostring(pPos.y) .. "&z=" .. tostring(pPos.z) .. "&pitch=" .. tostring(viewAngle.pitch) .. "&yaw=" .. tostring(viewAngle.yaw)) URLDownloadToFile("https://kibbewater.xyz/interium/submitspot.php?username=" .. Hack.GetUserName() .. "&map=" .. map .. "&location=" .. Menu.GetString("cSpotFName") .. "&throwtype=" .. throwTypes[Menu.GetInt("cSpotThrowType")+1] .. "&grenadetype=" .. wName .. "&x=" .. tostring(pPos.x) .. "&y=" .. tostring(pPos.y) .. "&z=" .. tostring(pPos.z) .. "&pitch=" .. tostring(viewAngle.pitch) .. "&yaw=" .. tostring(viewAngle.yaw), GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\kibbewater\\http.txt") local data = FileSys.GetTextFromFile(GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\kibbewater\\http.txt") if data ~= "true" then SendNotif("GHError", 1, "Submission Error", "Submission failed with '" .. data .. "'", false, 0, 0, 0, 7) else SendNotif("GH", 3, "Submission", "Thank you for your submitting '" .. Menu.GetString("cSpotFName") .. "'", false, 0, 0, 0, 7) end Menu.SetBool("cSubmitGrenadeSpot", false) end for i = 1, #coords do if #coords[i] == 8 and coords[i][3] == wName then if displayedID == 0 or i == displayedID then local string = coords[i][1] .. "\n" .. coords[i][2] local textPos = Vector.new(tonumber(coords[i][4]), tonumber(coords[i][5]), tonumber(coords[i][6]) + 50) local pos = Vector.new(tonumber(coords[i][4]), tonumber(coords[i][5]), tonumber(coords[i][6])) local ang = QAngle.new(tonumber(coords[i][7]), tonumber(coords[i][8]), 0) local angVec = Vector.new(0,0,0) local angVecEye = Vector.new(0,0,0) local toScreen = Vector.new(0,0,0) local sCircle = Vector.new(0,0,0) local dist = Math.VectorDistance(pos, localPos) local nadeDist = 300 local screen = Vector.new(0,0,0) Math.AngleVectors(ang, angVec) Math.AngleVectors(viewAngle, angVecEye) local throwPos = Vector.new(pos.x + (angVec.x * nadeDist), pos.y + (angVec.y * nadeDist), pos.z + (angVec.z * nadeDist) + 64) local throwPosText = Vector.new(pos.x + (angVec.x * nadeDist), pos.y + (angVec.y * nadeDist), pos.z + (angVec.z * nadeDist) + 54) local screenThrow = Vector.new(0,0,0) local eyePosition = Vector.new(localPos.x + (angVecEye.x * nadeDist), localPos.y + (angVecEye.y * nadeDist), localPos.z + (angVecEye.z * nadeDist) + 64) local aimDist = Math.VectorDistance(eyePosition, throwPos) if Math.WorldToScreen(textPos, toScreen) and dist <= Menu.GetInt("cHelperRenderDistance") and dist >= 50 then Render.Text_1(string, toScreen.x, toScreen.y, 15, Color.new(255, 255, 255, 255), false, true) end if dist <= Menu.GetInt("cHelperRenderDistance") then local radius = 17 local color = Color.new(255,0,0,255) if dist >= 17 then radius = 27 else radius = 7 end if dist <= 2 then displayedID = i color = Color.new(0,255,0,255) else color = Color.new(255,0,0,255) end Render.Circle3D(pos, 100, radius, color) --Render.Circle(sCircle.x, sCircle.y, radius, color, 25, 2) end if Math.WorldToScreen(throwPos, screenThrow) and dist <= 5 then if Math.WorldToScreen(throwPosText, screen) then Render.Text_1(string, screen.x, screen.y, 15, Color.new(255, 255, 255, 255), false, true) end local color = Color.new(255,0,0,255) if aimDist <= 1.5 then color = Color.new(0,255,0,255) end displayedID = i Render.Circle(screenThrow.x, screenThrow.y, 8, color, 25, 2) if Menu.GetBool("cHelperDrawLineAngle") then Render.Line(Globals.ScreenWidth()/2, Globals.ScreenHeight()/2, screenThrow.x, screenThrow.y, color, 1) end end if displayedID == i and dist >= 3 then displayedID = 0 end end end end end) function LineToObject(line) local data = Split(line, "*") return {data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]} end Hack.RegisterCallback("CreateMove", function (cmd, send) if (not Utils.IsInGame()) then coords = {} displayedID = 0 loadedMap = "" end if (not Utils.IsLocal()) then return end map = IEngine.GetLevelNameShort() viewAngle = cmd.viewangles --Load Coords if map ~= loadedMap then URLDownloadToFile("https://kibbewater.xyz/interium/getspots.php?map=" .. map, GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\kibbewater\\Grenade Helper\\" .. map .. ".txt") local data = FileSys.GetTextFromFile(GetAppData() .. "\\INTERIUM\\CSGO\\FilesForLUA\\kibbewater\\Grenade Helper\\" .. map .. ".txt"):gsub("<br>", "\n") local locations = Split(data, "\n") coords = {} for i = 1, #locations do table.insert(coords, LineToObject(locations[i])) end loadedMap = map end end) Setup()
ENT.Type = "anim" ENT.Base = "base_anim" ENT.Range = 1024 function ENT:SetupDataTables() self:NetworkVar( "Int", 0, "Team" ) self:NetworkVar( "Int", 1, "PropHealth" ) end
-- -- User: Glastis -- Date: 15-Sep-19 -- local constant = {} constant.IMAGE_PATH = 'images/' constant.IMAGE_PATH_HOME = constant.IMAGE_PATH .. '1484022678_go-home.png' return constant
-------------------------------------------------------------------------------- --[[ TouchPoint A vent that tracks to the touch point. --]] -------------------------------------------------------------------------------- local CBE = require("CBE.CBE") local vent = CBE.newVent({ preset = "burn" }) local function onScreenTouch(event) vent.emitX, vent.emitY = event.x, event.y -- We want the vent to move no matter what the phase of the event if "began" == event.phase then vent:start() -- Start if began elseif "ended" == event.phase then vent:stop() -- Stop if ended end end Runtime:addEventListener("touch", onScreenTouch)
local rgph = require "rgph" local edge_fmt = "%d -- %d [label=%q, color=%q];\n" local graph_label_fmt = "%d edges, %d vertices, core %d, seed %d, flags %q" local function dot(file, g, ...) local seed = g:seed() --local hash = rgph[g:hash()] file:write("graph {\n") for peel, key, h1, h2, h3 in g:edges("peel,key", ...) do local color = peel > 0 and "black" or "red" local label = string.format("%s", key) -- local label = string.format("%s %x %x %x", key, hash(key, seed)) file:write(edge_fmt:format(h1, h2, label, color)) if h3 then file:write(edge_fmt:format(h2, h3, label, color)) end end local label = graph_label_fmt:format(g:entries(), g:vertices(), g:core_size(), seed, g:flags()) file:write(string.format("label=%q;}\n", label)) end return { dot=dot }
#!/usr/bin/env tarantool test = require("sqltester") test:plan(7) test:do_catchsql_test( "pragma-1.3", [[ PRAGMA kek = 'ON'; ]], { 1, "no such pragma: KEK" }) --- --- gh-2199: SQL default engine pragma --- test:do_catchsql_test( "pragma-2.1", [[ pragma sql_default_engine='creepy'; ]], { 1, "Space engine 'creepy' does not exist" }) test:do_catchsql_test( "pragma-2.2", [[ pragma sql_default_engine='vinyl'; ]], { 0 }) test:do_catchsql_test( "pragma-2.3", [[ pragma sql_default_engine='memtx'; ]], { 0 }) test:do_catchsql_test( "pragma-2.4", [[ pragma sql_default_engine; ]], { 1, 'Illegal parameters, \'sql_default_engine\' was not specified' }) test:do_catchsql_test( "pragma-2.5", [[ pragma sql_default_engine 'memtx'; ]], { 1, 'near \"\'memtx\'\": syntax error' }) test:do_catchsql_test( "pragma-2.5", [[ pragma sql_default_engine 1; ]], { 1, 'near \"1\": syntax error' }) test:finish_test()
----------------------------------- -- -- tpz.effect.CHR_DOWN -- ----------------------------------- require("scripts/globals/status") ----------------------------------- function onEffectGain(target, effect) if ((target:getStat(tpz.mod.CHR) - effect:getPower()) < 0) then effect:setPower(target:getStat(tpz.mod.CHR)) end target:addMod(tpz.mod.CHR, -effect:getPower()) end function onEffectTick(target, effect) -- the effect restore charism of 1 every 3 ticks. local downCHR_effect_size = effect:getPower() if (downCHR_effect_size > 0) then effect:setPower(downCHR_effect_size - 1) target:delMod(tpz.mod.CHR, -1) end end function onEffectLose(target, effect) downCHR_effect_size = effect:getPower() if (downCHR_effect_size > 0) then target:delMod(tpz.mod.CHR, -downCHR_effect_size) end end
if CLIENT then include("shared.lua") net.Receive("ClientDeathNotify", function() -- Read the variables from the message local name = net.ReadString() local role = tonumber(net.ReadString()) local reason = net.ReadString() -- Format the number role into a human readable role local col = ROLE_COLORS[role] local role_string = ROLE_STRINGS_EXT[role] if role == ROLE_NONE then col = COLOR_WHITE role_string = "a hidden role" end -- Format the reason for their death if reason == "suicide" then chat.AddText(COLOR_WHITE, "You killed yourself!") elseif reason == "burned" then chat.AddText(COLOR_WHITE, "You burned to death!") elseif reason == "prop" then chat.AddText(COLOR_WHITE, "You were killed by a prop!") elseif reason == "ply" then chat.AddText(COLOR_WHITE, "You were killed by ", col, name, COLOR_WHITE, ", they were ", col, role_string .. "!") elseif reason == "fell" then chat.AddText(COLOR_WHITE, "You fell to your death!") elseif reason == "water" then chat.AddText(COLOR_WHITE, "You drowned!") else chat.AddText(COLOR_WHITE, "You died!") end end) end if SERVER then -- Precache the net message util.AddNetworkString("ClientDeathNotify") hook.Add("PlayerDeath", "Kill_Reveal_Notify", function(victim, entity, killer) if gmod.GetGamemode().Name == "Trouble in Terrorist Town" then local reason = "nil" local killerz = "nil" local role = "nil" if victim.DiedByWater then reason = "water" elseif killer == victim then reason = "suicide" elseif IsValid(entity) then if victim:IsPlayer() and (string.StartWith(entity:GetClass(), "prop_physics") or entity:GetClass() == "prop_dynamic") then -- If the killer is also a prop reason = "prop" elseif IsValid(killer) then if entity:GetClass() == "entityflame" and killer:GetClass() == "entityflame" then reason = "burned" elseif entity:GetClass() == "worldspawn" and killer:GetClass() == "worldspawn" then reason = "fell" elseif killer:IsPlayer() and victim ~= killer then reason = "ply" killerz = killer:Nick() -- If this Phantom was killed by a player and they are supposed to haunt them, hide their killer's role if GetRoundState() == ROUND_ACTIVE and victim:IsPhantom() and GetConVar("ttt_phantom_killer_haunt"):GetBool() then role = ROLE_NONE else role = killer:GetRole() end end end end -- Send the buffer message with the death information to the victim net.Start("ClientDeathNotify") net.WriteString(killerz) net.WriteString(role) net.WriteString(reason) net.Send(victim) end end) end
local utils = require 'mp.utils' local msg = require 'mp.msg' local assdraw = require 'mp.assdraw' local on_windows = (package.config:sub(1,1) ~= "/") local opts = { thumbs_dir = on_windows and "%APPDATA%\\mpv\\gallery-thumbs-dir" or "~/.mpv_thumbs_dir/", auto_generate_thumbnails = true, generate_thumbnails_with_mpv = false, thumbnail_width = 192, thumbnail_height = 108, dynamic_thumbnail_size = "", take_thumbnail_at = "20%", resume_when_picking = true, start_gallery_on_startup = false, start_gallery_on_file_end = false, toggle_behaves_as_accept = true, margin_x = 15, margin_y = 15, max_thumbnails = 64, show_scrollbar = true, scrollbar_side = "left", scrollbar_min_size = 10, show_placeholders = true, placeholder_color = "222222", always_show_placeholders = false, background = "0.1", show_filename = true, show_title = true, strip_directory = true, strip_extension = true, text_size = 28, selected_frame_color = "DDDDDD", flagged_frame_color = "5B9769", selected_flagged_frame_color = "BAFFCA", flagged_file_path = "./mpv_gallery_flagged", max_generators = 8, mouse_support = true, UP = "UP", DOWN = "DOWN", LEFT = "LEFT", RIGHT = "RIGHT", PAGE_UP = "PGUP", PAGE_DOWN = "PGDWN", FIRST = "HOME", LAST = "END", RANDOM = "r", ACCEPT = "ENTER", CANCEL = "ESC", REMOVE = "DEL", FLAG = "SPACE", } (require 'mp.options').read_options(opts) function split(input, char, tonum) local ret = {} for str in string.gmatch(input, "([^" .. char .. "]+)") do ret[#ret + 1] = (not tonum and str) or tonumber(str) end return ret end opts.dynamic_thumbnail_size = split(opts.dynamic_thumbnail_size, ";", false) for i = 1, #opts.dynamic_thumbnail_size do local preset = split(opts.dynamic_thumbnail_size[i], ",", true) if (#preset ~= 3) or not (preset[1] and preset[2] and preset[3]) then msg.error(opts.dynamic_thumbnail_size[i] .. " is not a valid preset") return end opts.dynamic_thumbnail_size[i] = preset end if on_windows then opts.thumbs_dir = string.gsub(opts.thumbs_dir, "^%%APPDATA%%", os.getenv("APPDATA") or "%APPDATA%") else opts.thumbs_dir = string.gsub(opts.thumbs_dir, "^~", os.getenv("HOME") or "~") end opts.max_thumbnails = math.min(opts.max_thumbnails, 64) local sha256 --[[ minified code below is a combination of: -sha256 implementation from http://lua-users.org/wiki/SecureHashAlgorithm -lua implementation of bit32 (used as fallback on lua5.1) from https://www.snpedia.com/extensions/Scribunto/engines/LuaCommon/lualib/bit32.lua both are licensed under the MIT below: 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. --]] do local b,c,d,e,f;if bit32 then b,c,d,e,f=bit32.band,bit32.rrotate,bit32.bxor,bit32.rshift,bit32.bnot else f=function(g)g=math.floor(tonumber(g))%0x100000000;return(-g-1)%0x100000000 end;local h={[0]={[0]=0,0,0,0},[1]={[0]=0,1,0,1},[2]={[0]=0,0,2,2},[3]={[0]=0,1,2,3}}local i={[0]={[0]=0,1,2,3},[1]={[0]=1,0,3,2},[2]={[0]=2,3,0,1},[3]={[0]=3,2,1,0}}local function j(k,l,m,n,o)for p=1,m do l[p]=math.floor(tonumber(l[p]))%0x100000000 end;local q=1;local r=0;for s=0,31,2 do local t=n;for p=1,m do t=o[t][l[p]%4]l[p]=math.floor(l[p]/4)end;r=r+t*q;q=q*4 end;return r end;b=function(...)return j('band',{...},select('#',...),3,h)end;d=function(...)return j('bxor',{...},select('#',...),0,i)end;e=function(g,u)g=math.floor(tonumber(g))%0x100000000;u=math.floor(tonumber(u))u=math.min(math.max(-32,u),32)return math.floor(g/2^u)%0x100000000 end;c=function(g,u)g=math.floor(tonumber(g))%0x100000000;u=-math.floor(tonumber(u))%32;local g=g*2^u;return g%0x100000000+math.floor(g/0x100000000)end end;local v={0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2}local function w(n)return string.gsub(n,".",function(t)return string.format("%02x",string.byte(t))end)end;local function x(y,z)local n=""for p=1,z do local A=y%256;n=string.char(A)..n;y=(y-A)/256 end;return n end;local function B(n,p)local z=0;for p=p,p+3 do z=z*256+string.byte(n,p)end;return z end;local function C(D,E)local F=-(E+1+8)%64;E=x(8*E,8)D=D.."\128"..string.rep("\0",F)..E;return D end;local function G(H)H[1]=0x6a09e667;H[2]=0xbb67ae85;H[3]=0x3c6ef372;H[4]=0xa54ff53a;H[5]=0x510e527f;H[6]=0x9b05688c;H[7]=0x1f83d9ab;H[8]=0x5be0cd19;return H end;local function I(D,p,H)local J={}for K=1,16 do J[K]=B(D,p+(K-1)*4)end;for K=17,64 do local L=J[K-15]local M=d(c(L,7),c(L,18),e(L,3))L=J[K-2]local N=d(c(L,17),c(L,19),e(L,10))J[K]=J[K-16]+M+J[K-7]+N end;local O,s,t,P,Q,R,S,T=H[1],H[2],H[3],H[4],H[5],H[6],H[7],H[8]for p=1,64 do local M=d(c(O,2),c(O,13),c(O,22))local U=d(b(O,s),b(O,t),b(s,t))local V=M+U;local N=d(c(Q,6),c(Q,11),c(Q,25))local W=d(b(Q,R),b(f(Q),S))local X=T+N+W+v[p]+J[p]T=S;S=R;R=Q;Q=P+X;P=t;t=s;s=O;O=X+V end;H[1]=b(H[1]+O)H[2]=b(H[2]+s)H[3]=b(H[3]+t)H[4]=b(H[4]+P)H[5]=b(H[5]+Q)H[6]=b(H[6]+R)H[7]=b(H[7]+S)H[8]=b(H[8]+T)end;local function Y(H)return w(x(H[1],4)..x(H[2],4)..x(H[3],4)..x(H[4],4)..x(H[5],4)..x(H[6],4)..x(H[7],4)..x(H[8],4))end;local Z={}sha256=function(D)D=C(D,#D)local H=G(Z)for p=1,#D,64 do I(D,p,H)end;return Y(H)end end -- end of sha code active = false playlist = {} -- copy of the current "playlist" property geometry = { window_w = 0, window_h = 0, rows = 0, columns = 0, size_x = 0, size_y = 0, margin_x = 0, margin_y = 0, } view = { -- 1-based indices into the "playlist" array first = 0, -- must be equal to N*columns last = 0, -- must be > first and <= first + rows*columns } overlays = { active = {}, -- array of 64 strings indicating the file associated to the current thumbnail (empty if no file) missing = {}, -- maps hashes of missing thumbnails to the index they should be shown at } selection = { old = 0, -- the playlist element selected when entering the gallery now = 0, -- the currently selected element } pending = { selection = -1, window_size_changed = false, deletion = false, } ass = { selection = "", scrollbar = "", placeholders = "", } flags = {} resume = {} -- maps filename to the time-pos it was at when starting the gallery misc = { old_idle = "", old_force_window = "", old_geometry = "", old_osd_level = "", old_background = "", old_vid = "", } generators = {} -- list of generator scripts that have registered themselves do local inited = false function init() if not inited then inited = true if utils.file_info then -- 0.28+ local res = utils.file_info(opts.thumbs_dir) if not res or not res.is_dir then msg.error(string.format("Thumbnail directory \"%s\" does not exist", opts.thumbs_dir)) end end if opts.auto_generate_thumbnails and #generators == 0 then msg.error("Auto-generation on, but no generators registered") end end end end function file_exists(path) if utils.file_info then -- 0.28+ local info = utils.file_info(path) return info ~= nil and info.is_file else local f = io.open(path, "r") if f ~= nil then io.close(f) return true end return false end end function thumbnail_size_from_presets(window_w, window_h) local size = window_w * window_h local picked = nil for _, preset in ipairs(opts.dynamic_thumbnail_size) do picked = { preset[2], preset[3] } if size <= preset[1] then break end end return picked end function select_under_cursor() local g = geometry local mx, my = mp.get_mouse_pos() if mx < 0 or my < 0 or mx > g.window_w or my > g.window_h then return end local mx, my = mx - g.margin_x, my - g.margin_y local on_column = (mx % (g.size_x + g.margin_x)) < g.size_x local on_row = (my % (g.size_y + g.margin_y)) < g.size_y if on_column and on_row then local column = math.floor(mx / (g.size_x + g.margin_x)) local row = math.floor(my / (g.size_y + g.margin_y)) local new_sel = view.first + row * g.columns + column if new_sel > view.last then return end if selection.now == new_sel then quit_gallery_view(selection.now) else selection.now = new_sel pending.selection = new_sel ass_show(true, false, false) end end end function toggle_selection_flag() local name = playlist[selection.now].filename if flags[name] == nil then flags[name] = true else flags[name] = nil end ass_show(true, false, false) end do local function increment_func(increment, clamp) local new = pending.selection == -1 and selection.now or pending.selection new = new + increment if new <= 0 or new > #playlist then if not clamp then return end new = math.max(1, math.min(new, #playlist)) end pending.selection = new end local bindings_repeat = {} bindings_repeat[opts.UP] = function() increment_func(- geometry.columns, false) end bindings_repeat[opts.DOWN] = function() increment_func( geometry.columns, false) end bindings_repeat[opts.LEFT] = function() increment_func(- 1, false) end bindings_repeat[opts.RIGHT] = function() increment_func( 1, false) end bindings_repeat[opts.PAGE_UP] = function() increment_func(- geometry.columns * geometry.rows, true) end bindings_repeat[opts.PAGE_DOWN] = function() increment_func( geometry.columns * geometry.rows, true) end bindings_repeat[opts.RANDOM] = function() pending.selection = math.random(1, #playlist) end bindings_repeat[opts.REMOVE] = function() pending.deletion = true end local bindings = {} bindings[opts.FIRST] = function() pending.selection = 1 end bindings[opts.LAST] = function() pending.selection = #playlist end bindings[opts.ACCEPT] = function() quit_gallery_view(selection.now) end bindings[opts.CANCEL] = function() quit_gallery_view(selection.old) end bindings[opts.FLAG] = toggle_selection_flag if opts.mouse_support then bindings["MBTN_LEFT"] = select_under_cursor bindings["WHEEL_UP"] = function() increment_func(- geometry.columns, true) end bindings["WHEEL_DOWN"] = function() increment_func( geometry.columns, true) end end local function window_size_changed() pending.window_size_changed = true end local function idle_handler() if pending.selection ~= -1 then increment_selection(pending.selection) pending.selection = -1 end if pending.window_size_changed then pending.window_size_changed = false local window_w, window_h = mp.get_osd_size() if window_w ~= geometry.window_w or window_h ~= geometry.window_h then resize_gallery(window_w, window_h) end end if pending.deletion then pending.deletion = false mp.commandv("playlist-remove", selection.now - 1) selection.now = selection.now + (selection.now == #playlist and -1 or 1) end end function setup_ui_handlers() for key, func in pairs(bindings_repeat) do mp.add_forced_key_binding(key, "gallery-view-"..key, func, {repeatable = true}) end for key, func in pairs(bindings) do mp.add_forced_key_binding(key, "gallery-view-"..key, func) end for _, prop in ipairs({ "osd-width", "osd-height" }) do mp.observe_property(prop, "native", window_size_changed) end mp.register_idle(idle_handler) end function teardown_ui_handlers() for key, _ in pairs(bindings_repeat) do mp.remove_key_binding("gallery-view-"..key) end for key, _ in pairs(bindings) do mp.remove_key_binding("gallery-view-"..key) end mp.unobserve_property(window_size_changed) mp.unregister_idle(idle_handler) end end function restore_playlist_and_select(select) mp.set_property_number("playlist-pos-1", select) if opts.resume_when_picking then local time = resume[playlist[select].filename] if time then local tmp local func = function() mp.commandv("seek", time, "absolute") mp.unregister_event(tmp) end tmp = func mp.register_event("file-loaded", func) end end end function restore_properties() mp.set_property("idle", misc.old_idle) mp.set_property("force-window", misc.old_force_window) mp.set_property("geometry", misc.old_geometry) mp.set_property("osd-level", misc.old_osd_level) mp.set_property("background", misc.old_background) mp.set_property("vid", misc.old_vid) mp.set_property_bool("pause", false) mp.commandv("script-message", "osc-visibility", "auto", "true") end function save_properties() misc.old_idle = mp.get_property("idle") misc.old_force_window = mp.get_property("force-window") misc.old_geometry = mp.get_property("geometry") misc.old_osd_level = mp.get_property("osd-level") misc.old_background = mp.get_property("background") misc.old_vid = mp.get_property("vid") mp.set_property_bool("pause", true) mp.set_property_bool("idle", true) mp.set_property_bool("force-window", true) mp.set_property_number("osd-level", 0) mp.set_property("background", opts.background) mp.set_property("vid", "no") mp.commandv("no-osd", "script-message", "osc-visibility", "never", "true") mp.set_property("geometry", geometry.window_w .. "x" .. geometry.window_h) end function compute_geometry(ww, wh) geometry.window_w, geometry.window_h = ww, wh local dyn_thumb_size = thumbnail_size_from_presets(ww, wh) if dyn_thumb_size then geometry.size_x = dyn_thumb_size[1] geometry.size_y = dyn_thumb_size[2] else geometry.size_x = opts.thumbnail_width geometry.size_y = opts.thumbnail_height end local margin_y = opts.show_filename and math.max(opts.text_size, opts.margin_y) or opts.margin_y geometry.rows = math.floor((wh - margin_y) / (geometry.size_y + margin_y)) geometry.columns = math.floor((ww - opts.margin_x) / (geometry.size_x + opts.margin_x)) if (geometry.rows * geometry.columns > opts.max_thumbnails) then local r = math.sqrt(geometry.rows * geometry.columns / opts.max_thumbnails) geometry.rows = math.floor(geometry.rows / r) geometry.columns = math.floor(geometry.columns / r) end geometry.margin_x = (ww - geometry.columns * geometry.size_x) / (geometry.columns + 1) geometry.margin_y = (wh - geometry.rows * geometry.size_y) / (geometry.rows + 1) end function increment_selection(inc) selection.now = inc ensure_view_valid() refresh_overlays(false) ass_show(true, true, true) end function resize_gallery(window_w, window_h) compute_geometry(window_w, window_h) if geometry.rows <= 0 or geometry.columns <= 0 then quit_gallery_view(selection.old) return end ensure_view_valid() refresh_overlays(true) ass_show(true, true, true) end -- makes sure that view.first and view.last are valid with regards to the playlist -- and that selection.now is within the view -- to be called after the playlist, view or selection was modified somehow function ensure_view_valid() local selection_row = math.floor((selection.now - 1) / geometry.columns) local max_thumbs = geometry.rows * geometry.columns if view.last >= #playlist then view.last = #playlist last_row = math.floor((view.last - 1) / geometry.columns) first_row = math.max(0, last_row - geometry.rows + 1) view.first = 1 + first_row * geometry.columns elseif view.first == 0 or view.last == 0 or view.last - view.first + 1 ~= max_thumbs then -- special case: the number of possible thumbnails was changed -- just recreate the view such that the selection is in the middle row local max_row = (#playlist - 1) / geometry.columns + 1 local row_first = selection_row - math.floor((geometry.rows - 1) / 2) local row_last = selection_row + math.floor((geometry.rows - 1) / 2) + geometry.rows % 2 if row_first < 0 then row_first = 0 elseif row_last > max_row then row_first = max_row - geometry.rows + 1 end view.first = 1 + row_first * geometry.columns view.last = math.min(#playlist, view.first - 1 + max_thumbs) return end if selection.now < view.first then -- the selection is now on the first line view.first = selection_row * geometry.columns + 1 view.last = math.min(#playlist, view.first + max_thumbs - 1) elseif selection.now > view.last then -- the selection is now on the last line view.last = (selection_row + 1) * geometry.columns view.first = math.max(1, view.last - max_thumbs + 1) view.last = math.min(#playlist, view.last) end end -- ass related stuff do local function refresh_placeholders() if not opts.show_placeholders then return end local a = assdraw.ass_new() a:new_event() a:append('{\\bord0}') a:append('{\\shad0}') a:append('{\\1c&' .. opts.placeholder_color .. '}') a:pos(0, 0) a:draw_start() for i = 0, view.last - view.first do if opts.always_show_placeholders or overlays.active[i + 1] == "" then local x = geometry.margin_x + (geometry.margin_x + geometry.size_x) * (i % geometry.columns) local y = geometry.margin_y + (geometry.margin_y + geometry.size_y) * math.floor(i / geometry.columns) a:rect_cw(x, y, x + geometry.size_x, y + geometry.size_y) end end a:draw_stop() ass.placeholders = a.text end local function refresh_scrollbar() if not opts.show_scrollbar then return end ass.scrollbar = "" local before = (view.first - 1) / #playlist local after = (#playlist - view.last) / #playlist -- don't show the scrollbar if everything is visible if before + after == 0 then return end local p = opts.scrollbar_min_size / 100 if before + after > 1 - p then if before == 0 then after = (1 - p) elseif after == 0 then before = (1 - p) else before, after = before / after * (1 - p) / (1 + before / after), after / before * (1 - p) / (1 + after / before) end end local y1 = geometry.margin_y + before * (geometry.window_h - 2 * geometry.margin_y) local y2 = geometry.window_h - (geometry.margin_y + after * (geometry.window_h - 2 * geometry.margin_y)) local x1, x2 if opts.scrollbar_side == "left" then x1, x2 = 4, 8 else x1, x2 = geometry.window_w - 8, geometry.window_w - 4 end local scrollbar = assdraw.ass_new() scrollbar:new_event() scrollbar:append('{\\bord0}') scrollbar:append('{\\shad0}') scrollbar:append('{\\1c&AAAAAA&}') scrollbar:pos(0, 0) scrollbar:draw_start() scrollbar:round_rect_cw(x1, y1, x2, y2, 2) scrollbar:draw_stop() ass.scrollbar = scrollbar.text end local function refresh_selection() local selection_ass = assdraw.ass_new() local draw_frame = function(index, color) if index < view.first or index > view.last then return end local i = index - view.first local x = geometry.margin_x + (geometry.margin_x + geometry.size_x) * (i % geometry.columns) local y = geometry.margin_y + (geometry.margin_y + geometry.size_y) * math.floor(i / geometry.columns) selection_ass:new_event() selection_ass:append('{\\bord5}') selection_ass:append('{\\3c&'.. color ..'&}') selection_ass:append('{\\1a&FF&}') selection_ass:pos(0, 0) selection_ass:draw_start() selection_ass:round_rect_cw(x, y, x + geometry.size_x, y + geometry.size_y, 2) selection_ass:draw_stop() end for i = view.first, view.last do local name = playlist[i].filename if flags[name] then if i == selection.now then draw_frame(i, opts.selected_flagged_frame_color) else draw_frame(i, opts.flagged_frame_color) end elseif i == selection.now then draw_frame(i, opts.selected_frame_color) end end if opts.show_filename or opts.show_title then selection_ass:new_event() local i = (selection.now - view.first) local an = 5 local x = geometry.margin_x + (geometry.margin_x + geometry.size_x) * (i % geometry.columns) + geometry.size_x / 2 local y = geometry.margin_y + (geometry.margin_y + geometry.size_y) * math.floor(i / geometry.columns) + geometry.size_y + geometry.margin_y / 2 local col = i % geometry.columns if geometry.columns > 1 then if col == 0 then x = x - geometry.size_x / 2 an = 4 elseif col == geometry.columns - 1 then x = x + geometry.size_x / 2 an = 6 end end selection_ass:an(an) selection_ass:pos(x, y) selection_ass:append(string.format("{\\fs%d}", opts.text_size)) selection_ass:append("{\\bord0}") local f local element = playlist[selection.now] if opts.show_title and element.title then f = element.title else f = element.filename if opts.strip_directory then if on_windows then f = string.match(f, "([^\\/]+)$") or f else f = string.match(f, "([^/]+)$") or f end end if opts.strip_extension then f = string.match(f, "(.+)%.[^.]+$") or f end end selection_ass:append(f) end ass.selection = selection_ass.text end function ass_show(selection, scrollbar, placeholders) if selection then refresh_selection() end if scrollbar then refresh_scrollbar() end if placeholders then refresh_placeholders() end local merge = function(a, b) return b ~= "" and (a .. "\n" .. b) or a end mp.set_osd_ass(geometry.window_w, geometry.window_h, merge(merge(ass.selection, ass.scrollbar), ass.placeholders) ) end function ass_hide() mp.set_osd_ass(1280, 720, "") end end function normalize_path(path) if string.find(path, "://") then return path end path = utils.join_path(utils.getcwd(), path) if on_windows then path = string.gsub(path, "\\", "/") end path = string.gsub(path, "/%./", "/") local n repeat path, n = string.gsub(path, "/[^/]*/%.%./", "/", 1) until n == 0 return path end function refresh_overlays(force) local todo = {} overlays.missing = {} for i = 1, 64 do local index = view.first + i - 1 if index <= view.last then local filename = playlist[index].filename if force or overlays.active[i] ~= filename then local filename_hash = string.sub(sha256(normalize_path(filename)), 1, 12) local thumb_filename = string.format("%s_%d_%d", filename_hash, geometry.size_x, geometry.size_y) local thumb_path = utils.join_path(opts.thumbs_dir, thumb_filename) if file_exists(thumb_path) then show_overlay(i, thumb_path) overlays.active[i] = filename else remove_overlay(i) overlays.missing[thumb_path] = { index = i, input = filename } todo[#todo + 1] = { input = filename, output = thumb_path } end end else remove_overlay(i) end end -- reverse iterate so that the first thumbnail is at the top of the stack if opts.auto_generate_thumbnails and #generators >= 1 then for i = #todo, 1, -1 do local generator = generators[i % #generators + 1] local t = todo[i] mp.commandv("script-message-to", generator, "push-thumbnail-front", mp.get_script_name(), t.input, tostring(geometry.size_x), tostring(geometry.size_y), opts.take_thumbnail_at, t.output, opts.generate_thumbnails_with_mpv and "true" or "false" ) end end end function show_overlay(index_1, thumb_path) local g = geometry local index_0 = index_1 - 1 mp.command(string.format("overlay-add %i %i %i %s 0 bgra %i %i %i;", index_0, g.margin_x + (g.margin_x + g.size_x) * (index_0 % g.columns), g.margin_y + (g.margin_y + g.size_y) * math.floor(index_0 / g.columns), thumb_path, g.size_x, g.size_y, 4*g.size_x )) mp.osd_message("", 0.01) end function remove_overlays() for i = 1, 64 do remove_overlay(i) end overlays.missing = {} end function remove_overlay(index_1) if overlays.active[index_1] == "" then return end overlays.active[index_1] = "" mp.command("overlay-remove " .. index_1 - 1) mp.osd_message("", 0.01) end function playlist_changed(key, value) local did_change = function() if #playlist ~= #value then return true end for i = 1, #playlist do if playlist[i].filename ~= value[i].filename then return true end end return false end if not did_change() then return end if #value == 0 then quit_gallery_view() return end local sel_old_file = playlist[selection.old].filename local sel_new_file = playlist[selection.now].filename playlist = value selection.old = math.max(1, math.min(selection.old, #playlist)) selection.now = math.max(1, math.min(selection.now, #playlist)) for i, f in ipairs(playlist) do if sel_old_file == f.filename then selection.old = i end if sel_new_file == f.filename then selection.now = i end end ensure_view_valid() refresh_overlays(false) ass_show(true, true, true) end function start_gallery_view() init() playlist = mp.get_property_native("playlist") if #playlist == 0 then return end mp.observe_property("playlist", "native", playlist_changed) local ww, wh = mp.get_osd_size() compute_geometry(ww, wh) if geometry.rows <= 0 or geometry.columns <= 0 then return end save_properties() local pos = mp.get_property_number("playlist-pos-1") if opts.resume_when_picking and pos then resume[playlist[pos].filename] = mp.get_property_number("time-pos") or 0 end selection.old = pos or 1 selection.now = selection.old ensure_view_valid() setup_ui_handlers() refresh_overlays(true) ass_show(true, true, true) active = true end function quit_gallery_view(select) teardown_ui_handlers() remove_overlays() mp.unobserve_property(playlist_changed) ass_hide() if select then restore_playlist_and_select(select) end restore_properties() active = false end function toggle_gallery() if not active then start_gallery_view() else quit_gallery_view(opts.toggle_behaves_as_accept and selection.now or selection.old) end end mp.register_script_message("thumbnail-generated", function(thumbnail_path) if not active then return end local missing = overlays.missing[thumbnail_path] if missing == nil then return end show_overlay(missing.index, thumbnail_path) overlays.active[missing.index] = missing.input if not opts.always_show_placeholders then ass_show(false, false, true) end overlays.missing[thumbnail_path] = nil end) mp.register_script_message("thumbnails-generator-broadcast", function(generator_name) if #generators >= opts.max_generators then return end for _, g in ipairs(generators) do if generator_name == g then return end end generators[#generators + 1] = generator_name end) function write_flag_file() if next(flags) == nil then return end local out = io.open(opts.flagged_file_path, "w") for f, _ in pairs(flags) do out:write(f .. "\n") end out:close() end mp.register_event("shutdown", write_flag_file) if opts.start_gallery_on_file_end then mp.register_event("end-file", function() if not active and mp.get_property_number("playlist-count") > 1 then start_gallery_view() end end) end if opts.start_gallery_on_startup then local autostart autostart = function(_, v) if v == 0 then return end mp.unobserve_property(autostart) start_gallery_view() end mp.observe_property("playlist-count", "number", autostart) end mp.add_key_binding("g", "gallery-view", toggle_gallery) mp.add_key_binding(nil, "gallery-write-flag-file", write_flag_file)
local insert insert = table.insert local config_cache, configs, default_config, merge_set, set, scope_meta, config, reset, run_with_scope, get_env, get config_cache = { } configs = { } default_config = { server = "nginx", port = "8080", secret = "please-change-me", session_name = "lapis_session", code_cache = "off", num_workers = "1", logging = { queries = true, requests = true, server = true } } merge_set = function(t, k, v) local existing = t[k] if type(v) == "table" then if type(existing) ~= "table" then existing = { } t[k] = existing end for sub_k, sub_v in pairs(v) do merge_set(existing, sub_k, sub_v) end else t[k] = v end end set = function(conf, k, v) if type(k) == "table" then for sub_k, sub_v in pairs(k) do merge_set(conf, sub_k, sub_v) end else if type(v) == "function" then return merge_set(conf, k, run_with_scope(v, { })) else return merge_set(conf, k, v) end end end scope_meta = { __index = function(self, name) local val = _G[name] if not (val == nil) then return val end do local _exp_0 = name if "set" == _exp_0 then val = function(...) return set(self._conf, ...) end elseif "unset" == _exp_0 then val = function(...) local _list_0 = { ... } for _index_0 = 1, #_list_0 do local k = _list_0[_index_0] self._conf[k] = nil end end elseif "include" == _exp_0 then val = function(fn) return run_with_scope(fn, self._conf) end else val = function(v) return set(self._conf, name, v) end end self[name] = val return val end end } config = function(environment, fn) if type(environment) == "table" then for _index_0 = 1, #environment do local env = environment[_index_0] config(env, fn) end return end configs[environment] = configs[environment] or { } table.insert(configs[environment], fn) return nil end reset = function(env) if env == true then for k in pairs(configs) do configs[k] = nil end for k in pairs(config_cache) do config_cache[k] = nil end else configs[env] = nil config_cache[env] = nil end end run_with_scope = function(fn, conf) local getfenv, setfenv do local _obj_0 = require("lapis.util.fenv") getfenv, setfenv = _obj_0.getfenv, _obj_0.setfenv end local old_env = getfenv(fn) local env = setmetatable({ _conf = conf }, scope_meta) setfenv(fn, env) fn() setfenv(fn, old_env) return conf end get_env = function() return require("lapis.environment").default_environment() end do local loaded_config = false get = function(name) if name == nil then name = get_env() end if not (name) then error("missing environment name") end if not (loaded_config) then loaded_config = true local success, err = pcall(function() return require("config") end) if not (success or err:match("module 'config' not found")) then error(err) end end if config_cache[name] then return config_cache[name] end local conf do local _tbl_0 = { } for k, v in pairs(default_config) do _tbl_0[k] = v end conf = _tbl_0 end conf._name = name do local fns = configs[name] if fns then for _index_0 = 1, #fns do local fn = fns[_index_0] local _exp_0 = type(fn) if "function" == _exp_0 then run_with_scope(fn, conf) elseif "table" == _exp_0 then set(conf, fn) end end end end config_cache[name] = conf return conf end end return setmetatable({ get = get, config = config, merge_set = merge_set, default_config = default_config, reset = reset }, { __call = function(self, ...) return config(...) end })
--[[ abstract-to-meta – move an "abstract" section into document metadata Copyright: © 2017–2020 Albert Krewinkel License: MIT – see LICENSE file for details ]] local looking_at_abstract = false local abstract = {} function Block (elem) if looking_at_abstract then abstract[#abstract + 1] = elem return {} end end function Header (elem) if elem.level == 1 and elem.identifier == 'abstract' then looking_at_abstract = true return {} else looking_at_abstract = looking_at_abstract and elem.level ~= 1 end end function Meta (meta) meta.abstract = meta.abstract or pandoc.MetaBlocks(abstract) return meta end
local test local testModel local sphere local skybox local time = 0 local testFont local rt local rtMat local camera local Camera = require "camera" require "helpers".global() local changeRot = 0 function _init() testModel = Model("test.fbx") testModel:getRootNode():setTransform(Matrix():scale(2,1,1)) sphere = Model("sphere.fbx") camera = Camera(Vector3(-2,0,-8)) camera.angles = {0.48500002529471, 0} skybox = Model("skybox.fbx") skybox:getMeshes()[1]:getMaterial(1):setShaded(false) RegisterFontFile("slkscr.ttf") testFont = Font("Silkscreen", 18, 1, false) local res = GetResolution() rt = RenderTarget(2048, 2048) rtMat = Material() rtMat:setHandle(1, rt:getHandle()) ShowCursor(false) SetCursorMode(CURSORMODE_CENTERED) end function _update(dt) if GetKeyDown(KEY_ESCAPE) then ExitGame() end if GetKeyDown(KEY_F2) then ShowCursor(not IsCursorVisible()) SetCursorMode(1-GetCursorMode()) end if GetKeyDown("m") then changeRot = 1 - changeRot end camera:update(dt) time = time + dt end function _render() rt:bind() CameraPerspective(62.5, 0.1, 500, true) camera.mat:bind(VIEW) skybox:draw(Matrix():translate(camera.pos)) withTexture(rt, function() sphere:draw(Matrix():translate(2 +math.cos(time)*1.2,0,-4)) end) testModel:getMeshes()[1]:setMaterial(rtMat) sphere:getMeshes()[1]:setMaterial(rtMat) testModel:draw() ClearTarget() CameraPerspective(62, 0.1, 500) rt:bind() CullMode(3) EnableLighting(false) ClearScene(20,20,69) skybox:draw(Matrix():translate(camera.pos)) withTexture(rt, function() sphere:draw(Matrix():translate(2 +math.cos(time)*1.2,0,-4)) end) testModel:draw() ClearTarget() ClearScene(120,20,69) skybox:draw(Matrix():translate(camera.pos)) withTexture(rt, function() sphere:draw(Matrix():translate(2 +math.cos(time)*1.2,0,-4)) end) testModel:draw() end function _render2d() testFont:drawText(0xFFFFFFFF, "RTT test (no shaders)\nWASD to move around\nM to toggle mirror rotation", 15, 30) end
--- === hs.roku === --- --- Stuff about the module local USERDATA_TAG = "hs.roku" -- local module = require(USERDATA_TAG..".internal") local module = {} local xml = require(USERDATA_TAG .. ".qduXML") 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 inspect = require("hs.inspect") local timer = require("hs.timer") local socket = require("hs.socket") local http = require("hs.http") local fnutils = require("hs.fnutils") local settings = require("hs.settings") local utf8 = require("hs.utf8") local image = require("hs.image") local logger = require("hs.logger") -- settings with periods in them can't be watched via KVO with hs.settings.watchKey, so -- in general it's a good idea not to include periods local SETTINGS_TAG = USERDATA_TAG:gsub("%.", "_") local log = logger.new(USERDATA_TAG, settings.get(SETTINGS_TAG .. "_logLevel") or "warning") -- private variables and methods ----------------------------------------- local flattenInspect = { newline = " ", indent = "" } -- for timers, etc so they don't get collected local __internals = {} -- we want to validate at assignment and trigger updates when changed, so handle via module __index/__newindex local __internalVariables = {} local ssdpQuery = function(queryTime) queryTime = queryTime or __internalVariables.ssdpQueryTime return [[ M-SEARCH * HTTP/1.1 HOST: 239.255.255.250:1900 MAN: "ssdp:discover" MX: ]] .. tostring(queryTime) .. "\n" .. [[ ST: "roku:ecp" USER-AGENT: Hammerspoon/]] .. hs.processInfo.version .. [[ UPnP/1.1 SSDPDiscover/0.0 ]] end -- discovered roku devices local __devices = setmetatable({}, { __index = function(self, key) end, __newindex = function(self, key, value) end, __tostring = function(self) local result = "" for k, v in pairs(self) do result = result .. k .. "\t" .. inspect(v, { newline = " ", indent = "", depth = 1 }) .. "\n" end return result end, }) local addDeviceHelper = function(host, port, s, b, h) if s == 200 then local data, msg = pcall(xml.parseXML, b) if not data then return nil, string.format("invalid xml data: %s", msg) end data = msg local serialNumber = data("serial-number")[1]:value() if not serialNumber then return nil, string.format("unable to determine serial number from %s", b) end if not __devices[serialNumber] then -- if it already exists, don't replace it rawset(__devices, serialNumber, {}) end local entry = __devices[serialNumber] entry.host = host entry.port = port entry.alive = true entry.name = xml.entityValue(data("user-device-name"), 1) or xml.entityValue(data("friendly-device-name"), 1) or xml.entityValue(data("friendly-model-name"), 1) or xml.entityValue(data("default-device-name"), 1) or serialNumber entry.isTV = tostring(xml.entityValue(data("is-tv"), 1)):upper() == "TRUE" entry.supportsFindRemote = tostring(xml.entityValue(data("supports-find-remote"), 1)):upper() == "TRUE" entry.supportsHeadphones = tostring(xml.entityValue(data("supports-private-listening"), 1)):upper() == "TRUE" return serialNumber end return nil, string.format("Unable to reach Roku device at %s -- %d -- %s -- %s", host, s, b, inspect(h, flattenInspect)) end local deviceMetatable = { name = function(self) return __devices[self[1]].name end, host = function(self) return __devices[self[1]].host end, port = function(self) return __devices[self[1]].port end, sn = function(self) return self[1] end, url = function(self, query) query = query or "" return "http://" .. self:host() .. ":" .. self:port() .. "/" .. query:match("^/?(.*)$") end, -- devInfo = function(self, root) -- local s, b, h = http.get(self:url(root and "/" or "/query/device-info"), {}) -- if s == 200 then -- return xml.parseXML(b) -- else -- log.ef("http query error -- %d -- %s -- %s", s, b, inspect(h, flattenInspect)) -- return xml.parseXML([[<error status="]] .. tostring(s) .. [[">]] .. b .. [[</error>]]) -- end -- end, devInfo = function(self, root) local s, b, h = http.get(self:url(root and "/" or "/query/device-info"), {}) if s == 200 then local state, bXML = pcall(xml.parseXML, b) if state then return setmetatable(bXML:asTable()[root and "root" or "device-info"], { __tostring = inspect }) else return nil, bXML end else return nil, string.format("http query error -- %d -- %s -- %s", s, b, inspect(h, flattenInspect)) end end, headphonesConnected = function(self) local info, msg = self:devInfo() if info then return info["headphones-connected"]:upper() == "TRUE" else return nil, msg end end, powerIsOn = function(self) local info, msg = self:devInfo() if info then return info["power-mode"] == "PowerOn" else return nil, msg end end, isTV = function(self) return __devices[self[1]].isTV end, supportsFindRemote = function(self) return __devices[self[1]].supportsFindRemote end, supportsHeadphones = function(self) return __devices[self[1]].supportsHeadphones end, remoteButtons = function(self) local buttonArray = { "Home", "Rev", "Fwd", "Play", "Select", "Left", "Right", "Down", "Up", "Back", "InstantReplay", "Info", "Backspace", "Search", "Enter", "A", "B", } if self:supportsFindRemote() then table.insert(buttonArray, "FindRemote") end if self:isTV() then table.insert(buttonArray, "ChannelUp") table.insert(buttonArray, "ChannelDown") table.insert(buttonArray, "VolumeDown") table.insert(buttonArray, "VolumeMute") table.insert(buttonArray, "VolumeUp") table.insert(buttonArray, "InputTuner") table.insert(buttonArray, "InputHDMI1") table.insert(buttonArray, "InputHDMI2") table.insert(buttonArray, "InputHDMI3") table.insert(buttonArray, "InputHDMI4") table.insert(buttonArray, "InputAV1") -- ECP docs only mention "PowerOff", but a little googling found forum posts mentioning "PowerOn" -- and "Power", so, maybe new additions? At any rate, it works for the one TV I have sporadic access to table.insert(buttonArray, "PowerOff") table.insert(buttonArray, "PowerOn") table.insert(buttonArray, "Power") end if self:supportsHeadphones() then if not fnutils.contains(buttonArray, "VolumeDown") then table.insert(buttonArray, "VolumeDown") end if not fnutils.contains(buttonArray, "VolumeUp") then table.insert(buttonArray, "VolumeUp") end end return setmetatable(buttonArray, { __tostring = function(self) local results = "" for _,v in ipairs(buttonArray) do results = results .. v .. "\n" end return results end }) end, remote = function(self, button, state, skipCheck) local action = (type(state) == "nil" and "keypress") or (state and "keydown" or "keyup") button = tostring(button) local availableButtons = self:remoteButtons() if not skipCheck then button = button:upper() local idx = 0 for i,v in ipairs(availableButtons) do if v:upper() == button then idx = i break end end if idx > 0 then button = availableButtons[idx] else error("invalid button specified: " .. button .. " not recognized") end end http.asyncPost( "http://" .. self:host() .. ":" .. self:port() .. "/" .. action .. "/" .. tostring(button), "", {}, function(s, b, h) if s ~= 200 and s ~= 202 then -- 202 indicates it has been accepted but not processed yet -- skip it if it's volume related and the headphones aren't attached if not (button:match("^Volume") and not self:headphonesConnected()) then log.ef("remote button error: %d -- %s -- %s", s, b, inspect(h, flattenInspect)) end end end) return self end, type = function(self, what) if type(what) ~= "nil" then what = utf8.fixUTF8(tostring(what)) for c in what:gmatch(utf8.charpattern) do local literal = "" for _, v in ipairs({ string.byte(c, 1, #c) }) do literal = literal .. string.format("%%%02X", v) end self:remote("Lit_" .. literal, nil, true) end end return self end, availableApps = function(self, withImages) local results = {} local s, b, h = http.get(self:url("/query/apps"), {}) if s == 200 then for _, v in ipairs(xml.parseXML(b)("app")) do local id = v.id local thisApp = { v:value(), {} } for k, v2 in pairs(v) do thisApp[2][k] = v2 end if withImages then thisApp[2]["image"] = image.imageFromURL(self:url("/query/icon/") .. tostring(id)) end table.insert(results, thisApp) end table.sort(results, function(a, b) return a[1]:upper() < b[1]:upper() end) else log.ef("availableApps error: %d -- %s -- %s", s, b, inspect(h, flattenInspect)) end return setmetatable(results, { __tostring = function(self) local results = "" local col = 0 for _, v in ipairs(self) do col = math.max(col, #v[1]) end for _, v in ipairs(self) do results = results .. string.format("%-" .. tostring(col) .. "s (%s)\n", v[1], v[2].id) end return results end, }) end, deviceImage = function(self) local info, msg = self:devInfo(true) if info then -- build in a way that doesn't break if somethings missing local imgURL = info["device"] imgURL = imgURL and imgURL["iconList"] imgURL = imgURL and imgURL["icon"] imgURL = imgURL and imgURL["url"] if imgURL then return image.imageFromURL(self:url("/" .. imgURL)) else return nil, "no image url provided by device" end else return nil, msg end end, currentApp = function(self) local result local s, b, h = http.get(self:url("/query/active-app"), {}) if s == 200 then result = xml.parseXML(b)("app")[1]:value() else log.ef("currentApp error: %d -- %s -- %s", s, b, inspect(h, flattenInspect)) end return result end, currentAppID = function(self) local result local s, b, h = http.get(self:url("/query/active-app"), {}) if s == 200 then result = xml.parseXML(b)("app")[1].id else log.ef("currentApp error: %d -- %s -- %s", s, b, inspect(h, flattenInspect)) end return result end, currentAppIcon = function(self) local result local s, b, h = http.get(self:url("/query/active-app"), {}) if s == 200 then local id = xml.parseXML(b)("app")[1].id if id then result = image.imageFromURL(self:url("/query/icon/") .. id) end else log.ef("currentAppIcon error: %d -- %s -- %s", s, b, inspect(h, flattenInspect)) end return result end, launch = function(self, id, allowInstall) local apps = self:availableApps() local isLaunch = false id = tostring(id) for _,v in ipairs(apps) do if id == v[1] or id == v[2].id then id = v[2].id isLaunch = true break end end if isLaunch then http.asyncPost( "http://" .. self:host() .. ":" .. self:port() .. "/launch/" .. id, "", {}, function(s, b, h) if s ~= 200 and s ~= 202 then -- 202 indicates it has been accepted but not processed yet log.ef("launch error: %d -- %s -- %s", s, b, inspect(h, flattenInspect)) end end ) elseif allowInstall then http.asyncPost( "http://" .. self:host() .. ":" .. self:port() .. "/install/" .. id, "", {}, function(s, b, h) if s ~= 200 and s ~= 202 then -- 202 indicates it has been accepted but not processed yet log.ef("install error: %d -- %s -- %s", s, b, inspect(h, flattenInspect)) end end ) else log.wf("id %s not recognized for launch and allowInstall flag not set", id) end return self end, __name = USERDATA_TAG, __tostring = function(self) return USERDATA_TAG .. ": " .. self:sn() end, __eq = function(a, b) return a.__name == USERDATA_TAG and b.__name == USERDATA_TAG and a:sn() == b:sn() end, } deviceMetatable.__index = deviceMetatable -- Public interface ------------------------------------------------------ --- hs.roku.ssdpQueryTime --- Variable --- Specifies the number of seconds, default 5, the SSDP query for Roku devices on the local network remains active. Must be an integer > 0. --- --- This is the number of seconds the SSDP query will remain active when [hs.roku.startDiscovery](#startDiscovery) is invoked or when rediscovery occurs (see [hs.roku.rediscoveryInterval](#rediscoveryInterval)). --- --- Changing this variable will not trigger a rediscovery, but the new value will be used the next time rediscovery occurs. __internalVariables.ssdpQueryTime = 10 --- hs.roku.rediscoveryInterval --- Variable --- Specifies the number of seconds, default 3600 (1 hour), between automatic discovery checks to determine if new Roku devices have been added to the network or removed from it. Must be an integer > [hs.roku.ssdpQueryTime](#ssdpQueryTime). --- --- Automatic discovery checks are enabled when [hs.roku.startDiscovery](#startDiscovery) is invoked. Changing this value after `startDiscovery` has been invoked will cause an immediate discovery process and future discovery process will occur as specified by the new interval. __internalVariables.rediscoveryInterval = 3600 module.startDiscovery = function() if not __internals.rediscoveryCheck then local rediscoveryFunction rediscoveryFunction = function() if not __internals.ssdpDiscovery then __internals.seenDevices = {} __internals.ssdpDiscovery = socket.udp.server(1900, function(data, addr) local status, headerTxt = data:match("^(HTTP/[%d%.]+ 200 OK)[\r\n]+(.*)$") if status then local headers = {} for _,v in pairs(fnutils.split(headerTxt, "[\r\n]+")) do if v ~= "" then local key, value = v:match("^([^:]+): ?(.*)$") -- print("'" .. v .. "'", "'" .. tostring(key) .. "'", "'" .. tostring(value) .. "'") key = key:upper() -- spec says key should be case insensitive headers[key] = value end end if headers["USN"] and headers["USN"]:match("^uuid:roku:ecp:") then local serial = headers["USN"]:match("^uuid:roku:ecp:(.*)$") local host, port = headers["LOCATION"]:match("^http://([%d%.]+):(%d+)/$") -- if a udp response is queued but clearQueryTimer callback is queued first -- seenDevices may disappear... its ok to add the Device and skip seenDevices -- since it's for clearing out things we *no longer* see.. if __internals.seenDevices then table.insert(__internals.seenDevices, serial) end -- add device to discovered list local url = "http://" .. host .. ":" .. tostring(port) .. "/query/device-info" http.asyncGet(url, {}, function(s, b, h) local sn, msg = addDeviceHelper(host, port, s, b, h) if sn then __devices[sn].ssdpDiscovery = headers else log.ef(msg) end end) end end end):receive() __internals.ssdpDiscovery:send(ssdpQuery(), "239.255.255.250", 1900) -- multicast udp ssdp m-search __internals.clearQueryTimer = timer.doAfter(__internalVariables.ssdpQueryTime, function() if __internals.clearQueryTimer then __internals.clearQueryTimer:stop() __internals.clearQueryTimer = nil end if __internals.ssdpDiscovery then __internals.ssdpDiscovery:close() __internals.ssdpDiscovery = nil -- purge devices that have disappeared from the network if __internals.seenDevices then for k,v in pairs(__devices) do if not fnutils.contains(__internals.seenDevices, k) then v.alive = false -- rawset(__devices, k, nil) end end __internals.seenDevices = nil end end end) end -- probably overkill, but lets be explicit if __internals.rediscoveryCheck then __internals.rediscoveryCheck:stop() __internals.rediscoveryCheck = nil end __internals.rediscoveryCheck = timer.doAfter(__internalVariables.rediscoveryInterval, rediscoveryFunction) end rediscoveryFunction() end end module.triggerRediscovery = function() if __internals.rediscoveryCheck then __internals.rediscoveryCheck:fire() return true else return false end end module.stopDiscovery = function() if __internals.rediscoveryCheck then __internals.rediscoveryCheck:stop() __internals.rediscoveryCheck = nil end if __internals.clearQueryTimer then __internals.clearQueryTimer:stop() __internals.clearQueryTimer = nil end if __internals.ssdpDiscovery then __internals.ssdpDiscovery:close() __internals.ssdpDiscovery = nil __internals.seenDevices = nil end end module.discoveredDevices = function() local results = {} for k, v in pairs(__devices) do if v.alive then results[k] = module.device(k) end end return setmetatable(results, { __tostring = function(self) local items = {} for k,v in pairs(self) do local item = __devices[k] table.insert(items, { item.name, k, item.host .. ":" .. tostring(item.port) }) end table.sort(items, function(a, b) return a[1] < b[1] end) local col1, col2, col3 = 0, 0, 0 for _, v in ipairs(items) do col1 = math.max(col1, #v[1]) col2 = math.max(col2, #v[2]) col3 = math.max(col2, #v[3]) end local result = "" for _, v in ipairs(items) do result = result .. string.format("%-" .. tostring(col1) .. "s (%" ..tostring(col2) .. "s) @ %" .. tostring(col3) .. "s\n", v[1], v[2], v[3]) end return result end }) end module.device = function(id) local deviceSN, devObject for k, v in pairs(__devices) do if id == k or id == v.name or id == v.host or id == (v.host .. ":" .. tostring(v.port)) then deviceSN = k break end end if deviceSN then devObject = setmetatable({ deviceSN }, deviceMetatable) end return devObject end module.addDevice = function(host, port) port = tonumber(port) or 8060 local url = "http://" .. host .. ":" .. tostring(port) .. "/query/device-info" local s, b, h = http.get(url, {}) local sn, msg = addDeviceHelper(host, port, s, b, h) if sn then return module.device(sn) else return nil, msg end end -- Return Module Object -------------------------------------------------- return setmetatable(module, { __index = function(self, key) return __internalVariables[key] end, __newindex = function(self, key, value) local errMsg = nil if key == "ssdpQueryTime" then if type(value) == "number" and math.type(value) == "integer" and value > 0 then __internalVariables[key] = value else errMsg = USERDATA_TAG .. ".ssdpQueryTime must be an integer > 0" end elseif key == "rediscoveryInterval" then if type(value) == "number" and math.type(value) == "integer" and value > __internalVariables["ssdpQueryTime"] then __internalVariables[key] = value if __internals.rediscoveryCheck then __internals.rediscoveryCheck:fire() end else errMsg = USERDATA_TAG .. ".rediscoveryInterval must be an integer > " .. USERDATA_TAG .. ".ssdpQueryTime" end else errMsg = tostring(key) .. " is not a recognized paramter of " .. USERDATA_TAG end if errMsg then error(errMsg, 2) end end, __gc = module.stopDiscovery, -- for debugging purposes; users should never need to see these directly __internals = __internals, __internalVariables = __internalVariables, __devices = __devices, xml = xml, })
local Shape = Shape local M_PI = math.pi local sqrt = math.sqrt local s = DisplayShape.new(stage:getSize()) :setLineWidth(30.0) :setLineCap("butt") :moveTo(64.0, 50.0) :lineTo(64.0, 200.0) :stroke() :setLineCap("round") :moveTo(128.0, 50.0) :lineTo(128.0, 200.0) :stroke() :setLineCap("square") :moveTo(192.0, 50.0) :lineTo(192.0, 200.0) :stroke() :setSourceColor(1, 0.2, 0.2) :setLineWidth(2.56) :moveTo(64.0, 50.0) :lineTo(64.0, 200.0) :moveTo(128.0, 50.0) :lineTo(128.0, 200.0) :moveTo(192.0, 50.0) :lineTo(192.0, 200.0) :stroke() stage:addChild(s)
object_tangible_quest_quest_start_ep3_hunt_loot_greyclimber_eye = object_tangible_quest_quest_start_shared_ep3_hunt_loot_greyclimber_eye:new { } ObjectTemplates:addTemplate(object_tangible_quest_quest_start_ep3_hunt_loot_greyclimber_eye, "object/tangible/quest/quest_start/ep3_hunt_loot_greyclimber_eye.iff")
function AIZSurvivorsInit() if isModEnabled("Survivors") and RPresetSpawns ~= nil and blAIZSurivors then print("AIZEnhanced: Found Survivors Mod."); InitPresetSpawns(); --ensure this is called, if not already, (from Survivors Mod) else print("AIZEnhanced: Did Not Find Survivors Mod."); return; end PSID=0; PresetSpawns = {}; -- set ChanceToSpawn from 1 to 100, nil assumes 100 --AIZ Edited Spawns --WESTPOINT BEGIN PresetSpawns[getPSID()] = {ShowName = true, Name = "Prison Guard", X = 11899, Y = 6937, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "YOU WANT SOME?! I\'LL TAKE YOU ALL DOWN!",ShowName = true, Name = "Prison Guard", X = 11900, Y = 6937, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ChanceToSpawn=75, ShowName = true, Name = "Prison Guard", X = 11901, Y = 6937, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Gun Shop Owner", X = 12066, Y = 6759, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=0,PY=3}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Gun Shop Owner", X = 12067, Y = 6759, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=0,PY=3}; PresetSpawns[getPSID()] = {Greeting = "YOU BETTER GET OUTTA HERE!",ShowName = true, Name = "Gun Shop Owner", X = 12068, Y = 6759, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=0,PY=3}; PresetSpawns[getPSID()] = {Greeting = "Pastor Bob was right, all us sinners are having to pay!",ShowName = true, Name = "Giga Shop Owner", X = 12033, Y = 6849, Z = 1 , Weapon = "Base.Screwdriver",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Great to see a friendly face. Take what you need",ShowName = true, Name = "Giga Shop Owner", X = 12033, Y = 6850, Z = 1 , Weapon = "Base.Screwdriver",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Thought you were Bob. Hope he is ok. Anyways, make yourself at home and I\'ll pour you a stiff one. Ya probably need it",ShowName = true, Name = "Twiggys Shop Owner", X = 12063, Y = 6798, Z = 0 , Weapon = "Base.Hammer",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Its like the end of the world out there! That military blockade made matters worse, kept the infected in town. Bastards!",ShowName = true, Name = "Twiggys Shop Owner", X = 12062, Y = 6797, Z = 0 , Weapon = "Base.Hammer",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Bonjour! Rooms are now free. Do you have somewhere better to stay?",ShowName = true, Name = "Hotel Manager", X = 12009, Y = 6919, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Thug", X = 12310, Y = 6729, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=0,PY=-5}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Thug", X = 12313, Y = 6729, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=0,PY=-5}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Thug", X = 12316, Y = 6729, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=0,PY=-5}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Principal", X = 11327, Y = 6765, Z = 1 , Weapon = "Base.Plank",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=2,PY=0}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 12132, Y = 7085, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true, Patrolling=true, PX=10,PY=10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 12133, Y = 7084, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true, Patrolling=true, PX=20,PY=0}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 12130, Y = 7083, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true, Patrolling=true, PX=-3,PY=15}; PresetSpawns[getPSID()] = {Greeting = "Hi, I\'m Negan",PerkName = "Blunt",PerkLevel = 10,isFemale = false, ShowName = true, Name = "I\'m Negan", X = 12131, Y = 7084, Z = 1 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 12138, Y = 7098, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true, Patrolling=true, PX=10,PY=10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 12146, Y = 7098, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true, Patrolling=true, PX=20,PY=0}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 12134, Y = 7099, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true, Patrolling=true, PX=-3,PY=15}; PresetSpawns[getPSID()] = {PerkName = "Aiming",PerkLevel = 4,Greeting = "Hey Milton, fellow survivors are here! Perhaps they can save us from The Wolves!",isFemale = true, ShowName = true, Name = "Andrea ", X = 12064, Y = 6922, Z = 0 , Weapon = "Base.Shovel",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Okay Andrea. There\'s no such thing as a free lunch... but it might be our only option! LETS GET OUT OF HERE!",isFemale = false, ShowName = true, Name = "Milton", X = 12064, Y = 6924, Z = 0 , Weapon = "Base.Shovel",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = 'Kill them!',ShowName = true, Name = "Wolves Member", X = 12056, Y = 6931, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true, Patrolling=true, PX=10,PY=10}; PresetSpawns[getPSID()] = {Greeting = "You\'re going to die!",ShowName = true, Name = "Wolves Member", X = 12057, Y = 6936, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true, Patrolling=true, PX=20,PY=0}; PresetSpawns[getPSID()] = {Greeting = 'HAHAHAHAHAHAHA!',ShowName = true, Name = "Wolves Member", X = 12057, Y = 6941, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true, Patrolling=true, PX=-3,PY=15}; PresetSpawns[getPSID()] = {Greeting = 'No one leaves alive!',ShowName = true, Name = "Wolves Member", X = 12056, Y = 6946, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = 'Die!!',ShowName = true, Name = "Wolves Member", X = 12093, Y = 6934, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true, Patrolling=true, PX=-3,PY=15}; PresetSpawns[getPSID()] = {Greeting = 'You are all dead!',ShowName = true, Name = "Wolves Member", X = 12093, Y = 6938, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "I am going to have kill you. All of you. Including the children",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Owen, Wolves Leader", X = 12096, Y = 6939, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Rescue Party", NoParty = true, X = 12070, Y = 6939, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Rescue Party", NoParty = true, X = 12075, Y = 6939, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Rescue Party", NoParty = true, X = 12080, Y = 6939, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Rescue Party", NoParty = true, X = 12085, Y = 6939, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {PerkName = "Aiming",PerkLevel = 2, NoParty = true, ShowName = true, Name = "Survivor Camp Guard", X = 11708, Y = 7938, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {PerkName = "Aiming",PerkLevel = 2, NoParty = true, ShowName = true, Name = "Survivor Camp Guard", X = 11711, Y = 7941, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {PerkName = "Aiming",PerkLevel = 2, NoParty = true, ShowName = true, Name = "Survivor Camp Guard", X = 11711, Y = 7944, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {PerkName = "Aiming",PerkLevel = 2, NoParty = true, ShowName = true, Name = "Survivor Camp Guard", X = 11708, Y = 7946, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Survivor Camp Member", X = 11722, Y = 7924, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=13,PY=-28}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Survivor Camp Member", X = 11735, Y = 7922, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=-19,PY=34}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Survivor Camp Member", X = 11715, Y = 7931, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=-15,PY=23}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Survivor Camp Member", X = 11735, Y = 7952, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=-21,PY=-23}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Survivor Camp Member", X = 11730, Y = 7942, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Survivor Camp Member", X = 11726, Y = 7939, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Survivor Camp Member", X = 11737, Y = 7942, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Survivor Camp Member", X = 11741, Y = 7936, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=-13,PY=16}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Survivor Camp Guard", X = 11711, Y = 7943, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {NoParty = true, Greeting = "Welcome! We saw something like this coming a long time ago, and set up this here woodland stronghold",ShowName = true, Name = "Survivor Camp Leader", X = 11729, Y = 7935, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Gang Member", X = 11373, Y = 7034, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Gang Member", X = 11370, Y = 7036, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Gang Member", X = 11374, Y = 7027, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Gang Member", X = 11364, Y = 7024, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Gang Member", X = 11365, Y = 7032, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Look man, it\'s nothing personal!",ShowName = true, Name = "Gang Leader", X = 11367, Y = 7024, Z = 0 , Weapon = "Base.Sledgehammer",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "How did you get past the traps? You\'ll be sorry for trespassing around here!",PerkName = "Aiming",PerkLevel = 5,ShowName = true, Name = "Hunter", X = 11827, Y = 6574, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Loslokos Gang Member", X = 11660, Y = 7039, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Loslokos Gang Member", X = 11660, Y = 7041, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Loslokos Gang Member", X = 11660, Y = 7040, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Loslokos Gang Member", X = 11659, Y = 7039, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Loslokos Gang Member", X = 11659, Y = 7041, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Amigo. We will be taking all your stuff. Gracias",ShowName = true, Name = "Loslokos Gang Leader", X = 11659, Y = 7040, Z = 0 , Weapon = "Base.Sledgehammer",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "GET OUT OF HERE ASSHOLES!!",ShowName = true, Name = "Gas Station Owner", X = 12070, Y = 7140, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Shit, she is not anwering her phone...",PerkName = "Blunt",PerkLevel = 5,ShowName = true, Name = "Mechanic", X = 11894, Y = 6804, Z = 0 , Weapon = "Base.Screwdriver",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=10,PY=0}; PresetSpawns[getPSID()] = {Greeting = "Take what you need. Just dont kill me!",ShowName = true, Name = "Pharmacist", X = 11939, Y = 6798, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Explore", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'m okay. I\'m okay. I\'m in control. It\'s fine, it\'s okay. Maybe I could use a little help here",ShowName = true, Name = "Mayor", X = 11954, Y = 6879, Z = 1 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Man, I don\'t get paid nearly enough for this gig",PerkName = "Aiming",PerkLevel = 5, ShowName = true, Name = "Body Guard", X = 11955, Y = 6879, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "You can take what you want, but take me with you! Any place is safer than here",ShowName = true, Name = "Shop Owner", X = 11905, Y = 6852, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Praise God! Hallelujah!",isFemale = false, ShowName = true, Name = "Pastor Bob", X = 11973, Y = 6990, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Please help us!",ShowName = true, Name = "Teacher", X = 11306, Y = 6785, Z = 1 , Weapon = "Base.Plank",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=10,PY=0}; PresetSpawns[getPSID()] = {Greeting = "Are you friendly?",ShowName = true, Name = "Teacher", X = 11345, Y = 6785, Z = 1 , Weapon = "Base.Plank",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=2,PY=0}; PresetSpawns[getPSID()] = {Greeting = "He has sent me a miracle. Amen!",isFemale = false, ShowName = true, Name = "Pastor Aaron", X = 11096, Y = 6710, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "You\'re the one stealing my crops? I\'m sure it was no damn zombie. These city folk don\'t know how to fend for themselves. We can work together here",isFemale = false, ShowName = true, Name = "Farmer John", X = 11138, Y = 6858, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-4}; PresetSpawns[getPSID()] = {PerkName = "Aiming",PerkLevel = 5,Greeting = "Did you have to sneak up on me?",ShowName = true, Name = "Sam", X = 11991, Y = 6945, Z = 2 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "As you can tell, I\'m an axe man",PerkName = "Axe",PerkLevel = 5,ShowName = true, Name = "Lumberjack", X = 12064, Y = 7213, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Chop Wood", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Shoot, you scared me, thought you were one of those damn zombies",PerkName = "Axe",PerkLevel = 5,ShowName = true, Name = "Lumberjack", X = 12070, Y = 7213, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Chop Wood", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Could have been the Russians, aliens, some secret military experiments",PerkName = "PlantScavenging",PerkLevel = 5, ShowName = true, Name = "Survivalist", X = 12074, Y = 7306, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Forage", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I focused on being prepared. Crazy is building the ark after the flood has already come. Don\'t you agree?",PerkName = "PlantScavenging",PerkLevel = 5, ShowName = true, Name = "Survivalist", X = 12084, Y = 7306, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Explore", isHostile = false}; -- WESTPOINT END PlantScavenging -- MULDRAUGH BEGIN if(blAIZTWDPrisonSurivors) then --spawn all core TWD characters at TWD Prison rather than around the map PresetSpawns[getPSID()] = {Greeting = "All life is precious",PerkName = "Blunt",PerkLevel = 10, isFemale=false, NoParty = true, ShowName = true, Name = "Morgan", X = 9834, Y = 9515, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We get comfortable here, we let our guard down, this place is gonna make us weak",PerkName = "Aiming",PerkLevel = 10, isFemale=false, NoParty = true, ShowName = true, Name = "Carol", X = 9833, Y = 9517, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=-15,PY=0}; PresetSpawns[getPSID()] = {Greeting = "Have you ever had to kill people because they had already killed your friends and were coming for you next? Have you ever done things that made you feel afraid of yourself afterward? Have you ever been covered in so much blood that you didn\'t know if it was yours or walkers\' or your friends\'? Huh? Then you don\'t know",PerkName = "Blunt",PerkLevel = 10, isFemale=true, NoParty = true, ShowName = true, Name = "Michonne", X = 9809, Y = 9501, Z = 0 , Weapon = "Base.Poolcue",hasOrder = true, Orders = "Guard", isHostile = false}; --ALT QUOTE: Don\'t you want one more day with a chance? PresetSpawns[getPSID()] = {Greeting = "Why are we running? What are we doing?",PerkName = "Aiming",PerkLevel = 10, isFemale=false, ShowName = true, Name = "Carl", X = 9833, Y = 9519, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'ve already lost three of the people that I care about most in this world",PerkName = "Aiming",PerkLevel = 10, isFemale=true, NoParty = true, ShowName = true, Name = "Maggie", X = 9803, Y = 9507, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Nice moves there, Clint Eastwood. You\'re the new sheriff come riding in to clean up the town?",PerkName = "Blunt",PerkLevel = 10, isFemale=false, NoParty = true, ShowName = true, Name = "Glenn", X = 9806, Y = 9506, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "You want to know what I was before all this? I was nobody. Nothing",PerkName = "Aiming",PerkLevel = 10, isFemale=false, NoParty = true, ShowName = true, Name = "Daryl", X = 9799, Y = 9503, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=10}; PresetSpawns[getPSID()] = {Greeting = "Everyone who made it this far, we\'ve all done worse kinds of things, just to stay alive.. But we can still come back. We\'re not too far gone",PerkName = "Axe",PerkLevel = 10,isFemale=false, ShowName = true, Name = "Rick", X = 9800, Y =9488, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Guard", isHostile = false}; else PresetSpawns[getPSID()] = {Greeting = "All life is precious. I\'m looking for Rick",PerkName = "Blunt",PerkLevel = 10, isFemale=false, ShowName = true, Name = "Morgan", X = 11741, Y = 8868, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We get comfortable here, we let our guard down, this place is gonna make us weak",PerkName = "Aiming",PerkLevel = 10, isFemale=true, ShowName = true, Name = "Carol", X = 13662, Y = 5052, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=-15,PY=0}; PresetSpawns[getPSID()] = {Greeting = "Have you ever had to kill people because they had already killed your friends and were coming for you next? Have you ever done things that made you feel afraid of yourself afterward? Have you ever been covered in so much blood that you didn\'t know if it was yours or walkers\' or your friends\'? Huh? Then you don\'t know",PerkName = "Blunt",PerkLevel = 10, isFemale=true, ShowName = true, Name = "Michonne", X = 10765, Y = 10553, Z = 0 , Weapon = "Base.Poolcue",hasOrder = true, Orders = "Guard", isHostile = false}; --ALT QUOTE: Don\'t you want one more day with a chance? PresetSpawns[getPSID()] = {Greeting = "Why are we running? What are we doing? I\'m looking for my father Rick",PerkName = "Aiming",PerkLevel = 10, isFemale=false, ShowName = true, Name = "Carl", X = 8606, Y = 8880, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'ve already lost three of the people that I care about most in this world",PerkName = "Aiming",PerkLevel = 10, isFemale=true, ShowName = true, Name = "Maggie", X = 11345, Y = 12165, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Nice moves there, Clint Eastwood. You\'re the new sheriff come riding in to clean up the town?",PerkName = "Blunt",PerkLevel = 10, isFemale=false, ShowName = true, Name = "Glenn", X = 11950, Y = 6886, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "You want to know what I was before all this? I was nobody. Nothing",PerkName = "Aiming",PerkLevel = 10, isFemale=false, ShowName = true, Name = "Daryl", X = 10942, Y = 6771, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=10}; PresetSpawns[getPSID()] = {Greeting = "Everyone who made it this far, we\'ve all done worse kinds of things, just to stay alive.. But we can still come back. We\'re not too far gone",PerkName = "Axe",PerkLevel = 10,isFemale=false, ShowName = true, Name = "Rick", X = 11087, Y =9235, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Guard", isHostile = false}; end PresetSpawns[getPSID()] = {Greeting = "It\'s so good to see friendly faces",PerkName = "Axe",PerkLevel = 5, ShowName = true, Name = "Lumberjack", X = 10470, Y = 9277, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Chop Wood", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We came back to McCoy\'s looking for supplies. Muldraugh is a god awful mess",PerkName = "Axe",PerkLevel = 5, ShowName = true, Name = "Lumberjack", X = 10472, Y = 9279, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Chop Wood", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Doctor Kildare? Oh.. how did you get up here? The doors should have been locked. Are you bitten?",PerkName = "Blade",PerkLevel = 3,isFemale=true,ShowName = true, Name = "Nurse", X = 10880, Y = 10029, Z = 1 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "They should be terrified. The world\'s ending. Otherwise, who gives a shit. With God, it\'s never too late to make things right",PerkName = "Aiming",PerkLevel = 10,isFemale=false,ShowName = true, Name = "Preacher", X = 10787, Y = 10172, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "HELP! HELP! They are trying to eat me!",ShowName = true, Name = "Food Inspector", X = 10621, Y = 9829, Z = 1 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Stay...STAY AWAY FROM ME! ARRRRGGH!!!",PerkName = "Aiming",PerkLevel = 1,isFemale=false,ShowName = true, Name = "Security Guard", X = 10627, Y = 9410, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Ya know wut? This is the most exciting goddamn thing that\'s ever happened in this town",PerkName = "Blade",PerkLevel = 5,isFemale=false,ShowName = true, Name = "Mad Man", X = 10686, Y = 10328, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; --MULDRAUGH END --WAREHOUSES OUTSIDE OF MULDRAUGH --Barney Calhoun ;-) PresetSpawns[getPSID()] = {Greeting = "Hey Gordon, is that you? What the bejesus?! Put your weapons away or I\'ll shoot!",isFemale=false,ShowName = true, Name = "Security Guard", X = 9987, Y = 10962, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; --WAREHOUSES END --MARCH RIDGE PresetSpawns[getPSID()] = {Greeting = "To hell with circumstances; I create opportunities. Knowing is not enough, we must apply. Willing is not enough, we must do",PerkName = "Blunt",PerkLevel = 10,isFemale=false,ShowName = true, Name = "Martial Arts Instructor", X = 10010, Y = 12735, Z = 1 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We\'ve got to get out of here! Its not safe. There is a gang of lunatics coming back here for me and the supplies. They want a doctor",isFemale=true,ShowName = true, Name = "Doctor", X = 10167, Y = 12754, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; --MARCH RIDGE END --ROSEWOOD PresetSpawns[getPSID()] = {Greeting = "Howdy. You can call me Tex. Been waiting for the military or some such, but you\'ll do my friend. Welcome!",PerkName = "Axe",PerkLevel = 5,isFemale=false,ShowName = true, Name = "Fire Fighter", X = 8143, Y = 11736, Z = 1 , Weapon = "Base.Axe",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "ARRRRGGH!!!! Got you! Don\'t even think about escaping!",ShowName = true, Name = "Attorney", X = 7991, Y = 11449, Z = 0 , Weapon = "Base.Golfclub",hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Thank God! Please help me!",ShowName = true, Name = "Librarian", X = 8335, Y = 11615, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'ve been to eight county fairs and a goat rodeo, but I\'ve never seen anything like that. Thanks for the rescue. Now I gotta find Rick",PerkName = "Aiming",PerkLevel = 10, isFemale=false, ShowName = true, Name = "Abraham", X = 8211, Y = 11805, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Thank you for saving me. So you\'re aware, I\'m on record as stating that I\'m not combat ready or even for that matter combat inclined",PerkName = "Blunt",PerkLevel = 3, isFemale=false, ShowName = true, Name = "Eugene", X = 8231, Y = 11816, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Guard", isHostile = false}; --ROSEWOOD END --RAILYARD SOUTH OF MULD PresetSpawns[getPSID()] = {Greeting = "Hey! Who goes there?! Better watch yer self pally!",PerkName = "Blunt",PerkLevel = 5,isFemale=false,ShowName = true, Name = "Hobo", X = 11629, Y = 9852, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Patrol", isHostile = false,Patrolling=true, PX=0,PY=-15}; ---RAILYARD END --cabins far east of muldraugh PresetSpawns[getPSID()] = {Greeting = "I\'ve have been watching you, but you seem friendly. How did you make it out alive?",PerkName = "Aiming",PerkLevel = 7,isFemale=false,ShowName = true, Name = "Hunter", X = 12475, Y = 8969, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Patrol", isHostile = false,Patrolling=true, PX=10,PY=0}; --end cabins --DIXIE PresetSpawns[getPSID()] = {Greeting = "I\'ve had my gun sight on you for the last 5 minutes, but you seem friendly. How did you make it out alive?",PerkName = "Aiming",PerkLevel = 7,isFemale=false,ShowName = true, Name = "Hunter", X = 11608, Y = 9303, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Patrol", isHostile = false,Patrolling=true, PX=10,PY=0}; ---END DIXIE --VALLEY & MALL AREA PresetSpawns[getPSID()] = {Greeting = "Oh my God! Normal people for a change! This is my BOOMSTICK! Groovy. Found it off a dead dude. Luckily they sell ammo at S-MART",PerkName = "Aiming",PerkLevel = 3,isFemale=false,ShowName = true, Name = "B-Movie Actor", X = 13643, Y = 5868, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false,Patrolling=true, PX=0,PY=15}; PresetSpawns[getPSID()] = {Greeting = "Honey, we\'ve got some visitors. Stop looking for where you left the champagne and get over here!",isFemale=true,ShowName = true, Name = "Shopper Kim", X = 13923, Y = 5829, Z = 2 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Patrol", isHostile = true,Patrolling=true, PX=0,PY=15}; PresetSpawns[getPSID()] = {Greeting = "What'\s up Goldigger?...Nothing in life is promised except.... death!",isFemale=false,ShowName = true, Name = "Shopper Kanye", X = 13923, Y = 5824, Z = 2 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = true,Patrolling=true, PX=-15,PY=0}; PresetSpawns[getPSID()] = {Greeting = "Ya better be real cool buddy, or I\'ll shovel your sorry ass outta here.",PerkName = "Blunt",PerkLevel = 3,isFemale=false,ShowName = true, Name = "Construction Worker", X = 14087, Y = 5453, Z = 0 , Weapon = "Base.Shovel",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Finally! Help has arrived! I..I...came to the Academy during the curfew to grab some books before we tried to escape by foot around the military blockade",isFemale=true,ShowName = true, Name = "Professor", X = 12869, Y = 4848, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; --END VALLEY & MALL AREA -- NORTH EAST BLOCKADE PresetSpawns[getPSID()] = {Greeting = "This is the North East Blockade. No one is aloud past the rear Blockade. Lethal force will be used if necessary", PerkName = "Aiming",PerkLevel = 10, NoParty = true, isFemale=false, ShowName = true, Name = "Captain B.J. Blazkowicz", X = 12508, Y = (-2*300) + 4487, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Move along now", PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12512, Y = (-2*300) + 4487, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12517, Y = (-2*300) +4487, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "You\'re not supposed to be up here, Move along!", PerkName = "Aiming", PerkLevel = 10, NoParty = true, isFemale=false, ShowName = true, Name = "Sniper", X = 12499, Y = (-2*300) + 4497, Z = 3 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "What are you doing up here? Move along!", PerkName = "Aiming", PerkLevel = 10, NoParty = true, isFemale=false, ShowName = true, Name = "Sniper", X = 12527, Y = (-2*300) + 4497, Z = 3 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'m busy", PerkName = "Aiming", PerkLevel = 2, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12527, Y = (-2*300) + 4485, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=-35,PY=-13}; PresetSpawns[getPSID()] = {Greeting = "I\'m busy", NoParty = true, isFemale=false, ShowName = true, Name = "Cook", X = 12481, Y = (-2*300) + 4446, Z = 0 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=-4,PY=-8}; PresetSpawns[getPSID()] = {Greeting = "I\'m scared", NoParty = true, ShowName = true, Name = "Refugee", X = 12490, Y = (-2*300) + 4443, Z = 0 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=-10,PY=12}; PresetSpawns[getPSID()] = {Greeting = "I can\'t get a good signal", NoParty = true, isFemale=false, ShowName = true, Name = "Refugee Bob", X = 12485, Y = (-2*300) + 4463, Z = 0 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {NoParty = true, ShowName = true, Name = "Refugee", X = 12485, Y = (-2*300) + 4463, Z = 0 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Explore", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'m busy", PerkName = "Aiming", PerkLevel = 2, NoParty = true, ShowName = true, Name = "Soldier", X = 12541, Y = (-2*300) + 4456, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=0,PZ=1}; PresetSpawns[getPSID()] = {Greeting = "We cannot wait any longer! We must proceed with operation Bluejay NOW!", PerkName = "Aiming", isFemale=false, PerkLevel = 2, NoParty = true, ShowName = true, Name = "Captian", X = 12540, Y = (-2*300) + 4402, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Communication has been down for far too long. We must assume the worst.", PerkName = "Aiming", isFemale=false, PerkLevel = 2, NoParty = true, ShowName = true, Name = "Major Mike", X = 12533, Y = (-2*300) + 4405, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We can\'t hold off here without backup for much longer. We need to do something!", PerkName = "Aiming", isFemale=false, PerkLevel = 2, NoParty = true, ShowName = true, Name = "Lt. Dan", X = 12533, Y = (-2*300) + 4407, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting="Halt!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12512, Y = (-2*300) + 4400, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Stop!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12515, Y = (-2*300) + 4400, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Go No Futher!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12519, Y = (-2*300) + 4397, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Halt!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12508, Y = (-2*300) + 4397, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "No one may pass the Blockade. NO exceptions!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12505, Y = (-2*300) + 4417, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=15,PY=0}; PresetSpawns[getPSID()] = {Greeting = "No one may pass the Blockade. NO exceptions!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12470, Y = (-2*300) + 4425, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=15,PY=17}; PresetSpawns[getPSID()] = {Greeting="Halt!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12552, Y = (-2*300) + 4397, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Go No Further!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12556, Y = (-2*300) + 4397, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Talk to the Captain up by the North West Entrance", PerkName = "Aiming", isFemale=false, PerkLevel = 2, NoParty = true, ShowName = true, Name = "Srgt. Sam", X = 12552, Y = (-2*300) + 4498, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Move along now", PerkName = "Aiming", isFemale=false, PerkLevel = 2, NoParty = true, ShowName = true, Name = "Soldier", X = 12555, Y = (-2*300) + 4498, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = false}; PresetSpawns[getPSID()] = {NoParty=true,Greeting = "I\'m supposed to take down all these trees.",PerkName = "Axe",PerkLevel = 5,ShowName = true, Name = "Worker", X = 12555, Y = (-2*300) + 4478, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Explore", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I tried to warn everyone, no one would listen.",PerkName = "Aiming",PerkLevel = 6,ShowName = true, Name = "Private Manning", X = 12467, Y = (-2*300) + 4409, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", Patrolling=true, PX=0,PY=9, isHostile = false}; PresetSpawns[getPSID()] = {Greeting="Hey! Your not allowed in here!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12497, Y = (-2*300) + 4366, Z = 3 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=-4,PY=-7}; PresetSpawns[getPSID()] = {Greeting="Hey! Your not allowed in here!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12537, Y = (-2*300) + 4368, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=-25,PY=1}; if isModEnabled("SurvivorQuests") then PresetSpawns[getPSID()] = {Greeting="Hey! You're not allowed up here!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12505, Y = 3742, Z = 0 , Weapon = "Base.Pistol",hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=0,PY=-7}; PresetSpawns[getPSID()] = {Greeting="Hey! You're not allowed over here!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12506, Y =3752, Z = 0 , Weapon = "Base.Pistol",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Hey! You're not allowed in here!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12499, Y = 3764, Z = 0 , Weapon = "Base.Pistol",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Hey! You're not allowed over here!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12459, Y = 3759, Z = 0 , Weapon = "Base.Pistol",hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Hey! You're not alloweed over here!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 12459, Y = 3778, Z = 0 , Weapon = "Base.Pistol",hasOrder = true, Orders = "Guard", isHostile = true}; end -- NORTH EAST BLOCKADE END -- OTHER START PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8217, Y = 11810, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=10,PY=0}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8256, Y = 11845, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8255, Y = 11850, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8248, Y = 11859, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8235, Y = 11837, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Hi, I\'m Negan",isFemale=false, ShowName = true, Name = "I\'m Negan", X = 8226, Y = 11869, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = true, Patrolling=true, PX=10,PY=-10}; -- OTHER END -- prison PresetSpawns[getPSID()] = {Greeting="Halt!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7753, Y = 11884, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Stop!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7753, Y = 11889, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Halt!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7743, Y = 11905, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Stop!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7709, Y = 11878, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Halt!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7680, Y = 11878, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Stop!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7680, Y = 11878, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Halt!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7651, Y = 11855, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Stop!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7651, Y = 11855, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Halt!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7729, Y = 11913, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting="Stop!",PerkName = "Aiming", PerkLevel = 5, NoParty = true, isFemale=false, ShowName = true, Name = "Soldier", X = 7729, Y = 11913, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; --AIZ Extra Spawns PresetSpawns[getPSID()] = {Greeting = "You protect and serve. You patrol, walk the wall, watch out for the kids. If there\'s a conflict, you solve it. And people will listen to you",PerkName = "Aiming",PerkLevel = 3,isFemale = true, ShowName = true, Name = "Deanna", X = 13305, Y = 5848, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "There\'s going to be a lot to remember. This is the beginning of this place. You should record all that. Along with everything I\'m gonna teach you about building things",PerkName = "Aiming",PerkLevel = 1,isFemale = false, ShowName = true, Name = "Reg", X = 13290, Y = 5856, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We were never safe here. But we didn\'t want to see that. We just wanted to dream. What happened to Aiden, that\'s all us!",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Spencer", X = 13290, Y = 5832, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Welcome to Alexandria! We need help!",PerkName = "Aiming",PerkLevel = 2,isFemale = false, ShowName = true, Name = "Alexandria Guard", X = 13371, Y = 5846, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "It\'s not a camp. It\'s a community. I think you all would make valuable additions. But it\'s not my call",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Aaron", X = 13370, Y = 5850, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Welcome to Alexandria! We need help!",PerkName = "Aiming",PerkLevel = 2,isFemale = false, ShowName = true, Name = "Alexandria Guard", X = 13266, Y = 5845, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Welcome to Alexandria! We need help!",PerkName = "Aiming",PerkLevel = 2,isFemale = false, ShowName = true, Name = "Alexandria Guard", X = 13327, Y = 5903, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Help us please!", ShowName = true, Name = "Alexandria Citizen", X = 13291, Y = 5810, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Help us please!", ShowName = true, Name = "Alexandria Citizen", X = 13293, Y = 5878, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Help us please!", ShowName = true, Name = "Alexandria Citizen", X = 13365, Y = 5812, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Help us please!", ShowName = true, Name = "Alexandria Citizen", X = 13339, Y = 5805, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Help us please!", ShowName = true, Name = "Alexandria Citizen", X = 13268, Y = 5773, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Welcome to Hilltop! We need help!",PerkName = "Blunt",PerkLevel = 2,isFemale = false, ShowName = true, Name = "Hilltop Guard", X = 13290, Y = 6677, Z = 0 , Weapon = getWeapon("Base.BaseballBat"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "You see what I have here? You see what I\'ve built? You don\'t have shit. Now, I\'m happy to help, I\'m a nice guy. But we can\'t just give things away for free", ShowName = true, Name = "Gregory", X = 13250, Y = 6642, Z = 1 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isFemale = false, isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We\'re on the same side - The living side. You\'re good people. And this is a good place", ShowName = true, Name = "Jesus", X = 13266, Y = 6654, Z = 0 , PerkName = "Blade",PerkLevel = 10, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isFemale = false,isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Welcome to Hilltop! We need help!",PerkName = "Blunt",PerkLevel = 2,isFemale = true, ShowName = true, Name = "Hilltop Guard", X = 13254, Y = 6640, Z = 0 , Weapon = getWeapon("Base.BaseballBat"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Welcome to Hilltop! We need help!",PerkName = "Blunt",PerkLevel = 2,isFemale = false, ShowName = true, Name = "Hilltop Guard", X = 13253, Y = 6647, Z = 0 , Weapon = getWeapon("Base.BaseballBat"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Please help us!", ShowName = true, Name = "Hilltop Citizen", X = 13261, Y = 6673, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Please help us!", ShowName = true, Name = "Hilltop Citizen", X = 13252, Y = 6682, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Please help us!", ShowName = true, Name = "Hilltop Citizen", X = 13276, Y = 6637, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Please help us!", ShowName = true, Name = "Hilltop Citizen", X = 13243, Y = 6631, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Kill the intruders!",PerkName = "Aiming",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Natania", X = 13436, Y = 6817, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Nobody\'s evil. They just decide to forget who they are",PerkName = "Aiming",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Cyndie", X = 13429, Y = 6817, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Intruders!",PerkName = "Aiming",PerkLevel = 2,isFemale = true, ShowName = true, Name = "Oceanside Guard", X = 13474, Y = 6797, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Intruders!",isFemale = true, ShowName = true, Name = "Oceanside Citizen", X = 13424, Y = 6794, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Intruders!",isFemale = true, ShowName = true, Name = "Oceanside Citizen", X = 13408, Y = 6816, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Intruders!",isFemale = true, ShowName = true, Name = "Oceanside Citizen", X = 13457, Y = 6807, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Intruders!",isFemale = true, ShowName = true, Name = "Oceanside Citizen", X = 13429, Y = 6837, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Intruders!",isFemale = true, ShowName = true, Name = "Oceanside Citizen", X = 13445, Y = 6837, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Welcome to Terminus. I\'m Gareth. A man\'s gotta eat",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Gareth", X = 11753, Y = 9368, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "They look delicious!",isFemale = true, ShowName = true, Name = "Terminus Citizen", X = 11756, Y = 9367, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "They look delicious!",isFemale = false, ShowName = true, Name = "Terminus Citizen", X = 11763, Y = 9368, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "The signs... they were real. It was a sanctuary. People came and took this place. But we got out and we fought it and we got it back. And we heard the message. \'You\'re the butcher... or you\'re the cattle\'",PerkName = "Blade",PerkLevel = 2,isFemale = true, ShowName = true, Name = "Mary", X = 11750, Y = 9370, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "They look delicious!",isFemale = true, ShowName = true, Name = "Terminus Citizen", X = 11749, Y = 9346, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "They look delicious!",isFemale = false, ShowName = true, Name = "Terminus Citizen", X = 11789, Y = 9366, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Since almost the start. When all the camps got overrun, people started finding this place. I think it was instinct, you know?",PerkName = "Aiming",PerkLevel = 3,isFemale = false, ShowName = true, Name = "Alex", X = 11749, Y = 9327, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "They look delicious!",isFemale = false, ShowName = true, Name = "Terminus Citizen", X = 11777, Y = 9313, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "You walk outside, you risk your life. You take a drink of water, you risk your life. Nowadays you breath and you risk your life. You don\'t have a choice. The only thing you can choose is what you\'re risking it for",PerkName = "Aiming",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Hershel", X = 11350, Y = 12160, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I know you look at me and you just see another dead girl. I\'m not Michonne. I\'m not Carol. I\'m not Maggie. I\'ve survived and you don\'t get it",PerkName = "Blade",PerkLevel = 10,isFemale = true, ShowName = true, Name = "Beth", X = 11346, Y = 12160, Z = 1 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; --for maggie, see further up PresetSpawns[getPSID()] = {Greeting = 'So now I\'m going to beat the HOLY FUCK FUCKING FUCKEDY FUCK out of you with my bat. Who I call \"Lucille\"',PerkName = "Blunt",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Negan", X = 8818, Y = 12720, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8821, Y = 12717, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8811, Y = 12719, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8816, Y = 12721, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8814, Y = 12716, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8816, Y = 12701, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8800, Y = 12700, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8820, Y = 12702, Z = 2 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8811, Y = 12700, Z = 3 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8817, Y = 12698, Z = 4 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8814, Y = 12692, Z = 3 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8811, Y = 12692, Z = 2 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8816, Y = 12707, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8814, Y = 12712, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "A Savior", X = 8833, Y = 12706, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Please help me get out of here!", ShowName = true, Name = "Concubine", X = 8810, Y = 12694, Z = 4 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false, isFemale=true}; PresetSpawns[getPSID()] = {Greeting = "Help me get out of here!", ShowName = true, Name = "Concubine", X = 8805, Y = 12703, Z = 4 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false, isFemale=true}; PresetSpawns[getPSID()] = {Greeting = "Help me please!", ShowName = true, Name = "Concubine", X = 8806, Y = 12707, Z = 4 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false, isFemale=true}; PresetSpawns[getPSID()] = {Greeting = 'No one can leave!',ShowName = true, Name = "Woodbury Guard", X = 8800, Y = 7976, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = 'No one can leave!',ShowName = true, Name = "Woodbury Guard", X = 8787, Y = 7976, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = 'No one can leave!',ShowName = true, Name = "Woodbury Guard", X = 8800, Y = 8067, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = 'Get Back!',ShowName = true, Name = "Woodbury Guard", X = 8793, Y = 7976, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = 'Stop right there!',ShowName = true, Name = "Woodbury Guard", X = 8805, Y = 7976, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "In this life now you kill or you die. Or you die and you kill",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "The Governor", X = 8797, Y = 7975, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Woodbury Citizen", X = 8791, Y = 8037, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Woodbury Citizen", X = 8806, Y = 8031, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Woodbury Citizen", X = 8824, Y = 8048, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Woodbury Citizen", X = 8793, Y = 7996, Z = 0 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Woodbury Citizen", X = 8772, Y = 7975, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {ShowName = true, Name = "Woodbury Citizen", X = 8829, Y = 7975, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = 'Welcome to the Kingdom! We need help!',ShowName = true, Name = "Kingdom Guard", X = 9742, Y = 10304, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = "We have got to strike now...or we will all be dead!",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Richard", X = 9740, Y = 10306, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = 'Welcome to the Kingdom! We need help!',ShowName = true, Name = "Kingdom Guard", X = 9739, Y = 10305, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10} PresetSpawns[getPSID()] = {Greeting = 'Welcome to the Kingdom! We need help!',ShowName = true, Name = "Kingdom Guard", X = 9700, Y = 10240, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10} PresetSpawns[getPSID()] = {Greeting = "Help us!",ShowName = true, Name = "Kingdom Citizen", X = 9667, Y = 10434, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = "Help us!",ShowName = true, Name = "Kingdom Citizen", X = 9656, Y = 10346, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = "Help us!",ShowName = true, Name = "Kingdom Citizen", X = 9562, Y = 10296, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = "Help us!",ShowName = true, Name = "Kingdom Citizen", X = 9669, Y = 10267, Z = 0 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = "Help us!",ShowName = true, Name = "Kingdom Citizen", X = 9689, Y = 10317, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = "Help us!",ShowName = true, Name = "Kingdom Citizen", X = 9737, Y = 10307, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = "Help us!",ShowName = true, Name = "Kingdom Citizen", X = 9712, Y = 10343, Z = 0 , Weapon = "Base.Plank",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = "Help us!", ShowName = true, Name = "Kingdom Citizen", X = 9659, Y = 10393, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Patrol", isHostile = false, Patrolling=true, PX=0,PY=-10}; PresetSpawns[getPSID()] = {Greeting = "There\'s a saying - the pessimist looks down and hits his head. The optimist looks up and loses his footing. The realist looks forward and adjusts his path accordingly. Welcome to the Kingdom!",PerkName = "Blunt",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Ezekiel", X = 9672, Y = 10329, Z = 1 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Huh Huh Nice. The bananas look a\'peelin",PerkName = "Axe",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Jerry", X = 9669, Y = 10328, Z = 1 , Weapon = "Base.Axe",hasOrder = true, Orders = "Standing Ground", isHostile = false}; --other PresetSpawns[getPSID()] = {Greeting = "The Lord sent you here to finally punish me. I\'m damned. I was damned before. I always lock the doors. I always lock the doors",PerkName = "Blade",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Father Gabriel", X = 10323, Y = 12787, Z = 0, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = " Nobody\'s got to die today",PerkName = "Axe",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Tyreese", X = 9206, Y = 12139, Z = 0 , Weapon = "Base.Axe",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I move through town... I\'m quiet... like a fire",PerkName = "Aiming",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Sasha", X = 9207, Y = 12143, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "The people around you dying...that\'s the hard part",PerkName = "Aiming",PerkLevel = 10,isFemale = true, ShowName = true, Name = "Rosita", X = 14421, Y = 4628, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "When you\'ve just emptied two barrels of a shotgun into the head of your favorite bartender, it\'s a pretty good bet that happy hour\'s over",PerkName = "Aiming",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Ash", X = 11153, Y = 13053, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "As Mr. Sloan always says, there is no \'I\' in team, but there is an \'I\' in pie. And there\'s an \'I\' in meat pie. Anagram of meat is team... I don\'t know what he\'s talking about.",PerkName = "Blunt",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Shaun", X = 14777, Y = 6811, Z = 0, Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Have a beer! It might be a bit warm, the cooler\'s off",PerkName = "Blunt",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Ed", X = 14776, Y = 6813, Z = 0, Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "In a world where the dead are returning to life, the word \'trouble\' loses much of its meaning. Welcome to what\'s left of Fiddler\'s Green",PerkName = "Blade",PerkLevel = 3,isFemale = false, ShowName = true, Name = "Kaufman", X = 14901, Y = 5628, Z = 1, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Isn\'t that what we\'re doing? Pretending to be alive? Put that thing away and put on your best Sunday smile. Just, just try to be friendly",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Riley", X = 14897, Y = 5627, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "There are three things a man must do alone - be born, die and, well, we all know the other one",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Cholo", X = 14908, Y = 5627, Z = 1 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Twenty years as a lifeguard teaches you to recognize people in trouble. I knew the second I saw this shitstorm, that I was in trouble and needed to save myself",PerkName = "Blade",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Mitch the Lifeguard", X = 14912, Y = 4676, Z = 1, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Hey. Let me tell you something. You, uh, you have my permission. I ever turn into one of those things? Do me a favor, blow my fucking head off",PerkName = "Blunt",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Steve the Yuppie", X = 12638, Y = 7912, Z = 0, Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We\'ve got... we have to wait for Johnny. We better go out and get him. We have to go out and get Johnny. He\'s out there. Please, don\'t you hear me?",PerkName = "Blade",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Barbara", X = 10595, Y = 7811, Z = 0, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "That girl was screaming. Surely you know what a girl screaming sounds like? Those things don\'t make any noise. Anybody would know somebody needed help!",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Ben", X = 10598, Y = 7807, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "They have overrun us, you know? We\'re in the minority now. Something like four hundred thousand to one, by my calculations. I haven\'t eaten. Is there food?",PerkName = "Blade",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Dr. Logan", X = (-9*300) + 7807, Y = 8589, Z = 3, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'ll kill each and every one of you to stay alive! You hear me? The plan is you drink a nice tall glass of shut the fuck up!",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "CJ the Security Guard", X = 7695, Y = 5775, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "My granddad was a priest in Trinidad. He used to tell us, \'When there\'s no more room in hell, the dead will walk the Earth\'",PerkName = "Blade",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Peter", X = 8571, Y = 10342, Z = 2, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'m afraid. You\'re hypnotized by this place. All of you! You don\'t see that it\'s not a sanctuary, it\'s a prison! Let\'s just take what we need and get out of here!",PerkName = "Blade",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Francine", X = 8578, Y = 10342, Z = 2, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'m sure you didn\'t just tag along so we could sing Kumbiya together at some boyscout bonfire, then again, maybe you did",PerkName = "Aiming",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Agent Leon", X = 10978, Y = 14185, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "In a survival situation, you must exist in a constant state of hope if you are to make it out alive. There\'s no room for bravado when you\'re alone in the bush",PerkName = "Blade",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Les", X = 13526, Y = 10716, Z = 2, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'m going to let you in on a little secret: every day, once a day, give yourself a present. Don\'t plan it; don\'t wait for it; just let it happen. It could be a new shirt in a men\'s store, a catnap in your office chair, or two cups of good, hot, black, coffee",PerkName = "Aiming",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Agent Cooper", X = 2520, Y = 13260, Z = 1 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "It\'s time to evolve. That\'s why we\'re troubled. You know why our institutions have failed us, the church, the state, everything\'s failing? It\'s because, um – they\'re no longer relevant. We\'re supposed to keep evolving. Evolution did not end with us growing opposable thumbs. You do know that, right?",PerkName = "Blade",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Bill", X = 11754, Y = 11422, Z = 3, Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "You\'ll have some tea... are you sure you don\'t want any? Aw go on, you\'ll have some. Go on go on go on go on go on go on go on go on GO ON!",PerkName = "Blade",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Mrs Doyle the Church Lady", X = 12402, Y = 9379, Z = 1, Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "For a while I was away, far away, in the hands of men with no faces. They broke me down, broke my story down, and convinced me it hadn\'t happened the way I remembered. Now, if you can help me, I, uh, I can make it worth your while",PerkName = "Blunt",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Kolchak the Reporter", X = 9136, Y = 15565, Z = 1 , Weapon = "Base.Plank",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We don\'t have decent radio gear. Now, you\'re telling me that you don\'t have the shit you need? We\'re running low on ammunition. We\'re running low on men for Christ\'s sake!",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Captain Rhodes", X = 13415, Y = 13927, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Pvt. Steel", X = 13413, Y = 13926, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Pvt. Rickles", X = 13413, Y = 13928, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "If it bleeds, we can kill it.",PerkName = "Aiming",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Dutch", X = (-4*300) + 8277, Y = (2*300) + 9567, Z = 1, Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Well, when you come to think about it, all that a person has is other folks. And I reckon there\'s a few folks left in these parts that could use a helping hand",PerkName = "Blunt",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Grizzly the Bear Tamer", X = 4781, Y = 12711, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I\'m a man with a van. If you have a van, we could be men with ven... You got any olives? I\'ve gone fucking mental for olives... I\'m craving the salt you see...",PerkName = "Blade",PerkLevel = 10,isFemale = false, ShowName = true, Name = "Simon", X = 2229, Y = 13705, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Red phosphorus in the presence of moisture and accelerated by heat yields phosphorus hydride. Phosphine gas. One good wiff, and phewf...",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Walter", X = 11556, Y = 6120, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Help me! You\'re my only hope!",PerkName = "Aiming",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Leia", X = 9880, Y = 7693, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Welcome to our gated community. We need help. Once you are done clearing up the vermin here, I will make you some tea that will help you relax",PerkName = "Blade",PerkLevel = 3,isFemale = true, ShowName = true, Name = "Missy", X = 9748, Y = 11475, Z = 0 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "You know what I say? I say one down, a couple hundred thousand to go. I don\'t mean to get on my high horse, but I\'m telling you I do not like the zombies, I\'m sick of it, they\'re taking over, they\'re like rats, they\'re destroying the ecosystem. I see a dead zombie on the side of the road and I think \'That\'s a start\'",PerkName = "Blunt",PerkLevel = 3,isFemale = false, ShowName = true, Name = "Dean", X = 9742, Y = 11472, Z = 0 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Vegetarians are cool. All I eat are vegetarians - except for the occasional mountain lion or survivor steak",PerkName = "Aiming",PerkLevel = 3,isFemale = false, ShowName = true, Name = "Ted", X = 13136, Y = 7933, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Hey, I\'m \'Hawk\' from the TV Show \'American Gladiators\'. Great to see someone alive. My fans used to just want autographs, now they really want a piece of me!",PerkName = "Blunt",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Hawk", X = 8845, Y = 10713, Z = 1 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; --- PresetSpawns[getPSID()] = {Greeting = "We\'ve been overrun!", ShowName = true, Name = "A Savior", X = 10569, Y = 14463, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Who left the gates open!!?", ShowName = true, Name = "A Savior", X = 10572, Y = 14454, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Guard", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "What the hell! Where did all these zombies come from?", ShowName = true, Name = "A Savior", X = 10623, Y = 14468, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "That dipshit who was on gate duty split!", ShowName = true, Name = "A Savior", X = 10560, Y = 14495, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "When we catch who is responsible for this, he'\s going into the arena!", ShowName = true, Name = "A Savior", X = 10606, Y = 14514, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Let'\s not get unnecessarily emotional here. We need to clean this mess up and get those gates closed!", ShowName = true, Name = "A Savior", X = 10573, Y = 14563, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "We\'ve been overrun!", ShowName = true, Name = "A Savior", X = 10581, Y = 14507, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Who left the gates open!!?", ShowName = true, Name = "A Savior", X = 10594, Y = 14541, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "You let those zombies in! Now you die!", ShowName = true, Name = "I\'m Negan", X = 10600, Y = 14542, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; --- PresetSpawns[getPSID()] = {Greeting = "We\'ve been overrun!", ShowName = true, Name = "A Scavenger", X = 8586, Y = 10625, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Who left the gates open!!?", ShowName = true, Name = "A Scavenger", X = 8573, Y = 10603, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "What the hell! Where did all these zombies come from?", ShowName = true, Name = "A Scavenger", X = 8546, Y = 10611, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "That dipshit who was on gate duty split!", ShowName = true, Name = "A Scavenger", X = 8516, Y = 10620, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "When we catch who is responsible for this, he'\s going into the arena!", ShowName = true, Name = "A Scavenger", X = 8559, Y = 10664, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Let'\s not get unnecessarily emotional here. We need to clean this mess up and get those gates closed!", ShowName = true, Name = "A Scavenger", X = 8562, Y = 10638, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "We take, we do not bother, our way", ShowName = true, isFemale = true, Name = "Jadis, Scavengers Leader", X = 8565, Y = 10638, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; --Riverside AIZ Extra Spawns PresetSpawns[getPSID()] = {Greeting = "Look at you. Getting all sentimental. We are the means to each other\'s end. We help each other get places. It is a useful arrangement. Let\'s not go confusing things with vague terms like friend",PerkName = "Blunt",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Victor", X = 5735, Y = 6448, Z = 1 , Weapon = "Base.BaseballBat",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "To kill the monster, you become the monster. You stare into the abyss, the abyss stares back. It is alive... It is hungry... And it devours",PerkName = "Blade",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Alicia", X = 5421, Y = 5877, Z = 0 , Weapon = "Base.HuntingKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "I have a son. He watches me. Waiting to see how I\'ll face it, the violence. I tried so hard not to be part of it. I knew it would change me. And that he\'d see it. I can\'t tell you what you want to hear",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Travis", X = 6281, Y = 5448, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "We\'ve lost loved ones, too. But we can stop that. We can start over. Both of our families. We have mutual interests. The next group that finds this place, and others will find this place, they could be cruel. We\'ve seen that. They\'re not gonna ask for your help. They won\'t try to reason. They\'re not gonna talk. They\'re gonna take and they\'ll kill",PerkName = "Blade",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Madison", X = 6275, Y = 5448, Z = 0 , Weapon = "Base.KitchenKnife",hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "When I was on the beach, I came face-to-face with one of them and I didn\'t feel fear, I didn\'t feel hate. I just knew I wasn\'t going to die. Not there, not that way. I move among them. Invisible. I will not die",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Nick", X = 6574, Y = 5365, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "My father told me not to have hatred in my heart. He said that men do these things not because of evil. They do evil because of fear. And at that moment, I realized my father is a fool, for believing there was a difference. If it happens, it will happen quickly and you must be prepared",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "Daniel", X = 7232, Y = 8374, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "Get out of here!", ShowName = true, Name = "A Scavenger", X = 6397, Y = 5751, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "You want some?", ShowName = true, Name = "A Scavenger", X = 6392, Y = 5769, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "You are dead!", ShowName = true, Name = "A Scavenger", X = 6371, Y = 5770, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "What are you doing here?", ShowName = true, Name = "A Scavenger", X = 6370, Y = 5746, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Standing Ground", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Get out of here!", ShowName = true, Name = "Thug", X = 12213, Y = 6479, Z = 0 , Weapon = getWeapon("Base.Shotgun"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "You want some?", ShowName = true, Name = "Thug", X = 12213, Y = 6483, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "You are dead!", ShowName = true, Name = "Thug", X = 12216, Y = 6479, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "What are you doing here?", ShowName = true, Name = "Thug", X = 12216, Y = 6483, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "Kill Them!", ShowName = true, Name = "Thug Leader", X = 12219, Y = 6481, Z = 0 , Weapon = getWeapon("Base.HuntingRifle"),hasOrder = true, Orders = "Explore", isHostile = true}; PresetSpawns[getPSID()] = {Greeting = "How did you know I am a nurse? I\'m looking for John. He\'s a nice man. Have you seen him?",PerkName = "Aiming",PerkLevel = 5,isFemale = true, ShowName = true, Name = "June", X = 3720, Y = 6483, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "What\'s your story? Where did you come from? What\'s your name?",PerkName = "Aiming",PerkLevel = 5,isFemale = true, ShowName = true, Name = "Althea", X = 15622, Y = 14628, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; PresetSpawns[getPSID()] = {Greeting = "If we don\'t believe things will get better, if we don\'t believe that we can make them that way, if we don\'t fight for every day, we\'re no different than the passed",PerkName = "Aiming",PerkLevel = 5,isFemale = false, ShowName = true, Name = "John", X = 9565, Y = 17212, Z = 0 , Weapon = getWeapon("Base.Pistol"),hasOrder = true, Orders = "Standing Ground", isHostile = false}; SurvivorCount = 1; local sc = 1; RPresetSpawns = {}; while PresetSpawns[sc] do local pindex = PresetSpawns[sc].X .. PresetSpawns[sc].Y; print("pindex:"..pindex.." for index: "..sc); RPresetSpawns[pindex] = PresetSpawns[sc]; RPresetSpawns[pindex].ID = sc; sc = sc + 1; end end Events.OnGameTimeLoaded.Add(AIZSurvivorsInit);
-- LuaLinq - http://code.google.com/p/lualinq/ -- ------------------------------------------------------------------------ -- Copyright (c) 2012, Marco Mastropaolo (Xanathar) -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without modification, -- are permitted provided that the following conditions are met: -- -- o Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- o Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- o Neither the name of Marco Mastropaolo nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -- IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -- OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED -- OF THE POSSIBILITY OF SUCH DAMAGE. -- ------------------------------------------------------------------------ -- how much log information is printed: 3 => verbose, 2 => info, 1 => only warning and errors, 0 => only errors, -1 => silent LOG_LEVEL = 1 -- prefix for the printed logs LOG_PREFIX = "LuaLinq: "
fx = { style = "STYLE_BEAM", properties = { property_11 = { name = "Texture_U_Repeat", type = "VARTYPE_ARRAY_TIMEFLOAT", value = { 0, 10, 1, 10, }, }, property_15 = { name = "LightCurve", type = "VARTYPE_ARRAY_TIMEFLOAT", value = { 0, 2.50000, 1, 3.25000, }, }, property_18 = { name = "LengthEpsilon", type = "VARTYPE_FLOAT", value = 0, }, property_17 = { name = "Arc", type = "VARTYPE_ARRAY_TIMEVECTOR3", value = { entry_00 = { 0, 0, 0, 0, }, entry_01 = { 1, 0, 0, 0, }, }, }, property_16 = { name = "Colour", type = "VARTYPE_ARRAY_TIMECOLOUR", value = { entry_00 = { 0, 0, 0, 0, 1, }, entry_01 = { 0.02537, 0.52830, 0.52830, 0.52830, 1, }, entry_02 = { 0.85672, 0.52830, 0.52830, 0.52830, 1, }, entry_03 = { 1, 0.51887, 0.51887, 0.51887, 1, }, }, }, property_19 = { name = "WidthEpsilon", type = "VARTYPE_FLOAT", value = 0, }, property_09 = { name = "Segments", type = "VARTYPE_ARRAY_TIMEFLOAT", value = { 0, 1, 1, 10, }, }, property_04 = { name = "CastLight", type = "VARTYPE_BOOL", value = 1, }, property_03 = { name = "Texture", type = "VARTYPE_STRING", value = "DATA:ART/FX/ION_BEAM/ION_BEAM.TGA", }, property_06 = { name = "Offset", type = "VARTYPE_ARRAY_TIMEVECTOR3", value = { entry_00 = { 0, 0, 0, 0, }, entry_01 = { 1, 0, 0, 0, }, }, }, property_05 = { name = "NonVisible", type = "VARTYPE_BOOL", value = 0, }, property_08 = { name = "Noise", type = "VARTYPE_ARRAY_TIMEFLOAT", value = { 0, 0, 1, 0, }, }, property_07 = { name = "Length", type = "VARTYPE_ARRAY_TIMEFLOAT", value = { 0, 1, 1, 1, }, }, property_02 = { name = "Blending", type = "VARTYPE_INT", value = 4, }, property_01 = { name = "Loop", type = "VARTYPE_BOOL", value = 0, }, property_13 = { name = "Light", type = "VARTYPE_ARRAY_TIMECOLOUR", value = { entry_02 = { 1, 0.51765, 0.62745, 1, 1, }, entry_00 = { 0, 0.51765, 0.62745, 1, 0, }, entry_01 = { 0.04776, 0.51765, 0.62745, 1, 1, }, }, }, property_14 = { name = "LightWidth", type = "VARTYPE_ARRAY_TIMEFLOAT", value = { 0, 0, 0.05125, 3, 0.09875, 9, 0.95125, 9, 1, 3, }, }, property_20 = { name = "LineDistance", type = "VARTYPE_FLOAT", value = 1750, }, property_12 = { name = "Width", type = "VARTYPE_ARRAY_TIMEFLOAT", value = { 0, 0, 0.05, 8, 0.2, 8, 0.2, 40, 0.25, 20, 0.3, 34, 0.4, 43, 3.6, 43, 4, 40, 2, 0, }, }, property_00 = { name = "Duration", type = "VARTYPE_FLOAT", value = 8, }, property_10 = { name = "Texture_U_Offset", type = "VARTYPE_ARRAY_TIMEFLOAT", value = { 0, 0, 1, 6, }, }, }, }
return function() local CorePackages = game:GetService("CorePackages") local CoreGui = game:GetService("CoreGui") local InGameMenuDependencies = require(CorePackages.InGameMenuDependencies) local Roact = InGameMenuDependencies.Roact local RoactRodux = InGameMenuDependencies.RoactRodux local Rodux = InGameMenuDependencies.Rodux local UIBlox = InGameMenuDependencies.UIBlox local InGameMenu = script.Parent.Parent local reducer = require(InGameMenu.reducer) local InGameMenuPolicy = require(InGameMenu.InGameMenuPolicy) local AppDarkTheme = require(CorePackages.AppTempCommon.LuaApp.Style.Themes.DarkTheme) local AppFont = require(CorePackages.AppTempCommon.LuaApp.Style.Fonts.Gotham) local appStyle = { Theme = AppDarkTheme, Font = AppFont, } local mockPolicyMapper = function(policy) return { enableEducationalPopup = function() return false end, educationalPopupMaxDisplayCount = function() return 0 end, } end local FullscreenTitleBar = require(script.Parent.FullscreenTitleBar) local mockProps = { titleText = "Roblox", displayOrder = 1, isMenuOpen = true, isEducationalPopupEnabled = true, maxDisplayCount = 1, openEducationalPopup = function() end, startLeavingGame = function() end, } it("should create and destroy without errors", function() local element = Roact.createElement(RoactRodux.StoreProvider, { store = Rodux.Store.new(reducer) }, { PolicyProvider = Roact.createElement(InGameMenuPolicy.Provider, { policy = { mockPolicyMapper }, }, { ThemeProvider = Roact.createElement(UIBlox.Core.Style.Provider, { style = appStyle, }, { FullscreenTitleBar = Roact.createElement(FullscreenTitleBar, mockProps), }), }), }) local handle = Roact.mount(element) Roact.unmount(handle) end) it("should be a child ScreenGui of CoreGui", function() local element = Roact.createElement(RoactRodux.StoreProvider, { store = Rodux.Store.new(reducer) }, { PolicyProvider = Roact.createElement(InGameMenuPolicy.Provider, { policy = { mockPolicyMapper }, }, { ThemeProvider = Roact.createElement(UIBlox.Core.Style.Provider, { style = appStyle, }, { FullscreenTitleBar = Roact.createElement(FullscreenTitleBar, mockProps), }), }), }) local handle = Roact.mount(element) local instance = CoreGui:FindFirstChild("InGameFullscreenTitleBarScreen") expect(instance).to.never.equal(nil) expect(instance.ClassName).to.equal("ScreenGui") Roact.unmount(handle) end) end
local statement = {} --local json = require'json' function statement.vardecl (ast,vm,al) local str = U.dotype(ast[0]).." ".. U.allocvar(vm,al,ast[1].content) if ast.len==3 then str = str .. " = " .. U.expr(ast[2],vm,al) end return str..";\n" end function statement.expr (ast,vm,al) local e = U.expr(ast[0],vm,al) return e..";\n" end local function mayexpr (ast,vm,al) if ast.len==0 then return "" end return U.expr(ast[0],vm,al) end function statement.forlp (ast,vm,al) local B = buffer() B:add("for(") B:add(mayexpr(ast[0],vm,al)) B:add(";") B:add(mayexpr(ast[1],vm,al)) B:add(";") B:add(mayexpr(ast[2],vm,al)) B:add(")\n") B:add(U.statement(ast[3],vm,al)) return B:str() end function statement.ifs (ast,vm,al) local B = buffer() B:add("if(") B:add(U.expr(ast[0],vm,al)) B:add(")\n") B:add(U.statement(ast[1],vm,al)) return B:str() end function statement.whlp (ast,vm,al) local B = buffer() B:add("while(") B:add(U.expr(ast[0],vm,al)) B:add(")\n") B:add(U.statement(ast[1],vm,al)) return B:str() end function statement.dowh (ast,vm,al) local B = buffer() B:add("do\n") B:add(U.statement(ast[0],vm,al)) B:add("while(") B:add(U.expr(ast[1],vm,al)) B:add(");\n") return B:str() end function statement.block (ast,vm,al) local B = buffer() B:add("{\n") vm = clone(vm) for i=0,ast.last,1 do b = ast[i] B:add( U.statement(b,vm,al) ) end B:add("}\n") return B:str() end function U.statement(ast,vm,al) return P.select(statement,ast,vm,al) end
function trynumber(value, base) return tonumber(value, base) or 0 end function tryint(value) return math.round(trynumber(value)) end function trybool(value) return (value ~= nil and value ~= false) end function trytable(value) if type(value) ~= "table" then value = {} end return value end
local PLUGIN = PLUGIN local backgroundColor = Color(0, 0, 0, 66) local PANEL = {} function PANEL:Init() if (IsValid(ix.gui.teams)) then ix.gui.teams:Remove() end ix.gui.teams = self self:Dock(FILL) self.teams = {} self.teamButtons = {} self.teamSubpanels = {} self.teamsPanel = self:Add("ixHelpMenuCategories") self.teamsPanel.Paint = function(this, width, height) surface.SetDrawColor(backgroundColor) surface.DrawRect(0, 0, width, height) end self.teamButtonPanel = self.teamsPanel:Add("DScrollPanel") self.teamButtonPanel:Dock(FILL) self.canvasPanel = self:Add("EditablePanel") self.canvasPanel:Dock(FILL) local teams = {} hook.Run("PopulateTeamMenu", teams) for k, v in pairs(teams) do self:AddTeam(k) self.teams[k] = v end local createButton = self.teamsPanel:Add("ixMenuButton") createButton:SetText("tabCreateTeam") createButton:SizeToContents() createButton:SetZPos(-99) createButton:Dock(BOTTOM) createButton.DoClick = function() ix.command.Send("PTCreate") end self.teamsPanel:SizeToContents() if (LocalPlayer().curTeam) then if (IsValid(createButton)) then createButton:Remove() end local leaveButton = self.teamsPanel:Add("ixMenuButton") leaveButton:SetText("tabLeaveTeam") leaveButton:SizeToContents() leaveButton:Dock(BOTTOM) leaveButton.DoClick = function() ix.command.Send("PTLeave") end end if (self.teams[ix.gui.lastTeamMenuTab] or LocalPlayer().curTeam) then local lastTab = self.teams[ix.gui.lastTeamMenuTab] and ix.gui.lastTeamMenuTab or LocalPlayer().curTeam self:OnCategorySelected(lastTab) end end function PANEL:AddTeam(name) local button = self.teamButtonPanel:Add("ixMenuButton") button:SetText(L("TeamName", name)) button:SetBackgroundColor(ix.config.Get("color")) button.backgroundAlpha = 255 button:SizeToContents() button:Dock(TOP) button.DoClick = function(this) self:OnCategorySelected(name) end button.DoRightClick = function(this) if ((LocalPlayer().curTeam != name or !LocalPlayer().isTeamOwner) and !LocalPlayer():IsDispatch()) then return end local reassignMenu = DermaMenu(this) reassignMenu:AddOption(L("TeamReassign"), function() Derma_StringRequest(L("cmdPTReassign"), L("cmdReassignPTDesc"), name, function(text) ix.command.Send("PTReassign", text, name) end) end) reassignMenu:Open() this.Menu = reassignMenu end local panel = self.canvasPanel:Add("DScrollPanel") panel:SetVisible(false) panel:Dock(FILL) -- reverts functionality back to a standard panel in the case that a category will manage its own scrolling panel.DisableScrolling = function() panel:GetCanvas():SetVisible(false) panel:GetVBar():SetVisible(false) panel.OnChildAdded = function() end end button.Paint = function(this, width, height) local alpha = panel:IsVisible() and this.backgroundAlpha or this.currentBackgroundAlpha surface.SetDrawColor(ColorAlpha(ix.config.Get("color"), alpha)) surface.DrawRect(0, 0, width, height) end self.teamSubpanels[name] = panel return button end function PANEL:OnCategorySelected(name) local panel = self.teamSubpanels[name] if (!IsValid(panel)) then return end if (!panel.bPopulated) then self.teams[name](panel) panel.bPopulated = true end if (IsValid(self.activeTeam)) then self.activeTeam:SetVisible(false) end panel:SetVisible(true) self.activeTeam = panel ix.gui.lastTeamMenuTab = name self:OnTeamSelected(name) end function PANEL:OnTeamSelected(index) if (LocalPlayer().curTeam != index and !LocalPlayer().curTeam) then if (IsValid(self.joinButton)) then self.joinButton:Remove() end self.joinButton = self.teamsPanel:Add("ixMenuButton") self.joinButton:SetText("tabJoinTeam") self.joinButton:SizeToContents() self.joinButton:Dock(BOTTOM) self.joinButton.DoClick = function(this) ix.command.Send("PTJoin", index) end end end vgui.Register("ixTeamMenu", PANEL, "EditablePanel") hook.Add("CreateMenuButtons", "ixTeamMenu", function(tabs) if (!LocalPlayer():IsCombine()) then return end tabs["tabProtectionTeam"] = function(container) container:Add("ixTeamMenu") end end) hook.Add("PopulateTeamMenu", "ixTeamMenu", function(tabs) if (!PLUGIN.teams or table.IsEmpty(PLUGIN.teams)) then return end for k, v in pairs(PLUGIN.teams) do tabs[k] = function(container) container:DisableScrolling() local panel = container:Add("DScrollPanel") panel:Dock(FILL) local memberList = {} for k2, v2 in pairs(v["members"]) do if (v2.isTeamOwner) then memberList[#memberList + 1] = { client = v2, owner = 1 } else memberList[#memberList + 1] = { client = v2, owner = 99 } end end for k2, v2 in SortedPairsByMemberValue(memberList, "owner", false) do if(IsValid(v2.client)) then local member = panel:Add("ixMenuButton") member:SetFont("ixMenuButtonFont") member:SetText(v2.client:Name() or "Unknown") member:SizeToContents() member:Dock(TOP) member.Paint = function(this, width, height) derma.SkinFunc("DrawImportantBackground", 0, 0, width, height, ColorAlpha(this.backgroundColor, this.currentBackgroundAlpha)) end member.DoRightClick = function(this) if (!LocalPlayer():IsDispatch()) then if (!LocalPlayer().isTeamOwner or LocalPlayer().curTeam != k) then return end end local interactMenu = DermaMenu(this) local member = interactMenu:AddOption(v2.client:Name()) member:SetContentAlignment(5) member.Paint = function(this, width, height) end local spacer = interactMenu:AddSpacer() spacer.Paint = function(this, width, height) surface.SetDrawColor( Color( 255, 255, 255, 100 ) ) surface.DrawRect( 0, 0, width, height ) end interactMenu:AddOption(L("TeamTransferOwner"), function() ix.command.Send("PTLead", v2.client:Name()) end):SetIcon( "icon16/award_star_gold_1.png" ) interactMenu:AddOption(L("TeamKickMember"), function() ix.command.Send("PTKick", v2.client:Name()) end):SetIcon( "icon16/cross.png" ) interactMenu:Open() this.Menu = interactMenu end if (v2.client.isTeamOwner) then member.backgroundColor = Color(50,150,100) end else memberList[k2] = nil end end end end end)
--------------- ---- ## A Boundary Plugin Framework for Luvit. ---- ---- For easy development of custom Boundary.com plugins. ---- ---- [Github Page](https://github.com/GabrielNicolasAvellaneda/boundary-plugin-framework-lua) ---- ---- @author Gabriel Nicolas Avellaneda <avellaneda.gabriel@gmail.com> ---- @copyright Boundary.com 2015 ---- @license Apache 2.0 --------------- local Emitter = require('core').Emitter local Object = require('core').Object local timer = require('timer') local math = require('math') local string = require('string') local os = require('os') local io = require('io') local http = require('http') local https = require('https') local net = require('net') local bit = require('bit') local table = require('table') local childprocess = require('childprocess') local json = require('json') local _url = require('url') local framework = {} local querystring = require('querystring') local boundary = require('boundary') framework.version = '0.9.2' framework.boundary = boundary framework.params = boundary.param or {} framework.string = {} framework.functional = {} framework.table = {} framework.util = {} framework.http = {} -- Remove this when we migrate to luvit 2.0.x function framework.util.parseUrl(url, parseQueryString) assert(url, 'parse expect a non-nil value') local href = url local chunk, protocol = url:match("^(([a-z0-9+]+)://)") url = url:sub((chunk and #chunk or 0) + 1) local auth chunk, auth = url:match('(([0-9a-zA-Z]+:?[0-9a-zA-Z]+)@)') url = url:sub((chunk and #chunk or 0) + 1) local host local hostname local port if protocol then host = url:match("^([%a%.%d-]+:?%d*)") if host then hostname = host:match("^([^:/]+)") port = host:match(":(%d+)$") end url = url:sub((host and #host or 0) + 1) end host = hostname -- Just to be compatible with our code base. Discuss this. local path local pathname local search local query local hash hash = url:match("(#.*)$") url = url:sub(1, (#url - (hash and #hash or 0))) if url ~= '' then path = url local temp temp = url:match("^[^?]*") if temp ~= '' then pathname = temp end temp = url:sub((pathname and #pathname or 0) + 1) if temp ~= '' then search = temp end if search then temp = search:sub(2) if temp ~= '' then query = temp end end end if parseQueryString then query = querystring.parse(query) end return { href = href, protocol = protocol, host = host, hostname = hostname, port = port, path = path or '/', pathname = pathname or '/', search = search, query = query, auth = auth, hash = hash } end _url.parse = framework.util.parseUrl -- Propagate the event to another emitter. -- TODO: Will be removed when migrating to luvit 2.0.x function Emitter:propagate(eventName, target) if (target and target.emit) then self:on(eventName, function (...) target:emit(eventName, ...) end) return target end return self end do local encode_alphabet = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' } local decode_alphabet = {} for i, v in ipairs(encode_alphabet) do decode_alphabet[v] = i-1 end local function translate(sixbit) return encode_alphabet[sixbit + 1] end local function unTranslate(char) return decode_alphabet[char] end local function toBytes(str) return { str:byte(1, #str) } end local function mask6bits(byte) return bit.band(0x3f, byte) end local function pad(bytes) local to_pad = 3 - #bytes % 3 while to_pad > 0 and to_pad ~= 3 do table.insert(bytes, 0x0) to_pad = to_pad - 1 end return bytes end local function encode(str, no_padding) local bytes = toBytes(str) local bytesTotal = #bytes if bytesTotal == 0 then return '' end bytes = pad(bytes) local output = {} local i = 1 while i < #bytes do -- read three bytes into a 24 bit buffer to produce 4 coded bytes. local buffer = bit.rol(bytes[i], 16) buffer = bit.bor(buffer, bit.rol(bytes[i+1], 8)) buffer = bit.bor(buffer, bytes[i+2]) -- get six bits at a time and translate to base64 for j = 18, 0, -6 do table.insert(output, translate(mask6bits(bit.ror(buffer, j)))) end i = i + 3 end -- If was padded then replace with = characters local padding_char = no_padding and '' or '=' if bytesTotal % 3 == 1 then output[#output-1] = padding_char output[#output] = padding_char elseif bytesTotal % 3 == 2 then output[#output] = padding_char end return table.concat(output) end local function decode(str) -- take four encoded octets and produce 3 decoded bytes. local output = {} local i = 1 while i < #str do local buffer = 0 -- get the octet represented by the coded base64 char -- shift left by 6 bits and or -- mask the 3 bytes, and convert to ascii for j = 18, 0, -6 do local octet = unTranslate(str:sub(i, i)) buffer = bit.bor(bit.rol(octet, j), buffer) i = i + 1 end for j = 16, 0, -8 do local byte = bit.band(0xff, bit.ror(buffer, j)) table.insert(output, byte) end end return string.char(unpack(output)) end framework.util.base64Encode = encode framework.util.base64Decode = decode end do local _pairs = pairs({ a = 0 }) -- get the generating function from pairs local gpairs = function(t, key) local value key, value = _pairs(t, key) return key, key, value end local function iterator (obj, param, state) if (type(obj) == 'table') then if #obj > 0 then return ipairs(obj) else return gpairs, obj, nil end elseif type(obj) == 'function' then return obj, param, state end error(("object %s of type %s can not be iterated."):format(obj, type(obj))) end local function call(func, state, ...) if state == nil then return nil end return state, func(...) end local function _each(func, gen, param, state) repeat state = call(func, gen(param, state)) until state == nil end local function each(func, gen, param, state) _each(func, iterator(gen, param, state)) end framework.functional.each = each local function toMap(gen, param, state) local t = {} each(function (k, v) v = v or k t[k] = v end, gen, param, state) return t end framework.functional.toMap = toMap -- naive version of map local function map(func, xs) local t = {} table.foreach(xs, function (i, v) --t[i] = func(v, i) table.insert(t, func(v)) end) return t end framework.functional.map = map -- naive version of filter local function filter(func, xs) local t = {} table.foreach(xs, function (i, v) if func(v) then table.insert(t, v) --t[i] = v end end) return t end framework.functional.filter = filter -- naive version of reduce local function reduce(func, acc, xs) table.foreach(xs, function (i, v) acc = func(acc, v) end) return acc end framework.functional.reduce = reduce end --- Trim blanks from the string function framework.string.trim(self) return string.match(self, '^%s*(.-)%s*$') end function framework.string.charAt(self, i) return string.sub(self, i, i) end local charAt = framework.string.charAt function framework.util.parseLinks(data) local links = {} for link in string.gmatch(data, '<a%s+h?ref=["\']([^"^\']+)["\'][^>]*>[^<]*</%s*a>') do table.insert(links, link) end return links end function framework.util.isRelativeLink(link) return not string.match(link, '^https?') end local trim = framework.string.trim function framework.util.absoluteLink(basePath, link) return basePath .. trim(link) end --- Wraps a function to calculate the time passed between the wrap and the function execution. function framework.util.timed(func, startTime) startTime = startTime or os.time() return function(...) return os.time() - startTime, func(...) end end function framework.util.isHttpSuccess(status) return status >= 200 and status < 300 end function framework.util.round(val, decimal) assert(val, 'round expect a non-nil value') if (decimal) then return math.floor( (val * 10^decimal) + 0.5) / (10^decimal) else return math.floor(val+0.5) end end function framework.util.currentTimestamp() return os.time() end local currentTimestamp = framework.util.currentTimestamp function framework.util.megaBytesToBytes(mb) return mb * 1024 * 1024 end function framework.functional.partial(func, x) return function (...) return func(x, ...) end end function framework.functional.identity(x) return x end local identity = framework.functional.identity function framework.functional.compose(f, g) return function(...) return g(f(...)) end end function framework.table.get(key, map) if type(map) ~= 'table' then return nil end return map[key] end function framework.table.indexOf(self, value) if type(self) ~= 'table' then return nil end for i,v in ipairs(self) do if value == v then return i end end return nil end function framework.table.keys(t) local result = {} for k,_ in pairs(t) do table.insert(result, k) end return result end local clone clone = function (t) if type(t) ~= 'table' then return t end local meta = getmetatable(t) local target = {} for k,v in pairs(t) do if type(v) == 'table' then target[k] = clone(v) else target[k] = v end end setmetatable(target, meta) return target end framework.table.clone = clone function framework.string.contains(pattern, str) local s,_ = string.find(str, pattern) return s ~= nil end function framework.string.replace(str, map) for k, v in pairs(map) do str = str:gsub('{' .. k .. '}', v) end return str end function framework.string.escape(str) local s, _ = string.gsub(str, '%.', '%%.') s, _ = string.gsub(s, '%-', '%%-') return s end function framework.string.urldecode(str) local char, gsub, tonumber = string.char, string.gsub, tonumber local function _(hex) return char(tonumber(hex, 16)) end str = gsub(str, '%%(%x%x)', _) return str end function framework.string.urlencode(str) if str then str = string.gsub(str, '\n', '\r\n') str = string.gsub(str, '([^%w])', function(c) return string.format('%%%02X', string.byte(c)) end) end return str end function framework.string.jsonsplit(self) local outResults = {} local theStart,theSplitEnd = string.find(self, "{") local numOpens = theStart and 1 or 0 theSplitEnd = theSplitEnd and theSplitEnd + 1 while theSplitEnd < string.len(self) do if self[theSplitEnd] == '{' then numOpens = numOpens + 1 elseif self[theSplitEnd] == '}' then numOpens = numOpens - 1 end if numOpens == 0 then table.insert( outResults, string.sub ( self, theStart, theSplitEnd ) ) theStart,theSplitEnd = string.find(self, "{", theSplitEnd) numOpens = theStart and 0 or 1 theSplitEnd = theSplitEnd or string.len(self) end theSplitEnd = theSplitEnd + 1 end return outResults end -- TODO: To be composable we need to change this interface to gsplit(separator, data) function framework.string.gsplit(data, separator) local pos = 1 local iter = function() if not pos then -- stop the generator (maybe using stateless is a better option?) return nil end local s, e = string.find(data, separator, pos) if s then local part = string.sub(data, pos, s-1) pos = e + 1 return part else local part = string.sub(data, pos) pos = nil return part end end return iter, data, 1 end local gsplit = framework.string.gsplit function framework.string.isplit(data, separator, func) for part in gsplit(data, separator) do func(part) end end local isplit = framework.string.isplit function framework.string.split(data, separator) if not data then return nil end local result = {} isplit(data, separator, function (part) table.insert(result, part) end) return result end local split = framework.string.split function framework.util.pack(metric, value, timestamp, source) return { metric = metric, value = value, timestamp = timestamp, source = source } end function framework.util.packValue(value, timestamp, source) return { value = value, timestamp = timestamp, source = source } end --- Check if the string is empty. Before checking it will be trimmed to remove blank spaces. function framework.string.isEmpty(str) return (str == nil or framework.string.trim(str) == '') end local isEmpty = framework.string.isEmpty --- If not empty returns the value. If is empty, an a default value was specified, it will return that value. function framework.string.notEmpty(str, default) return not framework.string.isEmpty(str) and str or default end local notEmpty = framework.string.notEmpty function framework.string.concat(s1, s2, char) if isEmpty(s2) then return s1 end return s1 .. char .. s2 end function framework.table.create(keys, values) local result = {} for i, k in ipairs(keys) do if notEmpty(trim(k)) then result[k] = values[i] end end return result end function framework.util.parseValue(x) return tonumber(x) or (isEmpty(x) and 0) or tostring(x) or 0 end local parseValue = framework.util.parseValue local map = framework.functional.map -- TODO: Convert this to a generator -- TODO: Use gsplit instead of split function framework.string.parseCSV(data, separator, comment, header) separator = separator or ',' local parsed = {} local lines = split(data, '\n') local headers if header then local header_line = string.match(lines[1], comment .. '%s*([' .. separator .. '%S]+)%s*') headers = split(trim(header_line), separator) end for _, v in ipairs(lines) do if notEmpty(v) then if not comment or not (charAt(v, 1) == comment) then local values = split(v, separator) values = map(parseValue, values) if headers then table.insert(parsed, framework.table.create(headers, values)) else table.insert(parsed, values) end end end end return parsed end function framework.util.auth(username, password) return notEmpty(username) and notEmpty(password) and (username .. ':' .. password) or nil end -- Returns an string for a Boundary Meter event. -- @param type could be 'CRITICAL', 'ERROR', 'WARN', 'INFO' function framework.util.eventString(type, message, tags) tags = tags or '' return string.format('_bevent: %s |t:%s|tags:%s', message, type, tags) end local eventString = framework.util.eventString -- You can call framework.string() to export all functions to the string table to the global table for easy access. local function exportable(t) setmetatable(t, { __call = function (u, warn) for k,v in pairs(u) do if (warn) then if _G[k] ~= nil then process.stderr:write('Warning: Overriding function ' .. k ..' on global space.') end end _G[k] = v end end }) end -- Allow to export functions to global table exportable(framework.string) exportable(framework.util) exportable(framework.functional) exportable(framework.table) exportable(framework.http) --- Cache class. -- @type Cache local Cache = Object:extend() function Cache:initialize(func) self.func = func self.cache = {} end function Cache:get(key) assert(key, 'Cache:get key must be non-nil') local result = self.cache[key] if not result then result = self.func() self.cache[key] = result -- now cache the value end return result end framework.Cache = Cache --- DataSource class. -- @type DataSource local DataSource = Emitter:extend() --- DataSource is the base class for any DataSource you want to implement. By default accepts a function/closure that will be called each fetch call. framework.DataSource = DataSource --- DataSource constructor. -- @name DataSource:new function DataSource:initialize(func) self.func = func end --- Chain the fetch result to the execution of the fetch on another DataSource. -- @param data_source the DataSource that will be fetched passing the transformed result of the fetch operation. -- @param transform (optional) transform function to be called on the result of the fetch operation in this instance. -- @usage: first_ds:chain(second_ds, transformFunc):chain(third_ds, transformFunc) function DataSource:chain(data_source, transform) assert(data_source, 'chain: data_source not set.') self.chained = { data_source, transform } return data_source end function DataSource:onFetch() self:emit('onFetch') end --- Fetch data from the datasource. This is an abstract method. -- @param context Context information, this can be the caller or another object that you want to set. -- @param callback A function that will be called when the fetch operation is done. If there are another DataSource chained, this call will be made when the ultimate DataSource in the chain is done. function DataSource:fetch(context, callback, params) self:onFetch(context, callback, params) local result = self.func(params) self:processResult(context, callback, result) end function DataSource:processResult(context, callback, ...) if self.chained then local ds, transform = unpack(self.chained) if type(ds) == 'function' then local f = ds local data_sources = f(self, callback, ...) if type(data_sources) == 'table' then for i, v in ipairs(data_sources) do v:fetch(self, callback, ...) -- TODO: This datasources where created by the function chained. Pass parameters on the constructor? end else --TODO: Use the result of f() or just result? because f can be also a transform function and if you are asigning to a chain the result of this will be the continuated value. callback(...) end else transform = transform or identity ds:fetch(self, callback, transform(...)) end else callback(...) end end --- NetDataSource class. -- @type NetDataSource local NetDataSource = DataSource:extend() function NetDataSource:initialize(host, port, close_connection) self.host = host self.port = port self.close_connection = close_connection or false end function NetDataSource:onFetch(socket) error('you must override the NetDataSource:onFetch') end --- Fetch data from the configured host and port -- @param context How calls this functions -- @func callback A callback that gets called when there is some data on the socket. function NetDataSource:fetch(context, callback) self:connect(function () self:onFetch(self.socket) if callback then self.socket:once('data', function (data) callback(data) if self.close_connection then self:disconnect() end end) else if self.close_connection then self:disconnect() end end end) end function NetDataSource:disconnect() self.socket:done() self.socket = nil end function NetDataSource:connect(callback) if self.socket then callback() return end self.socket = net.createConnection(self.port, self.host, callback) self.socket:on('error', function (err) self:emit('error', 'Socket error: ' .. err.message) end) end framework.NetDataSource = NetDataSource --- DataSourcePoller class -- @type DataSourcePoller local DataSourcePoller = Emitter:extend() --- DataSourcePoller constructor. -- DataSourcePoller Polls a DataSource at the specified interval and calls a callback when there is some data available. -- @int pollInterval number of milliseconds to poll for data -- @param dataSource A DataSource to be polled -- @name DataSourcePoller:new function DataSourcePoller:initialize(pollInterval, dataSource) self.pollInterval = pollInterval self.dataSource = dataSource dataSource:propagate('error', self) end function DataSourcePoller:_poll(callback) self.dataSource:fetch(self, callback) timer.setTimeout(self.pollInterval, function () self:_poll(callback) end) end --- Start polling for data. -- @func callback A callback function to call when the DataSource returns some data. function DataSourcePoller:run(callback) if self.running then return end self.running = true self:_poll(callback) end --- Plugin Class. -- @type Plugin local Plugin = Emitter:extend() framework.Plugin = Plugin --- Plugin constructor. -- A base plugin implementation that accept a dataSource and polls periodically for new data and format the output so the boundary meter can collect the metrics. -- @param params is a table of options that can be: -- pollInterval (optional) the poll interval between data fetchs. This is required if you pass a plain DataSource and not a DataSourcePoller. -- source (optional) -- version (options) the version of the plugin. -- @param dataSource A DataSource that will be polled for data. -- If is a DataSource a DataSourcePoller will be created internally to pool for data -- It can also be a DataSourcePoller or PollerCollection. -- @name Plugin:new function Plugin:initialize(params, dataSource) assert(dataSource, 'Plugin:new dataSource is required.') local pollInterval = params.pollInterval or 1000 if not Plugin:_isPoller(dataSource) then self.dataSource = DataSourcePoller:new(pollInterval, dataSource) self.dataSource:propagate('error', self) else self.dataSource = dataSource end self.source = notEmpty(params.source, os.hostname()) self.version = params.version or '1.0' self.name = params.name or 'Boundary Plugin' self.tags = params.tags or '' dataSource:propagate('error', self) self:on('error', function (err) self:error(err) end) end function Plugin:printError(err) self:printEvent('error', err) end function Plugin:printInfo(msg) self:printEvent('info', msg) end function Plugin:printWarn(msg) self:printEvent('warn', msg) end function Plugin:printCritical(msg) self:printEvent('critical', msg) end -- TODO: Add a unit test function framework.table.merge(t1, t2) local output = clone(t1) for k, v in pairs(t2) do if type(k) == 'number' then table.insert(output, v) else output[k] = v end end return output end local merge = framework.table.merge function Plugin.formatMessage(name, version, msg) return string.format('%s version %s: %s', name, version, msg) end function Plugin.formatTags(tags) tags = tags or {} if type(tags) == 'string' then tags = split(tags, ',') end return table.concat(merge({'lua', 'plugin'}, tags), ',') end function Plugin:printEvent(eventType, msg) msg = Plugin.formatMessage(self.name, self.version, msg) local tags = Plugin.formatTags(self.tags) print(eventString(eventType, msg, tags)) end function Plugin:emitEvent(type, msg) self:printEvent(type, msg) end function Plugin:_isPoller(poller) return poller.run end --- Called when the Plugin detect and error in one of his components. -- @param err the error emitted by one of the component that failed. function Plugin:error(err) local msg if type(err) == 'table' and err.message then msg = err.message else msg = tostring(err) end self:printError(msg) end --- Run the plugin and start polling from the configured DataSource function Plugin:run() self:printInfo('Up') self.dataSource:run(function (...) self:parseValues(...) end) end -- TODO: Use pcall? function Plugin:parseValues(...) local metrics = self:onParseValues(...) if not metrics then return end self:report(metrics) end function Plugin:onParseValues(...) error('You must implement onParseValues') end function Plugin:report(metrics) self:emit('report') self:onReport(metrics) end function Plugin:onReport(metrics) -- metrics can be { metric = value } -- or {metric = {value, source}} -- or {metric = {{value, source}, {value, source}, {value, source}} -- or {metric, value, source} -- or {{metric, value, source, timestamp}} for metric, v in pairs(metrics) do -- { { metric, value .. }, { metric, value .. } } if type(metric) == 'number' then print(self:format(v.metric, v.value, v.source, v.timestamp or currentTimestamp())) elseif type(v) ~= 'table' then print(self:format(metric, v, self.source, currentTimestamp())) elseif type(v[1]) ~= 'table' and v.value then -- looking for { metric = { value, source, timestamp }} local source = v.source or self.source local value = v.value local timestamp = v.timestamp or currentTimestamp() print(self:format(metric, value, source, timestamp)) else -- looking for { metric = {{ value, source, timestamp }}} for _, j in pairs(v) do local source = j.source or self.source local value = j.value local timestamp = j.timestamp or currentTimestamp() print(self:format(metric, value, source, timestamp)) end end end end function Plugin:format(metric, value, source, timestamp) self:emit('format') return self:onFormat(metric, value, source, timestamp) end --- Called by the framework before formating the metric output. -- @string metric the metric name -- @param value the value to format -- @string source the source to report for the metric -- @param timestamp the time the metric was retrieved -- You can override this on your plugin instance. function Plugin:onFormat(metric, value, source, timestamp) return string.format('%s %f %s %s', metric, value, source, timestamp) end local CommandPlugin = Plugin:extend() framework.CommandPlugin = CommandPlugin function CommandPlugin:initialize(params) Plugin.initialize(self, params) if not params.command then error('params.command undefined. You need to define the command to excetue.') end self.command = params.command end function CommandPlugin:execCommand(callback) local proc = io.popen(self.command, 'r') local output = proc:read("*a") proc:close() if callback then callback(output) end end function CommandPlugin:onPoll() self:execCommand(function (output) self.parseCommandOutput(self, output) end) end function CommandPlugin:parseCommandOutput(output) local metrics = self:onParseCommandOutput(output) self:report(metrics) end function CommandPlugin:onParseCommandOutput(output) print(output) return {} end local NetPlugin = Plugin:extend() framework.NetPlugin = NetPlugin local HttpPlugin = Plugin:extend() framework.HttpPlugin = HttpPlugin function HttpPlugin:initialize(params) Plugin.initialize(self, params) self.reqOptions = { host = params.host, port = params.port, path = params.path } end local PollingPlugin = Plugin:extend() framework.PollingPlugin = PollingPlugin function HttpPlugin:makeRequest(reqOptions, successCallback) local req = http.request(reqOptions, function (res) local data = '' res:on('data', function (chunk) data = data .. chunk successCallback(data) -- TODO: Verify when data its complete or when we need to use de end end) res:on('error', function (err) local msg = 'Error while receiving a response: ' .. err.message self:error(msg) end) end) req:on('error', function (err) local msg = 'Error while sending a request: ' .. err.message self:error(msg) end) req:done() end function HttpPlugin:onPoll() self:makeRequest(self.reqOptions, function (data) self:parseResponse(data) end) end function HttpPlugin:parseResponse(data) local metrics = self:onParseResponse(data) self:report(metrics) end function HttpPlugin:onParseResponse(data) -- To be overriden on class instance print(data) return {} end --- Acumulator Class -- @type Accumulator local Accumulator = Emitter:extend() --- Accumulator constructor. -- Keep track of values so we can return the delta for accumulated metrics. -- @name Accumulator:new function Accumulator:initialize() self.map = {} end --- Accumulates a value an return the delta between the actual an latest value. -- @string key the key for the item -- @param value the item value -- @return diff the delta between the latests and actual value. function Accumulator:accumulate(key, value) assert(value, "Accumulator:accumulate#value must not be null for key " .. key) local oldValue = self.map[key] if oldValue == nil then oldValue = value end self.map[key] = value local diff = value - oldValue return diff end --- Return the last accumulated valor or 0 if there isnt any for the key -- @param key the key for the item to retrieve function Accumulator:get(key) return self.map[key] or 0 end --- Reset the specified value -- @string key A key to untrack function Accumulator:reset(key) self.map[key] = nil end --- Clean up all the tracked key/values. function Accumulator:resetAll() self.map = {} end framework.Accumulator = Accumulator local PollerCollection = Emitter:extend() function PollerCollection:initialize(pollers) self.pollers = pollers or {} end function PollerCollection:add(poller) table.insert(self.pollers, poller) poller:propagate('error', self) end function PollerCollection:run(callback) if self.running then return end self.running = true for _,p in pairs(self.pollers) do p:run(callback) end end --- WebRequestDataSource Class -- @type WebRequestDataSource local WebRequestDataSource = DataSource:extend() function WebRequestDataSource:initialize(params) local options = params if type(params) == 'string' then options = _url.parse(params) end self.wait_for_end = options.wait_for_end or false self.options = options self.info = options.meta end local base64Encode = framework.util.base64Encode local replace = framework.string.replace function WebRequestDataSource:fetch(context, callback, params) assert(callback, 'WebRequestDataSource:fetch: callback is required') local start_time = os.time() local options = clone(self.options) -- Replace variables params = params or {} if type(params) == 'table' then options.path = replace(options.path, params) options.pathname = replace(options.pathname, params) end local buffer = '' local success = function (res) if self.wait_for_end then res:on('end', function () local exec_time = os.time() - start_time --callback(buffer, {info = self.info, response_time = exec_time, status_code = res.statusCode}) self:processResult(context, callback, buffer, {info = self.info, response_time = exec_time, status_code = res.statusCode}) res:destroy() end) else res:once('data', function (data) local exec_time = os.time() - start_time buffer = buffer .. data if not self.wait_for_end then self:processResult(context, callback, buffer, {info = self.info, response_time = exec_time, status_code = res.statusCode}) res:destroy() end end) end res:on('data', function (d) buffer = buffer .. d end) res:propagate('data', self) res:propagate('error', self) end options.headers = {} options.headers['User-Agent'] = 'Boundary Meter <support@boundary.com>' if options.auth then options.headers['Authorization'] = 'Basic ' .. base64Encode(options.auth, false) end local data = options.data local body if data and table.getn(data) > 0 then body = table.concat(data, '&') options.headers['Content-Type'] = 'application/x-www-form-urlencoded' options.headers['Content-Length'] = #body end local req if options.protocol == 'https' then req = https.request(options, success) else req = http.request(options, success) end if body and #body > 0 then req:write(body) end req:propagate('error', self) req:done() end --- RandomDataSource class returns a random number each time it get called. -- @type RandomDataSource -- @param context the object that called the fetch -- @func callback A callback to call with the random generated number -- @usage local ds = RandomDataSource:new(1, 100) -- Generate numbers from 1 to 100 local RandomDataSource = DataSource:extend() --- RandomDataSource constructor -- @int minValue the lower bounds for the random number generation. -- @int maxValue the upper bound for the random number generation. -- @usage local ds = RandomDataSource:new(1, 100) function RandomDataSource:initialize(minValue, maxValue) DataSource.initialize(self, function () return math.random(minValue, maxValue) end) end --- CommandOutputDataSource class -- @type CommandOutputDataSource local CommandOutputDataSource = DataSource:extend() --- CommandOutputDataSource constructor -- @paramas a table with path and args of the command to execute function CommandOutputDataSource:initialize(params) -- TODO: Handle commands for each operating system. assert(params, 'CommandOuptutDataSource:new exect a non-nil params parameter') self.path = params.path self.args = params.args self.success_exitcode = params.success_exitcode or 0 self.info = params.info self.callback_on_errors = params.callback_on_errors end function CommandOutputDataSource:isSuccess(exitcode) return tonumber(exitcode) == self.success_exitcode end --- Returns the output of execution of the command function CommandOutputDataSource:fetch(context, callback, parser, params) local output = '' local proc = childprocess.spawn(self.path, self.args) proc:propagate('error', self) proc.stdout:on('data', function (data) output = output .. data end) proc.stderr:on('data', function (data) output = output .. data end) proc:on('exit', function (exitcode) if not self:isSuccess(exitcode) then self:emit('error', {message = 'Command terminated with exitcode \'' .. exitcode .. '\' and message \'' .. output .. '\''}) if not self.callback_on_errors then return end end -- TODO: Add context for callback? if callback then callback({context = self, info = self.info, output = output}) end end) end local MeterDataSource = NetDataSource:extend() function MeterDataSource:initialize(host, port) host = host or '127.0.0.1' port = port or 9192 NetDataSource.initialize(self, host, port) end function MeterDataSource:fetch(context, callback) local parse = function (value) local parsed = json.parse(value) local result = {} if parsed.result.status ~= 'Ok' then self:error('Error with status: ' .. parsed.result.status) return end local query_metric = parsed.result.query_metric -- TODO: Return a generator if query_metric then for i = 1, table.getn(query_metric), 3 do table.insert(result, {metric = query_metric[i], value = query_metric[i+1], timestamp = query_metric[i+2]}) end end callback(result) end NetDataSource.fetch(self, context, parse) end function MeterDataSource:queryMetricCommand(params) params = params or { match = ''} return '{"jsonrpc":"2.0","method":"query_metric","id":1,"params":' .. json.stringify(params) .. '}\n' end framework.CommandOutputDataSource = CommandOutputDataSource framework.RandomDataSource = RandomDataSource framework.DataSourcePoller = DataSourcePoller framework.WebRequestDataSource = WebRequestDataSource framework.PollerCollection = PollerCollection framework.MeterDataSource = MeterDataSource return framework
--[[ Global game state controller ]] local ctrl = {} function ctrl.init() -- Init containers camera = {} mouse = {} -- Init camera camera.x = 0 camera.y = 0 camera.zoom = 1 -- Init mouse mouse.x = 0 mouse.y = 0 -- Mouse relative to zoom and camera mouse.rx = 0 mouse.ry = 0 mouse.wheel = 0 sleep = 0 end function ctrl.update(dt) -- Get mouse pos, relative to screen scale mouse.x, mouse.y = (love.mouse.getX() - window.x_offset), (love.mouse.getY() - window.y_offset) local mx, my = mouse.x / window.scale, mouse.y / window.scale mx = (mx - camera.x)/camera.zoom my = (my - camera.y)/camera.zoom mouse.rx = mx mouse.ry = my end return ctrl
require "nn" mlp=nn.Concat(2); mlp:add(nn.Linear(5,7)) mlp:add(nn.Linear(5,7)) print(mlp:forward(torch.randn(2, 5)))
slot0 = class("PublicGuildMainMediator", import("...base.ContextMediator")) slot0.ON_COMMIT = "PublicGuildMainMediator:ON_COMMIT" slot0.UPGRADE_TECH = "PublicGuildMainMediator:UPGRADE_TECH" slot0.register = function (slot0) slot0:bind(slot0.ON_COMMIT, function (slot0, slot1) slot0:sendNotification(GAME.PUBLIC_GUILD_COMMIT_DONATE, { id = slot1 }) end) slot0.bind(slot0, slot0.UPGRADE_TECH, function (slot0, slot1) slot0:sendNotification(GAME.PULIC_GUILD_UPGRADE_TECH, { id = slot1 }) end) slot0.viewComponent:SetPublicGuild(slot1) slot0.viewComponent:SetPlayer(getProxy(PlayerProxy):getData()) end slot0.listNotificationInterests = function (slot0) return { GAME.PUBLIC_GUILD_COMMIT_DONATE_DONE, GAME.PUBLIC_GUILD_REFRESH_DONATE_LIST_DONE, PlayerProxy.UPDATED, GAME.PULIC_GUILD_UPGRADE_TECH_DONE, GAME.GET_PUBLIC_GUILD_USER_DATA_DONE } end slot0.handleNotification = function (slot0, slot1) slot3 = slot1:getBody() if slot1:getName() == GAME.PUBLIC_GUILD_COMMIT_DONATE_DONE then slot0.viewComponent:emit(BaseUI.ON_ACHIEVE, slot3.awards) slot0.viewComponent:OnUpdateDonateList() elseif slot2 == GAME.PUBLIC_GUILD_REFRESH_DONATE_LIST_DONE then slot0.viewComponent:OnUpdateDonateList() elseif slot2 == PlayerProxy.UPDATED then slot0.viewComponent:OnPlayerUpdate(slot3) elseif slot2 == GAME.PULIC_GUILD_UPGRADE_TECH_DONE then slot0.viewComponent:OnTechGroupUpdate(slot3.id) elseif slot2 == GAME.GET_PUBLIC_GUILD_USER_DATA_DONE then slot0.viewComponent:SetPublicGuild(getProxy(GuildProxy):GetPublicGuild()) slot0.viewComponent:RefreshAll() end end return slot0
-- --entity require("prototypes.style") require("prototypes.hotkeys") -- --items -- require("prototypes.item.items") -- --recipies -- require("prototypes.recipe.recipes")
InteractiveObjectEx = { type = "InteractiveObjectEx", Properties = { Interaction = { -- All interactions share a single CGA which loads the geometry (in the case of one interaction this also supplies the ANM) object_Model = "Objects/prototype/ElevatorDoors/AnimatedElevatorDoors.cga", -- Old style specify one specific interaction Interaction = "OpenElevatorDoor", InteractionRadius = 1.5, InteractionAngle = 70, bRemoveDecalsOnUse = 0, bStartInteractionOnExplosion = 0, }, Physics = { bRigidBody = 0, }, }, Editor={ Icon="animobject.bmp", IconOnTop=1, }, userId = NULL_ENTITY, } function InteractiveObjectEx:OnInit() self:OnReset(); end function InteractiveObjectEx:OnPropertyChange() self:OnReset(); end function InteractiveObjectEx:OnReset() self.bUsable=self.Properties.bUsable; end function InteractiveObjectEx:OnSave(tbl) tbl.bUsable=self.bUsable; tbl.userId = self.userId; end function InteractiveObjectEx:OnLoad(tbl) self.bUsable=tbl.bUsable; self.userId = tbl.userId; end function InteractiveObjectEx:OnShutDown() end ---------------------------------------------------------------------------------- ------------------------------------Events---------------------------------------- ---------------------------------------------------------------------------------- function InteractiveObjectEx:Event_Use() self.interactiveObject:Use(self.userId); self:ActivateOutput( "Started", true ); end; function InteractiveObjectEx:Event_UserId(sender, user) self.userId = user.id; end; function InteractiveObjectEx:Event_Hide() self:Hide(1); self:ActivateOutput( "Hide", true ); end; function InteractiveObjectEx:Event_UnHide() self:Hide(0); self:ActivateOutput( "UnHide", true ); end; function InteractiveObjectEx:Event_EnableUsable() self.bUsable=1; self:ActivateOutput( "Enabled", true ); end; function InteractiveObjectEx:Event_DisableUsable() self.bUsable=0; self:ActivateOutput( "Disabled", true ); end; function InteractiveObjectEx:Event_Reset() Game.ResetEntity(self.id); self:ActivateOutput( "Reset", true ); end; ------------------------------------------------------------------------------------------------------ -- Flow events. ------------------------------------------------------------------------------------------------------ InteractiveObjectEx.FlowEvents = { Inputs = { Use = { InteractiveObjectEx.Event_Use, "bool" }, UserId = { InteractiveObjectEx.Event_UserId, "entity" }, Hide = { InteractiveObjectEx.Event_Hide, "bool" }, UnHide = { InteractiveObjectEx.Event_UnHide, "bool" }, Enable = { InteractiveObjectEx.Event_EnableUsable, "bool" }, Disable = { InteractiveObjectEx.Event_DisableUsable, "bool" }, Reset = { InteractiveObjectEx.Event_Reset, "bool" }, }, Outputs = { Started = "bool", Finished = "bool", Aborted = "bool", Enabled = "bool", Disabled = "bool", Hide = "bool", UnHide = "bool", Reset = "bool", UsedBy = "entity" }, } MakeUsable(InteractiveObjectEx); function InteractiveObjectEx:IsUsable(user) if self.bUsable ~= 0 then -- returns 0 if cannot use, otherwise returns action index + 1 return self.interactiveObject:CanUse(user.id); else return 0; end end function InteractiveObjectEx:OnUsed(user, idx) self.interactiveObject:Use(user.id); self:ActivateOutput( "UsedBy", user.id ); self:ActivateOutput( "Started", true ); BroadcastEvent(self, "Used"); end; function InteractiveObjectEx:StopUse(user, idx) self.interactiveObject:StopUse(user); self:ActivateOutput( "Finished", true ); end; function InteractiveObjectEx:AbortUse(user) self.interactiveObject:AbortUse(); self:ActivateOutput( "Aborted", true ); end;
-- Copyright 2017-2018 Dirk Brenken (dev@brenken.org) -- This is free software, licensed under the Apache License, Version 2.0 module("luci.controller.travelmate", package.seeall) local util = require("luci.util") local i18n = require("luci.i18n") local templ = require("luci.template") function index() if not nixio.fs.access("/etc/config/travelmate") then return end entry({"admin", "services", "travelmate"}, firstchild(), _("Travelmate"), 40).dependent = false entry({"admin", "services", "travelmate", "tab_from_cbi"}, cbi("travelmate/overview_tab", {hideresetbtn=true, hidesavebtn=true}), _("Overview"), 10).leaf = true entry({"admin", "services", "travelmate", "stations"}, template("travelmate/stations"), _("Wireless Stations"), 20).leaf = true entry({"admin", "services", "travelmate", "apqr"}, template("travelmate/ap_qr"), _("AP QR-Codes"), 30).leaf = true entry({"admin", "services", "travelmate", "logfile"}, call("logread"), _("View Logfile"), 40).leaf = true entry({"admin", "services", "travelmate", "advanced"}, firstchild(), _("Advanced"), 100) entry({"admin", "services", "travelmate", "advanced", "configuration"}, cbi("travelmate/configuration_tab"), _("Edit Travelmate Configuration"), 110).leaf = true entry({"admin", "services", "travelmate", "advanced", "cfg_wireless"}, cbi("travelmate/cfg_wireless_tab"), _("Edit Wireless Configuration"), 120).leaf = true entry({"admin", "services", "travelmate", "advanced", "cfg_network"}, cbi("travelmate/cfg_network_tab"), _("Edit Network Configuration"), 130).leaf = true entry({"admin", "services", "travelmate", "advanced", "cfg_firewall"}, cbi("travelmate/cfg_firewall_tab"), _("Edit Firewall Configuration"), 140).leaf = true entry({"admin", "services", "travelmate", "wifiscan"}, template("travelmate/wifi_scan")).leaf = true entry({"admin", "services", "travelmate", "wifiadd"}, cbi("travelmate/wifi_add", {hideresetbtn=true, hidesavebtn=true})).leaf = true entry({"admin", "services", "travelmate", "wifiedit"}, cbi("travelmate/wifi_edit", {hideresetbtn=true, hidesavebtn=true})).leaf = true entry({"admin", "services", "travelmate", "wifidelete"}, cbi("travelmate/wifi_delete", {hideresetbtn=true, hidesavebtn=true})).leaf = true entry({"admin", "services", "travelmate", "wifiorder"}, cbi("travelmate/wifi_order", {hideresetbtn=true, hidesavebtn=true})).leaf = true end function logread() local logfile if nixio.fs.access("/var/log/messages") then logfile = util.trim(util.exec("grep -F 'travelmate-' /var/log/messages")) else logfile = util.trim(util.exec("logread -e 'travelmate-'")) end templ.render("travelmate/logread", {title = i18n.translate("Travelmate Logfile"), content = logfile}) end
--[[ encoding: UTF-8 -- 中文互联网上迄今为止实现最正确、代码最漂亮且效率最高的大写人民币金额转换代码 -- Lua 5.1+ 版本 -- 作者:李维 <oldrev@gmail.com> -- 版权所有 (c) 2013 李维。保留所有权利。 -- 本代码基于 BSD License 授权。 --]] module("rmbupper", package.seeall) local _RMB_DIGITS = {'零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' } local _SECTION_CHARS = {'', '拾', '佰', '仟', '万' } local function _parse_integer(strio, value, zero_count, is_first_section) assert(value > 0 and value <= 9999) local ndigits = math.floor(math.log10(value)) + 1 if value < 1000 and not is_first_section then zero_count = zero_count + 1 end for i = 1, ndigits do local factor = math.floor(math.pow(10, (ndigits - i))) local digit = math.floor(value / factor) if digit > 0 then if zero_count > 0 then table.insert(strio, '零') end table.insert(strio, _RMB_DIGITS[digit + 1]) table.insert(strio, _SECTION_CHARS[ndigits - i + 1]) zero_count = 0 else zero_count = zero_count + 1 end value = value - math.floor(value / factor) * factor end return zero_count end local function _parse_decimal(strio, integer_part, value, zero_count) assert(value > 0 and value <= 99) local jiao = math.floor(value / 10) local fen = value % 10 if zero_count > 0 and (jiao > 0 or fen > 0) and integer_part > 0 then table.insert(strio, '零') end if jiao > 0 then table.insert(strio, _RMB_DIGITS[jiao + 1]) table.insert(strio, '角') end if zero_count == 0 and jiao == 0 and fen > 0 and integer_part > 0 then table.insert(strio, '零') end if fen > 0 then table.insert(strio, _RMB_DIGITS[fen + 1]) table.insert(strio, '分') else table.insert(strio, '整') end end function to_rmb_upper(price) local integer_part = math.floor(price) local wanyi_part = math.floor(integer_part / 1000000000000) local yi_part = math.floor(integer_part % 1000000000000 / 100000000) local wan_part = math.floor(integer_part % 100000000 / 10000) local qian_part = integer_part % 10000 local dec_part = math.floor(price * 100 % 100) local strio = {} local zero_count = 0 --处理万亿以上的部分 if integer_part >= 1000000000000 and wanyi_part > 0 then zero_count = _parse_integer(strio, wanyi_part, zero_count, true) table.insert(strio, '万') end --处理亿到千亿的部分 if integer_part >= 100000000 and yi_part > 0 then local is_first_section = integer_part >= 100000000 and integer_part < 1000000000000 zero_count = _parse_integer(strio, yi_part, zero_count, is_first_section) table.insert(strio, '亿') end --处理万的部分 if integer_part >= 10000 and wan_part > 0 then local is_first_section = integer_part >= 1000 and integer_part < 10000000 zero_count = _parse_integer(strio, wan_part, zero_count, is_first_section) table.insert(strio, '万') end --处理千及以后的部分 if qian_part > 0 then local is_first_section = integer_part < 1000 zero_count = _parse_integer(strio, qian_part, zero_count, is_first_section) else zero_count = zero_count + 1 end if integer_part > 0 then table.insert(strio, '元') end --处理小数 if dec_part > 0 then _parse_decimal(strio, integer_part, dec_part, zero_count) elseif dec_part == 0 and integer_part > 0 then table.insert(strio, '整') else table.insert(strio, '零元整') end return table.concat(strio, "") end
-------------------------------- -- @module ShatteredTiles3D -- @extend TiledGrid3DAction -- @parent_module cc -------------------------------- -- creates the action with a range, whether of not to shatter Z vertices, a grid size and duration -- @function [parent=#ShatteredTiles3D] create -- @param self -- @param #float duration -- @param #size_table gridSize -- @param #int range -- @param #bool shatterZ -- @return ShatteredTiles3D#ShatteredTiles3D ret (return value: cc.ShatteredTiles3D) -------------------------------- -- -- @function [parent=#ShatteredTiles3D] clone -- @param self -- @return ShatteredTiles3D#ShatteredTiles3D ret (return value: cc.ShatteredTiles3D) -------------------------------- -- -- @function [parent=#ShatteredTiles3D] update -- @param self -- @param #float time return nil
ReactCurrentOwner = require "ReactCurrentOwner" do print(ReactCurrentOwner.current) ReactCurrentOwner.current = "Fiber" print(ReactCurrentOwner.current) ReactCurrentOwner = require "ReactCurrentOwner" print(ReactCurrentOwner.current) end
--逆旋的有顶天 local m=14050020 local cm=_G["c"..m] function cm.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --tohand local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(m,0)) e2:SetCategory(CATEGORY_TODECK+CATEGORY_TOHAND) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_PHASE+PHASE_END) e2:SetRange(LOCATION_SZONE) e2:SetCountLimit(1) e2:SetCondition(cm.tdcon) e2:SetTarget(cm.tdtg) e2:SetOperation(cm.tdop) c:RegisterEffect(e2) --cannot be destroyed local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_INDESTRUCTABLE) e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e3:SetRange(LOCATION_SZONE) e3:SetValue(1) c:RegisterEffect(e3) end function cm.filter(c) return c:IsCode(0x46) and c:IsFaceup() end function cm.tdcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()~=tp end function cm.tdtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetFieldGroup(tp,LOCATION_HAND,0) local g1=Duel.GetFieldGroup(tp,LOCATION_GRAVE,0) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g1,1,0,0) end function cm.tdop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local ct=Duel.GetCounter(c:GetControler(),1,0,0x245) if not c:IsRelateToEffect(e) or ct==0 then return end local g=Duel.GetFieldGroup(tp,LOCATION_HAND,0) local g1=Duel.GetFieldGroup(tp,LOCATION_GRAVE,0) if Duel.SendtoDeck(g,nil,2,REASON_EFFECT)==0 then return end Duel.SendtoHand(g1,nil,REASON_EFFECT) end
local skynet = require "skynet" local log = require "log" local M = {} local runconf = require(skynet.getenv("runconfig")) local moveconf = runconf.ddz local MAX_GLOBAL_COUNT = #moveconf.global local function fetch_global(id) local index = id % MAX_GLOBAL_COUNT + 1 return moveconf.global[index] end local function call(cmd, id, ...) local global = fetch_global(id) if not global then ERROE("cmd:"..cmd..",id:"..id.." is nil") return false end return skynet.call(global, "lua", cmd, id, ...) end function M.create(id) DEBUG("libddz begin") local ret=call("ddz.create", id) DEBUG("libddz end") return ret end function M.enter(id, uid, data) return call("ddz.enter", id, uid, data) end function M.leave(id, uid) return call("ddz.leave", id, uid) end function M.get_forward(id) return fetch_global(id) end return M
-- Note: starting with Redis 5, the replication method described in this section (scripts effects replication) is the default and does not need to be explicitly enabled. redis.replicate_commands(); local namespace = KEYS[1]; local serviceId = ARGV[1]; local instanceId = ARGV[2]; local instanceIdxKey = namespace .. ':svc_itc_idx:' .. serviceId; local function getInstanceKey(instanceId) return namespace .. ":svc_itc:" .. instanceId; end local function ensureNotExpired(instanceIdxKey, instanceId) local instanceKey = getInstanceKey(instanceId); local instanceTtl = redis.call("ttl", instanceKey); -- -2: The key doesn't exist | -1: The key is fixed | >0: ttl(second) if instanceTtl == -2 then local removed = redis.call("srem", instanceIdxKey, instanceId); if removed > 0 then redis.call("publish", instanceKey, "expired"); end end return instanceTtl; end local instanceTtl = ensureNotExpired(instanceIdxKey, instanceId); if instanceTtl == -1 or instanceTtl == -2 then return instanceTtl; end local nowTime = redis.call('time')[1]; local ttlAt = nowTime + instanceTtl; return ttlAt;
tamed_huurton = Creature:new { objectName = "@mob/creature_names:rebel_tamed_huurton", socialGroup = "rebel", faction = "rebel", level = 12, chanceHit = 0.29, damageMin = 130, damageMax = 140, baseXp = 514, baseHAM = 1200, baseHAMmax = 1400, armor = 0, resists = {10,10,10,10,10,10,10,-1,-1}, meatType = "meat_wild", meatAmount = 12, hideType = "hide_wooly", hideAmount = 12, boneType = "bone_mammal", boneAmount = 12, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + HERD, optionsBitmask = AIENABLED, diet = CARNIVORE, templates = {"object/mobile/huurton_hue.iff"}, hues = { 0, 1, 2, 3, 4, 5, 6, 7 }, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { } } CreatureTemplates:addCreatureTemplate(tamed_huurton, "tamed_huurton")
--$Name: Волк, коза и якудза.$ --$Version: 0.1$ instead_version "1.8.1"; require "xact" require "para" require "dash" -- если для объекта не прописана реакция, то реагировать будем так: game.act = "Ничего не произошло."; -- если нажали на объект на сцене game.inv = "И откуда это у меня?"; -- если применили объект из инвентаря сам на себя game.use = "Так не пойдёт."; -- если применили объект на другой объект --------------------------------------------------------------------------------------------------- -- этот код демонстрирует: -- задание собственной функции -- определение кто где находится --------------------------------------------------------------------------------------------------- -- проблемы: -- если на плоту нет никого, кто мог бы им управлять, то пропадает описание объектов -- как правильно разрулить запятые в конце списка людей на берегу? -- после победы остаётся последнее сообщение, типа: 'папа сошёл на берег' -- можно ли сократить игру, если использовать наследование, которое пригодится в следующей игре? -- как ещё можно улучшить код? --------------------------------------------------------------------------------------------------- -- добавлено для совместимости xwalk = xact('xact', code [[ stead.walk(arg1) ]]); -------------------------------------------------------------------------------------------------- function desc(t) -- выводим описание объекта с запятой или точкой в конце return function(s) pr(t) if objs()[#objs()] == s then -- последний? p '.' else p ',' end end end --------------------------------------------------------------------------------------------------- function pereprava() -- переправляемся на другой берег if not (have(mama) or have(papa) or have(pol)) then p 'На плоту нет никого, кто мог бы им управлять!'; return; end; if ((where(papa) == where(tanya)) or (where(papa) == where(masha))) and (where(papa) ~= where(mama)) then p 'Нельзя оставлять папу с любой из дочерей без присмотра мамы!'; return; end; if ((where(mama) == where(vanya)) or (where(mama) == where(boris))) and (where(mama) ~= where(papa)) then p 'Нельзя оставлять маму с любым из сыновей без присмотра папы!'; return; end; if ((where(zak) == where(tanya)) or (where(zak) == where(masha)) or (where(zak) == where(vanya)) or (where(zak) == where(boris)) or (where(zak) == where(mama)) or (where(zak) == where(papa))) and (where(zak) ~= where(pol)) then p 'Нельзя оставлять преступника с любым из членов семьи без присмотра полицейского!'; return; end; if here()==LeftBank then walk(RightBank); else walk(LeftBank); end; end; --------------------------------------------------------------------------------------------------- function shod(s) -- персонаж выходит на берег plot._n = plot._n-1; if here()== LeftBank then LeftBank._n = LeftBank._n+1; else RightBank._n = RightBank._n+1; end; drop(s); if RightBank._n == 8 then pclr(); walk(FinalRoom); end; end; --------------------------------------------------------------------------------------------------- function zahod(s) -- персонаж заходит на плот if plot._n<2 then plot._n = plot._n+1; else p 'На плоту могут поместиться только два человека.'; return; end; if here(pl)== LeftBank then LeftBank._n = LeftBank._n-1; else RightBank._n = RightBank._n-1; end; return true; end; --------------------------------------------------------------------------------------------------- plot = obj { _n = 0; nam = 'плот'; inv = pereprava; } --------------------------------------------------------------------------------------------------- main = room { nam = 'Волк, коза и якудза'; dsc = [[ Представляю Вашему вниманию японскую головоломку, на подобии "волк, коза и капуста". ^ Неблагополучная семья, и полицейский с заключённым направляются в исправительное поселение. В игре время не ограничено, но для получения максимального фана от игры-головоломки, рекомендую засечь время. Интересно, как быстро Вы сможете её решить?^^ Цель игры:^ Перевести группу из 8-ми человек через реку. Когда все будут на другом берегу -- победа ваша.^^ Правила следущие:^ Перебраться через реку можно только на плоту. Одновременно на плоту помещаются не более 2-х человек. Управлять плотом умеют только родители и полисмен. Нельзя оставлять заключённого с членами семьи без присмотра полицейского. Нельзя оставлять папу с дочками без присмотра мамы. Нельзя оставлять маму с сыновьями без присмотра папы.^^ {xwalk(LeftBank)| Начать игру}]]; exit = function() take('plot'); -- put('mama','LeftBank'); put('tanya','LeftBank'); put('masha','LeftBank'); put('papa','LeftBank'); put('vanya','LeftBank'); put('boris','LeftBank'); put('zak','LeftBank'); put('pol','LeftBank'); -- plot._n = 0; LeftBank._n = 8; RightBank._n = 0; end; } --------------------------------------------------------------------------------------------------- LeftBank = room { _n = 8; nam = 'Левый берег'; dsc = 'Цель игры -- перевезти всех на правый берег.'; obj = { 'bereg'; }; } --------------------------------------------------------------------------------------------------- bereg = obj{ nam = 'берег'; dsc = function() if here()._n==0 then p 'На этом {берегу} никого нет.'; elseif here()._n == 1 then p 'На {берегу} находится:'; else p 'На {берегу} находятся:'; end; end; act = 'Кого вы хотите высадить на берег?'; } --------------------------------------------------------------------------------------------------- mama = obj { nam = 'мама'; dsc = desc'{мама}'; tak = function(s) if zahod(s)==true then p('Мама зашла на плот.'); else return false; end; end; inv = 'Мама умеет управлять плотом, маму нельзя оставлять с сыновьями без присмотра папы.'; use = function(s,w) if w == bereg then p 'Мама сошла на берег.'; shod(s); elseif w == plot then if pereprava() then p 'Мама переправила плот на другой берег.'; end; else p 'Вы можете высаживать людей на берег.'; end; end; } --------------------------------------------------------------------------------------------------- tanya = obj { nam = 'Таня'; dsc = desc'{Таня}'; tak = function() if zahod(s)==true then p('Таня зашла на плот.'); else return false; end; end; inv = 'Таня -- дочь мамы и папы.'; use = function(s,w) if w == bereg then p 'Таня сошла на берег.'; shod(s); elseif w == plot then p 'Таня не умеет управлять плотом.'; else p 'Вы можете высаживать людей на берег.'; end; end; } --------------------------------------------------------------------------------------------------- masha = obj { nam = 'Маша'; dsc = desc'{Маша}'; tak = function() if zahod(s)==true then p('Маша зашла на плот.'); else return false; end; end; inv = 'Маша -- дочь мамы и папы.'; use = function(s,w) if w == bereg then p 'Маша сошла на берег.'; shod(s); elseif w == plot then p 'Маша не умеет управлять плотом.'; else p 'Вы можете высаживать людей на берег.'; end; end; } --------------------------------------------------------------------------------------------------- papa = obj { nam = 'папа'; dsc = desc'{папа}'; tak = function() if zahod(s)==true then p('Папа зашёл на плот.'); else return false; end; end; inv = 'Папа умеет управлять плотом, папу нельзя оставлять с дочерьми без присмотра мамы.'; use = function(s,w) if w == bereg then p 'Папа сошёл на берег.'; shod(s); elseif w == plot then if pereprava() then p 'Папа переправил плот на другой берег.'; end; else p 'Вы можете высаживать людей на берег.'; end; end; } --------------------------------------------------------------------------------------------------- vanya = obj { nam = 'Ваня'; dsc = desc'{Ваня}'; tak = function() if zahod(s)==true then p('Ваня зашёл на плот.'); else return false; end; end; inv = 'Ваня -- сын мамы и папы.'; use = function(s,w) if w == bereg then p 'Ваня сошёл на берег.'; shod(s); elseif w == plot then p 'Ваня не умеет управлять плотом.'; else p 'Вы можете высаживать людей на берег.'; end; end; } --------------------------------------------------------------------------------------------------- boris = obj { nam = 'Борис'; dsc = desc'{Борис}'; tak = function() if zahod(s)==true then p('Борис зашёл на плот.'); else return false; end; end; inv = 'Борис -- сын мамы и папы.'; use = function(s,w) if w == bereg then p 'Борис сошёл на берег.'; shod(s); elseif w == plot then p 'Борис не умеет управлять плотом.'; else p 'Вы можете высаживать людей на берег.'; end; end; } --------------------------------------------------------------------------------------------------- zak = obj { nam = 'преступник'; dsc = desc'{преступник}'; tak = function() if zahod(s)==true then p('Преступник зашёл на плот.'); else return false; end; end; inv = 'Преступника нельзя оставлять с любым из членов семьи без присмотра полицейского.'; use = function(s,w) if w == bereg then p 'Преступник сошёл на берег.'; shod(s); elseif w == plot then p 'Преступник не умеет управлять плотом.'; else p 'Вы можете высаживать людей на берег.'; end; end; } --------------------------------------------------------------------------------------------------- pol = obj { nam = 'полицейский'; dsc = desc'{полицейский}'; tak = function() if zahod(s)==true then p('Полицейский зашёл на плот.'); else return false; end; end; inv = 'Полицейский умеет управлять плотом.'; use = function(s,w) if w == bereg then p 'Полицейский сошёл на берег.'; shod(s); elseif w == plot then if pereprava() then p 'Полицейский переправил плот на другой берег.'; end; else p 'Вы можете высаживать людей на берег.'; end; end; } --------------------------------------------------------------------------------------------------- RightBank = room { _n=0; -- сколько человек уже на правом берегу nam = 'Правый берег'; obj = { 'bereg'; }; } --------------------------------------------------------------------------------------------------- FinalRoom = room { nam = 'Победа'; dsc = [[Поздравляю, вы решили эту головоломку! ^^И зэк с копом, и вся неблагополучная семейка успешно добрались до исправительного поселения Бобруйск-2050.^^Конец.]]; } --------------------------------------------------------------------------------------------------- -- на плоту могут поместиться только два человека -- переправа: -- на плоту должен находиться кто-то, кто может им управлять -- маму нельзя оставлять с сыновьями без присмотра папы -- папу нельзя оставлять с дочерьми без присмотра мамы -- зека нельзя оставлять с членами семьи без присмотра полицейского
--gameLevel2 local LevelBase = require 'gamestates.LevelBase' local gameLevel2 = LevelBase:extend() local Player = require 'objects.Player' local Enemy = require 'objects.Enemy' local Gate = require 'objects.Gate' local player=nil local weapon=nil local enemy=nil local gate=nil ENTITIES={} function gameLevel2:new() gameLevel2.super.new(self,'levels/level_2.lua') end function gameLevel2:enter() if PLAYER.player == nil then player = Player(self.world, 0,0) PLAYER.player = player else player = PLAYER.player player:transfer(self.world) end for i, p in ipairs(self.map.layers.entities.objects) do if p.name == "spawn_player" then player.world:update(player,p.x,p.y) player.x=p.x player.y=p.y self.Entities:addMany(player:components()) elseif p.name == "spawn_enemy" then enemy = Enemy(self.world, p.x,p.y, player) self.Entities:addMany(enemy:components()) elseif p.name == "door_level_1" then gate = Gate(self.world,p.x,p.y) self.Entities:add(gate) elseif p.name == "door_level_=dummy" then local gate = Gate(self.world,p.x,p.y) gate.active = false self.Entities:add(gate) end end ENTITIES = self.Entities end function gameLevel2:update(dt) if LDR.finishedLoading then if gate.proceed then --self.Entities:clear() -- return Gamestate.switch(LEVELS.GameLevel1.level()) end self.map:update(dt) self.Entities:update(dt) self:positionCamera(player, camera) --print( table.getn(self.Entities.entityList) ) end end function gameLevel2:draw() if LDR.finishedLoading then camera:set() self.map:draw(-camera.x,-camera.y) self.Entities:draw() camera:unset() end end function gameLevel2:keypressed(key) gameLevel2.super:keypressed(key) if key == 'x' then local x,y = love.mouse.getPosition() x = math.floor(x/32)*32 y = math.floor(y/32)*32 enemy = Enemy(self.world, x, y, player) self.Entities:addMany(enemy:components()) end player:keypressed(key) end return gameLevel2
------------------------ -- Configuration keeper ------------------------ local _M = {} local sep = "/" if WIN32 then sep = "\\" end local FILENAME = _USERHOME..sep.."spellchecker.conf" _M.ON = 2 _M.OFF = 1 function _M:load() local handle = io.open(FILENAME, "r") if not handle then return end for line in handle:lines() do key, val = line:match("([^=]+)=(.+)") if key then self[key] = tonumber(val) or val end end handle:close() end function _M:save() local handle = io.open(FILENAME, "w") if handle then for key, val in pairs(self) do if type(val) == "string" or type(val) == "number" then handle:write(tostring(key).."="..tostring(val).."\n") end end handle:close() end end local function shutdown() _M:save() end function _M.init() _M:load() events.connect(events.RESET_BEFORE, shutdown) events.connect(events.QUIT, shutdown) end return _M
local pug = {} pug["!!!"] = "{doctype html}" return pug
--------------------------------------------------------------- -- Copyright 2020 Deviap (https://deviap.com/) -- --------------------------------------------------------------- -- Made available under the MIT License: -- -- https://github.com/deviap/sample-apps/blob/master/LICENSE -- --------------------------------------------------------------- -- local serialiser = require("devgit:source/serialiser/main.lua") serialiser.fromFile("client/assets/starterScene.json") --core.io:write("client/assets/starterScene.json", serialiser.toJSON(core.scene))
local brick = Instance.new("Part") brick.BrickColor = BrickColor.new("Brown") brick.Parent = game.Workspace.acb227 brick.Name = "Right Arm" brick.Size = Vector3.new(2, 2, 2) brick.Position = Vector3.new(-5, 1, 17) brick.Anchored = false brick.CanCollide = true brick.Locked = true brick.Material = "Plastic" brick.Shape = "Cylinder" brick.TopSurface = "Smooth" brick.BottomSurface = "Smooth" brick.LeftSurface = "Hinge" --h = Instance.new("BlockMesh") --h.Scale = Vector3.new(1, 1, 1) --h.Offset = Vector3.new(0, 0, 0) --h.Parent = brick local brick = Instance.new("Part") brick.BrickColor = BrickColor.new("Brown") brick.Parent = game.Workspace.acb227 brick.Name = "Right Arm" brick.Size = Vector3.new(2, 2, 2) brick.Position = Vector3.new(-5, 1, 0) brick.Anchored = false brick.CanCollide = true brick.Locked = true brick.Material = "Plastic" brick.Shape = "Cylinder" brick.TopSurface = "Smooth" brick.BottomSurface = "Smooth" brick.LeftSurface = "Hinge" --h = Instance.new("BlockMesh") --h.Scale = Vector3.new(1, 1, 1) --h.Offset = Vector3.new(0, 0, 0) --h.Parent = brick local brick = Instance.new("Part") brick.BrickColor = BrickColor.new("Brown") brick.Parent = game.Workspace.acb227 brick.Name = "Right Arm" brick.Size = Vector3.new(2, 2, 2) brick.Position = Vector3.new(-17, 1, 17) brick.Anchored = false brick.CanCollide = true brick.Locked = true brick.Material = "Plastic" brick.Shape = "Cylinder" brick.TopSurface = "Smooth" brick.BottomSurface = "Smooth" brick.RightSurface = "Hinge" --------------------------------------------------- local brick = Instance.new("Part") brick.BrickColor = BrickColor.new("Brown") brick.Parent = game.Workspace.acb227 brick.Name = "Right Arm" brick.Size = Vector3.new(2, 2, 2) brick.Position = Vector3.new(-17, 1, 0) brick.Anchored = false brick.CanCollide = true brick.Locked = true brick.Material = "Plastic" brick.Shape = "Cylinder" brick.TopSurface = "Smooth" brick.BottomSurface = "Smooth" brick.RightSurface = "Hinge" ------------------------------------------------------- local brick1 = Instance.new("Part") brick1.BrickColor = BrickColor.new("Brown") brick1.Parent = game.Workspace.acb227 brick1.Name = "Right Arm" brick1.Size = Vector3.new(10, 1, 19) brick1.Position = Vector3.new(-11, 2.5, 8.5) brick1.Anchored = false brick1.CanCollide = true brick1.Locked = true brick1.TopSurface = "Weld" brick1.BottomSurface = "Smooth" -------------------------------------------------- local brick = Instance.new("VehicleSeat") brick2.BrickColor = BrickColor.new("Brown") brick2.Parent = game.Workspace.acb227 brick2.Name = "Right Arm" brick2.Size = Vector3.new(2, 1, 2) brick2.Position = Vector3.new(-11, 3, 8.5) brick2.CanCollide = true brick2.Locked = true brick2.TopSurface = "Smooth" brick2.BottomSurface = "Weld"
local network = {} function network.isLocalWiFiAvailable() return CCNetwork:isLocalWiFiAvailable() end function network.isInternetConnectionAvailable() return CCNetwork:isInternetConnectionAvailable() end function network.isHostNameReachable(hostname) if type(hostname) ~= "string" then echoError("network.isHostNameReachable() - invalid hostname %s", tostring(hostname)) return false end return CCNetwork:isHostNameReachable(hostname) end function network.getInternetConnectionStatus() return CCNetwork:getInternetConnectionStatus() end function network.createHTTPRequest(callback, url, method) if not method then method = "GET" end if string.upper(tostring(method)) == "GET" then method = kCCHTTPRequestMethodGET else method = kCCHTTPRequestMethodPOST end return CCHTTPRequest:createWithUrl(callback, url, method) end --- Upload a file through a CCHTTPRequest instance. -- @author zrong(zengrong.net) -- Creation: 2014-04-14 -- @param callback As same as the first parameter of network.createHTTPRequest. -- @param url As same as the second parameter of network.createHTTPRequest. -- @param datas Includes following values: -- fileFiledName(The input label name that type is file); -- filePath(A absolute path for a file) -- contentType(Optional, the file's contentType, default is application/octet-stream) -- extra(Optional, the key-value table that transmit to form) -- for example: --[[ network.uploadFile(function(evt) if evt.name == "completed" then local request = evt.request printf("REQUEST getResponseStatusCode() = %d", request:getResponseStatusCode()) printf("REQUEST getResponseHeadersString() =\n%s", request:getResponseHeadersString()) printf("REQUEST getResponseDataLength() = %d", request:getResponseDataLength()) printf("REQUEST getResponseString() =\n%s", request:getResponseString()) end end, "http://127.0.0.1/upload.php", { fileFieldName="filepath", filePath=device.writablePath.."screen.jpg", contentType="Image/jpeg", extra={ {"act", "upload"}, {"submit", "upload"}, } } ) ]] -- function network.uploadFile(callback, url, datas) assert(datas or datas.fileFieldName or datas.filePath, "Need file datas!") local request = network.createHTTPRequest(callback, url, "POST") local fileFieldName = datas.fileFieldName local filePath = datas.filePath local contentType = datas.contentType if contentType then request:addFormFile(fileFieldName, filePath, contentType) else request:addFormFile(fileFieldName, filePath) end if datas.extra then for i in ipairs(datas.extra) do local data = datas.extra[i] request:addFormContents(data[1], data[2]) end end request:start() return request end local function parseTrueFalse(t) t = string.lower(tostring(t)) if t == "yes" or t == "true" then return true end return false end function network.makeCookieString(cookie) local arr = {} for name, value in pairs(cookie) do if type(value) == "table" then value = tostring(value.value) else value = tostring(value) end arr[#arr + 1] = tostring(name) .. "=" .. string.urlencode(value) end return table.concat(arr, "; ") end function network.parseCookie(cookieString) local cookie = {} local arr = string.split(cookieString, "\n") for _, item in ipairs(arr) do item = string.trim(item) if item ~= "" then local parts = string.split(item, "\t") -- ".amazon.com" represents the domain name of the Web server that created the cookie and will be able to read the cookie in the future -- TRUE indicates that all machines within the given domain can access the cookie -- "/" denotes the path within the domain for which the variable is valid -- "FALSE" indicates that the connection is not secure -- "2082787601" represents the expiration date in UNIX time (number of seconds since January 1, 1970 00:00:00 GMT) -- "ubid-main" is the name of the cookie -- "002-2904428-3375661" is the value of the cookie local c = { domain = parts[1], access = parseTrueFalse(parts[2]), path = parts[3], secure = parseTrueFalse(parts[4]), expire = toint(parts[5]), name = parts[6], value = string.urldecode(parts[7]), } cookie[c.name] = c end end return cookie end return network
--[[ MIT License Copyright (c) 2018 JWRR.COM git clone https://github.com/jwrr/lued.git 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. --]] function lued.def_snippet(snippets, key_str, fn) local keys = lued.explode(key_str, " ") for i=1,#keys do local key = keys[i] snippets[key] = fn end end function lued.is_snippet(haystack, plain_text) haystack = " " .. haystack .. " " plain_text = " " .. plain_text .. " " -- lued.dbg_prompt("haystack=") -- ..haystack.."++plain_text="..plain_text.."++") return string.find( haystack , plain_text , 1 , plain) end function lued.handle_snippets() local filetype = lued.get_filetype() if not lued.snippets[filetype] then return false end local dd2 = 1 local r,c=get_cur_pos() lued.sel_left_pattern( "[%w_.#*()^+*:!]" , dd2) local sel_str, sel_sr, sel_sc = lued.get_sel_str() if sel_str==nil or sel_str=='' then return false end if not lued.snippets[filetype][sel_str] then set_sel_off() set_cur_pos(r,c) return false end lued.del_sel(dd2) set_cur_pos(sel_sr,sel_sc) local cnt = 0 local tok, ii = lued.get_token(sel_str, 1) repeat local snippet_routine = lued.snippets[filetype][sel_str] if snippet_routine then g_dont_display = 1 snippet_routine(tok) g_dont_display = 0 end tok, ii = lued.get_token(sel_str,ii) cnt = cnt + 1 until tok == "" or cnt == 5 -- lued.disp(dd) return true end
local playsession = { {"liqwid", {1443253}}, {"rlidwka", {1473558}}, {"Dofolo", {204902}}, {"ksb4145", {249716}}, {"rbas333", {905660}}, {"tyssa", {995011}}, {"zzHz", {581511}}, {"greattohave", {321671}}, {"foggyliziouz", {935876}}, {"Morkol", {6212}}, {"Liutio", {708037}}, {"helic99", {1218614}}, {"weziscool10", {466}}, {"bakstar000", {330}}, {"Commander_Power", {11958}}, {"pickles28", {35995}}, {"ausmister", {913955}}, {"Ride2die", {4731}}, {"PhaseMachine", {906865}}, {"mewmew", {18355}}, {"greggk124", {5343}}, {"firstandlast", {376231}}, {"HYPPS", {286981}}, {"Bricktator", {7887}}, {"dorpdorp", {8155}}, {"banakeg", {23474}}, {"WD_STEVE2", {64241}}, {"Ed9210", {706927}}, {"David_686", {8975}}, {"factoroi", {598916}}, {"Nikkichu", {553528}}, {"Devildog", {45099}}, {"jrz126", {3592}}, {"antuan309", {31415}}, {"463851425", {143371}}, {"realDonaldTrump", {229411}}, {"Altot", {25183}}, {"matthew1206", {613138}}, {"lazerandy", {12373}}, {"Random-Dud", {55097}}, {"antiPETA", {43734}}, {"BadAtNoScoping", {12862}}, {"Sirnumnum", {311182}}, {"Miguel724", {379202}}, {"tmoneyfizzle", {141025}}, {"petebra11", {455859}}, {"zlema01", {100938}}, {"OmegaLunch", {440252}}, {"TriggerFinger", {5226}}, {"waxman", {90549}}, {"Patton1918", {9612}}, {"IndustrialGradeCow", {4098}}, {"Beetle426", {181341}}, {"MrCrazy", {259609}}, {"Mr_T", {233213}}, {"gmhinch", {230982}}, {"vad7ik", {216917}}, {"T0eknee", {1563}}, {"jagger23", {185690}}, {"GreenTree42", {13253}}, {"2117882862", {5543}}, {"Achskelmos", {72467}}, {"ballbuster", {28663}} } return playsession
a = {} a.x = 1 a.y = 0 b = {} b.x = 1 b.y = 0 c = a print(a == c) print(a ~= b)
local Prop = {} Prop.Name = "Nº17 Rua Gole de Skol" Prop.Cat = "House" Prop.Price = 340 Prop.Doors = { Vector(563, 407, -142), Vector(694, 404, -114), } GM.Property:Register( Prop )
-- If you're not sure your plugin is executing, uncomment the line below and restart Kong -- then it will throw an error which indicates the plugin is being loaded at least. --assert(ngx.get_phase() == "timer", "The world is coming to an end!") -- Grab pluginname from module name local plugin_name = ({...})[1]:match("^kong%.plugins%.([^%.]+)") -- load the base plugin object and create a subclass local plugin = require("kong.plugins.base_plugin"):extend() local crc32 = ngx.crc32_short -- constructor function plugin:new() plugin.super.new(self, plugin_name) -- do initialization here, runs in the 'init_by_lua_block', before worker processes are forked end --------------------------------------------------------------------------------------------- -- In the code below, just remove the opening brackets; `[[` to enable a specific handler -- -- The handlers are based on the OpenResty handlers, see the OpenResty docs for details -- on when exactly they are invoked and what limitations each handler has. -- -- The call to `.super.xxx(self)` is a call to the base_plugin, which does nothing, except logging -- that the specific handler was executed. --------------------------------------------------------------------------------------------- --[[ handles more initialization, but AFTER the worker process has been forked/created. -- It runs in the 'init_worker_by_lua_block' function plugin:init_worker() plugin.super.init_worker(self) -- your custom code here end --]] --[[ runs in the ssl_certificate_by_lua_block handler function plugin:certificate(plugin_conf) plugin.super.certificate(self) -- your custom code here end --]] --[[ runs in the 'rewrite_by_lua_block' (from version 0.10.2+) -- IMPORTANT: during the `rewrite` phase neither the `api` nor the `consumer` will have -- been identified, hence this handler will only be executed if the plugin is -- configured as a global plugin! function plugin:rewrite(plugin_conf) plugin.super.rewrite(self) -- your custom code here end --]] ---[[ runs in the 'access_by_lua_block' function plugin:access(plugin_conf) plugin.super.access(self) -- your custom code here local json_data = kong.request.get_body() local tmpId = json_data['tmpId'] local alphaUserList = plugin_conf.alphaUserList local use_test_upstream = false if alphaUserList ~= nil and #alphaUserList>0 then for key,value in ipairs(alphaUserList) do kong.log.debug("alphaUserList "..key..":"..value) if value == tmpId then use_test_upstream=true end end end -- 如果该用户不是内测用户,则根据用户id进行分流 if not use_test_upstream then ngx.header["X-Kong-abtest-tmpId"] = tmpId local hash_value = crc32(tmpId) ngx.header["X-Kong-abtest-crc32"] = hash_value local bucket = hash_value % 100 ngx.header["X-Kong-abtest-bucket"] = bucket if bucket <= plugin_conf.percentage then use_test_upstream = true end end if use_test_upstream then -- 设置upstream local ok,err = kong.service.set_upstream(plugin_conf.upstream) if not ok then kong.log.err(err) return end -- 匹配成功添加特定头部方便监控 ngx.header["X-Kong-abtest-upstream"]=plugin_conf.upstream end end --]] ---[[ runs in the 'header_filter_by_lua_block' function plugin:header_filter(plugin_conf) plugin.super.header_filter(self) -- your custom code here, for example; -- ngx.header["Bye-World"] = "this is on the response" end --]] --[[ runs in the 'body_filter_by_lua_block' function plugin:body_filter(plugin_conf) plugin.super.body_filter(self) -- your custom code here end --]] --[[ runs in the 'log_by_lua_block' function plugin:log(plugin_conf) plugin.super.log(self) -- your custom code here end --]] -- set the plugin priority, which determines plugin execution order plugin.PRIORITY = 1000 -- return our plugin object return plugin
-- Copyright 2021 SmartThings -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. --- @type st.zwave.CommandClass local cc = require "st.zwave.CommandClass" --- @type st.zwave.CommandClass.Configuration local Configuration = (require "st.zwave.CommandClass.Configuration")({ version=4 }) local configsMap = require "configurations" local ZWAVE_AEOTEC_MINIMOTE_FINGERPRINTS = { {mfr = 0x0312, prod = 0x0924, model = 0xD001} -- Minoston Wallmote } local function can_handle_minoston_wallmote(opts, driver, device, ...) for _, fingerprint in ipairs(ZWAVE_AEOTEC_MINIMOTE_FINGERPRINTS) do if device:id_match(fingerprint.mfr, fingerprint.prod, fingerprint.model) then return true end end return false end local function update_preferences(driver, device, args) local preferences = configsMap.get_device_parameters(device) if preferences then for id, value in pairs(device.preferences) do if not (args and args.old_st_store) or (args.old_st_store.preferences[id] ~= value and preferences and preferences[id]) then local new_parameter_value = configsMap.to_numeric_value(device.preferences[id]) device:send(Configuration:Set({parameter_number = preferences[id].parameter_number, size = preferences[id].size, configuration_value = new_parameter_value})) end end end end --- Handle preference changes --- --- @param driver st.zwave.Driver --- @param device st.zwave.Device --- @param event table --- @param args local function info_changed(self, device, event, args) if not device:is_cc_supported(cc.WAKE_UP) then update_preferences(self, device, args) end end local function device_init(self, device) device:set_update_preferences_fn(update_preferences) end local function do_configure(driver, device) device:refresh() if not device:is_cc_supported(cc.WAKE_UP) then update_preferences(driver, device) end end local minoston_wallmote = { lifecycle_handlers = { init = device_init, infoChanged = info_changed, doConfigure = do_configure }, can_handle = can_handle_minoston_wallmote, } return minoston_wallmote
local wibox = require("wibox") local gears = require("gears") local awful = require("awful") local theme = require("beautiful") local naughty = require("naughty") local glib = require("lgi").GLib local dpi = theme.xresources.apply_dpi local module = {} local client, screen, mouse = client, screen, mouse local instances = {} local function update_on_signal(c, signal, widget) local sig_instances = instances[signal] if sig_instances == nil then sig_instances = setmetatable({}, {__mode = "k"}) instances[signal] = sig_instances client.connect_signal(signal, function(cl) local widgets = sig_instances[cl] if widgets then for _, w in pairs(widgets) do w.update() end end end) end local widgets = sig_instances[c] if widgets == nil then widgets = setmetatable({}, {__mode = "v"}) sig_instances[c] = widgets end table.insert(widgets, widget) end local glib_context = function(fn) return function(args) glib.idle_add(glib.PRIORITY_DEFAULT_IDLE, function() fn(args) end) end end local function ori(pos) if pos == "left" or pos == "right" then return "v" end return "h" end local function list2map(list) local set = {} for _, l in ipairs(list) do set[l] = true end return set end local function len(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end local function doubleclicked(obj) if obj.doubleclick_timer then obj.doubleclick_timer:stop() obj.doubleclick_timer = nil return true end obj.doubleclick_timer = gears.timer.start_new(0.3, function() obj.doubleclick_timer = nil end) return false end local menu_selection_symbol local menu_marker = function(condition) if condition then return menu_selection_symbol end return "" end local menu_move2tag = function(c, scr) local list = {} local s = scr or awful.screen.focused() local count = 0 for _, t in pairs(s.tags) do if t ~= awful.screen.focused().selected_tag then count = count + 1 local entry = { t.index .. ": " .. t.name .. menu_marker(t.selected) .. " ", function() c:move_to_tag(t) end, } table.insert(list, entry) end end if count > 0 then return list end return nil end local menu_move2screen = function(c) local list = {} local count = 0 for s in screen do local desc = next(s.outputs) or "" if s.index ~= awful.screen.focused().index then count = count + 1 local entry = {s.index .. ": " .. desc .. " ", menu_move2tag(c, s)} table.insert(list, entry) end end if count > 1 then return list end return nil end function module.menu_client(custom_menu, c) local list = {} local list_tags = menu_move2tag(c) if list_tags then table.insert(list, {"move to tag", list_tags}) end local list_screens = menu_move2screen(c) if list_screens then table.insert(list, {"move to screen", list_screens}) end table.insert(list, { "fullscreen" .. menu_marker(c.fullscreen), function() c.fullscreen = not c.fullscreen c:raise() end, }) table.insert(list, { "maximize" .. menu_marker(c.maximized), function() c.maximized = not c.maximized c:raise() end, }) table.insert(list, { "master" .. menu_marker(c == awful.client.getmaster()), function() c:swap(awful.client.getmaster()) end, }) table.insert(list, { "sticky" .. menu_marker(c.sticky), function() c.sticky = not c.sticky end, }) table.insert(list, { "top" .. menu_marker(c.ontop), function() c.ontop = not c.ontop end, }) table.insert(list, { "minimize" .. menu_marker(c.minimized), function() if c.minimized then c.minimized = false c:raise() else c.minimized = true end end, }) table.insert(list, { "floating" .. menu_marker(c.floating), function() c.floating = not c.floating end, }) table.insert(list, { menu_marker(nil) .. "close", function() c:kill() end, }) if custom_menu and len(custom_menu) > 0 then local function generate_menu_entry(e) if e and type(e) == 'table' and e.text then local text = "" if type(e.text) == 'string' then text = e.text end if type(e.text) == 'function' then text = e.text(c) end return { text, function() if e.func then e.func(c) end end, } end end local class = c.class or "" for regex, entries in pairs(custom_menu) do if string.find(class, regex) then for _, e in ipairs(entries) do local menu_entry = generate_menu_entry(e) if menu_entry then table.insert(list, menu_entry) end end end end end return list end local rounded_corner_shape = function(radius, position) if position == "bottom" then return function(cr, width, height) gears.shape.partially_rounded_rect(cr, width, height, false, false, true, true, radius) end elseif position == "top" then return function(cr, width, height) gears.shape.partially_rounded_rect(cr, width, height, true, true, false, false, radius) end end return nil end local add_hot_corner = function(args) args = args or {} local position = args.position or "" local placement = awful.placement[position] if not placement then return end local actions = args.buttons or {} local s = args.screen or awful.screen.focused() local width = args.width local height = args.height local color = args.color local corner = awful.popup({ screen = s, placement = placement, ontop = true, border_width = 0, minimum_height = height, maximum_height = height, minimum_width = width, maximum_width = width, bg = color, widget = wibox.widget.background, }) -- this will run for every screen, so we have to make sure to only add one signal handler for every assigned signal local must_connect_signal = (s.index == 1) local function signal_name(pos, action) return "hot_corners::" .. pos .. "::" .. action end local defs = { {name = "left_click", button = 1}, {name = "middle_click", button = 2}, {name = "right_click", button = 3}, {name = "wheel_up", button = 4}, {name = "wheel_down", button = 5}, {name = "back_click", button = 8}, {name = "forward_click", button = 9}, } local buttons = {} for _, btn in ipairs(defs) do if actions[btn.name] then local signal = signal_name(position, btn.name) table.insert(buttons, awful.button({}, btn.button, function() awesome.emit_signal(signal) end)) if must_connect_signal then awesome.connect_signal(signal, glib_context(actions[btn.name])) end end end corner:buttons(buttons) for _, action in pairs({"enter", "leave"}) do if actions[action] then local signal = signal_name(position, action) corner:connect_signal("mouse::" .. action, function() awesome.emit_signal(signal) end) if must_connect_signal then awesome.connect_signal(signal, glib_context(actions[action])) end end end end local function new(config) local cfg = config or {} local positions = cfg.positions or {"left", "right", "top", "bottom"} local button_positions = cfg.button_positions or {"top"} local border_width = cfg.border_width or dpi(6) local rounded_corner = cfg.rounded_corner or nil local color_normal = cfg.color_normal or "#56666f" local color_focus = cfg.color_focus or "#a1bfcf" local color_hover = cfg.color_hover or nil local color_floating = cfg.color_floating or nil local color_maximized = cfg.color_maximized or nil local button_size = cfg.button_size or dpi(40) local spacing_widget = cfg.spacing_widget or nil local button_maximize_size = cfg.button_maximize_size or button_size local button_minimize_size = cfg.button_minimize_size or button_size local button_floating_size = cfg.button_floating_size or button_size local button_top_size = cfg.button_top_size or button_size local button_sticky_size = cfg.button_sticky_size or button_size local button_close_size = cfg.button_close_size or button_size local color_maximize_normal = cfg.color_maximize_normal or "#a9dd9d" local color_maximize_focus = cfg.color_maximize_focus or "#a9dd9d" local color_maximize_hover = cfg.color_maximize_hover or "#c3f7b7" local color_minimize_normal = cfg.color_minimize_normal or "#f0eaaa" local color_minimize_focus = cfg.color_minimize_focus or "#f0eaaa" local color_minimize_hover = cfg.color_minimize_hover or "#f6ffea" local color_close_normal = cfg.color_close_normal or "#fd8489" local color_close_focus = cfg.color_close_focus or "#fd8489" local color_close_hover = cfg.color_close_hover or "#ff9ea3" local color_floating_normal = cfg.color_floating_normal or "#ddace7" local color_floating_focus = cfg.color_floating_focus or "#ddace7" local color_floating_hover = cfg.color_floating_hover or "#f7c6ff" local color_sticky_normal = cfg.color_sticky_normal or "#fb8965" local color_sticky_focus = cfg.color_sticky_focus or "#fb8965" local color_sticky_hover = cfg.color_sticky_hover or "#ffa37f" local color_top_normal = cfg.color_top_normal or "#7fc1ca" local color_top_focus = cfg.color_top_focus or "#7fc1ca" local color_top_hover = cfg.color_top_hover or "#99dbe4" local stealth = cfg.stealth or false local snapping = cfg.snapping or false local snapping_center_mouse = cfg.snapping_center_mouse or false local snapping_max_distance = cfg.snapping_max_distance or nil local hot_corners = cfg.hot_corners or {} local hot_corners_color = cfg.hot_corners_color or "#00000000" local hot_corners_width = cfg.hot_corners_width or dpi(1) local hot_corners_height = cfg.hot_corners_height or dpi(1) local show_button_tooltips = cfg.show_button_tooltips or false -- tooltip might intercept mouseclicks; not recommended! local show_title_tooltip = cfg.show_title_tooltip or false -- might fuck up sloppy mouse focus; not recommended! local custom_menu_entries = cfg.custom_menu_entries or {} menu_selection_symbol = cfg.menu_selection_symbol or " ✔" local layout = cfg.layout or "fixed" -- "fixed" | "ratio" local button_ratio = cfg.button_ratio or 0.2 local align_horizontal = cfg.align_horizontal or "right" -- "left" | "center" | "right" local align_vertical = cfg.align_vertical or "center" -- "top" | "center" | "bottom" local buttons = cfg.buttons or {"floating", "minimize", "maximize", "close"} local button_left_click = cfg.button_left_click or function(c) if c.maximized then c.maximized = false end c:emit_signal("request::activate", "mouse_click", {raise = true}) awful.mouse.client.move(c) end local button_double_click = cfg.button_double_click or function(c) c.maximized = not c.maximized end local button_middle_click = cfg.middle_click or function(c) c:emit_signal("request::activate", "mouse_click", {raise = true}) awful.mouse.client.resize(c) end local button_right_click = cfg.right_click or function(c) if c.client_menu then c.client_menu:hide() end c.client_menu = awful.menu(module.menu_client(custom_menu_entries, c)) c.client_menu:toggle() end local resize_factor = cfg.resize_factor or 0.01 local button_wheel_up = cfg.button_wheel_up or function(_) awful.client.incwfact(resize_factor) end local button_wheel_down = cfg.button_wheel_down or function(_) awful.client.incwfact(-1 * resize_factor) end local button_back = cfg.button_back or function(_) awful.client.swap.byidx(-1) end local button_forward = cfg.button_forward or function(_) awful.client.swap.byidx(1) end local button_funcs = {} local left_click_function = function(c) if doubleclicked(c) then button_double_click(c) else button_left_click(c) end end client.connect_signal("smart_borders::left_click", left_click_function) client.connect_signal("smart_borders::middle_click", button_middle_click) client.connect_signal("smart_borders::right_click", button_right_click) client.connect_signal("smart_borders::wheel_up", button_wheel_up) client.connect_signal("smart_borders::wheel_down", button_wheel_down) client.connect_signal("smart_borders::back_click", button_back) client.connect_signal("smart_borders::forward_click", button_forward) button_funcs[1] = function(c) c:emit_signal("smart_borders::left_click") end button_funcs[2] = function(c) c:emit_signal("smart_borders::middle_click") end button_funcs[3] = function(c) c:emit_signal("smart_borders::right_click") end button_funcs[4] = function(c) c:emit_signal("smart_borders::wheel_up") end button_funcs[5] = function(c) c:emit_signal("smart_borders::wheel_down") end button_funcs[8] = function(c) c:emit_signal("smart_borders::back_click") end button_funcs[9] = function(c) c:emit_signal("smart_borders::forward_click") end local function handle_button_press(c, button) local func = button_funcs[button] if func then func(c) end end local button_definitions = {} button_definitions["maximize"] = { name = "maximize", color_normal = color_maximize_normal, color_focus = color_maximize_focus, color_hover = color_maximize_hover, button_size = button_maximize_size, action = function(cl) cl.maximized = not cl.maximized end, } button_definitions["minimize"] = { name = "minimize", color_normal = color_minimize_normal, color_focus = color_minimize_focus, color_hover = color_minimize_hover, button_size = button_minimize_size, action = function(cl) -- for whatever reason setting minimized does not work without wrapping it. awful.spawn.easy_async_with_shell("sleep 0", function() cl.minimized = true end) end, } button_definitions["floating"] = { name = "floating", color_normal = color_floating_normal, color_focus = color_floating_focus, color_hover = color_floating_hover, button_size = button_floating_size, action = function(cl) cl.floating = not cl.floating end, } button_definitions["close"] = { name = "close", color_normal = color_close_normal, color_focus = color_close_focus, color_hover = color_close_hover, button_size = button_close_size, action = function(cl) cl:kill() end, } button_definitions["sticky"] = { name = "sticky", color_normal = color_sticky_normal, color_focus = color_sticky_focus, color_hover = color_sticky_hover, button_size = button_sticky_size, action = function(cl) cl.sticky = not cl.sticky end, } button_definitions["top"] = { name = "top", color_normal = color_top_normal, color_focus = color_top_focus, color_hover = color_top_hover, button_size = button_top_size, action = function(cl) cl.ontop = not cl.ontop end, } for s in screen do for pos, buttons in pairs(hot_corners) do add_hot_corner({ buttons = buttons, screen = s, position = pos, color = hot_corners_color, width = hot_corners_width, height = hot_corners_height, }) end end if layout ~= "fixed" and layout ~= "ratio" then layout = "fixed" end if type(button_positions) == "string" then button_positions = {button_positions} end if snapping then if awful and awful.mouse and awful.mouse.append_global_mousebindings then local mouse_closest_client = function() local s = awful.screen.focused() local m_x = mouse.coords().x local m_y = mouse.coords().y local closest_distance, closest_c for _, c in ipairs(s.all_clients) do if c:isvisible() then local x = c.x + (c.width / 2) local y = c.y + (c.height / 2) local dx = math.max(math.abs(m_x - x) - (c.width / 2), 0) local dy = math.max(math.abs(m_y - y) - (c.height / 2), 0) local distance = math.sqrt(dx * dx + dy * dy) if (not snapping_max_distance or (distance <= snapping_max_distance)) and (not closest_distance or distance < closest_distance) then closest_distance = distance closest_c = c end end end if closest_c and closest_c.valid then closest_c:emit_signal("request::activate", "smart_borders::snapping", {raise = true}) end return closest_c end awful.mouse.append_global_mousebindings({ awful.button({}, 1, function() local c = mouse_closest_client() if c then if snapping_center_mouse then mouse.coords {x = c.x + c.width / 2, y = c.y + c.height / 2} end left_click_function(c) end end), awful.button({}, 2, function() local c = mouse_closest_client() if c then button_middle_click(c) end end), awful.button({}, 3, function() local c = mouse_closest_client() if c then button_right_click(c) end end), awful.button({}, 4, function() local c = mouse_closest_client() if c then button_wheel_up(c) end end), awful.button({}, 5, function() local c = mouse_closest_client() if c then button_wheel_down(c) end end), awful.button({}, 8, function() local c = mouse_closest_client() if c then button_back(c) end end), awful.button({}, 9, function() local c = mouse_closest_client() if c then button_forward(c) end end), }) else naughty.notify({title = "smart_borders", text = "snapping requires awesomewm git version!", timeout = 0}) end end local smart_border_titlebars = function(c) local button_widgets = {} local border_bg = wibox.widget.base.make_widget_declarative( { {widget = wibox.container.margin}, id = "border_bg", bg = color_normal, widget = wibox.container.background, }) border_bg:connect_signal("button::press", function(_, _, _, button) handle_button_press(c, button) end) if color_hover then border_bg:connect_signal("mouse::enter", function() border_bg.bg = color_hover end) border_bg:connect_signal("mouse::leave", function() if client.focus == c then border_bg.bg = color_focus else border_bg.bg = color_normal end end) end local border_expander, border_expander_center if layout == "fixed" then border_expander_center = wibox.widget.base.make_widget_declarative( { fill_vertical = true, fill_horizontal = true, content_fill_vertical = true, content_fill_horizontal = true, border_bg, widget = wibox.container.place, }) border_expander = wibox.widget.base.make_widget_declarative( { {layout = wibox.layout.fixed.horizontal}, border_bg, {layout = wibox.layout.fixed.horizontal}, widget = wibox.layout.align.horizontal, }) end local _button_positions = list2map(button_positions) for _, pos in pairs(positions) do local tb = awful.titlebar(c, {size = border_width, position = pos, bg = "#00000000"}) local btn_layout if layout == "fixed" then btn_layout = ori(pos) == "v" and wibox.layout.fixed.vertical or wibox.layout.fixed.horizontal end if layout == "ratio" then btn_layout = ori(pos) == "v" and wibox.layout.ratio.vertical or wibox.layout.ratio.horizontal end if _button_positions[pos] then -- border with buttons local button_layout = wibox.widget.base.make_widget_declarative( {id = "button_layout", spacing_widget = spacing_widget, layout = btn_layout}) local titlebar_widget if layout == "fixed" then if ori(pos) == "v" then local expander = align_vertical == "center" and border_expander_center or border_expander titlebar_widget = wibox.widget.base.make_widget_declarative( { align_vertical == "top" and button_layout or expander, align_vertical == "center" and button_layout or expander, align_vertical == "bottom" and button_layout or expander, expand = align_vertical == "center" and "none" or "inside", layout = wibox.layout.align.vertical, }) else local expander = align_horizontal == "center" and border_expander_center or border_expander titlebar_widget = wibox.widget.base.make_widget_declarative( { align_horizontal == "left" and button_layout or expander, align_horizontal == "center" and button_layout or expander, align_horizontal == "right" and button_layout or expander, expand = align_horizontal == "center" and "none" or "inside", layout = wibox.layout.align.horizontal, }) end end if layout == "ratio" then titlebar_widget = wibox.widget.base.make_widget_declarative( {button_layout, id = "titlebar_widget", bg = color_normal, widget = wibox.container.background}) end tb:setup{ titlebar_widget, bg = "#00000000", shape = rounded_corner and rounded_corner_shape(rounded_corner, pos) or nil, widget = wibox.container.background(), } local ratio_button_layout = wibox.widget.base.make_widget_declarative( { homogeneous = layout == "ratio" and true or false, expand = true, layout = ori(pos) == "h" and wibox.layout.grid.horizontal or wibox.layout.grid.vertical, }) local list_of_buttons = {} for _, btn in pairs(buttons) do local b = button_definitions[btn] if not b then -- custom button b = {} b.name = cfg["button_" .. btn .. "_name"] or btn b.button_size = cfg["button_" .. btn .. "_size"] or button_size b.color_focus = cfg["color_" .. btn .. "_focus"] or "#ff00ff" b.color_normal = cfg["color_" .. btn .. "_normal"] or "#ff00ff" b.color_hover = cfg["color_" .. btn .. "_hover"] or "#ff1aff" b.action = cfg["button_" .. btn .. "_function"] or nil end local button_widget = wibox.widget.base.make_widget_declarative( { {widget = wibox.container.margin}, id = b.name, forced_width = ori(pos) == "h" and b.button_size or nil, forced_height = ori(pos) == "v" and b.button_size or nil, bg = b.color_normal, widget = wibox.container.background, }) if show_button_tooltips then awful.tooltip { objects = {button_widget}, mode = 'outside', timer_function = function() return b.name end, } end button_widget:connect_signal("mouse::enter", function() button_widget.bg = b.color_hover end) button_widget:connect_signal("mouse::leave", function() if stealth then if c == client.focus then button_widget.bg = color_focus else button_widget.bg = color_normal end else if c == client.focus then button_widget.bg = b.color_focus else button_widget.bg = b.color_normal end end end) button_widget:connect_signal("button::press", function(_, _, _, button) if button == 1 then if b.action then b.action(c) end else handle_button_press(c, button) end end) table.insert(list_of_buttons, button_widget) button_widgets[b.name] = button_widget local update = function() if client.focus == c then button_widget.bg = stealth and color_focus or b.color_focus return end button_widget.bg = stealth and color_normal or b.color_normal end button_widget.update = update update_on_signal(c, "focus", button_widget) update_on_signal(c, "unfocus", button_widget) end if layout == "ratio" then ratio_button_layout:set_children(list_of_buttons) local ratio_children = {} table.insert(ratio_children, border_bg) table.insert(ratio_children, ratio_button_layout) table.insert(ratio_children, border_bg) button_layout:set_children(ratio_children) if (ori(pos) == "h" and align_horizontal == "left") or (ori(pos) == "v" and align_vertical == "top") then button_layout:ajust_ratio(2, 0, button_ratio, 1.0 - button_ratio) end if (ori(pos) == "h" and align_horizontal == "right") or (ori(pos) == "v" and align_vertical == "bottom") then button_layout:ajust_ratio(2, 1.0 - button_ratio, button_ratio, 0) end if (ori(pos) == "h" and align_horizontal == "center") or (ori(pos) == "v" and align_vertical == "center") then local side_ratio = (1.0 - button_ratio) / 2 button_layout:ajust_ratio(2, side_ratio, button_ratio, side_ratio) end end if layout == "fixed" then button_layout:set_children(list_of_buttons) end else tb:setup{ border_bg, bg = "#00000000", shape = rounded_corner and rounded_corner_shape(rounded_corner, pos) or nil, widget = wibox.container.background, } end end -- show client title tooltip on border hover if show_title_tooltip then awful.tooltip { objects = {border_bg}, timer_function = function() return c.name end, } end local update_border = function() if client.focus == c then border_bg.bg = color_focus return end if color_maximized and c.maximized then border_bg.bg = color_maximized return end if color_floating and c.floating then border_bg.bg = color_floating return end border_bg.bg = color_normal end border_bg.update = update_border update_on_signal(c, "focus", border_bg) update_on_signal(c, "unfocus", border_bg) update_on_signal(c, "property::maximized", border_bg) update_on_signal(c, "property::floating", border_bg) end client.connect_signal("request::tag", smart_border_titlebars) end return setmetatable(module, { __call = function(_, ...) new(...) return module end, })
local uv = require "lluv" local lua = uv.exepath() local fake = lua .. "123456" local counter = 0 local proc1 proc1 = uv.spawn({ file = lua; args = {}; }, function(handle, err, status, signal) counter = counter + 1 assert(handle == proc1) assert(err == nil) assert(status == 0) end) assert(proc1) assert(proc1:active()) assert(not proc1:closing()) local proc2 proc2 = uv.spawn({ file = fake; args = {}; }, function(handle, err, status, signal) counter = counter + 1 assert(handle == proc2) assert(err ~= nil) assert(status == nil) end) assert(proc2) assert(not proc2:active()) assert(not proc2:closing()) local proc3 proc3 = uv.spawn({ file = lua; args = {}; }) assert(proc3) assert(proc3:active()) assert(not proc3:closing()) local proc4, err proc4, err = uv.spawn({ file = fake; args = {}; }) assert(proc4 == nil) assert(err ~= nil) local function find_proc4() for _, handle in ipairs(uv.handles()) do if not( (handle == proc1 ) or (handle == proc2 ) or (handle == proc3 ) ) then return handle end end end assert(#uv.handles() == 4) proc4 = assert(find_proc4()) assert(not proc4:active()) assert(proc4:closing()) uv.run() assert(counter == 2) print("Done!")
return {'urinaal','urine','urineblaas','urinebuis','urinebuisopening','urinecontrole','urineleider','urinemonster','urineonderzoek','urineren','urinestaal','urinetest','urinevergiftiging','urineverlies','urineweg','urineweginfectie','urinezuur','urinoir','urineproductie','urinekatheter','urinelozing','urinestraal','urinestroom','urinelucht','uriot','uri','urinewegen','urineweginfecties','urinalen','urinecontroles','urineer','urineerde','urineerden','urineert','urineleiders','urinetesten','urinetests','urinoirs','urineblazen','urinebuizen','urinestalen','urinemonsters','urinezuren','urineonderzoeken'}
require 'torch' require 'nn' require 'optim' require 'eladtools' require 'recurrent' require 'utils.OneHot' require 'utils.textDataProvider' ------------------------------------------------------- cmd = torch.CmdLine() cmd:addTime() cmd:text() cmd:text('Training recurrent networks on character-level text dataset') cmd:text() cmd:text('==>Options') cmd:text('===>Data Options') cmd:option('-input', 'data/tinyshakespeare.txt', 'file with input data') cmd:option('-shuffle', false, 'shuffle training samples') cmd:text('===>Model And Training Regime') cmd:option('-model', 'LSTM', 'Recurrent model [RNN, iRNN, LSTM, GRU]') cmd:option('-seqLength', 50, 'number of timesteps to unroll for') cmd:option('-rnnSize', 128, 'size of rnn hidden layer') cmd:option('-numLayers', 2, 'number of layers in the LSTM') cmd:option('-dropout', 0, 'dropout p value') cmd:option('-LR', 2e-3, 'learning rate') cmd:option('-LRDecay', 0, 'learning rate decay (in # samples)') cmd:option('-weightDecay', 0, 'L2 penalty on the weights') cmd:option('-momentum', 0, 'momentum') cmd:option('-batchSize', 50, 'batch size') cmd:option('-decayRate', 1.03, 'exponential decay rate') cmd:option('-initWeight', 0.08, 'uniform weight initialization range') cmd:option('-earlyStop', 5, 'number of bad epochs to stop after') cmd:option('-optimization', 'rmsprop', 'optimization method') cmd:option('-gradClip', 5, 'clip gradients at this value') cmd:option('-epoch', 100, 'number of epochs to train') cmd:option('-epochDecay', 5, 'number of epochs to start decay learning rate') cmd:text('===>Platform Optimization') cmd:option('-threads', 8, 'number of threads') cmd:option('-type', 'cuda', 'float or cuda') cmd:option('-devid', 1, 'device ID (if using CUDA)') cmd:option('-nGPU', 1, 'num of gpu devices used') cmd:option('-seed', 123, 'torch manual random number generator seed') cmd:option('-constBatchSize', false, 'do not allow varying batch sizes') cmd:text('===>Save/Load Options') cmd:option('-load', '', 'load existing net weights') cmd:option('-save', os.date():gsub(' ',''), 'save directory') cmd:option('-optState', false, 'Save optimization state every epoch') cmd:option('-checkpoint', 0, 'Save a weight check point every n samples. 0 for off') opt = cmd:parse(arg or {}) opt.save = paths.concat('./Results', opt.save) torch.setnumthreads(opt.threads) torch.manualSeed(opt.seed) torch.setdefaulttensortype('torch.FloatTensor') ---------------------------------------------------------------------- -- data prep local byteVec, vocab, decoder = loadTextFileChars(opt.input) local numTrain = math.floor(byteVec:nElement() * 0.95) local vocabSize = #decoder data = { trainingData = byteVec:narrow(1, 1, numTrain), validationData = byteVec:narrow(1, numTrain + 1, byteVec:nElement() - numTrain - 1), vocabSize = vocabSize, decoder = decoder, vocab = vocab, decode = decodeFunc(vocab, 'char'), encode = encodeFunc(vocab, 'char') } ---------------------------------------------------------------------- if paths.filep(opt.load) then modelConfig = torch.load(opt.load) print('==>Loaded Net from: ' .. opt.load) else modelConfig = {} local rnnTypes = {LSTM = nn.LSTM, RNN = nn.RNN, GRU = nn.GRU, iRNN = nn.iRNN} local rnn = rnnTypes[opt.model] local hiddenSize = vocabSize modelConfig.recurrent = nn.Sequential() for i=1, opt.numLayers do modelConfig.recurrent:add(rnn(hiddenSize, opt.rnnSize, opt.initWeight, 0)) if opt.dropout > 0 then modelConfig.recurrent:add(nn.Dropout(opt.dropout)) end hiddenSize = opt.rnnSize end modelConfig.embedder = nn.OneHot(vocabSize) modelConfig.classifier = nn.Linear(opt.rnnSize, vocabSize) end local trainingConfig = require 'utils.trainRecurrent' local train = trainingConfig.train local evaluate = trainingConfig.evaluate local sample = trainingConfig.sample local optimState = trainingConfig.optimState local saveModel = trainingConfig.saveModel local logFilename = paths.concat(opt.save,'LossRate.log') local log = optim.Logger(logFilename) local decreaseLR = EarlyStop(1,opt.epochDecay) local stopTraining = EarlyStop(opt.earlyStop, opt.epoch) local epoch = 1 repeat print('\nEpoch ' .. epoch ..'\n') LossTrain = train(data.trainingData) saveModel(epoch) if opt.optState then torch.save(optStateFilename .. '_epoch_' .. epoch .. '.t7', optimState) end print('\nTraining Loss: ' .. LossTrain) local LossVal = evaluate(data.validationData) print('\nValidation Loss: ' .. LossVal) log:add{['Training Loss']= LossTrain, ['Validation Loss'] = LossVal} log:style{['Training Loss'] = '-', ['Validation Loss'] = '-'} log:plot() print('\nSampled Text:\n' .. sample(nil, 400)) epoch = epoch + 1 if decreaseLR:update(LossVal) then optimState.learningRate = optimState.learningRate / opt.decayRate print("Learning Rate decreased to: " .. optimState.learningRate) decreaseLR = EarlyStop(1,1) decreaseLR:reset() end until stopTraining:update(LossVal) local lowestLoss, bestIteration = stopTraining:lowest() print("Best Iteration was " .. bestIteration .. ", With a validation loss of: " .. lowestLoss)
--[[ [WIP] Currently, I don't recommend to use it. It may change. ]] ---@class general_util : module local M = {} --#region constants local call = remote.call --#endregion -- Events local on_reload_scenario_event local on_new_character_event local on_player_on_admin_surface_event local on_player_on_scenario_surface_event local on_player_on_lobby_surface_event local on_toggle_event ---@type table<string, integer> M.custom_events = {} ---@return table<string, integer> M.get_events = function() return call("EasyAPI", "get_events") end ---@return table<string, table> M.get_data = function() return call("EasyAPI", "get_data") end local function get_data() on_reload_scenario_event = call("EasyAPI", "get_event_name", "on_reload_scenario") on_new_character_event = call("EasyAPI", "get_event_name", "on_new_character") on_player_on_admin_surface_event = call("EasyAPI", "get_event_name", "on_player_on_admin_surface") on_player_on_scenario_surface_event = call("EasyAPI", "get_event_name", "on_player_on_scenario_surface") on_player_on_lobby_surface_event = call("EasyAPI", "get_event_name", "on_player_on_lobby_surface") on_toggle_event = call("EasyAPI", "get_event_name", "on_toggle") M.custom_events = { on_reload_scenario = on_reload_scenario_event, on_new_character = on_new_character_event, on_player_on_admin_surface = on_player_on_admin_surface_event, on_player_on_scenario_surface = on_player_on_scenario_surface_event, on_player_on_lobby_surface = on_player_on_lobby_surface_event, on_toggle = on_toggle_event } end M.on_load = get_data M.on_init = get_data return M
------------------------------------------------------------------------------- -- Spine Runtimes Software License v2.5 -- -- Copyright (c) 2013-2016, Esoteric Software -- All rights reserved. -- -- You are granted a perpetual, non-exclusive, non-sublicensable, and -- non-transferable license to use, install, execute, and perform the Spine -- Runtimes software and derivative works solely for personal or internal -- use. Without the written permission of Esoteric Software (see Section 2 of -- the Spine Software License Agreement), you may not (a) modify, translate, -- adapt, or develop new applications using the Spine Runtimes or otherwise -- create derivative works or improvements of the Spine Runtimes or (b) remove, -- delete, alter, or obscure any trademarks or any copyright, trademark, patent, -- or other intellectual property or proprietary rights notices on or in the -- Software, including any copy thereof. Redistributions in binary or source -- form must include this license and terms. -- -- THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -- EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF -- USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -- IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- local setmetatable = setmetatable local SkeletonData = {} SkeletonData.__index = SkeletonData function SkeletonData.new () local self = { name, bones = {}, slots = {}, skins = {}, defaultSkin = nil, events = {}, animations = {}, ikConstraints = {}, transformConstraints = {}, pathConstraints = {}, width, height, version, hash, imagesPath, slotNameIndices = {} } setmetatable(self, SkeletonData) return self end function SkeletonData:findBone (boneName) if not boneName then error("boneName cannot be nil.", 2) end for i,bone in ipairs(self.bones) do if bone.name == boneName then return bone end end return nil end function SkeletonData:findBoneIndex (boneName) if not boneName then error("boneName cannot be nil.", 2) end for i,bone in ipairs(self.bones) do if bone.name == boneName then return i end end return -1 end function SkeletonData:findSlot (slotName) if not slotName then error("slotName cannot be nil.", 2) end for i,slot in ipairs(self.slots) do if slot.name == slotName then return slot end end return nil end function SkeletonData:findSlotIndex (slotName) if not slotName then error("slotName cannot be nil.", 2) end return self.slotNameIndices[slotName] or -1 end function SkeletonData:findSkin (skinName) if not skinName then error("skinName cannot be nil.", 2) end for i,skin in ipairs(self.skins) do if skin.name == skinName then return skin end end return nil end function SkeletonData:findEvent (eventName) if not eventName then error("eventName cannot be nil.", 2) end for i,event in ipairs(self.events) do if event.name == eventName then return event end end return nil end function SkeletonData:findAnimation (animationName) if not animationName then error("animationName cannot be nil.", 2) end for i,animation in ipairs(self.animations) do if animation.name == animationName then return animation end end return nil end function SkeletonData:findIkConstraint (constraintName) if not constraintName then error("constraintName cannot be nil.", 2) end for i,constraint in ipairs(self.ikConstraints) do if constraint.name == constraintName then return constraint end end return nil end function SkeletonData:findTransformConstraint (constraintName) if not constraintName then error("constraintName cannot be nil.", 2) end for i,constraint in ipairs(self.transformConstraints) do if constraint.name == constraintName then return constraint end end return nil end function SkeletonData:findPathConstraint (constraintName) if not constraintName then error("constraintName cannot be nil.", 2) end for i,constraint in ipairs(self.pathConstraints) do if constraint.name == constraintName then return constraint end end return nil end function SkeletonData:findPathConstraintIndex (constraintName) if not constraintName then error("constraintName cannot be nil.", 2) end for i,constraint in ipairs(self.pathConstraints) do if constraint.name == constraintName then return i end end return -1 end return SkeletonData
require('nn') require('cudnn') require('inn') require('detection') caffeConverter = detection.CaffeModelConverter('./models/VGG16/VGG16_imgnet.lua','/mnt/mag5tb/data/detection/data/imagenet_models/VGG16.prototxt','/mnt/mag5tb/data/detection/data/imagenet_models/VGG16.v2.caffemodel','VGG16.v2','./') caffeConverter:convert()
local BREAKINFOFUNC, XPCALLFUNC = require("LuaDebug")("localhost", 7003) coroutine.start( function() while true do coroutine.wait(0.1) BREAKINFOFUNC() end end) --主入口函数。从这里开始lua逻辑 function Main() print("logic start") end --场景切换通知 function OnLevelWasLoaded(level) collectgarbage("collect") Time.timeSinceLevelLoad = 0 end function OnApplicationQuit() end
-- Project: PonyTiled a Corona Tiled Map Loader -- -- Loads LUA saved map files from Tiled http://www.mapeditor.org/ local M = {} local physics = require "physics" local FlippedHorizontallyFlag = 0x80000000 local FlippedVerticallyFlag = 0x40000000 local FlippedDiagonallyFlag = 0x20000000 local ClearFlag = 0x1FFFFFFF local function hasbit(x, p) return x % (p + p) >= p end local function setbit(x, p) return hasbit(x, p) and x or x + p end local function clearbit(x, p) return hasbit(x, p) and x - p or x end local function inherit(image, properties) for k,v in pairs(properties) do image[k] = v end return image end function M.new(data) local map = display.newGroup() local layers = data.layers local tilesets = data.tilesets local width, height = data.width * data.tilewidth, data.height * data.tileheight local function gidLookup(gid) -- turn a gid into a filename for i = 1, #tilesets do local tileset = tilesets[i] local firstgid = tileset.firstgid local lastgid = firstgid + tileset.tilecount if gid >= firstgid and gid <= lastgid then for j = 1, #tileset.tiles do local tile = tileset.tiles[j] if tile.id == (gid - firstgid) then return tile.image -- may need updating with documents directory end end end end return false end for i = 1, #layers do local layer = layers[i] if layer.type == "objectgroup" then local objectGroup = display.newGroup() for j = 1, #layer.objects do local object = layer.objects[j] if object.gid then -- Flipping merged from code by Sergey Lerg local gid = object.gid print (gid) local flip = {} flip.x = hasbit(gid, FlippedHorizontallyFlag) flip.y = hasbit(gid, FlippedVerticallyFlag) flip.xy = hasbit(gid, FlippedDiagonallyFlag) gid = clearbit(gid, FlippedHorizontallyFlag) gid = clearbit(gid, FlippedVerticallyFlag) gid = clearbit(gid, FlippedDiagonallyFlag) gid = gidLookup(gid) local image = display.newImageRect(gid, object.width, object.height) -- name and type image.name = object.name image.type = object.type -- apply base properties image.anchorX, image.anchorY = 0, 1 image.x, image.y = object.x, object.y image.rotation = object.rotation image.isVisible = object.visible -- move anchor to center if image.contentBounds then local bounds = image.contentBounds local actualCenterX, actualCenterY = (bounds.xMin + bounds.xMax)/2 , (bounds.yMin + bounds.yMax)/2 image.anchorX, image.anchorY = 0.5, 0.5 image.x = actualCenterX image.y = actualCenterY end -- flip it print (flip.x, flip.y) if flip.xy then print("WARNING: Unsupported Tiled rotation x,y in ", object.name) else if flip.x then image.xScale = -1 end if flip.y then image.yScale = -1 end end -- simple phyics if object.properties.bodyType then physics.addBody(image, object.properties.bodyType, object.properties) end -- apply custom properties image = inherit(image, object.properties) image = inherit(image, layer.properties) objectGroup:insert(image) end end objectGroup.name = layer.name objectGroup.isVisible = layer.visible objectGroup.alpha = layer.opacity map:insert(objectGroup) end end function map:extend(...) local plugins = arg or {} -- each custom object above has its own game.scene module for t = 1, #plugins do -- load each module based on type local plugin = require ("com.ponywolf.plugins." .. plugins[t]) -- find each type of tiled object local images = map:listTypes(plugins[t]) if images then -- do we have at least one? for i = 1, #images do -- extend the display object with its own custom code images[i] = plugin.new(images[i]) end end end end -- return first display object with name function map:findObject(name) for layers = self.numChildren,1,-1 do local layer = self[layers] if layer.numChildren then for i = layer.numChildren,1,-1 do if layer[i].name == name then return layer[i] end end end end return false end -- return all display objects with type function map:listTypes(...) local objects = {} for layers = self.numChildren,1,-1 do local layer = self[layers] if layer.numChildren then for i = layer.numChildren,1,-1 do for j = 1, #arg do if arg[j]==nil or layer[i].type == arg[j] then objects[#objects+1] = layer[i] end end end end end return objects end -- add helpful values to the map itself map.designedWidth, map.designedHeight = width, height return map end return M
addEvent("Music:onStreamVerify", true) addEventHandler("Music:onStreamVerify", resourceRoot, function(streamer) outputChatBox("#00ff00[Live Stream] #ffffffLive stream is online! Streamer: "..streamer.."#ffffff. M -> Stream to tune in!", root, 255, 255, 255, true) end)
---@class CS.FairyGUI.GearDisplay2 : CS.FairyGUI.GearBase ---@field public condition number ---@field public pages String[] ---@type CS.FairyGUI.GearDisplay2 CS.FairyGUI.GearDisplay2 = { } ---@return CS.FairyGUI.GearDisplay2 ---@param owner CS.FairyGUI.GObject function CS.FairyGUI.GearDisplay2.New(owner) end function CS.FairyGUI.GearDisplay2:Apply() end function CS.FairyGUI.GearDisplay2:UpdateState() end ---@return boolean ---@param connected boolean function CS.FairyGUI.GearDisplay2:Evaluate(connected) end return CS.FairyGUI.GearDisplay2
--- === cp.blackmagic.resolve.color.Color === --- --- Color Module. local require = require --local log = require "hs.logger".new "Color" local axutils = require "cp.ui.axutils" local Group = require "cp.ui.Group" local Tracker = require "cp.blackmagic.resolve.color.Tracker" local childMatching = axutils.childMatching local Color = Group:subclass("cp.blackmagic.resolve.color.Color") Color.static.DESCRIPTION = "Color" --- cp.blackmagic.resolve.color.Color(app) -> Color --- Constructor --- Creates a new `Color` instance. --- --- Parameters: --- * app - The Final Cut Pro app instance. --- --- Returns: --- * The new `Color`. function Color:initialize(primaryWindow) local UI = primaryWindow.UI:mutate(function(original) if self:isShowing() then return childMatching(original(), Group.matches) end end) Group.initialize(self, primaryWindow, UI) end function Color.lazy.value:active() return self:parent().colorActive end function Color.lazy.prop:isShowing() return self.active.checked end function Color:show() if not self:isShowing() then self.active:click() end return self end function Color.lazy.value:tracker() return Tracker(self) end return Color
local cqueues = require "cqueues" local irc = require "ircclient" local s1 = irc.create_session() s1:register("connect", function(s) s:join("#test") end) s1:register("channel", function(s, origin, chan, text) if text:match("^foo") then s:msg(chan, "bar") end end) s1:connect{ host = "127.0.0.1", nick = "test1" } local s2 = irc.create_session() s2:register("connect", function(s) s:join("#test") end) s2:register("channel", function(s, origin, chan, text) if text:match("^bar") then s:msg(chan, "baz") end end) s2:connect{ host = "127.0.0.1", nick = "test2" } local mainloop = function() while true do local rfd, wfd = s1:add_descriptors({}, {}) s2:add_descriptors(rfd, wfd) local fds = {} for i, v in ipairs(rfd) do fds[#fds+1] = { pollfd = v, events = "r" } end for i, v in ipairs(wfd) do fds[#fds+1] = { pollfd = v, events = "w" } end local out = { cqueues.poll(unpack(fds)) } rfd, wfd = {}, {} for i, v in ipairs(out) do if v.events == "r" then rfd[#rfd+1] = v.pollfd else wfd[#wfd+1] = v.pollfd end end s1:process_descriptors(rfd, wfd) s2:process_descriptors(rfd, wfd) end end local cq = cqueues.new() cq:wrap(mainloop) assert(cq:loop())
-- Load CB_DEBUG Value local CB_DEBUG = rawget(_G, "CB_DEBUG") and _G.CB_DEBUG or false -- Load Screen Helpers local Screen = require "helpers/ScreenHelpers" -- Max Status Handler local CB_MaxStatus = function(inst) -- Exit If PlayerHud Missing if not (Screen.IsHudScreen() or Screen.IsPauseScreen()) then return end -- Set Instance If its missing if not inst or type(inst) ~= "table" or not inst:HasTag("player") then inst = GetPlayer() end -- Exit if HealthComponent missing if not (type(inst.components) == "table" and type(inst.components.health) == "table" and type(inst.components.hunger) == "table" and type(inst.components.sanity) == "table" ) then return end -- Set id default value to all local id = TUNING.CHEAT_BOX.TYPE_MAXSTATUS -- Set Max Health if id == 0 -- All or id == 1 -- Health or id == 2 -- Health+Hunger or id == 6 -- Health+Sanity then if CB_DEBUG then print("Setting Player Health To Max") end inst.components.health:SetPercent(1) end -- Set Max Hunger if id == 0 -- All or id == 2 -- Hunger+Health or id == 3 -- Hunger or id == 4 -- Hunger+Sanity then if CB_DEBUG then print("Setting Player Hunger To Max") end inst.components.hunger:SetPercent(1) end -- Set Max Sanity if id == 0 -- All or id == 4 -- Sanity+Hunger or id == 5 -- Sanity or id == 6 -- Sanity+Health then if CB_DEBUG then print("Setting Player Sanity To Max") end inst.components.sanity:SetPercent(1) end -- Say status inst.components.talker:Say(GetString(inst.prefab,"CB_MAX_STATUS")) end return CB_MaxStatus
-- ############################################################################# -- ## ## -- ## Language : German ## -- ## Locale : DE ## -- ## Last updated : 7 Dec 2009 ## -- ## Origin : Translated ## -- ## Author : Necrocrypt of Siochain (EN/EU) ## -- ## Corrections : skitey at Curse ## -- ## ## -- ## Thanks very much for the help. ## -- ## ## -- ############################################################################# -- General --UMM_TITLE = "Ultimate Mail Mod"; --UMM_PROMPT = "UltimateMailMod"; UMM_LOADED = " geladen."; -- Slash settings UMM_SLASH_HELP1 = "Eingabehilfe:"; UMM_SLASH_HELP2 = "/umm sound : Audio Warnung ein-/ausschalten."; UMM_SLASH_HELP3 = "/umm reset : Setzt die Liste eigener Charaktere zurück."; UMM_SLASH_AUDIODISABLED = "Audio Warnung bei eingehender Post ist jetzt ausgeschaltet."; UMM_SLASH_AUDIOENABLED = "Audio Warnung bei eingehender Post ist jetzt eingeschaltet."; UMM_SLASH_CHARSRESET = "Liste der eigenen Charaktere wurde zurückgesetzt."; -- New mail notify UMM_NOTIFY_NEWMAILARRIVED = "Du hast neue Post"; UMM_NOTIFY_TOOLTIP_TITLE = "Neue Post"; UMM_NOTIFY_TOOLTIP_NEWMAIL = "Auf dich wartet neue Post."; UMM_NOTIFY_TOOLTIP_NEWMAILS = "Auf dich warten %d neue Briefe."; UMM_NOTIFY_TOOLTIP_MOVETIP = "Shift+Right-mouse: Icon bewegen."; -- Menu tabs UMM_MENU_TAB1 = "Eingang"; UMM_MENU_TAB2 = "Versenden"; UMM_MENU_TAB3 = "Massenversand Gegenstände"; -- Tooltip specific UMM_TOOLTIP_BOUND = "Gebunden"; -- Setting UMM_SETTINGS_AUDIOWARNING = "Sound abspielen, wenn Ich neue Post erhalte."; -- Inbox UMM_HELP_INBOX_LINE1 = "Du kannst mehrere Mails markieren:"; UMM_HELP_INBOX_LINE2 = "1) Gegenstand / Geld / Diamanten nehmen"; UMM_HELP_INBOX_LINE3 = "2) Mehrere Briefe zurückschicken."; UMM_HELP_INBOX_LINE4 = "3) Mehrere Briefe löschen."; UMM_HELP_INBOX_LINE5 = "Strg + Links-click um einen Brief zu markieren / entmarkieren."; UMM_HELP_INBOX_RETURNTAGGED = "Alle markierten Briefe zurückschicken."; UMM_HELP_INBOX_DELETETAGGED = "Alle markierten Briefe löschen."; UMM_INBOX_LOADING = "Postfach wird geladen - Bitte warten..."; UMM_INBOX_EMPTY = "Dein Postfach ist leer."; UMM_INBOX_BUTTON_TAGCHARS = "Charaktere"; UMM_INBOX_BUTTON_TAGFRIENDS = "Freunde"; UMM_INBOX_BUTTON_TAGGUILDIES = "Gildenmitglieder"; UMM_INBOX_BUTTON_TAGOTHER = "Andere"; UMM_INBOX_BUTTON_TAGEMPTY = "Leer"; UMM_INBOX_BUTTON_TAKE = "Entnehmen"; UMM_INBOX_BUTTON_RETURN = "Zurückschicken"; UMM_INBOX_BUTTON_DELETE = "Löschen"; UMM_INBOX_OPTION_1 = "Alles."; UMM_INBOX_OPTION_2 = "Gegenstände."; UMM_INBOX_OPTION_3 = "Geld."; UMM_INBOX_OPTION_4 = "Diamanten."; UMM_INBOX_CHECK_DELETEDONE = "Briefe nach Entnahme löschen."; UMM_INBOX_LABEL_MASSTAG = "Mehrere Briefe markieren:"; UMM_INBOX_LABEL_TOTALMONEY = "Gesamtmenge Geld im Postfach:"; UMM_INBOX_LABEL_TOTALDIAMONDS = "Gesamtmenge Diamanten im Postfach:"; UMM_INBOX_LABEL_MAILCOUNT = "Anzahl der Briefe"; UMM_INBOX_STATUS_TAKEALLTAGGED = "Automatisches Briefe öffnen - Bitte warten ..."; UMM_INBOX_STATUS_PREPARETAKEDELETE = "Löschen der Briefe wird vorbereitet - Bitte warten ..."; UMM_INBOX_STATUS_RETURNTAGGED = "Automatisches Briefe zurückschicken - Bitte warten ..."; UMM_INBOX_STATUS_DELETETAGGED = "Automatisches Briefe löschen - Bitte warten ..."; -- Viewer UMM_VIEWER_LABEL_FROM = "Absender: "; UMM_VIEWER_LABEL_SUBJECT = "Betreff:"; UMM_VIEWER_BUTTON_REPLY = "Antwort:"; UMM_VIEWER_BUTTON_RETURN = "Zurückschicken"; UMM_VIEWER_BUTTON_DELETE = "Löschen"; UMM_VIEWER_BUTTON_CLOSE = "Schließen"; UMM_VIEWER_ATTACHED = "Anhang:"; UMM_VIEWER_ATTACHMENTCOD = "Nachnahmepreis:"; UMM_VIEWER_ATTACHMENTACCEPT = "Nachnahme akzeptieren"; UMM_VIEWER_ATTACHMENT_NOT_ACCEPTED = "Bitte Nachnahme akzeptieren auswählen und wiederholen."; -- Composer UMM_COMPOSER_ADDRESSEE = "An:"; UMM_COMPOSER_SUBJECT = "Betreff:"; UMM_COMPOSER_BUTTON_RESET = "Zurücksetzen"; UMM_COMPOSER_BUTTON_SEND = "Senden"; UMM_COMPOSER_ATTACHMENT = "Anhang:"; UMM_COMPOSER_AUTOSUBJECT = "Geld: "; UMM_COMPOSER_SENDGOLD = "Gold senden"; UMM_COMPOSER_SENDCOD = "Nachnahme"; UMM_COMPOSER_CONFIRM_TEXT1 = "Sind Sie sicher, dass Sie den angezeigten Betrag "; UMM_COMPOSER_CONFIRM_TEXT2 = "an %s senden wollen?"; UMM_COMPOSER_CONFIRM_YES = "Ja"; UMM_COMPOSER_CONFIRM_NO = "Nein"; UMM_RECIPIENT_OWN = "Charaktere"; UMM_RECIPIENT_FRIEND = "Freunde"; UMM_RECIPIENT_GUILD = "Gildenmitglieder"; -- Mass Send Items UMM_MSI_MARKBUTTON1 = "Runen"; UMM_MSI_MARKBUTTON2 = "F. Steine"; UMM_MSI_MARKBUTTON3 = "Juwelen"; UMM_MSI_MARKBUTTON4 = "Erz"; UMM_MSI_MARKBUTTON5 = "Holz"; UMM_MSI_MARKBUTTON6 = "Kräuter"; UMM_MSI_MARKBUTTON7 = "R. Mats."; UMM_MSI_MARKBUTTON8 = "P. Runen"; UMM_MSI_MARKBUTTON9 = "Nahrung"; UMM_MSI_MARKBUTTON10 = "Nachspeisen"; UMM_MSI_MARKBUTTON11 = "Tränke"; UMM_MSI_MARK_LABEL = "Wähle:"; UMM_MSI_MARK_TOOLTIP1 = "Runen"; UMM_MSI_MARK_TOOLTIP2 = "Fusions Steine"; UMM_MSI_MARK_TOOLTIP3 = "Juwelen"; UMM_MSI_MARK_TOOLTIP4 = "Erz"; UMM_MSI_MARK_TOOLTIP5 = "Holz"; UMM_MSI_MARK_TOOLTIP6 = "Kräuter"; UMM_MSI_MARK_TOOLTIP7 = "Rohe Materialien"; UMM_MSI_MARK_TOOLTIP8 = "Produktions Runen"; UMM_MSI_MARK_TOOLTIP9 = "Nahrung"; UMM_MSI_MARK_TOOLTIP10 = "Nachspeisen"; UMM_MSI_MARK_TOOLTIP11 = "Tränke"; UMM_MSI_MARK_TOOLTIPCLICK = "Klicken um alle Gegenstände dieser Kategorie zu markieren."; UMM_MSI_BUTTON_ADDRESSEE = "An:"; UMM_MSI_BUTTON_RESET = "Zurücksetzen"; UMM_MSI_MAILSTOSEND = "Briefe zu versenden: %d"; UMM_MSI_ADDRESSEE = "An:"; UMM_MSI_SUBJECT = "Betreff:"; UMM_MSI_COD = "Nachnahme"; UMM_MSI_STATUS = "Status:"; UMM_MSI_STATUS_SENDING = "Versenden..."; UMM_MSI_STATUS_QUEUED = "Warteschlange."; UMM_MSI_BUTTON_SEND = "Senden"; UMM_MSI_BUTTON_COD = "Nachnahme"; UMM_MSI_BUTTON_CANCEL = "Abbrechen"; UMM_MSI_SEND_STATUS = "Versenden %d von %d - Bitte warten..."; UMM_MSI_SEND_MAILBODY = " "; -- Error messages UMM_ERROR_CANTSENDSELF = "Du kannst dir selbst keine Briefe schicken."; UMM_ERROR_NOSUBJECT = "Bitte einen Betreff angeben."; UMM_ERROR_CANTSENDBOUND = "Du kannst keine Gebundenen Gegenstände versenden."; UMM_ERROR_AUTOMATIONFAILED = "Automatisierter Prozess fehlgeschlagen - Prozess gestoppt."; UMM_ERROR_NOTHINGTAGGED = "Bitte markiere einen oder mehrere Briefe!"; UMM_ERROR_CANTDELETE = "Briefe mit Anhang konnten nicht gelöscht werden !"; UMM_ERROR_CANTRETURN = "Zurückschicken des Briefes fehlgeschlagen !"; UMM_ERROR_CANTTAKECOD = "Nachnahmebriefe konnten nicht automatisch angenommen werden !"; UMM_ERROR_CANTTAKE = "Markierter Brief trifft nicht die nötigen Entnahmebedingungen !";
/run local items=({1520]=true,[9335]=true,[9333]=true,[9332]=true,[1645]=true,[4599]=true} for b=0,4,1 do for s=1,32,1 do local id=select(10,GetContainerItemInfo(b,s)) if items[id] then PickupContainerItem(b,s) DeleteCursorItem() end end end
--- Cycle through recently focused clients (Alt-Tab and more). -- -- Author: http://daniel.hahler.de -- Github: https://github.com/blueyed/awesome-cyclefocus local awful = require('awful') -- local setmetatable = setmetatable local naughty = require("naughty") local table = table local tostring = tostring local floor = require("math").floor local capi = { -- tag = tag, client = client, keygrabber = keygrabber, -- mousegrabber = mousegrabber, mouse = mouse, screen = screen, awesome = awesome, } local wibox = require("wibox") local xresources = require("beautiful").xresources local dpi = xresources and xresources.apply_dpi or function() end --- Escape pango markup, taken from naughty. local escape_markup = function(s) local escape_pattern = "[<>&]" local escape_subs = { ['<'] = "&lt;", ['>'] = "&gt;", ['&'] = "&amp;" } return s:gsub(escape_pattern, escape_subs) end -- Configuration. This can be overridden: global or via args to cyclefocus.cycle. local cyclefocus cyclefocus = { -- Should clients get shown during cycling? -- This should be a function (or `false` to disable showing clients), which -- receives a client object, and can make use of `cyclefocus.show_client` -- (the default implementation). show_clients = true, -- Should clients get focused during cycling? -- This is required for the tasklist to highlight the selected entry. focus_clients = true, -- Should the selected client get raised? -- This calls `cyclefocus.raise_client_without_focus` by default, which you -- can use when overriding this with a function (that gets the client as -- argument). raise_client = true, -- Should the mouse pointer be moved away during cycling? -- This is normally done to avoid interference from sloppy focus handling, -- but can be disabled if you do not use sloppy focus. move_mouse_pointer = true, -- How many entries should get displayed before and after the current one? display_next_count = 3, display_prev_count = 3, -- Default preset to use for entries. -- `preset_for_offset` (below) gets added to it. default_preset = {}, --- Templates for entries in the list. -- The following arguments get passed to a callback: -- - client: the current client object. -- - idx: index number of current entry in clients list. -- - displayed_list: the list of entries in the list, possibly filtered. preset_for_offset = { -- Default callback, which will gets applied for all offsets (first). default = function (preset, args) -- Default font and icon size (gets overwritten for current/0 index). preset.font = 'sans 8' preset.icon_size = dpi(24) preset.text = escape_markup(cyclefocus.get_client_title(args.client, false)) end, -- Preset for current entry. ["0"] = function (preset, args) preset.font = 'sans 14' preset.icon_size = dpi(36) preset.text = escape_markup(cyclefocus.get_client_title(args.client, true)) -- Add screen number if there is more than one. if screen.count() > 1 then preset.text = preset.text .. " [screen " .. tostring(args.client.screen.index) .. "]" end preset.text = preset.text .. " [#" .. args.idx .. "] " preset.text = '<b>' .. preset.text .. '</b>' end, -- You can refer to entries by their offset. -- ["-1"] = function (preset, args) -- -- preset.icon_size = 32 -- end, -- ["1"] = function (preset, args) -- -- preset.icon_size = 32 -- end }, -- Default builtin filters. -- (meant to get applied always, but you could override them) cycle_filters = { function(c, source_c) return not c.minimized end, --luacheck: no unused args }, -- Experimental: Width of icon column ("max_icon_size", used for margin). -- This could be "margin" etc instead, but currently only the width for the -- current entry is known. icon_col_width = dpi(36), -- EXPERIMENTAL: only add clients to the history that have been focused by -- cyclefocus. -- This allows to switch clients using other methods, but those are then -- not added to cyclefocus' internal history. -- The get_next_client function will then first consider the most recent -- entry in the history stack, if it's not focused currently. -- -- You can use cyclefocus.history.add to manually add an entry, or -- cyclefocus.history.append if you want to add it to the end of the stack. -- This might be useful in a request::activate signal handler. -- XXX: needs to be also handled in request::activate then probably. -- TODO: make this configurable during runtime of the binding, e.g. by -- flagging entries in the stack or using different stacks. -- only_add_internal_focus_changes_to_history = true, -- The filter to ignore clients altogether (get not added to the history stack). -- This is different from the cycle_filters. -- The function should return true / the client if it's ok, nil otherwise. filter_focus_history = awful.client.focus.filter, -- Display notifications while cycling? -- WARNING: without raise_clients this will not make sense probably! display_notifications = true, -- Debugging: messages get printed, and should show up in ~/.xsession-errors etc. -- 1: enable, 2: verbose, 3: very verbose, 4: much verbose. debug_level = 0, -- Use naughty notifications for debugging (additional to printing)? debug_use_naughty_notify = false, } -- Wrap icon widget with margin. local get_icon_wrapper_widget = function(w, preset) local icon_margin = preset.icon_margin or dpi(5) local icon_center_margin = icon_margin + math.max(0, (cyclefocus.icon_col_width - preset.icon_size)/2) local iconmarginbox = wibox.container.margin(w) iconmarginbox:set_left(icon_center_margin) iconmarginbox:set_right(icon_center_margin) iconmarginbox:set_top(icon_margin) iconmarginbox:set_bottom(icon_margin) return iconmarginbox end -- Get widget for client icon. Uses awful.widget.clienticon if available. if awful.widget.clienticon then cyclefocus.get_client_icon_widget = function(c, preset) local w = awful.widget.clienticon(c) w:set_forced_width(preset.icon_size) w:set_forced_height(preset.icon_size) return get_icon_wrapper_widget(w, preset) end else local has_gears, gears = pcall(require, 'gears') local icon_loader if has_gears then -- Use gears to prevent memory leaking. icon_loader = gears.surface.load else icon_loader = function(icon) return icon end end cyclefocus.get_client_icon_widget = function(c, preset) if not c.icon then return end local icon = icon_loader(c.icon) local icon_size = preset.icon_size -- Code originally via naughty. local cairo = require("lgi").cairo local scaled = cairo.ImageSurface(cairo.Format.ARGB32, icon_size, icon_size) local cr = cairo.Context(scaled) cr:scale(preset.icon_size / icon:get_height(), preset.icon_size / icon:get_width()) cr:set_source_surface(icon, 0, 0) cr:paint() icon = scaled local iconbox = wibox.widget.imagebox() iconbox:set_resize(false) iconbox:set_image(icon) return get_icon_wrapper_widget(iconbox, preset) end end -- A set of default filters, which can be used for cyclefocus.cycle_filters. cyclefocus.filters = { -- Filter clients on the same screen. same_screen = function (c, source_c) return (c.screen or capi.mouse.screen) == source_c.screen end, same_class = function (c, source_c) return c.class == source_c.class end, -- Only marked clients (via awful.client.mark and .unmark). marked = function (c, source_c) --luacheck: no unused args return awful.client.ismarked(c) end, common_tag = function (c, source_c) if c == source_c then return true end cyclefocus.debug("common_tag_filter\n" .. cyclefocus.get_object_name(c) .. " <=> " .. cyclefocus.get_object_name(source_c), 3) for _, t in pairs(c:tags()) do for _, t2 in pairs(source_c:tags()) do if t == t2 then cyclefocus.debug('common_tag_filter: client shares tag "' .. cyclefocus.get_object_name(t) .. '" with "' .. cyclefocus.get_object_name(c)..'"', 2) return true end end end return false end, -- EXPERIMENTAL: -- Skip clients that were added through "focus" signal. -- Replaces only_add_internal_focus_changes_to_history. not_through_focus_signal = function (c, source_c) --luacheck: no unused args local attribs = cyclefocus.history.attribs(c) return not attribs.source or attribs.source ~= "focus" end, } local ignore_focus_signal = false -- Flag to ignore the focus signal internally. local showing_client -- This can be used in signal handlers to e.g. skip changing border_width. cyclefocus.get_shown_client = function() return showing_client end -- Debug function. Set focusstyle.debug to activate it. {{{ cyclefocus.debug = function(msg, level) level = level or 1 if not cyclefocus.debug_level or cyclefocus.debug_level < level then return end if cyclefocus.debug_use_naughty_notify then naughty.notify({ -- TODO: use indenting -- text = tostring(msg)..' ['..tostring(level)..']', text = tostring(msg), timeout = 10, }) end print("cyclefocus: " .. msg) end local get_object_name = function (o) if not o then return '[no object]' elseif not o.valid then return '[invalid object]' elseif not o.name then return '[no object name]' else return o.name end end cyclefocus.get_object_name = get_object_name local utf8_truncate = function (s, length) if length == 0 then return s end local n = 0 for i = 1, s:len() do local b = s:byte(i) if b < 0x80 or b >= 0xc0 then n = n + 1 if n > length then return s:sub(1, i - 1) .. '…' end end end return s end cyclefocus.get_client_title = function (c, current) --luacheck: no unused args -- Use get_object_name to handle .name=nil. local title = cyclefocus.get_object_name(c) return utf8_truncate(title, 80) end -- }}} -- Internal functions to handle the focus history. {{{ -- Based on awful.client.focus.history. local history = { stack = {} } --- Remove a client from the history stack. -- @tparam table Client. function history.delete(c) local k = history._get_key(c) if k then table.remove(history.stack, k) end end function history._get_key(c) for k, v in ipairs(history.stack) do if v[1] == c then return k end end end function history.attribs(c) local k = history._get_key(c) if k then return history.stack[k][2] end end function history.clear() history.stack = {} end -- @param filter: a function / boolean to filter clients: true means to add it. function history.add(c, filter, append, attribs) filter = filter or cyclefocus.filter_focus_history append = append or false attribs = attribs or {} -- Less verbose debugging during startup/restart. cyclefocus.debug("history.add: " .. get_object_name(c), capi.awesome.startup and 4 or 2) if filter and type(filter) == "function" then if not filter(c) then cyclefocus.debug("Filtered! " .. get_object_name(c), 2) return true end end -- Remove any existing entries from the stack. history.delete(c) if append then table.insert(history.stack, {c, attribs}) else table.insert(history.stack, 1, {c, attribs}) end -- Manually add it to awesome's internal history (where we've removed the -- signal from). awful.client.focus.history.add(c) end function history.movetotop(c) local attribs = history.attribs(c) history.add(c, true, false, attribs) end function history.append(c, filter, attribs) return history.add(c, filter, true, attribs) end --- Save the history into a X property. function history.persist() local ids = {} for _, v in ipairs(history.stack) do table.insert(ids, v[1].window) end local xprop = table.concat(ids, " ") capi.awesome.set_xproperty('awesome.cyclefocus.history', xprop) end --- Load history from the X property. function history.load() local xprop = capi.awesome.get_xproperty('awesome.cyclefocus.history') if not xprop or xprop == "" then return end local cls = capi.client.get() local ids = {} for id in string.gmatch(xprop, "%S+") do table.insert(ids, 1, id) end for _,window in ipairs(ids) do for _,c in pairs(cls) do if tonumber(window) == c.window then history.add(c, true, false, {source="load"}) break end end end end -- Persist history when restarting awesome. capi.awesome.register_xproperty('awesome.cyclefocus.history', 'string') capi.awesome.connect_signal("exit", function(restarting) ignore_focus_signal = true if restarting then history.persist() end end) -- On startup / restart: load the history and jump to the last focused client. cyclefocus.load_on_startup = function() capi.awesome.disconnect_signal("refresh", cyclefocus.load_on_startup) ignore_focus_signal = true history.load() if history.stack[1] then showing_client = history.stack[1][1] showing_client:jump_to() showing_client = nil end ignore_focus_signal = false end capi.awesome.connect_signal("refresh", cyclefocus.load_on_startup) -- Export it. At least history.add should be. cyclefocus.history = history -- }}} -- Connect to signals. {{{ -- Add clients that got focused to the history stack, -- but not when we are cycling through the clients ourselves. capi.client.connect_signal("focus", function (c) if ignore_focus_signal or capi.awesome.startup then cyclefocus.debug("Ignoring focus signal: " .. get_object_name(c), 4) return end history.add(c, nil, nil, {source="focus"}) end) -- Disable awesome's internal history handler to handle `ignore_focus_signal`. -- https://github.com/awesomeWM/awesome/pull/906. if awful.client.focus.history.disable_tracking then awful.client.focus.history.disable_tracking() else capi.client.disconnect_signal("focus", awful.client.focus.history.add) end capi.client.connect_signal("manage", function (c) if ignore_focus_signal then cyclefocus.debug("Ignoring focus signal (manage): " .. get_object_name(c), 2) return end -- During startup: append any clients, to make them known, -- but not override history.load etc. if capi.awesome.startup then history.append(c) else history.add(c, nil, false, {source="manage"}) end end) capi.client.connect_signal("unmanage", function (c) history.delete(c) end) -- }}} -- Raise a client (does not include focusing). -- Default implementation for raise_client option. -- NOTE: awful.client.jumpto also focuses the screen / resets the mouse. -- See https://github.com/blueyed/awesome-cyclefocus/issues/6 -- Based on awful.client.jumpto, without the code for mouse. -- Calls tag:viewonly always to update the tag history, also when -- the client is visible. cyclefocus.raise_client_without_focus = function(c) -- Try to make client visible, this also covers e.g. sticky local t = c:tags()[1] if t then t:view_only() end c:jump_to() end local restore_callback_show_client local show_client_restore_client_props = {} client.connect_signal("unmanage", function (c) if c == restore_callback_show_client then restore_callback_show_client = nil end if c == showing_client then showing_client = nil end if show_client_restore_client_props[c] then show_client_restore_client_props[c] = nil end end) local beautiful = require("beautiful") --- Callback to get properties for clients that are shown during cycling. -- @client c -- @return table cyclefocus.decorate_show_client = function(c) return { -- border_color = beautiful.fg_focus, border_color = beautiful.border_focus, border_width = c.border_width or 1, -- XXX: changes layout / triggers resizes. -- border_width = 10, } end --- Callback to get properties for other clients that are visible during cycling. -- @client c -- @return table cyclefocus.decorate_show_client_others = function(c) --luacheck: no unused args return { -- XXX: too distracting. -- opacity = 0.7 } end local show_client_apply_props = {} local show_client_apply_props_others = {} local show_client_restore_client_props_others = {} local callback_show_client_lock local decorate_if_showing_client = function (c) if c == showing_client then cyclefocus.callback_show_client(c) end end -- A table with property callbacks. Could be merged with decorate_if_showing_client. local update_show_client_restore_client_props = {} --- Callback when a client gets shown during cycling. -- This can be overridden itself, but it's meant to be configured through -- decorate_show_client instead. -- @client c -- @param boolean Restore the previous state? cyclefocus.callback_show_client = function (c, restore) if callback_show_client_lock then return end callback_show_client_lock = true if restore then -- Restore all saved properties. if show_client_restore_client_props[c] then -- Disconnect signals. for k,_ in pairs(show_client_restore_client_props[c]) do client.disconnect_signal("property::" .. k, decorate_if_showing_client) client.disconnect_signal("property::" .. k, update_show_client_restore_client_props[c][k]) end for k,v in pairs(show_client_restore_client_props[c]) do c[k] = v end -- Restore properties for other clients. for _c,props in pairs(show_client_restore_client_props_others[c]) do for k,v in pairs(props) do -- XXX: might have an "invalid object" here! _c[k] = v end end show_client_apply_props[c] = nil show_client_restore_client_props[c] = nil show_client_restore_client_props_others[c] = nil end else -- Save orig settings on first call. local first_call = not show_client_restore_client_props[c] if first_call then show_client_restore_client_props[c] = {} show_client_apply_props[c] = {} -- Get props to apply and store original values. show_client_apply_props[c] = cyclefocus.decorate_show_client(c) update_show_client_restore_client_props[c] = {} for k,_ in pairs(show_client_apply_props[c]) do show_client_restore_client_props[c][k] = c[k] end -- Get props for other clients and store original values. -- TODO: handle all screens?! show_client_apply_props_others[c] = cyclefocus.decorate_show_client_others(c) show_client_restore_client_props_others[c] = {} for s in capi.screen do for _,_c in pairs(awful.client.visible(s)) do if _c ~= c then show_client_restore_client_props_others[c][_c] = {} for k,_ in pairs(show_client_apply_props_others[c]) do show_client_restore_client_props_others[c][_c][k] = _c[k] end end end end end -- Apply props from callback. for k,v in pairs(show_client_apply_props[c]) do c[k] = v end -- Apply props for other clients. for _c,_ in pairs(show_client_restore_client_props_others[c]) do for k,v in pairs(show_client_apply_props_others[c]) do _c[k] = v -- see: XXX_1 end end if first_call then for k,_ in pairs(show_client_apply_props[c]) do client.connect_signal("property::" .. k, decorate_if_showing_client) -- Update client props to be restored during showing a client, -- e.g. border_color from focus signals. update_show_client_restore_client_props[c][k] = function() if c.valid then show_client_restore_client_props[c][k] = c[k] end end client.connect_signal("property::" .. k, update_show_client_restore_client_props[c][k]) end -- TODO: merge with above; also disconnect on restore. -- for k,v in pairs(show_client_apply_props_others[c]) do -- client.connect_signal("property::" .. k, decorate_if_showing_client) -- end end end callback_show_client_lock = false end -- Handle temporarily setting "ontop" for shown clients. -- This is a function that keeps track and handles the related "below", -- "above", and "fullscreen" properties. -- Ref: https://github.com/awesomeWM/awesome/issues/667 local restore_ontop_c -- Helper function to restore state of the temporarily selected client. cyclefocus.show_client = function (c) showing_client = c if c then if restore_callback_show_client then cyclefocus.callback_show_client(restore_callback_show_client, true) end restore_callback_show_client = c -- Restore ontop (and related) properties. if restore_ontop_c then restore_ontop_c() restore_ontop_c = nil end -- Handle setting ontop for the current client. -- This involves managing other properties, since setting "ontop" -- resets "fullscreen", "below", and "above". if not c.ontop then if c.fullscreen then -- Keep fullscreen clients as is. -- This requires to temporarily unset ontop for others. -- NOTE: the client might not be visible with other ontop clients -- after selecting it. This could be handled by setting -- ontop in the end (unsetting its fullscreen then though). local ontop_restore_clients = {} for _,_c in pairs(awful.client.visible(client.screen)) do if _c.ontop then table.insert(ontop_restore_clients, _c) _c.ontop = false end end if #ontop_restore_clients then function restore_ontop_c() for _,_c in pairs(ontop_restore_clients) do if _c.valid then _c.ontop = true end end end end else local ontop_orig_props = {c.ontop, c.below, c.above, c.fullscreen} function restore_ontop_c() if c.valid then c.ontop = ontop_orig_props[1] c.below = ontop_orig_props[2] c.above = ontop_orig_props[3] c.fullscreen = ontop_orig_props[4] end end c.ontop = true end end -- Make the clients tag visible, if it currently is not. local sel_tags = c.screen.selected_tags local c_tag = c.first_tag or c:tags()[1] if c_tag and not awful.util.table.hasitem(sel_tags, c_tag) then -- Select only the client's first tag, after de-selecting -- all others. -- Make the client sticky temporarily, so it will be -- considered visbile internally. -- NOTE: this is done for client_maybevisible (used by autofocus). local restore_sticky = c.sticky c.sticky = true for _, t in pairs(c.screen.tags) do if t ~= c_tag then t.selected = false end end c_tag.selected = true -- Restore. c.sticky = restore_sticky end cyclefocus.callback_show_client(c, false) else -- No client provided, restore only. if restore_ontop_c then restore_ontop_c() restore_ontop_c = nil end cyclefocus.callback_show_client(restore_callback_show_client, true) showing_client = nil end end --- Cached main wibox. local wbox local wbox_screen local layout -- Main function. cyclefocus.cycle = function(startdirection_or_args, args) if type(startdirection_or_args) == 'number' then awful.util.deprecate('startdirection is not used anymore: pass in args only', {raw=true}) else args = startdirection_or_args end args = awful.util.table.join(awful.util.table.clone(cyclefocus), args) -- The key name of the (last) modifier: this gets used for the "release" event. local modifier = args.modifier or 'Alt_L' local keys = args.keys or {'Tab', 'ISO_Left_Tab'} local shift = args.shift or 'Shift' -- cycle_filters: merge with defaults from module. local cycle_filters = awful.util.table.join(args.cycle_filters or {}, cyclefocus.cycle_filters) -- Use "Escape" as exit_key if not used as key. local exit_key = args.exit_key if exit_key == nil then for _,key in pairs({'Escape', 'q'}) do if not awful.util.table.hasitem(keys, key) then exit_key = key break end end end -- Not documented. local get_client_icon_widget = args.get_client_icon_widget local filter_result_cache = {} -- Holds cached filter results. local show_clients = args.show_clients if show_clients and type(show_clients) ~= 'function' then show_clients = cyclefocus.show_client end local raise_client_fn = args.raise_client if raise_client_fn and type(raise_client_fn) ~= 'function' then raise_client_fn = cyclefocus.raise_client_without_focus end -- Support single filter. if args.cycle_filter then cycle_filters = awful.util.table.clone(cycle_filters) table.insert(cycle_filters, args.cycle_filter) end -- Set flag to ignore any focus events while cycling through clients. ignore_focus_signal = true -- Internal state. local initiating_client = args.initiating_client or capi.client.focus -- Will be jumped to via Escape (abort). -- Save list of selected tags for all screens. local restore_tag_selected = {} for s in capi.screen do restore_tag_selected[s] = {} for _,t in pairs(s.tags) do restore_tag_selected[s][t] = t.selected end end --- Helper function to get the next client. -- @param direction 1 (forward) or -1 (backward). -- @param idx Current index in the stack. -- @param stack Current stack (default: history.stack). -- @param consider_cur_idx Also look at the current idx, and consider it -- when it's not focused. -- @return client or nil and current index in stack. local get_next_client = function(direction, idx, stack, consider_cur_idx) local startidx = idx stack = stack or history.stack consider_cur_idx = consider_cur_idx or args.focus_clients local nextc cyclefocus.debug('get_next_client: #' .. idx .. ", dir=" .. direction .. ", start=" .. startidx .. ", consider_cur=" .. tostring(consider_cur_idx), 2) local n = #stack if consider_cur_idx then local c_top = stack[idx][1] if c_top ~= capi.client.focus then n = n+1 cyclefocus.debug("Considering nextc from top of stack: " .. tostring(c_top), 2) else consider_cur_idx = false end end for loop_stack_i = 1, n do if not consider_cur_idx or loop_stack_i ~= 1 then idx = idx + direction if idx < 1 then idx = #stack elseif idx > #stack then idx = 1 end end cyclefocus.debug('find loop: #' .. idx .. ", dir=" .. direction, 3) nextc = stack[idx][1] if nextc then -- Filtering. if cycle_filters then -- Get and init filter cache data structure. {{{ -- TODO: move function(s) up? local get_cached_filter_result = function(f, a, b) b = b or false -- handle nil if filter_result_cache[f] == nil then filter_result_cache[f] = { [a] = { [b] = { } } } return nil elseif filter_result_cache[f][a] == nil then filter_result_cache[f][a] = { [b] = { } } return nil elseif filter_result_cache[f][a][b] == nil then return nil end return filter_result_cache[f][a][b] end local set_cached_filter_result = function(f, a, b, value) b = b or false -- handle nil get_cached_filter_result(f, a, b) -- init filter_result_cache[f][a][b] = value end -- }}} -- Apply filters, while looking up cache. local filter_result for _k, filter in pairs(cycle_filters) do cyclefocus.debug("Checking filter ".._k.."/"..#cycle_filters..": "..tostring(filter), 4) filter_result = get_cached_filter_result(filter, nextc, initiating_client) if filter_result ~= nil then if not filter_result then nextc = false break end else filter_result = filter(nextc, initiating_client) set_cached_filter_result(filter, nextc, initiating_client, filter_result) if not filter_result then cyclefocus.debug("Filtering/skipping client: " .. get_object_name(nextc), 3) nextc = false break end end end end if nextc then -- Found client to switch to. break end end end cyclefocus.debug("get_next_client returns: " .. get_object_name(nextc) .. ', idx=' .. idx, 1) return nextc, idx end local first_run = true local nextc local idx = 1 -- Currently focused client in the stack. -- Get the screen before moving the mouse. local initial_screen = awful.screen.focused and awful.screen.focused() or mouse.screen -- Move mouse pointer away to avoid sloppy focus kicking in. local restore_mouse_coords if show_clients and args.move_mouse_pointer then local s = capi.screen[capi.mouse.screen] local coords = capi.mouse.coords() restore_mouse_coords = {s = s, x = coords.x, y = coords.y} local pos = {x = s.geometry.x, y = s.geometry.y} -- move cursor without triggering signals mouse::enter and mouse::leave capi.mouse.coords(pos, true) restore_mouse_coords.moved = pos end capi.keygrabber.run(function(mod, key, event) -- Helper function to exit out of the keygrabber. -- If a client is given, it will be jumped to. local exit_grabber = function(c) cyclefocus.debug("exit_grabber: " .. get_object_name(c), 2) if wbox then wbox.visible = false end capi.keygrabber.stop() -- Restore. if show_clients then show_clients() end -- Restore previously selected tags for screen(s). -- With a given client, handle other screens first, otherwise -- the focus might be on the wrong screen. if restore_tag_selected then for s in capi.screen do if not c or s ~= c.screen then for _,t in pairs(s.tags) do t.selected = restore_tag_selected[s][t] end end end end -- Restore mouse if it has not been moved during cycling. if restore_mouse_coords then if restore_mouse_coords.s == capi.screen[capi.mouse.screen] then local coords = capi.mouse.coords() local moved_coords = restore_mouse_coords.moved if moved_coords.x == coords.x and moved_coords.y == coords.y then capi.mouse.coords({x = restore_mouse_coords.x, y = restore_mouse_coords.y}, true) end end end if c then showing_client = c raise_client_fn(c) if c ~= initiating_client then history.movetotop(c) end showing_client = nil end ignore_focus_signal = false return true end cyclefocus.debug("grabber: mod: " .. table.concat(mod, ',') .. ", key: " .. tostring(key) .. ", event: " .. tostring(event) .. ", modifier_key: " .. tostring(modifier), 3) if exit_key and key == exit_key then return exit_grabber(initiating_client) elseif #mod == 1 and mod[1] == 'Control' and key == 'c' then -- exit on Ctrl-C always. return exit_grabber(initiating_client) end -- Direction (forward/backward) is determined by status of shift. local direction = awful.util.table.hasitem(mod, shift) and -1 or 1 if event == "release" and key == modifier then -- Focus selected client when releasing modifier. -- When coming here on first run, the trigger was pressed quick and -- we need to fetch the next client while exiting. if first_run then nextc, idx = get_next_client(direction, idx) end if show_clients then show_clients(nextc) end return exit_grabber(nextc) end -- Ignore any "release" events and unexpected keys, except for the first run. if not first_run then if not awful.util.table.hasitem(keys, key) then cyclefocus.debug("Ignoring unexpected key: " .. tostring(key), 1) return true end if event == "release" then return true end end first_run = false nextc, idx = get_next_client(direction, idx) if not nextc then return exit_grabber() end -- Show the client, which triggers setup of restore_callback_show_client etc. if show_clients then show_clients(nextc) end -- Focus client. if args.focus_clients then capi.client.focus = nextc end if not args.display_notifications then return true end local container_margin_top_bottom = dpi(5) local container_margin_left_right = dpi(5) if not wbox then wbox = wibox({ontop = true }) wbox._for_screen = mouse.screen wbox:set_fg(beautiful.fg_normal) wbox:set_bg("#ffffff00") local container_inner = wibox.layout.align.vertical() local container_layout = wibox.container.margin( container_inner, container_margin_left_right, container_margin_left_right, container_margin_top_bottom, container_margin_top_bottom) container_layout = wibox.container.background(container_layout) container_layout:set_bg(beautiful.bg_normal..'cc') wbox:set_widget(container_layout) -- "fixed" appears to work better for when there are no icons to -- prevent cropping of the text. layout = wibox.layout.fixed.vertical() container_inner:set_middle(layout) else layout:reset() end -- Set geometry always, the screen might have changed. if not wbox_screen or wbox_screen ~= initial_screen then wbox_screen = initial_screen local wa = screen[wbox_screen].workarea local w = math.ceil(wa.width * 0.618) wbox:geometry({ -- right-align. x = math.ceil(wa.x + wa.width - w), width = w, }) end local wbox_height = 0 -- Create entry with index, name and screen. local display_entry_for_idx_offset = function(offset, c, _idx, displayed_list) -- {{{ local preset = awful.util.table.clone(args.default_preset) -- Callback. local args_for_cb = { client=c, offset=offset, idx=_idx, displayed_list=displayed_list } local preset_for_offset = args.preset_for_offset -- Callback for all. if preset_for_offset.default then preset_for_offset.default(preset, args_for_cb) end -- Callback for offset. local preset_cb = preset_for_offset[tostring(offset)] if preset_cb then preset_cb(preset, args_for_cb) end local entry_layout = wibox.layout.fixed.horizontal() if preset.icon_size then local icon_widget = get_client_icon_widget(c, preset) if icon_widget then entry_layout:add(icon_widget) end end local textbox = wibox.widget.textbox() textbox:set_markup(preset.text) textbox:set_font(preset.font) textbox:set_wrap("word_char") textbox:set_ellipsize("middle") -- Set height to no wrap with fixed main layout. local _, h = textbox:get_preferred_size(c.screen) textbox:set_forced_height(h) local textbox_margin = wibox.container.margin(textbox) textbox_margin:set_margins(dpi(5)) entry_layout:add(textbox_margin) entry_layout = wibox.container.margin( entry_layout, dpi(5), dpi(5), dpi(2), dpi(2)) local entry_with_bg = wibox.container.background(entry_layout) if offset == 0 then entry_with_bg:set_fg(beautiful.fg_focus) entry_with_bg:set_bg(beautiful.bg_focus) else entry_with_bg:set_fg(beautiful.fg_normal) -- entry_with_bg:set_bg(beautiful.bg_normal.."dd") end layout:add(entry_with_bg) -- Add height to outer wibox. local context = {dpi=beautiful.xresources.get_dpi(initial_screen)} _, h = entry_with_bg:fit(context, wbox.width, 2^20) wbox_height = wbox_height + h end -- }}} -- Get clients before and after currently selected one. local prevnextlist = awful.util.table.clone(history.stack) -- Use a copy, entries will get nil'ed. local _idx = idx local dlist = {} -- A table with offset => stack index. dlist[0] = _idx prevnextlist[_idx][1] = false -- Build dlist for both directions, depending on how many entries should get displayed. for _,dir in ipairs({1, -1}) do _idx = dlist[0] local n = dir == 1 and args.display_next_count or args.display_prev_count for i = 1, n do local _i = i * dir _, _idx = get_next_client(dir, _idx, prevnextlist, false) if _ then dlist[_i] = _idx end prevnextlist[_idx][1] = false end end -- Sort the offsets. local offsets = {} for n in pairs(dlist) do table.insert(offsets, n) end table.sort(offsets) -- Display the wibox. for _,i in ipairs(offsets) do _idx = dlist[i] display_entry_for_idx_offset(i, history.stack[_idx][1], _idx, dlist) end local wa = screen[initial_screen].workarea local h = wbox_height + container_margin_top_bottom*2 wbox:geometry({ height = h, y = wa.y + floor(wa.height/2 - h/2), }) wbox.visible = true return true end) end -- A helper method to wrap awful.key. function cyclefocus.key(mods, key, startdirection_or_args, args) mods = mods or {modkey} or {"Mod4"} key = key or "Tab" if type(startdirection_or_args) == 'number' then awful.util.deprecate('startdirection is not used anymore: pass in mods, key, args', {raw=true}) else args = startdirection_or_args end args = args and awful.util.table.clone(args) or {} if not args.keys then if key == "Tab" then args.keys = {"Tab", "ISO_Left_Tab"} else args.keys = {key} end end if not args.modifier then -- Convert modifier to key name. -- Table from awful.key. local conversion = { mod4 = "Super_L", control = "Control_L", shift = "Shift_L", mod1 = "Alt_L", -- AltGr (https://github.com/awesomeWM/awesome/pull/2515). mod5 = "ISO_Level3_Shift", } args.modifier = conversion[mods[1]:lower()] if not args.modifier then args.modifier = mods[1] end end return awful.key(mods, key, function(c) args.initiating_client = c -- only for clientkeys, might be nil! cyclefocus.cycle(args) end) end return cyclefocus
local x = { 1, 2, 3, 4, } for k, v in pairs(x) do print(k, v) end print("done")
return { code = 'PARAM_ILLEGAL', key = "PARAM_ILLEGAL", }
local QuestConstants = { Tables = { { Name = "QuestTagType", Type = "Enumeration", NumValues = 16, MinValue = 0, MaxValue = 15, Fields = { { Name = "Tag", Type = "QuestTagType", EnumValue = 0 }, { Name = "Profession", Type = "QuestTagType", EnumValue = 1 }, { Name = "Normal", Type = "QuestTagType", EnumValue = 2 }, { Name = "PvP", Type = "QuestTagType", EnumValue = 3 }, { Name = "PetBattle", Type = "QuestTagType", EnumValue = 4 }, { Name = "Bounty", Type = "QuestTagType", EnumValue = 5 }, { Name = "Dungeon", Type = "QuestTagType", EnumValue = 6 }, { Name = "Invasion", Type = "QuestTagType", EnumValue = 7 }, { Name = "Raid", Type = "QuestTagType", EnumValue = 8 }, { Name = "Contribution", Type = "QuestTagType", EnumValue = 9 }, { Name = "RatedReward", Type = "QuestTagType", EnumValue = 10 }, { Name = "InvasionWrapper", Type = "QuestTagType", EnumValue = 11 }, { Name = "FactionAssault", Type = "QuestTagType", EnumValue = 12 }, { Name = "Islands", Type = "QuestTagType", EnumValue = 13 }, { Name = "Threat", Type = "QuestTagType", EnumValue = 14 }, { Name = "CovenantCalling", Type = "QuestTagType", EnumValue = 15 }, }, }, { Name = "RelativeContentDifficulty", Type = "Enumeration", NumValues = 5, MinValue = 0, MaxValue = 4, Fields = { { Name = "Trivial", Type = "RelativeContentDifficulty", EnumValue = 0 }, { Name = "Easy", Type = "RelativeContentDifficulty", EnumValue = 1 }, { Name = "Fair", Type = "RelativeContentDifficulty", EnumValue = 2 }, { Name = "Difficult", Type = "RelativeContentDifficulty", EnumValue = 3 }, { Name = "Impossible", Type = "RelativeContentDifficulty", EnumValue = 4 }, }, }, { Name = "QuestWatchConsts", Type = "Constants", Values = { { Name = "MAX_QUEST_WATCHES", Type = "number", Value = 25 }, { Name = "MAX_WORLD_QUEST_WATCHES_AUTOMATIC", Type = "number", Value = 1 }, { Name = "MAX_WORLD_QUEST_WATCHES_MANUAL", Type = "number", Value = 5 }, }, }, }, }; APIDocumentation:AddDocumentationTable(QuestConstants);
-- 6Harmonics Qige @ K2E 7S4 -- 2017.03.01 local cmd = require 'six.cmd' local conf = require 'six.conf' local fmt = require 'six.fmt' local ABB = require 'kpi.ABB' local NW = {} NW.conf = {} NW.conf.eth_ifname = 'eth0' NW.conf.wls_ifname = 'wlan0' NW.conf.ap_ifname = 'br-lan' NW.cache = {} NW.cache._bridge = 0 NW.cache._eth_ip = '' NW.cache._wls_ip = '' NW.cache._eth_txb = 0 NW.cache._eth_rxb = 0 NW.cache._wls_txb = 0 NW.cache._wls_rxb = 0 NW.cache.ts = os.time() NW.ops = {} function NW.ops.Update() local _result local _fmt = '{"bridge": %d, "wan_ip": "%s", "lan_ip": "%s"' _fmt = _fmt .. ' ,"eth_rxb": %d, "eth_txb": %d, "wls_rxb": %d, "wls_txb": %d }' local _data = NW.ops.read() _result = string.format(_fmt, _data.bridge or 1, _data.wan_ip or '-', _data.lan_ip or '-', _data.eth_rxb or 0, _data.eth_txb or 0, _data.wls_rxb or 0, _data.wls_txb or 0) return _result end function NW.ops.Data() local _data = NW.ops.read() return _data end function NW.ops.conf() if (conf.file.get('network', 'lan', 'type') == 'bridge') then NW.cache._bridge = 1 else NW.cache._bridge = 0 end NW.cache._wls_ip = conf.file.get('network', 'lan', 'ipaddr') NW.cache._eth_ip = conf.file.get('network', 'wan', 'ipaddr') end -- TODO: fix CAR with muilti EARs function NW.ops.thrpt() local wls_mode = ABB.cache.mode() if (wls_mode == 'CAR' or wls_mode == 'Mesh') then wls_ifname = NW.conf.ap_ifname eth_ifname = NW.conf.eth_ifname else wls_ifname = NW.conf.wls_ifname eth_ifname = NW.conf.eth_ifname end -- read LAN rxbytes, txbytes local _wls_rxbtxb = NW.get.rxbtxb(wls_ifname) if (_wls_rxbtxb and #_wls_rxbtxb >= 2) then NW.cache._wls_rxb = _wls_rxbtxb[1] NW.cache._wls_txb = _wls_rxbtxb[2] else NW.cache._wls_rxb = 0 NW.cache._wls_txb = 0 end -- read WAN rxbytes, txbytes local _eth_rxbtxb = NW.get.rxbtxb(eth_ifname) if (_eth_rxbtxb and #_eth_rxbtxb >= 2) then NW.cache._eth_rxb = _eth_rxbtxb[1] NW.cache._eth_txb = _eth_rxbtxb[2] else NW.cache._eth_rxb = 0 NW.cache._eth_txb = 0 end end function NW.ops.read() local _nw = {} -- call for update NW.ops.conf() NW.ops.thrpt() _nw.bridge = NW.cache._bridge _nw.wan_ip = NW.cache._eth_ip _nw.lan_ip = NW.cache._wls_ip _nw.eth_rxb = fmt.n(NW.cache._eth_rxb) _nw.eth_txb = fmt.n(NW.cache._eth_txb) _nw.wls_rxb = fmt.n(NW.cache._wls_rxb) _nw.wls_txb = fmt.n(NW.cache._wls_txb) return _nw end NW.get = {} -- read rxbytes, txbytes -- /proc/net/dev col2=rxbytes, col10=txbytes function NW.get.rxbtxb(ifname) local _fmt = "cat /proc/net/dev | grep %s -m1 | awk '{print $2,$10}'\n" local _cmd = string.format(_fmt, ifname) local _bytes = cmd.exec(_cmd) local _rxbtxb if (_bytes) then _rxbtxb = fmt.str.split(_bytes, ' ') end return _rxbtxb end return NW
--海造賊-黒翼の水先人 --Ravenwing, the Plunder Patroll Pilot --Scripted by Kohana Sonogami function c101104018.initial_effect(c) --to hand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(101104018,0)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_HAND) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCountLimit(1,101104018) e1:SetTarget(c101104018.thtg) e1:SetOperation(c101104018.thop) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(101104018,1)) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY) e2:SetCode(EVENT_TO_GRAVE) e2:SetCountLimit(1,101104018+100) e2:SetCondition(c101104018.spcon) e2:SetTarget(c101104018.sptg) e2:SetOperation(c101104018.spop) c:RegisterEffect(e2) end function c101104018.thfilter(c) return c:IsSetCard(0x13f) and c:IsType(TYPE_MONSTER) and not c:IsCode(101104018) and c:IsAbleToHand() end function c101104018.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c101104018.thfilter(chkc) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingTarget(c101104018.thfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND) local g=Duel.SelectTarget(tp,c101104018.thfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0) end function c101104018.thop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)~=0 and tc:IsRelateToEffect(e) then Duel.SendtoHand(tc,nil,REASON_EFFECT) end local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetTarget(c101104018.splimit) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) end function c101104018.splimit(e,c,sump,sumtype,sumpos,targetp,se) return not c:IsSetCard(0x13f) end function c101104018.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsPreviousLocation(LOCATION_HAND+LOCATION_MZONE) end function c101104018.spfilter(c,e,tp) return c:IsSetCard(0x13f) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE) end function c101104018.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and c101104018.spfilter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c101104018.spfilter,tp,LOCATION_SZONE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c101104018.spfilter,tp,LOCATION_SZONE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c101104018.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE) end end
require("opener").setup({ post_open = { function(new_dir) require('fzf-lua').files() end }, })
object_tangible_meatlump_event_meatlump_bomb_01_03 = object_tangible_meatlump_event_shared_meatlump_bomb_01_03:new { } ObjectTemplates:addTemplate(object_tangible_meatlump_event_meatlump_bomb_01_03, "object/tangible/meatlump/event/meatlump_bomb_01_03.iff")
local gemm = require("gemm") local cstdio = terralib.includec("stdio.h") local stdlib = terralib.includec("stdlib.h") -- Set number to float in case of Single Float Point tests local number = double local function isinteger(x) return math.floor(x) == x end local llvmprefetch = terralib.intrinsic("llvm.prefetch",{&opaque,int,int,int} -> {}) local dotune = false -- terra naivel1conv(A : &number, B : &number, C : &number, lda : int, ldb : int, ldc : int, alpha : number) function symmat(name,I,...) if not I then return symbol(name) end local r = {} for i = 0,I-1 do r[i] = symmat(name..tostring(i),...) end return r end function printMatrix(m,rows,columns) local matrix = m for i=0,rows-1 do for j=0,columns-1 do io.write(" " .. matrix[i*columns + j]) end io.write("\n") end io.write("\n") end terra max(a : int, b : int) return terralib.select(a > b, a, b) end -- terra min(a : int, b : int) -- return terralib.select(a < b, a, b) -- end -- function blockedloop(M,N,blocksizes,bodyfn) -- local function generatelevel(n,ii,jj,bb0,bb1) -- if n > #blocksizes then -- return bodyfn(ii,jj) -- end -- local blocksize = blocksizes[n] -- return quote for i = ii,min(ii+bb0,M),blocksize do -- for j = jj,min(jj+bb1,N),blocksize do -- [ generatelevel(n+1,i,j,blocksize,blocksize) ] -- end end end -- end -- return generatelevel(1,0,0,M,N) -- end function gennaivegemm() return terra(gettime : {} -> number, CC : &number, AA : &number, BB : &number, M : int, N : int, K : int, ix : int, iy : int) for m=ix, M do for n=iy, N do CC[m*N + n] = 0 for k=0, K do CC[m*N + n] = CC[m*N + n] + AA[m*K + k] * BB[k*N + n] end end end end end function gennaiveconv() return terra(gettime : {} -> number, M : int, N : int, K : int, L: int, alpha : number, A : &number, sda: int, lda : int, B : &number, ldb : int, C : &number, sdc : int, ldc : int, kCenterX: int, kCenterY: int, depth : int) var dimKer : int = K*L var kCenterX : int = K/2 var kCenterY : int = L/2 var e = 0 for d=0, depth do var baseKer = dimKer * d for i=kCenterX, M-kCenterX do for j=kCenterY, N-kCenterY do C[e] = 0 for m=0, K do for n=0,L do -- boundaries var ii: int = i + (m - kCenterY) var jj: int = j + (n - kCenterX) if ii>=0 and ii<M and jj>=0 and jj<N then C[e] = C[e] + A[ii * N + jj] * B[baseKer + m * L + n] end end end e = e+1 end end end end end -- function blockedloop(M,N,blocksizes,bodyfn) -- local function generatelevel(n,ii,jj,bb0,bb1) -- if n > #blocksizes then -- return bodyfn(ii,jj) -- end -- local blocksize = blocksizes[n] -- return quote for i = ii,min(ii+bb0,M),blocksize do -- for j = jj,min(jj+bb1,N),blocksize do -- [ generatelevel(n+1,i,j,blocksize,blocksize) ] -- end end end -- end -- return generatelevel(1,0,0,M,N) -- end function genlowimage(loweringtype,NB) return terra(M : int, N : int, K : int, L: int, A : &number, AA : &number) if loweringtype == 1 then var cx : int = K/2 var cy : int = L/2 var base : int var elem : int for mm = cx,M-cx,NB do for nn = cy,N-cy,NB do for m = mm,min(mm+NB,M-cx) do for n = nn,min(nn+NB,N-cy) do for k=0, K do for l=0, L do var ii: int = m + (k - cy) var jj: int = n + (l - cx) elem = (m-cx)*(N-2*cy)+(n-cy) base = K*L AA[elem*base + k*K+l] = A[ii * N + jj] end end end end end end end end end -- Different types according to Caffe con Troll can be implemented function genlowkernel(loweringtype) return terra( Bs : &number, K : int, L : int, BBs : &number, Klow : int, Llow : int) if loweringtype == 1 then var base = Klow var count = 0 for d=0,Llow do for i=0,Klow do BBs[i*Llow + d] = Bs[base*d + i] end end end end end function liftresult(loweringtype) return terra(C : &number, M : int, N : int, Clow : &number, Mlow : int, Llow : int) if loweringtype == 1 then var count = 0 for i=0,Llow do for j=0,Mlow do -- iterate over all the columns first C[count] = Clow[j*Llow + i] count = count + 1 end end end end end terra printMatrix(m : &number,rows : int,columns : int,depth : int) var dim = rows * columns if depth > 1 then -- print each output for d=0,depth-1 do var base = dim * d for i=0,rows-1 do for j=0,columns-1 do io.write(" " .. m[base + i*columns + j]) end io.write("\n") end io.write("\n") end else -- usual matrix print for i=0,rows-1 do for j=0,columns-1 do io.write(" " .. m[i*columns + j]) end io.write("\n") end end io.write("\n") end terra print2D(A : &number, M : int, N : int) for i=0,M do for j=0,N do cstdio.printf("%1.f ", A[i*N + j]) end cstdio.printf("\n") end cstdio.printf("\n") end function genconvolution(NBL,NB,NBF,RM,RN,V,thsize) -- Lowering type according to CcT (http://arxiv.org/abs/1504.04343) local ltype = 1 -- Lower the image is the 2D direct method without the multiplication -- These are not kernels, they are FULL OPERATIONS -- naive gemm for borders -- local my_loweredimg = genLowImage(NB, NBF, RM, RN, V, K, L) local my_gemmopt = generatedgemm((NB*NB),5,RM,RN,V,thsize) local my_naivegemm = gennaivegemm() local my_loweredimg = genlowimage(ltype,NBL) local my_loweredker = genlowkernel(ltype) local my_liftedresult = liftresult(ltype) return terra(gettime : {} -> double, A : &number, M : int, N : int, K : int, L: int, alpha : number, B : &number, ldb : int, C : &number, sdc : int, ldc : int, kCenterX: int, kCenterY: int, depth : int, AA : &number, BB : &number, CC : &number) -- MlowxNlow * KlowxLlow, where Nlow == Llow ---> Mlow x Llow var Mlow, Nlow, Klow, Llow = sdc*ldc, K*L, K*L, depth -- (1) lower -- print2D(A,M,N) my_loweredimg(M,N,K,L,A,AA) -- print2D(AA,Mlow,Klow) my_loweredker(B,K,L,BB,Klow,Llow) -- print2D(BB,Klow,Llow) -- (2) gemm my_gemmopt(nil,Mlow,Llow,Klow,1.0,AA ,Klow,BB ,Llow,CC,Llow) -- print2D(CC,Mlow,Llow) -- (3) lifting my_liftedresult(C,M,N,CC,Mlow,Llow) -- print2D(CC,Mlow,Llow) -- printMatrix(C,sdc,ldc,depth) end end -- function genLowImageOPT(NB,NBF,RM,RN,V,K,L) -- -- register blocking does not need to be a a multiple of the blocksize anymore -- if not isinteger(NB/RN) or not isinteger(NB/RM) then -- print("3rd level blocksizes must be a multiple of the 2nd") -- return false -- end -- --5 times NB minimum by dgemm -- --local NB2 = NBF * NB -- local NB2 = NB * NBF -- local l1conv0 = genkernel(NB, RM, RN, true, K, L, false) -- local l1conv0b = genkernel(NB, 1, 1, true, K, L, true) -- return terra(gettime : {} -> number, M : int, N : int, K : int, L: int, -- alpha : number, A : &number, sda: int, lda : int, B : &number, ldb : int, C : &number, -- sdc : int, ldc : int, kCenterX: int, kCenterY: int, depth : int, batches : int) -- M = M-kCenterX -- N = N-kCenterY -- for mm = kCenterX,M,NB2 do -- for nn = kCenterY,N,NB2 do -- for m = mm,min(mm+NB2,M),NB do -- for n = nn,min(nn+NB2,N),NB do -- var MM,NN = min(M-m,NB),min(N-n,NB) -- var isboundary = MM < NB or NN < NB -- var AA,CC = A + ((m-kCenterX)*lda + (n-kCenterY)),C + ((m-kCenterX)*ldc + (n-kCenterY)) -- if isboundary then -- do not enter here YET -- l1conv0b(AA, -- B, -- CC, -- sda,lda,ldb,sdc,ldc,0,MM,NN) -- else -- l1conv0(AA, -- B, -- CC, -- sda,lda,ldb,sdc,ldc,0) -- -- todo: analyze prefetch argument, past => terralib.select(k == 0,0,1) -- end -- end -- end -- end -- end -- -- [ blockedloop(M,N,{NB2,NB}, -- -- function(m,n) -- -- return quote -- -- var MM,NN = min(M-m,NB),min(N-n,NB) -- -- var isboundary = MM < NB or NN < NB -- -- var AA,CC = A + (m*lda + n),C + (m*ldc + n) -- -- if isboundary then -- do not enter here YET -- -- l1conv0b(AA, -- -- B, -- -- CC, -- -- sda,lda,ldb,ldc,0,MM,NN) -- -- else -- -- l1conv0(AA, -- -- B, -- -- CC, -- -- sda,lda,ldb,ldc,0) -- -- todo: analyze prefetch argument, past => terralib.select(k == 0,0,1) -- -- end -- -- end end) -- -- ] -- end -- end -- Different blocksizes for the same result implies in padding overheading -- ending in s means SIZE -- starting with n, means NUMBER local blocksizes = {16,20,32} local regblocksM = {1,2,4} local regblocksN = {1,2,4} local vectors = {1,2,4,8} local filters = {3,7,13} local nfilter = {256} local nthread = {8} -- initialized (defined structure of best) local best = { gflops = 0, b = 5, rm = 5, rn = 5, v = 1, k = 3, f = 3 } local NBF = 5 local bl = 8 -- lowering blocksize if dotune then -- full size of the matrix local tunefor = 32--1024 --change for 10 later local harness = require("lib/low-matrixtestharness") for _,t in ipairs(nthread) do for _,f in ipairs(nfilter) do for _,k in ipairs(filters) do for _,b in ipairs(blocksizes) do for _,rm in ipairs(regblocksM) do for _,rn in ipairs(regblocksN) do for _,v in ipairs(vectors) do -- local my_conv = gennaiveconv() local my_conv = genconvolution(bl,b,NBF,rm,rn,v,t) -- local my_conv = generatedgemm(b,NB2,rm,rn,v) if my_conv then -- print(b,rm,rn,v,k,f) my_conv:compile() -- bellow line makes do not need boundary cases (image multiple of blocksize) local i = math.floor(tunefor / b) * b local curr_gflops = 0 local ctyp local time,correct, exectimes = harness.timefunctions(tostring(number),i,i,k,k,f, function(Me,Ne,K,L,M,N,A,Bs,Cs,f,AA,BB,CC) -- to gennaive pass the #kernels here my_conv(nil,A,Me,Ne,K,L,1.0,Bs,L,Cs,M,N,K/2,L/2,f,AA,BB,CC) -- my_conv receives integer parameter i.e. it represents floor of K/2 and L/2 end) -- test only GEMM -- local correct, exectimes = harness.timefunctionsGEMM(tostring(number),i,i,i,function(M,K,N,A,B,C) -- my_conv(nil,M,N,K,1.0,A,K,B,N,C,N) -- end) print(b,rm,rn,v,k,f,time) if not correct then print("<error>") break end --print(i,unpack (exectimes),"[OK]") local curr_gflops = exectimes[1] -- print(curr_gflops) -- print analysis if best.gflops < curr_gflops then -- Maximization problem (the greater gflops, the better) best = { gflops = curr_gflops, b = b, rm = rm, rn = rn, v = v, k = k, f = f } -- terralib.tree.printraw(best) end end end end end end end end end end local my_numconv = genconvolution(bl,best.b,NBF,best.rm,best.rn,best.v,nthread[1]) if number == double then terralib.saveobj("../bin/my_numconv.o", {my_numconv = my_numconv}) -- terralib.saveobj("../bin/my_dconv.o", {my_convolution = my_convolution}) else terralib.saveobj("../bin/my_numconv.o", {my_numconv = my_numconv}) end
local Color1 = color(Var "Color1"); local Color2 = color(Var "Color2"); local a1 = LoadActor(Var "File1") .. { OnCommand= function(self) self:cropto(SCREEN_WIDTH/2,SCREEN_HEIGHT/2):diffuse(Color1) :effectclock("music") -- Explanation in StretchNoLoop.lua. if self.GetTexture then self:GetTexture():rate(self:GetParent():GetUpdateRate()) end end, GainFocusCommand=cmd(play); LoseFocusCommand=cmd(pause); }; local a2 = LoadActor(Var "File2") .. { OnCommand= function(self) self:cropto(SCREEN_WIDTH/2,SCREEN_HEIGHT/2):diffuse(Color2):effectclock("music") -- Explanation in StretchNoLoop.lua. if self.GetTexture then self:GetTexture():rate(self:GetParent():GetUpdateRate()) end end, GainFocusCommand=cmd(play); LoseFocusCommand=cmd(pause); }; local t = Def.ActorFrame { a1 .. { OnCommand=cmd(x,scale(1,0,4,SCREEN_LEFT,SCREEN_RIGHT);y,scale(1,0,4,SCREEN_TOP,SCREEN_BOTTOM)); }; a2 .. { OnCommand=cmd(x,scale(3,0,4,SCREEN_LEFT,SCREEN_RIGHT);y,scale(1,0,4,SCREEN_TOP,SCREEN_BOTTOM)); }; a2 .. { OnCommand=function(self) self:x(scale(1,0,4,SCREEN_LEFT,SCREEN_RIGHT)):y(scale(3,0,4,SCREEN_TOP,SCREEN_BOTTOM)) if self.SetDecodeMovie then self:SetDecodeMovie(false) end end }; a1 .. { OnCommand=function(self) self:x(scale(3,0,4,SCREEN_LEFT,SCREEN_RIGHT)):y(scale(3,0,4,SCREEN_TOP,SCREEN_BOTTOM)) if self.SetDecodeMovie then self:SetDecodeMovie(false) end end }; }; return t;
local L = LibStub("AceLocale-3.0"):NewLocale("Grindon_Currency", "enUS", true) L["PluginName"] = "Currency" L["Gold"] = "Gold"
custom_halloween1_outfit = { { {objectTemplate = "object/tangible/tcg/series1/wearable_glowing_red_eyes.iff", customizationVariables = {} }, {objectTemplate = "object/tangible/wearables/robe/exar_cultist_hood_up.iff", customizationVariables = {} } } } addOutfitGroup("custom_halloween1_outfit", custom_halloween1_outfit)
platformParts:registerNewCase({ id = "_case_1", quad = "a1" }) platformParts:registerNewCase({ id = "_case_2", quad = "a2" }) platformParts:registerNewCase({ id = "_case_3", quad = "a3" }) platformParts:registerNewCase({ id = "_case_4", quad = "a4" }) platformParts:registerNewCase({ id = "_case_5", quad = "a5" }) platformParts:registerNewCase({ id = "_case_6", quad = "a6" })platformParts:registerNewCase({ id = "_case_7", quad = "a7" }) platformParts:registerNewCase({ id = "_case_8", quad = "a8" }) platformParts:registerNewCase({ id = "_case_9", quad = "a9" }) platformParts:registerNewCase({ id = "_case_10", quad = "a10" }) platformParts:registerNewCase({ id = "_case_11", quad = "a11" }) platformParts:registerNewCase({ id = "_case_12", quad = "a12" }) platformParts:registerNewCase({ id = "_case_13", quad = "a13" }) platformParts:registerNewCase({ id = "_case_14", quad = "a14" }) platformParts:registerNewCase({ id = "_case_15", quad = "a15" }) platformParts:registerNewCase({ id = "_case_16", quad = "a16" }) platformParts:registerNewCase({ id = "_case_17", quad = "a17" }) --platformParts:registerNewCase({ -- id = "_case_18", -- quad = "a18" --}) platformParts:registerNewCase({ id = "_case_19", quad = "a19" }) platformParts:registerNewCase({ id = "_case_20", quad = "a20" }) platformParts:registerNewCase({ id = "_case_21", quad = "a21" }) platformParts:registerNewCase({ id = "_case_221", quad = "a22" }) platformParts:registerNewCase({ id = "_case_23", quad = "a23" }) platformParts:registerNewCase({ id = "_case_24", quad = "a24" }) platformParts:registerNewCase({ id = "_case_25", quad = "a25" }) platformParts:registerNewCase({ id = "_case_26", quad = "a26" }) platformParts:registerNewCase({ id = "_case_27", quad = "a27" }) platformParts:registerNewCase({ id = "_case_28", quad = "a28" }) platformParts:registerNewCase({ id = "_case_29", quad = "a29" }) platformParts:registerNewCase({ id = "_case_30", quad = "a30" }) platformParts:registerNewCase({ id = "_case_31", quad = "a31" }) platformParts:registerNewCase({ id = "_case_33", quad = "a33" }) platformParts:registerNewCase({ id = "_case_34", quad = "a34" }) platformParts:registerNewCase({ id = "_case_35", quad = "a35" }) platformParts:registerNewCase({ id = "_case_36", quad = "a36" }) platformParts:registerNewCase({ id = "_case_37", quad = "a37" }) platformParts:registerNewCase({ id = "_case_38", quad = "a38" }) platformParts:registerNewCase({ id = "_case_39", quad = "a39" }) platformParts:registerNewCase({ id = "_case_40", quad = "a40" }) platformParts:registerNewCase({ id = "_case_42", quad = "a42" }) platformParts:registerNewCase({ id = "_case_43", quad = "a43" }) platformParts:registerNewCase({ id = "_case_44", quad = "a44" }) platformParts:registerNewCase({ id = "_case_45", quad = "a45" }) platformParts:registerNewCase({ id = "_case_46", quad = "a46" }) platformParts:registerNewCase({ id = "_case_47", quad = "a47" })
local night_table = { --name, material, invimg {'Wood Nightstand', 'wood'}, {'Acacia Wood Nightstand', 'acacia_wood'}, {'Aspen Wood Nightstand', 'aspen_wood'}, {'Pine Wood Nightstand', 'pine_wood'}, {'Jungle Wood Nightstand', 'junglewood'} } for i in ipairs (night_table) do local name = night_table[i][1] local material = night_table[i][2] local invimg = night_table[i][3] minetest.register_node('ma_pops_furniture:nightstand_'..material, { description = name, drawtype = 'nodebox', tiles = {'default_'..material..'.png'}, groups = {choppy=2, oddly_breakably_by_hand=2, furniture=1, flammable=1}, paramtype = 'light', paramtype2 = 'facedir', sounds = moditems.WOOD_SOUNDS, on_construct = function(pos) local meta = minetest.env:get_meta(pos) local inv = meta:get_inventory() inv:set_size('main', 8*4) inv:set_size('storage', 3*3) meta:set_string('formspec', 'size [9,10]'.. 'bgcolor[#080808BB;true]'.. 'list[current_name;storage;3,1.5;3,3;]'.. 'list[current_player;main;0.5,6.2;8,4;]') end, can_dig = function(pos,player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() return inv:is_empty('storage') and inv:is_empty('storage1') end, node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.4375, 0.5, -0.4375, 0.5}, -- NodeBox1 {-0.5, 0.4375, -0.4375, 0.5, 0.5, 0.5}, -- NodeBox2 {-0.5, -0.4375, -0.375, 0.5, 0.4375, 0.5}, -- NodeBox3 {-0.4375, 0.0625, -0.4375, 0.4375, 0.375, -0.375}, -- NodeBox4 {-0.4375, -0.375, -0.4375, 0.4375, -0.0625, -0.375}, -- NodeBox5 {-0.125, -0.3125, -0.5, 0.125, -0.125, -0.4375}, -- NodeBox6 {-0.125, 0.125, -0.5, 0.125, 0.3125, -0.4375}, -- NodeBox7 } } }) end
-- Functions for menu creation and manipulation -- A menu is defined by a table of menu items, which can contain the following fields -- (none are required): -- { -- name = "item", -- menu item text -- onActivate = func, -- function to be called when the item is clicked -- submenu = { } -- a submenu to be opened on click. If onActivate is also present -- -- then the arrow must be clicked to open submenu -- createWidget = function() CreateWidgetByDesc(desc) end -- custom menu item, no other fields are used -- } -- -- Usage example: -- local menu = { -- { name = "option1", onActivate = function() LogInfo( "", "option1 clicked" ) end } -- { name = "option2", onActivate = function() LogInfo( "", "option2 clicked" ) end } -- { name = "submenu", -- submenu = { -- { name = "suboption1" } -- { name = "suboption2" } -- } } } -- ShowMenu( { x = 100, y = 100 }, menu ) local Actions = {} -- maps widget to action executed upon clicking it -- templates for creating menu parts local MenuTemplate = mainForm:GetChildChecked( "MenuTemplate", true ):GetWidgetDesc() local ItemTemplate = mainForm:GetChildChecked( "ItemTemplate", true ):GetWidgetDesc() local SubmenuTemplate = mainForm:GetChildChecked( "SubmenuTemplate", true ):GetWidgetDesc() local CombinedTemplate = mainForm:GetChildChecked( "CombinedTemplate", true ):GetWidgetDesc() function ShowMenu( screenPosition, menu, parent ) local menuWidget = mainForm:CreateWidgetByDesc( MenuTemplate ) mainForm:AddChild( menuWidget ) local menuPlacement = menuWidget:GetPlacementPlain() local margin = menuPlacement.sizeY / 2 local width = 0 local height = margin for _, item in ipairs( menu ) do local itemWidget if item.createWidget then itemWidget = item.createWidget() else itemWidget = CreateItemWidget( item ) end local placement = itemWidget:GetPlacementPlain() placement.posY = height itemWidget:SetPlacementPlain( placement ) height = height + placement.sizeY width = math.max( width, placement.sizeX ); menuWidget:AddChild( itemWidget ) itemWidget:Show( true ) end local menuPlacement = menuWidget:GetPlacementPlain() menuPlacement.posX = screenPosition.x menuPlacement.posY = screenPosition.y menuPlacement.sizeX = width + margin * 2 menuPlacement.sizeY = height + margin MakeVisible( menuPlacement ) menuWidget:SetPlacementPlain( menuPlacement ) SaveAction( menuWidget, { parentMenu = parent and parent:GetInstanceId(), childMenu = nil } ) menuWidget:Show( true ) return menuWidget end function DestroyMenu( menuWidget ) local childMenu = Actions[ menuWidget:GetInstanceId() ].childMenu if childMenu then DestroyMenu( childMenu ) end ClearActions( menuWidget ) menuWidget:DestroyWidget() end ---------------------------------------------------------------------------------------------------- function SaveAction( widget, action ) Actions[ widget:GetInstanceId() ] = action end function ClearActions( widget ) local name = widget:GetInstanceId() if Actions[ name ] then Actions[ name ] = nil end local children = widget:GetNamedChildren() for _, child in pairs( children ) do ClearActions( child ) end end function CreateItemWidget( item ) local widget if item.submenu and item.onActivate then widget = mainForm:CreateWidgetByDesc( CombinedTemplate ) widget:GetChildChecked( "CombinedItem", true ):SetVal( "button_label", item.name ) SaveAction( widget:GetChildChecked( "CombinedItem", true ), item.onActivate ) SaveAction( widget:GetChildChecked( "CombinedSubmenu", true ), item.submenu ) elseif item.submenu then widget = mainForm:CreateWidgetByDesc( SubmenuTemplate ) widget:SetVal( "button_label", item.name ) SaveAction( widget, item.submenu ) else widget = mainForm:CreateWidgetByDesc( ItemTemplate ) widget:SetVal( "button_label", item.name ) if item.onActivate then SaveAction( widget, item.onActivate ) end end return widget end function GetParentMenu( childWidget ) local menu = childWidget while menu:GetParent():GetInstanceId() ~= mainForm:GetInstanceId() do menu = menu:GetParent() end return menu end function MakeVisible( placement ) local posConverter = widgetsSystem:GetPosConverterParams() if placement.posX + placement.sizeX > posConverter.fullVirtualSizeX then placement.posX = posConverter.fullVirtualSizeX - placement.sizeX end if placement.posY + placement.sizeY > posConverter.fullVirtualSizeY then placement.posY = posConverter.fullVirtualSizeY - placement.sizeY end end ---------------------------------------------------------------------------------------------------- -- Reaction handlers function OnActivate( params ) if params.active and not IsDragging() then local action = Actions[ params.widget:GetInstanceId() ] local menu = GetParentMenu( params.widget ) local parentMenuInfo = Actions[ Actions[ menu:GetInstanceId() ].parentMenu ] if parentMenuInfo then parentMenuInfo.childMenu = nil end DestroyMenu( menu ) if action then action() end end end function OnOpenSubmenu( params ) if params.active then local action = Actions[ params.widget:GetInstanceId() ] if action then local wt = params.widget local pos = { x = wt:GetPlacementPlain().sizeX, y = 0 } while wt do local placement = wt:GetPlacementPlain() pos.x = pos.x + placement.posX pos.y = pos.y + placement.posY wt = wt:GetParent() end local menuWidget = GetParentMenu( params.widget ) local menuInfo = Actions[ menuWidget:GetInstanceId() ] if menuInfo.childMenu then DestroyMenu( menuInfo.childMenu ) menuInfo.childMenu = nil end menuInfo.childMenu = ShowMenu( pos, action, menuWidget ) end end end function OnCloseSubmenu( params ) if params.active then local menuWidget = GetParentMenu( params.widget ) local menuInfo = Actions[ menuWidget:GetInstanceId() ] if menuInfo.childMenu then DestroyMenu( menuInfo.childMenu ) menuInfo.childMenu = nil end end end ---------------------------------------------------------------------------------------------------- function InitMenu() common.RegisterReactionHandler( OnActivate, "MenuActivateItemReaction" ) common.RegisterReactionHandler( OnOpenSubmenu, "MenuOpenSubmenuReaction" ) common.RegisterReactionHandler( OnOpenSubmenu, "SubmenuMouseOverReaction" ) common.RegisterReactionHandler( OnCloseSubmenu, "ItemMouseOverReaction" ) end
local function spairs(t, order) local keys = {} for k in pairs(t) do keys[#keys+1] = k end if order then table.sort(keys, function(a,b) return order(t, a, b) end) else table.sort(keys) end local i = 0 return function() i = i + 1 if keys[i] then return keys[i], t[keys[i]] end end end local Keys = { [289] = "F2", [170] = "F3", [166] = "F5", [167] = "F6", [168] = "F7" ,[56] = "F9", [57] = "F10" } local p_anims = {} local favorites = {} local currentKeys = { {["key"] = {289},["anim"] = ""}, {["key"] = {170},["anim"] = ""}, {["key"] = {166},["anim"] = ""}, {["key"] = {167},["anim"] = ""}, {["key"] = {168},["anim"] = ""}, {["key"] = {56},["anim"] = ""}, {["key"] = {57},["anim"] = ""}, {["key"] = {289,21},["anim"] = ""}, {["key"] = {170,21},["anim"] = ""}, {["key"] = {166,21},["anim"] = ""}, {["key"] = {167,21},["anim"] = ""}, {["key"] = {168,21},["anim"] = ""}, {["key"] = {56,21},["anim"] = ""}, {["key"] = {57,21},["anim"] = ""}, } local dToggle = false local dogEmote = { [289] = "dogsit", [170] = "bark", [166] = "bark2", [167] = "beg", [168] = "paw", [56] = "pet", [57] = "dump", -- Shift + key , done via key + 21 [310] = "pee", [191] = "indicateahead", [187] = "laydown", } WarMenu.CreateMenu("emotes", "Emotes") WarMenu.SetSubTitle("emotes", "Emote List") WarMenu.SetMenuWidth("emotes", 0.5) WarMenu.SetMenuX("emotes", 0.71) WarMenu.SetMenuY("emotes", 0.017) WarMenu.SetMenuMaxOptionCountOnScreen("emotes", 15) WarMenu.SetTitleColor("emotes", 135, 206, 250, 255) WarMenu.SetTitleBackgroundColor("emotes", 0 , 0, 0, 150) WarMenu.SetMenuBackgroundColor("emotes", 0, 0, 0, 100) WarMenu.SetMenuSubTextColor("emotes", 255, 255, 255, 255) WarMenu.CreateSubMenu("favorites", "emotes", "Favorites (Press F to remove a favorite)") WarMenu.SetMenuWidth("favorites", 0.5) WarMenu.SetMenuMaxOptionCountOnScreen("favorites", 30) WarMenu.SetTitleColor("favorites", 135, 206, 250, 255) WarMenu.SetTitleBackgroundColor("favorites", 0 , 0, 0, 150) WarMenu.SetMenuBackgroundColor("favorites", 0, 0, 0, 100) WarMenu.SetMenuSubTextColor("favorites", 255, 255, 255, 255) local selected_page = 1 local function DrawMenu() if WarMenu.Button("Page:", selected_page.."/"..#p_anims, {r = 135, g = 206, b = 250, a = 150}) then ClearPedTasks(PlayerPedId()) playing_emote = false end if WarMenu.Button("Favorites", "Press F to favorite an emote", {r = 135, g = 206, b = 250, a = 150}) then WarMenu.OpenMenu("favorites") end local key = "" for i,v in ipairs(currentKeys) do if v.key[2] ~= nil and "Cancel Emote" == v.anim then key = "Shift+"..Keys[v.key[1]] elseif v.key[1] ~= nil and "Cancel Emote" == v.anim then key = Keys[v.key[1]] end end if WarMenu.Button("Cancel Emote",key, {r = 135, g = 206, b = 250, a = 150}) then ClearPedTasks(PlayerPedId()) playing_emote = false end for k,v in spairs(p_anims[selected_page], function(t, a, b) return string.lower(tostring(a)) < string.lower(tostring(b)) end) do local msg = "" for i,v in ipairs(currentKeys) do if v.key[2] ~= nil and k == v.anim then msg = "Shift+"..Keys[v.key[1]] elseif v.key[1] ~= nil and k == v.anim then msg = Keys[v.key[1]] end end if WarMenu.Button(k,msg) then TriggerEvent("animation:PlayAnimation", k) end end end local function DrawFavorites() if WarMenu.Button("Cancel Emote", nil, {r = 135, g = 206, b = 250, a = 150}) then ClearPedTasks(PlayerPedId()) playing_emote = false end if WarMenu.MenuButton("Back", "emotes", {r = 135, g = 206, b = 250, a = 150}) then end for k,v in spairs(favorites, function(t, a, b) return string.lower(tostring(t[a])) < string.lower(tostring(t[b])) end) do if WarMenu.Button(v) then TriggerEvent("animation:PlayAnimation", v) end end end function addKey(anim,keys) if anim == "Page:" or anim == "Favorites" or anim == "Back" then return end for i,v in ipairs(currentKeys) do if keys[2] ~= nil then if v.key[1] == keys[1] and v.key[2] == 21 then v.anim = anim end else if v.key[1] == keys[1] and v.key[2] == nil then v.anim = anim end end end TriggerServerEvent("police:setEmoteData",currentKeys) end local function addFavorite(anim) if not anims[anim] then return end for k,v in pairs(favorites) do if v == anim then return end end local key = 0 for k,v in pairs(favorites) do local c = tonumber(string.match(k, "%d+")) if c >= key then key = c end end key = key + 1 favorites["fav:"..key] = anim SetResourceKvp("fav:"..key, anim) end local function removeFavorite(anim) for k,v in pairs(favorites) do if v == anim then DeleteResourceKvp(k) favorites[k] = nil end end end function DrawText3Ds(x,y,z, text) local onScreen,_x,_y=World3dToScreen2d(x,y,z) local px,py,pz=table.unpack(GetGameplayCamCoords()) SetTextScale(0.35, 0.35) SetTextFont(4) SetTextProportional(1) SetTextColour(255, 255, 255, 215) SetTextEntry("STRING") SetTextCentre(1) AddTextComponentString(text) DrawText(_x,_y) end Citizen.CreateThread(function() local c = 0 local page = 1 for k,v in spairs(anims, function(t, a, b) return string.lower(tostring(a)) < string.lower(tostring(b)) end) do p_anims[page] = p_anims[page] and p_anims[page] or {} p_anims[page][k] = v c = c + 1 if c >= 7 then c = 0 page = page + 1 end end local KvpHandle = StartFindKvp("fav:") repeat local key = FindKvp(KvpHandle) if key then favorites[key] = GetResourceKvpString(key) end until not key while true do Citizen.Wait(1) if WarMenu.IsMenuOpened("emotes") then DrawMenu() WarMenu.Display() local plyCoords = GetEntityCoords(PlayerPedId()) DrawText3Ds(plyCoords["x"],plyCoords["y"],plyCoords["z"]+0.4,"~g~Enter~s~ Plays Emote") DrawText3Ds(plyCoords["x"],plyCoords["y"],plyCoords["z"]+0.3,"~g~Arrows~s~ Navigate Pages") DrawText3Ds(plyCoords["x"],plyCoords["y"],plyCoords["z"]+0.2,"~g~Backspace~s~ Exits") DrawText3Ds(plyCoords["x"],plyCoords["y"],plyCoords["z"]-0.1,"You can also type ~g~/e emotename~s~ in chat to perform them") if IsControlJustReleased(0, 174) then selected_page = selected_page > 1 and selected_page - 1 or #p_anims elseif IsControlJustReleased(0, 175) then selected_page = selected_page < #p_anims and selected_page + 1 or 1 elseif IsControlJustReleased(0, 26) then for i,v in ipairs(currentKeys) do local curButton = WarMenu.GetCurrentButton() if v.anim == curButton.text then v.anim = "" end end elseif IsControlJustPressed(0, 23) then local curButton = WarMenu.GetCurrentButton() if curButton then addFavorite(curButton.text) end end for i,v in ipairs(currentKeys) do if v.key[2] ~= nil then if IsControlPressed(0,21) and IsControlJustReleased(0, v.key[1]) then local curButton = WarMenu.GetCurrentButton() if curButton then addKey(curButton.text,{v.key[1],21}) end end else if not IsControlPressed(0,21) and IsControlJustReleased(0, v.key[1]) then local curButton = WarMenu.GetCurrentButton() if curButton then addKey(curButton.text,{v.key[1]}) end end end end elseif WarMenu.IsMenuOpened("favorites") then DrawFavorites() WarMenu.Display() if IsControlJustPressed(0, 23) then local curButton = WarMenu.GetCurrentButton() if curButton then removeFavorite(curButton.text) end end else Citizen.Wait(500) end end end) RegisterNetEvent("emotes:OpenMenu") AddEventHandler("emotes:OpenMenu", function() TriggerServerEvent("police:getAnimData") TriggerServerEvent("police:getEmoteData") WarMenu.OpenMenu("emotes") end) RegisterNetEvent("emote:setEmotesFromDB"); AddEventHandler("emote:setEmotesFromDB", function(emotesResult) if emotesResult == nil or emotesResult[1] == nil then return end currentKeys = emotesResult end) RegisterNetEvent("npc-admin:currentDevmode") AddEventHandler("npc-admin:currentDevmode", function(devmode) dToggle = devmode end) -- Citizen.CreateThread(function() -- while true do -- Citizen.Wait(1) -- if not dToggle then -- local model = GetEntityModel(PlayerPedId()) -- for i,v in ipairs(currentKeys) do -- if v.key[2] ~= nil then -- if IsControlPressed(0,21) and IsControlJustReleased(0, v.key[1]) then -- if v.anim == "Cancel Emote" then -- ClearPedTasks(PlayerPedId()) playing_emote = false -- else -- if model == GetHashKey("a_c_chop") then -- TriggerEvent("animation:PlayAnimation", dogEmote[v.key[1]+21]) -- else -- TriggerEvent("animation:PlayAnimation", v.anim) -- end -- end -- end -- else -- if not IsControlPressed(0,21) and IsControlJustReleased(0, v.key[1]) then -- if v.anim == "Cancel Emote" then -- ClearPedTasks(PlayerPedId()) playing_emote = false -- else -- if model == GetHashKey("a_c_chop") then -- TriggerEvent("animation:PlayAnimation", dogEmote[v.key[1]]) -- else -- TriggerEvent("animation:PlayAnimation", v.anim) -- end -- end -- end -- end -- end -- end -- end -- end)
AddCSLuaFile("cl_init.lua") DeriveGamemode("nutscript")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Data Storer" ENT.WireDebugName = "Data Store" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Values = {A=0, B=0, C=0, D=0, E=0, F=0, G=0, H=0} end duplicator.RegisterEntityClass("gmod_wire_data_store", WireLib.MakeWireEnt, "Data")
local sqlite3 = require("ffi-sqlite3") local conn = sqlite3.open('my_database.sqlite3') if not conn then os.exit(0) end conn:exec("CREATE TABLE IF NOT EXISTS my_table(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)") conn:exec("INSERT INTO my_table (name,age) VALUES('adam',50);") local stmt = conn:prepare("SELECT * FROM my_table WHERE age=50;") while stmt:step() do print(stmt[1], stmt[2]) end stmt:finalize() conn:close()
----------------------------------- -- Area: Maze of Shakhrami -- Mob: Abyss Worm ----------------------------------- require("scripts/globals/regimes") ----------------------------------- function onMobDeath(mob, player, isKiller) tpz.regime.checkRegime(player, mob, 699, 1, tpz.regime.type.GROUNDS) tpz.regime.checkRegime(player, mob, 700, 1, tpz.regime.type.GROUNDS) end
---@class QuestChoice C_QuestChoice = {}
-- This first example, maintaining tradition, prints a "Hello World" message. -- Furthermore it shows: -- - Using the Sample utility functions as a base for the application -- - Adding a Text element to the graphical user interface -- - Subscribing to and handling of update events require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create "Hello World" Text CreateText() -- Finally, hook-up this HelloWorld instance to handle update events SubscribeToEvents() end function CreateText() -- Construct new Text object local context = GetContext() local helloText = Text:new(context) -- Set String to display helloText.text = "Hello World from Urho3D!" -- Set font and text color local cache = GetCache() helloText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 30) helloText.color = Color(0.0, 1.0, 0.0) -- Align Text center-screen helloText.horizontalAlignment = HA_CENTER; helloText.verticalAlignment = VA_CENTER; -- Add Text instance to the UI root element local ui = GetUI() ui.root:AddChild(helloText) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Do nothing for now, could be extended to eg. animate the display end
local typedefs = require "kong.db.schema.typedefs" return { name = "kong-signature-and-remove-attr", fields = { { run_on = typedefs.run_on_first }, { protocols = typedefs.protocols_http }, { config = { type = "record", fields = { {signature_secret_key = { type = "string" }}, {remove_attr = { type = "set", elements = { type = "string" }, default = {} }} } } } } }
-- ALF implementation for ngx_lua/Kong -- ALF version: 1.1.0 -- @version 2.0.0 -- @see https://github.com/Mashape/galileo-agent-spec -- -- Incompatibilities with ALF 1.1 and important notes -- ================================================== -- * The following fields cannot be retrieved as of ngx_lua 0.10.2: -- * response.statusText -- * response.headersSize -- -- * Kong can modify the request/response due to its nature, hence, -- we distinguish the original req/res from the current req/res -- * request.headersSize will be the size of the _original_ headers -- received by Kong -- * request.headers will contain the _current_ headers -- * response.headers will contain the _current_ headers -- -- * bodyCaptured properties are determined using HTTP headers -- * timings.blocked is ignored -- * timings.connect is ignored -- -- * we are waiting for lua-cjson support of granular 'empty table -- as JSON arrays' to be released in OpenResty. Until then, we -- have to use a workaround involving string substituion, which -- is slower and limits the maximum size of ALFs we can deal with. -- ALFs are thus limited to 20MB local cjson = require "cjson.safe" local resp_get_headers = ngx.resp.get_headers local req_start_time = ngx.req.start_time local req_get_method = ngx.req.get_method local req_get_headers = ngx.req.get_headers local req_get_uri_args = ngx.req.get_uri_args local req_raw_header = ngx.req.raw_header local encode_base64 = ngx.encode_base64 local http_version = ngx.req.http_version local setmetatable = setmetatable local tonumber = tonumber local os_date = os.date local type = type local pairs = pairs local _M = { _VERSION = "2.0.0", _ALF_VERSION = "1.1.0", _ALF_CREATOR = "galileo-agent-kong" } local _mt = { __index = _M } function _M.new(log_bodies, server_addr) local alf = { server_addr = server_addr, log_bodies = log_bodies, entries = {} } return setmetatable(alf, _mt) end local _empty_arr_placeholder = "__empty_array_placeholder__" local _empty_arr_t = {_empty_arr_placeholder} -- Convert a table such as returned by ngx.*.get_headers() -- to integer-indexed arrays. -- @warn Encoding of empty arrays workaround forces us -- to replace empty arrays with a placeholder to be substituted -- at serialization time. -- waiting on the releast of: -- https://github.com/openresty/lua-cjson/pull/6 local function hash_to_array(t) local arr = {} for k, v in pairs(t) do if type(v) == "table" then for i = 1, #v do arr[#arr+1] = {name = k, value = v[i]} end else arr[#arr+1] = {name = k, value = v} end end if #arr == 0 then return _empty_arr_t else return arr end end local function get_header(t, name, default) local v = t[name] if not v then return default elseif type(v) == "table" then return v[#v] end return v end --- Add an entry to the ALF's `entries` -- @param[type=table] _ngx The ngx table, containing .var and .ctx -- @param[type=string] req_body_str The request body -- @param[type=string] res_body_str The response body -- @treturn table The entry created -- @treturn number The new size of the `entries` array function _M:add_entry(_ngx, req_body_str, resp_body_str) if not self.entries then return nil, "no entries table" elseif not _ngx then return nil, "arg #1 (_ngx) must be given" elseif req_body_str ~= nil and type(req_body_str) ~= "string" then return nil, "arg #2 (req_body_str) must be a string" elseif resp_body_str ~= nil and type(resp_body_str) ~= "string" then return nil, "arg #3 (resp_body_str) must be a string" end -- retrieval local var = _ngx.var local ctx = _ngx.ctx local http_version = "HTTP/"..http_version() local request_headers = req_get_headers() local request_content_len = get_header(request_headers, "content-length", 0) local request_transfer_encoding = get_header(request_headers, "transfer-encoding") local request_content_type = get_header(request_headers, "content-type", "application/octet-stream") -- if log_bodies is false, we don't want to still call -- ngx.req.read_body() anyways, hence we rely on RFC 2616 -- to determine if the request seems to have a body. local req_has_body = tonumber(request_content_len) > 0 or request_transfer_encoding ~= nil or request_content_type == "multipart/byteranges" local resp_headers = resp_get_headers() local resp_content_len = get_header(resp_headers, "content-length", 0) local resp_transfer_encoding = get_header(resp_headers, "transfer-encoding") local resp_content_type = get_header(resp_headers, "content-type", "application/octet-stream") local resp_has_body = tonumber(resp_content_len) > 0 or resp_transfer_encoding ~= nil or resp_content_type == "multipart/byteranges" -- request.postData. we don't check has_body here, but rather -- stick to what the request really contains, since it was -- already read anyways. local post_data, response_content local req_body_size, resp_body_size = 0, 0 if self.log_bodies then if req_body_str then req_body_size = #req_body_str post_data = { text = encode_base64(req_body_str), encoding = "base64", mimeType = request_content_type } end if resp_body_str then resp_body_size = #resp_body_str response_content = { text = encode_base64(resp_body_str), encoding = "base64", mimeType = resp_content_type } end end -- timings local send_t = ctx.KONG_PROXY_LATENCY or 0 local wait_t = ctx.KONG_WAITING_TIME or 0 local receive_t = ctx.KONG_RECEIVE_TIME or 0 local idx = #self.entries + 1 self.entries[idx] = { time = send_t + wait_t + receive_t, startedDateTime = os_date("!%Y-%m-%dT%TZ", req_start_time()), serverIPAddress = self.server_addr, clientIPAddress = var.remote_addr, request = { httpVersion = http_version, method = req_get_method(), url = var.scheme .. "://" .. var.host .. var.request_uri, queryString = hash_to_array(req_get_uri_args()), headers = hash_to_array(request_headers), headersSize = #req_raw_header(), postData = post_data, bodyCaptured = req_has_body, bodySize = req_body_size, }, response = { status = _ngx.status, statusText = "", httpVersion = http_version, headers = hash_to_array(resp_headers), content = response_content, headersSize = 0, bodyCaptured = resp_has_body, bodySize = resp_body_size }, timings = { send = send_t, wait = wait_t, receive = receive_t } } return self.entries[idx], idx end local buf = { version = _M._ALF_VERSION, serviceToken = nil, environment = nil, har = { log = { creator = { name = _M._ALF_CREATOR, version = _M._VERSION }, entries = nil } } } local gsub = string.gsub local pat = '"'.._empty_arr_placeholder..'"' local _alf_max_size = 20 * 2^20 --- Encode the current ALF to JSON -- @param[type=string] service_token The ALF `serviceToken` -- @param[type=string] environment (optional) The ALF `environment` -- @treturn string The ALF, JSON encoded function _M:serialize(service_token, environment) if not self.entries then return nil, "no entries table" elseif type(service_token) ~= "string" then return nil, "arg #1 (service_token) must be a string" elseif environment ~= nil and type(environment) ~= "string" then return nil, "arg #2 (environment) must be a string" end buf.serviceToken = service_token buf.environment = environment buf.har.log.entries = self.entries -- tmp workaround for empty arrays -- this prevents us from dealing with ALFs -- larger than a few MBs at once local encoded = cjson.encode(buf) if #encoded > _alf_max_size then return nil, "ALF too large (> 20MB)" end encoded = gsub(encoded, pat, "") return gsub(encoded, "\\/", "/"), #self.entries --return cjson.encode(buf) end --- Empty the ALF function _M:reset() self.entries = {} end return _M
-- Generated by CSharp.lua Compiler local System = System local SlipeClientDx local SlipeMtaDefinitions local SlipeSharedUtilities local SystemNumerics System.import(function (out) SlipeClientDx = Slipe.Client.Dx SlipeMtaDefinitions = Slipe.MtaDefinitions SlipeSharedUtilities = Slipe.Shared.Utilities SystemNumerics = System.Numerics end) System.namespace("Slipe.Client.Dx", function (namespace) -- <summary> -- Represents a drawable image -- </summary> namespace.class("Image", function (namespace) local getFilePath, setFilePath, getMaterial, setMaterial, Draw, internal, __ctor1__, __ctor2__, __ctor3__, __ctor4__, __ctor5__, __ctor6__ internal = function (this) this.Dimensions = System.default(SystemNumerics.Vector2) this.RotationCenter = System.default(SystemNumerics.Vector2) end -- <summary> -- Create an image from a filepath with a color -- </summary> __ctor1__ = function (this, position, dimensions, filePath, rotation, rotationCenter, color, postGUI) internal(this) SlipeClientDx.Dx2DObject.__ctor__(this) this:setPosition(position:__clone__()) this.Dimensions = dimensions:__clone__() setFilePath(this, filePath) this.Rotation = rotation this.RotationCenter = rotationCenter:__clone__() this.Color = color this.PostGUI = postGUI this.usePath = true end -- <summary> -- Create an image from a filepath with rotation -- </summary> __ctor2__ = function (this, position, dimensions, filePath, rotation, rotationCenter) __ctor1__(this, position:__clone__(), dimensions:__clone__(), filePath, rotation, rotationCenter:__clone__(), SlipeSharedUtilities.Color.getWhite(), false) end -- <summary> -- Create an image from a filepath -- </summary> __ctor3__ = function (this, position, dimensions, filePath, rotation) __ctor2__(this, position:__clone__(), dimensions:__clone__(), filePath, rotation, SystemNumerics.Vector2.getZero()) end -- <summary> -- Create an image from a material with color -- </summary> __ctor4__ = function (this, position, dimensions, imageMaterial, rotation, rotationCenter, color, postGUI) internal(this) SlipeClientDx.Dx2DObject.__ctor__(this) this:setPosition(position:__clone__()) this.Dimensions = dimensions:__clone__() setMaterial(this, imageMaterial) this.Rotation = rotation this.RotationCenter = rotationCenter:__clone__() this.Color = color this.PostGUI = postGUI this.usePath = false end -- <summary> -- Create an image from a material with rotation -- </summary> __ctor5__ = function (this, position, dimensions, imageMaterial, rotation, rotationCenter) __ctor4__(this, position:__clone__(), dimensions:__clone__(), imageMaterial, rotation, rotationCenter:__clone__(), SlipeSharedUtilities.Color.getWhite(), false) end -- <summary> -- Create an image from a material -- </summary> __ctor6__ = function (this, position, dimensions, imageMaterial, rotation) __ctor5__(this, position:__clone__(), dimensions:__clone__(), imageMaterial, rotation, SystemNumerics.Vector2.getZero()) end getFilePath = function (this) return this.filePath end setFilePath = function (this, value) this.filePath = value this.usePath = true end getMaterial = function (this) return this.material end setMaterial = function (this, value) this.material = value this.usePath = false end Draw = function (this, source, eventArgs) if this.usePath then return SlipeMtaDefinitions.MtaClient.DxDrawImage(this:getPosition().X, this:getPosition().Y, this.Dimensions:__clone__().X, this.Dimensions:__clone__().Y, getFilePath(this), this.Rotation, this.RotationCenter:__clone__().X, this.RotationCenter:__clone__().Y, this.Color:getHex(), this.PostGUI) else local default = getMaterial(this) if default ~= nil then default = default:getMaterialElement() end return SlipeMtaDefinitions.MtaClient.DxDrawImage(this:getPosition().X, this:getPosition().Y, this.Dimensions:__clone__().X, this.Dimensions:__clone__().Y, default, this.Rotation, this.RotationCenter:__clone__().X, this.RotationCenter:__clone__().Y, this.Color:getHex(), this.PostGUI) end end return { __inherits__ = function (out) return { out.Slipe.Client.Dx.Dx2DObject, out.Slipe.Client.Dx.IDrawable } end, usePath = false, getFilePath = getFilePath, setFilePath = setFilePath, getMaterial = getMaterial, setMaterial = setMaterial, Rotation = 0, Draw = Draw, __ctor__ = { __ctor1__, __ctor2__, __ctor3__, __ctor4__, __ctor5__, __ctor6__ }, __metadata__ = function (out) return { fields = { { "filePath", 0x3, System.String }, { "material", 0x3, out.Slipe.Client.Dx.Material }, { "usePath", 0x3, System.Boolean } }, properties = { { "Dimensions", 0x6, System.Numerics.Vector2 }, { "FilePath", 0x106, System.String, getFilePath, setFilePath }, { "Material", 0x106, out.Slipe.Client.Dx.Material, getMaterial, setMaterial }, { "Rotation", 0x6, System.Single }, { "RotationCenter", 0x6, System.Numerics.Vector2 } }, methods = { { ".ctor", 0x706, __ctor1__, System.Numerics.Vector2, System.Numerics.Vector2, System.String, System.Single, System.Numerics.Vector2, out.Slipe.Shared.Utilities.Color, System.Boolean }, { ".ctor", 0x506, __ctor2__, System.Numerics.Vector2, System.Numerics.Vector2, System.String, System.Single, System.Numerics.Vector2 }, { ".ctor", 0x406, __ctor3__, System.Numerics.Vector2, System.Numerics.Vector2, System.String, System.Single }, { ".ctor", 0x706, __ctor4__, System.Numerics.Vector2, System.Numerics.Vector2, out.Slipe.Client.Dx.Material, System.Single, System.Numerics.Vector2, out.Slipe.Shared.Utilities.Color, System.Boolean }, { ".ctor", 0x506, __ctor5__, System.Numerics.Vector2, System.Numerics.Vector2, out.Slipe.Client.Dx.Material, System.Single, System.Numerics.Vector2 }, { ".ctor", 0x406, __ctor6__, System.Numerics.Vector2, System.Numerics.Vector2, out.Slipe.Client.Dx.Material, System.Single }, { "Draw", 0x286, Draw, out.Slipe.Client.Elements.RootElement, out.Slipe.Client.Rendering.Events.OnRenderEventArgs, System.Boolean } }, class = { 0x6 } } end } end) end)