content stringlengths 5 1.05M |
|---|
local kernel = {}
kernel.language = "glsl"
kernel.category = "filter"
kernel.name = "grayscale"
kernel.fragment =
[[
const P_COLOR vec3 kWeights = vec3( 0.2125, 0.7154, 0.0721 );
P_COLOR vec4 FragmentKernel( P_UV vec2 texCoord )
{
P_COLOR vec4 texColor = texture2D( u_FillSampler0, texCoord ) * v_ColorScale;
P_COLOR float luminance = dot( texColor.rgb, kWeights );
return vec4( vec3( luminance ), texColor.a );
}
]]
return kernel
|
local Players = game:GetService("Players")
local Modules = Players.LocalPlayer.PlayerGui.AvatarEditorInGame.Modules
local AppPage = require(Modules.NotLApp.AppPage)
local ResetNavigationHistory = require(Modules.NotLApp.Thunks.ResetNavigationHistory)
local NavigateToRoute = require(Modules.NotLApp.Thunks.NavigateToRoute)
local GetFFlagAvatarExperienceNavigationFix = function() return true end
local FFlagAvatarExperienceEmptyHistoryFix = true
local function getDefaultRoute()
return { { name = AppPage.Home } }
end
return function()
return function(store)
local state = store:getState()
local history = state.Navigation.history
local currentRoute = history[#history]
if not currentRoute then
currentRoute = getDefaultRoute()
end
local newRoute = {}
for index = 1, #currentRoute do
if currentRoute[index].name ~= AppPage.ItemDetails then
newRoute[#newRoute + 1] = currentRoute[index]
end
end
-- Ensure that the history isn't being overwritten with an empty route. Fall back to the HomePage.
if #newRoute == 0 then
if GetFFlagAvatarExperienceNavigationFix() then
return store:dispatch(NavigateToRoute(getDefaultRoute()))
else
newRoute = getDefaultRoute()
end
end
local newHistory = {}
if not FFlagAvatarExperienceEmptyHistoryFix or (FFlagAvatarExperienceEmptyHistoryFix and #newRoute > 1) then
for i = 1, #newRoute - 1 do
local tempRoute = {}
for j = 1, i do
tempRoute[#tempRoute + 1] = newRoute[j]
end
newHistory[#newHistory + 1] = tempRoute
end
elseif FFlagAvatarExperienceEmptyHistoryFix then
newHistory = { newRoute }
end
return store:dispatch(ResetNavigationHistory(newRoute, newHistory))
end
end |
--
-- Created by IntelliJ IDEA.
-- User: chen0
-- Date: 9/7/2017
-- Time: 10:12 AM
-- To change this template use File | Settings | File Templates.
--
describe('BreadthFirstSearch()', function()
local g = require('luagraphs.data.graph').create(6)
g:addEdge(0, 5);
g:addEdge(2, 4);
g:addEdge(2, 3);
g:addEdge(1, 2);
g:addEdge(0, 1);
g:addEdge(3, 4);
g:addEdge(3, 5);
g:addEdge(0, 2);
local bfs = require('luagraphs.search.BreadthFirstSearch').create()
local s = 0
bfs:run(g, s)
for i = 0, g:vertexCount()-1 do
local v = g:vertexAt(i)
if v ~= s and bfs:hasPathTo(v) then
local path = bfs:getPathTo(v)
local pathText = ''
while path:isEmpty() == false do
local x = path:pop()
if pathText == '' then
pathText = pathText .. x
else
pathText = pathText .. ' -> ' .. x
end
end
print(pathText)
end
end
end)
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('StoryBit', {
ActivationEffects = {},
Comment = "make this Follow-up immediate (no sol delay after the choice)",
Effects = {},
Image = "UI/Messages/Events/02_video_call_2.tga",
Prerequisites = {},
ScriptDone = true,
Text = T(576575765241, --[[StoryBit RedMars_2 Text]] 'On the screen there is only a black silhouette. The person talks to you through a voice modulator.\n\n"Commander, you\'ve made quite a mess by revealing the location of our facility. Now, we have to send a clean-up team, and it would cost us a lot of money and precious time. Of course, you can help us help you and do the dirty work yourself – remove all evidence that the facility you discovered ever existed. Your call."'),
TextReadyForValidation = true,
TextsDone = true,
Title = T(198669391331, --[[StoryBit RedMars_2 Title]] "Hot Seat"),
VoicedText = T(317649281591, --[[voice:narrator]] "The expedition team returns and you diligently and dutifully file in the report about the discovery. It’s not too long before you get the call."),
group = "Expeditions",
id = "RedMars_2",
qa_info = PlaceObj('PresetQAInfo', {
data = {
{
action = "Modified",
time = 1553175195,
user = "Radomir",
},
},
}),
PlaceObj('StoryBitReply', {
'Text', T(617235319542, --[[StoryBit RedMars_2 Text]] "I don’t like being threatened!"),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Enables', {
"RedMars_3",
},
'Effects', {},
}),
PlaceObj('StoryBitReply', {
'Text', T(474144864309, --[[StoryBit RedMars_2 Text]] "I will organize the clean-up immediately!"),
}),
PlaceObj('StoryBitParamFunding', {
'Name', "reward_funding",
'Value', 250000000,
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'VoicedText', T(274260689272, --[[voice:narrator]] "You have the strong feeling that the mysterious figure isn’t joking. Probably it would be best to organize a new flight to the facility coordinates immediately."),
'Text', T(646429066953, --[[StoryBit RedMars_2 Text]] "<goal>Return to the coordinates of the secret facility. Upon completion, you will receive <funding(reward_funding)> Funding."),
'Enables', {
"RedMars_4",
},
'Effects', {
PlaceObj('CreatePlanetaryAnomaly', {
'id', "RedMarsReturn",
'display_name', T(11381, --[[StoryBit RedMars_2 display_name]] "Secret Nuke Facility"),
'description', T(11382, --[[StoryBit RedMars_2 description]] "Top-secret facility from the Cold War period. You have promised to wipe all evidence of its existence."),
'required_crew', 5,
'required_crew_specialization', "security",
'required_rover', "RCTransport",
'reward', "custom",
'outcome_text', T(101937911549, --[[StoryBit RedMars_2 outcome_text]] "Funding"),
}),
},
}),
})
|
function Boss2Spinner(x,y, index, core, direction, angular_speed)
local spinner = pewpew.new_customizable_entity(x, y)
pewpew.customizable_entity_set_mesh(spinner, "/dynamic/BossPack/enemy_meshes.lua", index)
pewpew.customizable_entity_set_position_interpolation(spinner, true)
local angle = 0fx
pewpew.entity_set_update_callback(spinner, function()
if pewpew.entity_get_is_alive(core) then
if not pewpew.entity_get_is_started_to_be_destroyed(core) then
local ex, ey = pewpew.entity_get_position(core)
pewpew.entity_set_position(spinner, ex, ey)
pewpew.customizable_entity_set_mesh_angle(spinner, angle, 0fx, 0fx, 1fx)
angle = angle + angular_speed * direction
else
pewpew.customizable_entity_start_exploding(spinner, 30)
pewpew.entity_set_update_callback(spinner, nil)
end
end
end)
return spinner
end
function Boss2Projectile(x,y,angle,speed,core, ship_id)
local target = ship_id
local Projectile = pewpew.new_customizable_entity(x,y)
local direction = angle
local rotation = 0fx
local sin, cos = fmath.sincos(direction)
local size = 60fx
local basecolor = 0xfc4997ff
local colors = {basecolor, 0xfc49e8ff, 0xcc49fcff, 0x9a49fcff, 0x5849fcff, 0x497ffcff, 0x49b4fcff, 0x49e4fcff, 0x49fcd5ff, 0x3dff91ff, 0x3dff91ff}
pewpew.customizable_entity_set_mesh(Projectile, "/dynamic/BossPack/enemy_meshes.lua", 16)
pewpew.entity_set_radius(Projectile, size)
pewpew.customizable_entity_start_spawning(Projectile,5)
pewpew.customizable_entity_set_position_interpolation(Projectile, true)
pewpew.customizable_entity_set_mesh_color(Projectile, basecolor)
pewpew.add_arrow_to_player_ship(ship_id, Projectile, basecolor)
local health = 10
local ChangeDebounce = true
local DamageDebounce = true
local TargetDebounce = true
pewpew.customizable_entity_configure_wall_collision(Projectile, true, function()
pewpew.customizable_entity_start_exploding(Projectile, 10)
end)
pewpew.entity_set_update_callback(Projectile, function()
local ex, ey = pewpew.entity_get_position(Projectile)
pewpew.customizable_entity_set_mesh_color(Projectile, colors[11-health])
pewpew.customizable_entity_set_mesh_angle(Projectile, rotation, cos, sin, 0fx)
rotation = rotation + fmath.tau()/30fx
pewpew.entity_set_position(Projectile, ex + cos * speed, ey + sin * speed)
if target == core and TargetDebounce and #game[core].spinners > 0 then
local cx, cy = pewpew.entity_get_position(core)
local dx = cx - ex
local dy = cy - ey
local distance = fmath.sqrt(dx*dx + dy*dy)
if distance <= game[core].size + size and pewpew.entity_get_is_alive(Projectile) then
if not pewpew.entity_get_is_started_to_be_destroyed(Projectile) then
TargetDebounce = false
game[core].spinnercount = game[core].spinnercount - 1
pewpew.customizable_entity_start_exploding(Projectile, 10)
pewpew.entity_set_update_callback(Projectile, nil)
end
end
end
end)
pewpew.customizable_entity_set_weapon_collision_callback(Projectile, function()
if pewpew.entity_get_is_alive(Projectile) then
if not pewpew.entity_get_is_started_to_be_destroyed(Projectile) then
if health > 0 then
health = health - 1
return true
elseif ChangeDebounce then
ChangeDebounce = false
target = core
local px, py = pewpew.entity_get_position(ship_id)
local ex, ey = pewpew.entity_get_position(Projectile)
local dx = px - ex
local dy = py - ey
direction = fmath.atan2(dy, dx) + fmath.tau()/2fx
sin, cos = fmath.sincos(direction)
elseif TargetDebounce then
return true
end
end
end
end)
pewpew.customizable_entity_set_player_collision_callback(Projectile, function()
if target ~= core and DamageDebounce then
DamageDebounce = false
pewpew.add_damage_to_player_ship(ship_id, 2)
pewpew.customizable_entity_start_exploding(Projectile, 15)
end
end)
end
function Boss2Bullet(x, y, angle, damage, speed, core)
local bullet = pewpew.new_customizable_entity(x,y)
pewpew.entity_set_radius(bullet, 15fx)
pewpew.customizable_entity_set_mesh(bullet, "/dynamic/BossPack/enemy_meshes.lua", 11)
pewpew.customizable_entity_set_position_interpolation(bullet, true)
pewpew.customizable_entity_start_spawning(bullet, 5)
local rotation = 0fx
pewpew.entity_set_update_callback(bullet, function()
if pewpew.entity_get_is_alive(core) then
if pewpew.entity_get_is_started_to_be_destroyed(core) then
pewpew.customizable_entity_start_exploding(bullet, 15)
end
end
local x2, y2 = pewpew.entity_get_position(bullet)
local sin, cos = fmath.sincos(angle)
local dx = x2 + cos * speed
local dy = y2 + sin * speed
pewpew.entity_set_position(bullet, dx, dy)
pewpew.customizable_entity_set_mesh_angle(bullet, rotation, sin, cos, 0fx)
rotation = rotation + fmath.tau()/15fx
end)
pewpew.customizable_entity_set_player_collision_callback(bullet, function(player_id, player_ship)
pewpew.add_damage_to_player_ship(player_ship, damage)
pewpew.customizable_entity_start_exploding(bullet, 12)
end)
pewpew.customizable_entity_configure_wall_collision(bullet, true, function()
pewpew.customizable_entity_start_exploding(bullet, 12)
end)
end
function Boss2Rain(x,y,z,fallspeed, core)
local Rain = pewpew.new_customizable_entity(x,y)
local height = z
local Indicator = pewpew.new_customizable_entity(x,y)
local angle = 0fx
local radius = 60fx
pewpew.customizable_entity_set_mesh_z(Rain, height)
pewpew.customizable_entity_set_position_interpolation(Rain, true)
pewpew.customizable_entity_set_mesh(Rain, "/dynamic/BossPack/enemy_meshes.lua", 12)
pewpew.customizable_entity_start_spawning(Rain, 5)
pewpew.entity_set_radius(Rain, radius)
pewpew.customizable_entity_set_mesh_color(Rain, 0xffffff11)
local color = 0xffffff11
pewpew.customizable_entity_set_mesh(Indicator, "/dynamic/BossPack/enemy_meshes.lua", 13)
pewpew.customizable_entity_set_string(Indicator, "#ff3333ffX")
pewpew.entity_set_update_callback(Rain, function()
height = height - fallspeed
pewpew.customizable_entity_set_mesh_z(Rain, height)
pewpew.customizable_entity_set_mesh_angle(Rain, angle, 0.23fx, 0.07fx, 0.16fx)
angle = angle + fmath.tau()/30fx
if color < 0xfffffffa then
color = color + 5
pewpew.customizable_entity_set_mesh_color(Rain, color)
end
if pewpew.entity_get_is_alive(core) then
if pewpew.entity_get_is_started_to_be_destroyed(core) then
if pewpew.entity_get_is_alive(Rain) then
pewpew.customizable_entity_start_exploding(Rain, 15)
end
if pewpew.entity_get_is_alive(Indicator) then
pewpew.customizable_entity_start_exploding(Indicator, 15)
end
end
end
if height >= -radius and height <= radius then
pewpew.customizable_entity_set_player_collision_callback(Rain, function(player_index, player_ship)
pewpew.add_damage_to_player_ship(player_ship, 1)
pewpew.customizable_entity_start_exploding(Rain, 15)
pewpew.customizable_entity_start_exploding(Indicator, 15)
pewpew.customizable_entity_set_string(Indicator, "")
pewpew.customizable_entity_set_player_collision_callback(Rain, nil)
pewpew.entity_set_update_callback(Rain, nil)
end)
elseif height < -radius then
pewpew.customizable_entity_start_exploding(Rain, 15)
pewpew.customizable_entity_start_exploding(Indicator, 15)
pewpew.customizable_entity_set_string(Indicator, "")
pewpew.customizable_entity_set_player_collision_callback(Rain, nil)
pewpew.entity_set_update_callback(Rain, nil)
end
end)
end
function Boss2Inertiac(x,y,angle,core,speed,lifetime)
local InertiacBullet = pewpew.new_customizable_entity(x,y)
local life = lifetime
pewpew.customizable_entity_set_mesh(InertiacBullet, "/dynamic/BossPack/enemy_meshes.lua", 15)
pewpew.customizable_entity_set_position_interpolation(InertiacBullet, true)
pewpew.entity_set_radius(InertiacBullet, 30fx)
pewpew.customizable_entity_set_mesh_color(InertiacBullet, 0xff7f08ff)
pewpew.customizable_entity_set_mesh_angle(InertiacBullet, angle+ fmath.tau()/4fx, 0fx,0fx,1fx)
pewpew.customizable_entity_start_spawning(InertiacBullet, 0)
pewpew.entity_set_update_callback(InertiacBullet, function()
if pewpew.entity_get_is_alive(core) then
if pewpew.entity_get_is_started_to_be_destroyed(core) then
pewpew.customizable_entity_start_exploding(InertiacBullet, 5)
pewpew.entity_set_update_callback(InertiacBullet,nil)
end
end
local ex, ey = pewpew.entity_get_position(InertiacBullet)
local sin, cos = fmath.sincos(angle)
local dx = ex + cos * speed
local dy = ex + sin * speed
pewpew.entity_set_position(InertiacBullet, dx, dy)
life = life - 1
local scoredebounce = true
if life <= 0 then
local wx, wy = pewpew.entity_get_position(InertiacBullet)
local NewInertiac = pewpew.new_inertiac(wx, wy, 1fx, angle)
pewpew.entity_set_update_callback(NewInertiac, function()
if pewpew.entity_get_is_alive(core) then
if pewpew.entity_get_is_started_to_be_destroyed(core) then
pewpew.entity_destroy(NewInertiac)
pewpew.entity_set_update_callback(NewInertiac,nil)
end
end
if pewpew.entity_get_is_alive(NewInertiac) then
if pewpew.entity_get_is_started_to_be_destroyed(NewInertiac) and PracticeBoolean and scoredebounce then
scoredebounce = false
end
end
end)
pewpew.customizable_entity_start_exploding(InertiacBullet, 5)
pewpew.entity_set_update_callback(InertiacBullet,nil)
end
end)
end
function Boss2MarchingCube(x,y,angle,core,speed,lifetime)
local CubeBullet = pewpew.new_customizable_entity(x,y)
local life = lifetime
pewpew.customizable_entity_set_mesh(CubeBullet, "/dynamic/BossPack/enemy_meshes.lua", 15)
pewpew.customizable_entity_set_position_interpolation(CubeBullet, true)
pewpew.entity_set_radius(CubeBullet, 30fx)
pewpew.customizable_entity_set_mesh_color(CubeBullet, 0xfffc4dff)
pewpew.customizable_entity_set_mesh_angle(CubeBullet, angle+ fmath.tau()/4fx, 0fx,0fx,1fx)
pewpew.customizable_entity_start_spawning(CubeBullet, 0)
pewpew.entity_set_update_callback(CubeBullet, function()
if pewpew.entity_get_is_alive(core) then
if pewpew.entity_get_is_started_to_be_destroyed(core) then
pewpew.customizable_entity_start_exploding(CubeBullet, 5)
pewpew.entity_set_update_callback(CubeBullet,nil)
end
end
local ex, ey = pewpew.entity_get_position(CubeBullet)
local sin, cos = fmath.sincos(angle)
local dx = ex + cos * speed
local dy = ex + sin * speed
pewpew.entity_set_position(CubeBullet, dx, dy)
life = life - 1
local scoredebounce = true
if life <= 0 then
local wx, wy = pewpew.entity_get_position(CubeBullet)
local NewCube = pewpew.new_rolling_cube(wx, wy)
pewpew.entity_set_update_callback(NewCube, function()
if pewpew.entity_get_is_alive(core) then
if pewpew.entity_get_is_started_to_be_destroyed(core) then
pewpew.entity_destroy(NewCube)
pewpew.entity_set_update_callback(NewCube,nil)
end
end
if pewpew.entity_get_is_alive(NewCube) then
if pewpew.entity_get_is_started_to_be_destroyed(NewCube) and PracticeBoolean and scoredebounce then
scoredebounce = false
end
end
end)
pewpew.customizable_entity_start_exploding(CubeBullet, 5)
pewpew.entity_set_update_callback(CubeBullet,nil)
end
end)
end
function newBoss2(x,y,range, ship_id)
local core = pewpew.new_customizable_entity(x, y)
local radius = 60fx
local mode = 1
local HitDebounce = 0
game[core] = {size = radius, spinnercount = 4}
pewpew.customizable_entity_set_mesh(core, "/dynamic/BossPack/enemy_meshes.lua", 6)
pewpew.entity_set_radius(core, radius)
local debounce = true
local health = 150
local cooldown = 90
local rotation = 0fx
local ShootAngle = 0fx
local RainCooldown = 10
local InertiacCooldown = 150
local CubeCooldown = 120
local hurt = 0
local sendangle
local sendspeed = 0fx
local spinner1 = Boss2Spinner(x, y, 7, core, -1fx, 3fx)
local spinner2 = Boss2Spinner(x, y, 8, core, 1fx, 2fx)
local spinner3 = Boss2Spinner(x, y, 9, core, -1fx, 1fx)
local spinner4 = Boss2Spinner(x, y, 10, core, -1fx, 2fx)
game[core].spinners = {spinner4, spinner3, spinner2, spinner1}
pewpew.customizable_entity_set_player_collision_callback(core, function(player_id, player_ship)
if HitDebounce == 0 then
local playerx, playery = pewpew.entity_get_position(player_ship)
local entityx, entityy = pewpew.entity_get_position(core)
local x = playerx - entityx
local y = playery - entityy
sendangle = fmath.atan2(y,x)
sendspeed = 30fx
pewpew.add_damage_to_player_ship(player_ship, 3)
end
end)
pewpew.customizable_entity_set_weapon_collision_callback(core, function()
if health > 0 then
if(#game[core].spinners == 0) and game[core].spinnercount == 0 then
health = health - 1
hurt = 5
return true
else
return true
end
elseif debounce then
debounce = false
if pewpew.entity_get_is_alive(core) then
pewpew.customizable_entity_start_exploding(core, 30)
end
end
end)
pewpew.entity_set_update_callback(core, function()
if HitDebounce > 0 then
HitDebounce = HitDebounce - 1
end
if sendspeed > 0fx and pewpew.entity_get_is_alive(ship_id) then
local x, y = pewpew.entity_get_position(ship_id)
local ychange, xchange = fmath.sincos(sendangle)
if x + xchange < 0fx or x + xchange > level_length then
xchange = 0fx
end
if y + ychange < 0fx or y + ychange > level_height then
ychange = 0fx
end
pewpew.entity_set_position(ship_id, x + xchange * sendspeed, y + ychange * sendspeed)
if ychange == 0fx or xchange == 0fx then
sendspeed = sendspeed - 10fx
else
sendspeed = sendspeed - 1fx
end
end
if InertiacCooldown > 0 then
InertiacCooldown = InertiacCooldown - 1
else
InertiacCooldown = 210
local x,y = pewpew.entity_get_position(core)
local angle = fmath.tau()/40fx * fmath.random_fixedpoint(0fx,40fx)
local InertiacLifetime = fmath.random_int(30,40)
--Boss2Inertiac(x,y,angle,core,13fx,30)
end
if CubeCooldown > 0 then
CubeCooldown = CubeCooldown - 1
else
CubeCooldown = 120
local x,y = pewpew.entity_get_position(core)
local angle = fmath.tau()/40fx * fmath.random_fixedpoint(0fx,40fx)
local InertiacLifetime = fmath.random_int(30,40)
--Boss2MarchingCube(x,y,angle,core,13fx,30)
end
if hurt > 0 then
hurt = hurt - 1
pewpew.customizable_entity_set_mesh(core, "/dynamic/BossPack/enemy_meshes.lua", 14)
else
pewpew.customizable_entity_set_mesh(core, "/dynamic/BossPack/enemy_meshes.lua", 6)
end
if RainCooldown > 0 then
RainCooldown = RainCooldown - 1
else
RainCooldown = 10
local ex, ey = pewpew.entity_get_position(core)
local x = ex + fmath.random_fixedpoint(-range, range)
local y = ey + fmath.random_fixedpoint(-range, range)
local z = fmath.random_fixedpoint(1000fx, 1200fx)
local fallspeed = fmath.random_fixedpoint(20fx,30fx)
Boss2Rain(x,y,z,fallspeed,core)
end
pewpew.customizable_entity_set_mesh_angle(core, rotation, 0.3fx, 0.4fx, 0.5fx)
rotation = rotation + fmath.tau()/20fx
if #game[core].spinners > game[core].spinnercount then
game[core].size = game[core].size - 10fx
pewpew.customizable_entity_start_exploding(table.remove(game[core].spinners, #game[core].spinners), 30)
pewpew.entity_set_radius(core, game[core].size)
end
if #game[core].spinners == 0 and game[core].spinnercount == 0 and mode == 1 then
mode = 2
end
if mode == 1 then
if cooldown > 0 then
cooldown = cooldown - 1
elseif debounce and pewpew.entity_get_is_alive(ship_id) then
local px, py = pewpew.entity_get_position(ship_id)
local ex, ey = pewpew.entity_get_position(core)
local dx = px - ex
local dy = py - ey
local angle = fmath.atan2(dy, dx)
cooldown = fmath.random_int(120,180)
Boss2Projectile(ex,ey,angle,12fx,core,ship_id)
end
elseif mode == 2 then
if cooldown > 0 then
cooldown = cooldown - 1
elseif debounce then
local ex, ey = pewpew.entity_get_position(core)
local offset = fmath.tau()/4fx
-- cooldown = 5
cooldown = 2
Boss2Bullet(ex, ey, ShootAngle + offset * 1fx, 1, 15fx, core)
Boss2Bullet(ex, ey, ShootAngle + offset * 2fx, 1, 15fx, core)
Boss2Bullet(ex, ey, ShootAngle + offset * 3fx, 1, 15fx, core)
Boss2Bullet(ex, ey, ShootAngle + offset * 4fx, 1, 15fx, core)
-- ShootAngle = ShootAngle + fmath.tau()/20fx
ShootAngle = ShootAngle + fmath.tau()/120fx
end
end
end)
end
return newBoss2 |
vector = {}
--vector.__index = vector
vector.isMathType = true
vector.isvector = true
function vector.zero( len, con )
con = con or 0
local v = {}
for i = 1, len do
v[i] = con
end
return vector.new( v )
end
-- function vector.isvector( v )
-- return getmetatable( v ) == vector
-- end
function vector:tostring( parensQ )
parensQ = parensQ or true
local res = ''
if parensQ then res = '( ' end
local selfstr = map( self, mathToStr )
res = res .. table.concat( selfstr, ', ' )
if parensQ then res = res .. ')' end
return res
end
function vector:clone()
local tmp = table.pack( table.unpack( self ) )
return vector.new( tmp )
end
function vector.unm(a)
local res = a:clone()
for i = 1, #a do
res[i] = -res[i]
end
return res
end
function vector.add(a,b)
assert(a.isvector and b.isvector, "Add: wrong argument types (<vector> expected)")
assert( #a == #b, "Add: wrong argument lengths (same dim expected)")
local sum = {}
for i = 1, #a do
sum[i] = a[i] + b[i]
end
return vector.new( sum )
end
function vector.sub(a,b)
assert( a.isvector and b.isvector, "Add: wrong argument types (<vector> expected)")
assert( #a == #b, "Add: wrong argument lengths (same dim expected)")
local dif = {}
for i = 1, #a do
dif[i] = a[i] - b[i]
end
return vector.new( dif )
end
function vector.scalarMult( s, v )
--io.write("Scalar mult...")
local res = {}
for i = 1, #v do
table.insert( res, s * v[i] )
end
return vector.new( res )
end
function dotProd( v1, v2 )
assert( #v1 == #v2, "Add: wrong argument lengths (same dim expected)")
local res = 0
for i = 1, #v1 do
res = res + v1[i] * v2[i]
end
return res
end
function vector.mul(a,b)
local tanQ, tbnQ = type(a)=='number' or frc.isfraction(a), type(b)=='number' or frc.isfraction(b)
if tanQ and b.isvector then
return scalarMult( a, b )
elseif tbnQ and a.isvector then
return scalarMult( b, a )
else
assert(a.isvector and b.isvector, "Mul: wrong argument types (<vector> or <number> expected)")
return dotProd( a, b )
end
end
function vector.div(a,b)
assert(a.isvector and type(b) == "number", "wrong argument types (expected <vector> / <number>)")
return scalarMult( 1 / b , a )
end
function vector.eq(a,b)
if #a ~= #b then return false end
local res = true
for i = 1, #a do
res = res and ( a[i] == b[i] )
end
return res
end
function vector:len()
local sqs = 0
for _, x in ipairs( self ) do
sqs = sqs + x * x
end
return math.sqrt( sqs )
end
function vector.random( l, max, sgnF )
if sgnF == nil then sgnF = true end
local lst = {}
for i = 1, l do
if sgnF then
table.insert( lst, math.random( -max, max ) )
else
table.insert( lst, math.random( 0, max ) )
end
end
return vector.new( lst )
end
function vector.randomNonNeg( l, max )
local lst = {}
for i = 1, l do
table.insert( lst, math.random( max ) )
end
return vector.new( lst )
end
function vector:tolatex()
local ltx = map( self, mathToLatex )
ltx = table.concat( ltx, [[\ \ ]] )
--return [[ (\,]] .. (self:__tostring()):sub(2,-2) .. [[\,)]]
return [[ [\ ]] .. ltx .. [[\ ] ]]
end
-- -- return setmetatable({new = new, isvector = isvector, zero = zero,
-- -- random = random, randomNonNeg = randomNonNeg },
-- -- {__call = function(_, ...) return new(...) end})
function vector.new( lst )
local newvec = copy( vector )
for k,v in ipairs(lst) do
newvec[k] = v
end
return newvec
end
return vector
|
target("DopplerEffect")
set_group("Examples")
set_kind("binary")
add_deps("NazaraAudio", "NazaraPlatform")
add_files("main.cpp") |
--lua端的全局事件号以10000起始,c#的是1~9999
local GlobalEvents = BaseClass(CS.UnityMMO.GlobalEvents)
GlobalEvents.GameStart = 10000
GlobalEvents.SetMainUIVisible = 10001
return GlobalEvents |
#!/usr/bin/env tarantool
local test = require("sqltester")
test:plan(4)
-- Make sure that the comparison between DECIMAL and large DOUBLE is correct.
test:do_execsql_test(
"gh-6376-1",
[[
SELECT CAST(1 AS DECIMAL) < -1e40;
]], {
false
})
test:do_execsql_test(
"gh-6376-2",
[[
SELECT CAST(-1 AS DECIMAL) > -1e400;
]], {
true
})
test:do_execsql_test(
"gh-6376-3",
[[
SELECT CAST(1 AS DECIMAL) <= 1e40;
]], {
true
})
test:do_execsql_test(
"gh-6376-4",
[[
SELECT CAST(1 AS DECIMAL) >= 1e400;
]], {
false
})
test:finish_test()
|
---------------
--Unbreakable--
---------------
--Stone
minetest.register_node("tower_defense:red_stone", {
tiles = {"tower_defense_red_stone.png"},
description = "Unbreakable stone for TD games",
groups = {not_in_creative_inventory = 1, unbreakable = 1},
})
--Sand
minetest.register_node("tower_defense:yellow_stone", {
tiles = {"tower_defense_yellow_stone.png"},
description = "Unbreakable sand for TD games",
groups = {not_in_creative_inventory = 1, unbreakable = 1},
})
--Barrier
minetest.register_node("tower_defense:barrier", {
drawtype = "airlike",
paramtype = "light",
sunlight_propagates = true,
description = "Unbreakable barrier for TD games",
groups = {not_in_creative_inventory = 1, unbreakable = 1},
})
--Flag
minetest.register_node("tower_defense:flag", {
tiles = {
"tower_defense_flag_top.png^[transform1",
"tower_defense_flag_top.png^[transform1",
"tower_defense_flag_front.png",
"tower_defense_flag_back.png",
"tower_defense_flag_side.png^[transform4",
"tower_defense_flag_side.png",
},
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
{-5/16,-8/16,-1/16,-3/16,8/16,1/16},
{-3/16,1/16,-1/16,6/16,7/16,1/16},
}
},
description = "Flag",
paramtype = "light",
groups = {not_in_creative_inventory = 1, unbreakable = 1, health = 1000}
})
------------------
----Barricades----
------------------
minetest.register_node("tower_defense:wood_barricade",{
description = "Wood Barricade",
tiles = {"default_wood.png"},
groups = {not_in_creative_inventory = 1, oddly_breakable_by_hand = 3, health = 50}
})
minetest.register_node("tower_defense:stone_barricade",{
description = "Stone Barricade",
tiles = {"default_stone.png"},
groups = {not_in_creative_inventory = 1, oddly_breakable_by_hand = 3, health = 100}
})
minetest.register_node("tower_defense:steel_barricade",{
description = "Steel Barricade",
tiles = {"default_steel_block.png"},
groups = {not_in_creative_inventory = 1, oddly_breakable_by_hand = 3, health = 250}
})
minetest.register_node("tower_defense:obsidian_barricade",{
description = "Obsidian Barricade",
tiles = {"default_obsidian.png"},
groups = {not_in_creative_inventory = 1, oddly_breakable_by_hand = 3, health = 500}
})
|
local state = {}
state._NAME = ...
local Body = require'Body'
local util = require'util'
local vector = require'vector'
local HT = require'libHeadTransform'
local T = require'Transform'
local movearm = require'movearm'
local forwardR = movearm.rPlanner.forward
local t_entry, t_update
-- TODO: need to compensate the torso pose
local headSpeed = 30 * DEG_TO_RAD * vector.ones(2)
local headThresh = 1 * DEG_TO_RAD * vector.ones(2)
function state.entry()
print(state._NAME..' Entry' )
-- When entry was previously called
local t_entry_prev = t_entry
-- Update the time of entry
t_entry = Body.get_time()
t_update = t_entry
end
local function get_world_tf()
local bH = mcm.get_stance_bodyHeight()
local uTorso = mcm.get_stance_uTorsoComp()
local pitch = Body.get_rpy()[2]
return T.trans(uTorso[1], uTorso[2], bH) * T.rotY(pitch)
end
function state.update()
-- print(_NAME..' Update' )
-- Get the time of update
local t = Body.get_time()
local dt = t - t_update
-- Save this at the last update time
t_update = t
local qRArm = Body.get_rarm_position()
local qWaist = Body.get_waist_position()
local headNow = Body.get_head_command_position()
local tfArm = forwardR(qRArm)
local tfWorld = get_world_tf()
local tfHand = tfWorld * tfArm
local headAngles = vector.new{HT.ikineCam(unpack(T.position(tfHand)))}
local apprAng, doneHead = util.approachTol(headNow, headAngles, headSpeed, dt, headThresh)
Body.set_head_command_position(apprAng)
return doneHead and 'done'
end
function state.exit()
print(state._NAME..' Exit')
end
return state
|
mineunit:set_modpath("technic", "spec/fixtures")
technic = {}
technic.chests = {}
technic.chests.colors = {
{"black", S("Black")},
{"blue", S("Blue")},
{"brown", S("Brown")},
{"cyan", S("Cyan")},
{"dark_green", S("Dark Green")},
{"dark_grey", S("Dark Grey")},
{"green", S("Green")},
{"grey", S("Grey")},
{"magenta", S("Magenta")},
{"orange", S("Orange")},
{"pink", S("Pink")},
{"red", S("Red")},
{"violet", S("Violet")},
{"white", S("White")},
{"yellow", S("Yellow")},
}
function technic.chests.change_allowed(pos, player, owned, protected)
if owned then
if minetest.is_player(player) and not default.can_interact_with_node(player, pos) then
return false
end
elseif protected then
if minetest.is_protected(pos, player:get_player_name()) then
return false
end
end
return true
end
|
module 'mock'
CLASS: PhysicsBodyDef ()
:MODEL{
Field 'tag' :string();
'----';
Field 'bodyType' :enum( EnumPhysicsBodyType );
'----';
Field 'allowSleep' :boolean();
Field 'isBullet' :boolean();
Field 'fixedRotation' :boolean();
'----';
Field 'gravityScale' :number();
Field 'linearDamping' :number();
Field 'angularDamping' :number();
'----';
Field 'defaultMaterial' :asset( 'physics_material' )
}
function PhysicsBodyDef:__init()
self.tag = ''
self.bodyType = 'dynamic'
self.allowSleep = true
self.isBullet = false
self.fixedRotation = false
self.gravityScale = 1
self.linearDamping = 1
self.angularDamping = 1
self.defaultMaterial = false
end
local defaultBodyDef = PhysicsBodyDef()
defaultBodyDef.tag = '_default'
function getDefaultPhysicsBodyDef()
return table.simplecopy(defaultBodyDef)
end
--------------------------------------------------------------------
local function loadPhysicsBodyDef( node )
local data = mock.loadAssetDataTable( node:getObjectFile('def') )
local def = mock.deserialize( nil, data )
return def
end
registerAssetLoader( 'physics_body_def', loadPhysicsBodyDef )
|
local archetypes = {}
local CACHE_WITH = {}
local CACHE_WITHOUT = {}
-- Version of the last registered archetype. Used to cache the systems execution plan
local Version = 0
--[[
An Archetype is a unique combination of component types. The EntityRepository uses the archetype to group all
entities that have the same sets of components.
An entity can change archetype fluidly over its lifespan. For example, when you add or remove components,
the archetype of the affected entity changes.
An archetype object is not a container; rather it is an identifier to each unique combination of component
types that an application has created at run time, either directly or implicitly.
You can create archetypes directly using ECS.Archetype.Of(Components[]). You also implicitly create archetypes
whenever you add or remove a component from an entity. An Archetype object is an immutable singleton;
creating an archetype with the same set of components, either directly or implicitly, results in the same
archetype.
The ECS framework uses archetypes to group entities that have the same structure together. The ECS framework stores
component data in blocks of memory called chunks. A given chunk stores only entities having the same archetype.
You can get the Archetype object for a chunk from its Archetype property.
Use ECS.Archetype.Of(Components[]) to get a Archetype reference.
]]
local Archetype = {}
Archetype.__index = Archetype
--[[
Gets the reference to an archetype from the informed components
@param componentClasses {ComponentClass[]} Component that define this archetype
@return Archetype
]]
function Archetype.Of(componentClasses)
local ids = {}
local cTypes = {}
for _, cType in ipairs(componentClasses) do
if (cType.IsCType and not cType.isComponent) then
if cType.IsQualifier then
if cTypes[cType] == nil then
cTypes[cType] = true
table.insert(ids, cType.Id)
end
cType = cType.SuperClass
end
if cTypes[cType] == nil then
cTypes[cType] = true
table.insert(ids, cType.Id)
end
end
end
table.sort(ids)
local id = "_" .. table.concat(ids, "_")
if archetypes[id] == nil then
archetypes[id] = setmetatable({
id = id,
_components = cTypes
}, Archetype)
Version = Version + 1
end
return archetypes[id]
end
--[[
Get the version of archetype definitions
@return number
]]
function Archetype.Version()
return Version
end
--[[
Checks whether this archetype has the informed component
@param componentClass {ComponentClass}
@return bool
]]
function Archetype:Has(componentClass)
return (self._components[componentClass] == true)
end
--[[
Gets the reference to an archetype that has the current components + the informed component
@param componentClass {ComponentClass}
@return Archetype
]]
function Archetype:With(componentClass)
if self._components[componentClass] == true then
-- component exists in that list, returns the archetype itself
return self
end
local cache = CACHE_WITH[self]
if not cache then
cache = {}
CACHE_WITH[self] = cache
end
local other = cache[componentClass]
if other == nil then
local componentTs = {componentClass}
for component,_ in pairs(self._components) do
table.insert(componentTs, component)
end
other = Archetype.Of(componentTs)
cache[componentClass] = other
end
return other
end
--[[
Gets the reference to an archetype that has the current components + the informed components
@param componentClasses {ComponentClass[]}
@return Archetype
]]
function Archetype:WithAll(componentClasses)
local cTypes = {}
for component,_ in pairs(self._components) do
table.insert(cTypes, component)
end
for _,component in ipairs(componentClasses) do
if self._components[component] == nil then
table.insert(cTypes, component)
end
end
return Archetype.Of(cTypes)
end
--[[
Gets the reference to an archetype that has the current components - the informed component
@param componentClass {ComponentClass}
@return Archetype
]]
function Archetype:Without(componentClass)
if self._components[componentClass] == nil then
-- component does not exist in this list, returns the archetype itself
return self
end
local cache = CACHE_WITHOUT[self]
if not cache then
cache = {}
CACHE_WITHOUT[self] = cache
end
local other = cache[componentClass]
if other == nil then
local componentTs = {}
for component,_ in pairs(self._components) do
if component ~= componentClass then
table.insert(componentTs, component)
end
end
other = Archetype.Of(componentTs)
cache[componentClass] = other
end
return other
end
--[[
Gets the reference to an archetype that has the current components - the informed components
@param componentClasses {ComponentClass[]}
@return Archetype
]]
function Archetype:WithoutAll(componentClasses)
local toIgnoreIdx = {}
for _,component in ipairs(componentClasses) do
toIgnoreIdx[component] = true
end
local cTypes = {}
for component,_ in pairs(self._components) do
if toIgnoreIdx[component] == nil then
table.insert(cTypes, component)
end
end
return Archetype.Of(cTypes)
end
-- Generic archetype, for entities that do not have components
Archetype.EMPTY = Archetype.Of({})
return Archetype
|
need_boolean(in_site({'setup_mode', 'skip'}), false)
|
local utils = require("browse.utils")
local M = {}
M.devdocs_search = function()
vim.ui.input("Search String: ", function(input)
if input == nil or input == "" then
return
end
local open_cmd = utils.get_open_cmd()
local input_with_filetype = vim.bo.filetype .. " " .. input
vim.fn.jobstart(string.format("%s 'https://devdocs.io/#q=%s'", open_cmd, input_with_filetype))
end)
end
M.devdocs_search_without_filetype = function()
vim.ui.input("Search String: ", function(input)
if input == nil or input == "" then
return
end
local open_cmd = utils.get_open_cmd()
vim.fn.jobstart(string.format("%s 'https://devdocs.io/#q=%s'", open_cmd, input))
end)
end
return M
|
-------------------------------------------------------------------------------
-- modt.lua
--
-- author: Lawrence Hoffman
--
-- an example of how to write unit tests with bgtest
-------------------------------------------------------------------------------
local function add(a, b)
return a+b
end
-- Tests have a specific signature, the take a test object, and return either
-- nil or a string. Returning nil indicates success, returning a string means
-- that the test failed, the string is shown as a message to the user.
local function t_add(t)
t:Info("I'm an informative but oververly verbose message")
if add(2, 2) == 4 then
return
end
return "That doesn't add up"
end
local function t_bad(t)
t:Warn("I'm going fail on purpose")
return "OOPS!"
end
-- Check if we've been loaded by a test harness
if __TESTING then
local Suite = __TESTING
return Suite:New("example_basic")
:Test("Good add", t_add)
:Test("Bad add", t_bad)
:Done()
end
-- Our totally normal return here
return {
add = add
}
|
local ffi = require "ffi"
local bit = require "bit"
local string = require "string"
local table = require "table"
local ffi_new = ffi.new
local ffi_str = ffi.string
local ffi_cast = ffi.cast
local is_luajit = pcall(require, "jit")
local clib
local consts = {}
---
-- aux
---
local aux = {}
if is_luajit then
function aux.is_null(ptr)
return ptr == nil
end
else
function aux.is_null(ptr)
return ptr == ffi.C.NULL
end
end
function aux.wrap_string(c_str)
if not aux.is_null(c_str) then
return ffi_str(c_str)
end
return nil
end
function aux.wrap_bool(c_bool)
return c_bool ~= 0
end
---
-- sqlite3
---
local _M = {}
local function init_mod(mod, opts)
if clib ~= nil then
return mod
end
clib = _M._load_clib(opts)
_M.C = clib
_M._bind_clib()
return mod
end
function _M._load_clib(opts)
if opts == nil then
return ffi.C
end
return ffi.load(opts)
end
function _M._bind_clib()
_M.consts = consts
consts.OK = 0
consts.ERROR = 1
consts.INTERNAL = 2
consts.PERM = 3
consts.ABORT = 4
consts.BUSY = 5
consts.LOCKED = 6
consts.NOMEM = 7
consts.READONLY = 8
consts.INTERRUPT = 9
consts.IOERR = 10
consts.CORRUPT = 11
consts.NOTFOUND = 12
consts.FULL = 13
consts.CANTOPEN = 14
consts.PROTOCOL = 15
consts.EMPTY = 16
consts.SCHEMA = 17
consts.TOOBIG = 18
consts.CONSTRAINT = 19
consts.MISMATCH = 20
consts.MISUSE = 21
consts.NOLFS = 22
consts.AUTH = 23
consts.FORMAT = 24
consts.RANGE = 25
consts.NOTADB = 26
consts.NOTICE = 27
consts.WARNING = 28
consts.ROW = 100
consts.DONE = 101
consts.INTEGER = 1
consts.FLOAT = 2
consts.TEXT = 3
consts.BLOB = 4
consts.NULL = 5
if not is_luajit then
consts.C_NULL = ffi.C.NULL
end
consts.OPEN_READONLY = 0x00000001
consts.OPEN_READWRITE = 0x00000002
consts.OPEN_CREATE = 0x00000004
consts.OPEN_URI = 0x00000040
consts.OPEN_MEMORY = 0x00000080
consts.OPEN_NOMUTEX = 0x00008000
consts.OPEN_FULLMUTEX = 0x00010000
consts.OPEN_SHAREDCACHE = 0x00020000
consts.OPEN_PRIVATECACHE = 0x00040000
consts.OPEN_NOFOLLOW = 0x01000000
ffi.cdef [[
typedef __int64 sqlite3_int64;
typedef unsigned __int64 sqlite3_uint64;
typedef void (*sqlite3_destructor_type)(void *);
typedef struct sqlite3 sqlite3;
typedef struct sqlite3_stmt sqlite3_stmt;
typedef struct sqlite3_value sqlite3_value;
]]
consts.STATIC = ffi_cast("sqlite3_destructor_type", 0)
consts.TRANSIENT = ffi_cast("sqlite3_destructor_type", -1)
ffi.cdef [[
const char *sqlite3_libversion();
const char *sqlite3_sourceid();
int sqlite3_libversion_number();
int sqlite3_threadsafe();
void sqlite3_free(void*);
int sqlite3_errcode(sqlite3 *);
const char *sqlite3_errmsg(sqlite3 *);
int sqlite3_extended_errcode(sqlite3 *);
const char *sqlite3_errstr(int);
int sqlite3_extended_result_codes(sqlite3 *, int);
]]
function _M.libversion()
return aux.wrap_string(clib.sqlite3_libversion())
end
function _M.sourceid()
return aux.wrap_string(clib.sqlite3_sourceid())
end
function _M.libversion_number()
return clib.sqlite3_libversion_number()
end
function _M.threadsafe()
-- return 0, 1, or 2
return clib.sqlite3_threadsafe()
end
function _M.free(pointer)
clib.sqlite3_free(pointer)
end
function _M.extended_result_codes(db, onoff)
return clib.sqlite3_extended_result_codes(db, onoff)
end
function _M.errcode(db)
return clib.sqlite3_errcode(db)
end
function _M.extended_errcode(db)
return clib.sqlite3_extended_errcode(db)
end
function _M.errmsg(db)
return aux.wrap_string(clib.sqlite3_errmsg(db))
end
function _M.errstr(code)
return aux.wrap_string(clib.sqlite3_errstr(code))
end
ffi.cdef [[
int sqlite3_open(const char *, sqlite3 **);
int sqlite3_open_v2(const char *, sqlite3 **, int, const char *);
int sqlite3_close(sqlite3 *);
int sqlite3_close_v2(sqlite3 *);
]]
function _M.open(filename)
local db_p = ffi_new("sqlite3*[1]")
local rc = clib.sqlite3_open(filename, db_p)
return rc, db_p[0]
end
function _M.open_v2(filename, flags, vfs)
local db_p = ffi_new("sqlite3*[1]")
local rc = clib.sqlite3_open_v2(filename, db_p, flags, vfs)
return rc, db_p[0]
end
function _M.close(db)
return clib.sqlite3_close(db)
end
function _M.close_v2(db)
return clib.sqlite3_close_v2(db)
end
ffi.cdef [[
int sqlite3_exec(sqlite3 *, const char *sql,
int (*callback)(void *arg1, int argc, char **argv, char **col_names),
void *arg1,
char **errmsg
);
sqlite3_int64 sqlite3_last_insert_rowid(sqlite3 *);
void sqlite3_set_last_insert_rowid(sqlite3 *, sqlite3_int64);
]]
function _M.exec(db, sql, callback, arg1, errmsg)
if errmsg == true then
local cstr = ffi_new("char*[1]")
local rc = clib.sqlite3_exec(db, sql, callback, arg1, cstr)
local errstr = aux.wrap_string(cstr[0])
clib.sqlite3_free(cstr[0])
return rc, errstr
end
return clib.sqlite3_exec(db, sql, callback, arg1, errmsg)
end
function _M.last_insert_rowid(db)
return clib.sqlite3_last_insert_rowid(db)
end
function _M.set_last_insert_rowid(db, rowid)
clib.sqlite3_set_last_insert_rowid(db, rowid)
end
ffi.cdef [[
int sqlite3_prepare(sqlite3*, const char*, int, sqlite3_stmt**, const char**);
int sqlite3_prepare_v2(sqlite3 *,
const char *sql,
int nbytes,
sqlite3_stmt **ppStmt,
const char **pzTail);
int sqlite3_finalize(sqlite3_stmt*);
]]
function _M.prepare_v2(db, sql)
local pstmt = ffi.new("sqlite3_stmt*[1]")
local rc = clib.sqlite3_prepare_v2(db, sql, #sql + 1, pstmt, nil);
if rc == consts.OK then
return rc, pstmt[0]
else
return rc, nil
end
end
function _M.finalize(stmt)
return clib.sqlite3_finalize(stmt)
end
ffi.cdef [[
int sqlite3_step(sqlite3_stmt *);
int sqlite3_reset(sqlite3_stmt *);
int sqlite3_clear_bindings(sqlite3_stmt *);
]]
function _M.step(stmt)
return clib.sqlite3_step(stmt)
end
function _M.reset(stmt)
return clib.sqlite3_reset(stmt)
end
function _M.clear_bindings(stmt)
return clib.sqlite3_sqlite3_clear_bindings(stmt)
end
ffi.cdef [[
int sqlite3_bind_parameter_count(sqlite3_stmt*);
const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
int sqlite3_bind_parameter_index(sqlite3_stmt*, const char*);
]]
function _M.bind_parameter_count(stmt)
return clib.sqlite3_bind_parameter_count(stmt)
end
function _M.bind_parameter_name(stmt, index)
return aux.wrap_string(clib.sqlite3_bind_parameter_name(stmt, index))
end
function _M.bind_parameter_index(stmt, name)
return clib.sqlite3_bind_parameter_index(stmt, name)
end
ffi.cdef [[
int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64, void(*)(void*));
int sqlite3_bind_double(sqlite3_stmt*, int, double);
int sqlite3_bind_int(sqlite3_stmt *, int index, int value);
int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
int sqlite3_bind_null(sqlite3_stmt*, int);
int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int, void(*)(void*));
int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*, void(*)(void*));
]]
function _M.bind_blob(stmt, index, pointer, size, destructor)
return clib.sqlite3_bind_blob(stmt, index, pointer, size, destructor)
end
function _M.bind_blob64(stmt, index, pointer, size, destructor)
return clib.sqlite3_bind_blob64(stmt, index, pointer, size, destructor)
end
function _M.bind_double(stmt, index, value)
return clib.sqlite3_bind_double(stmt, index, value)
end
function _M.bind_int(stmt, index, value)
return clib.sqlite3_bind_int(stmt, index, value)
end
function _M.bind_null(stmt, index)
return clib.sqlite3_bind_null(stmt, index)
end
function _M.bind_text(stmt, index, text, nbytes, destructor)
if type(text) == "string" then
return clib.sqlite3_bind_text(stmt, index, text, nbytes or #text + 1, nil)
end
return clib.sqlite3_bind_text(stmt, index, text, nbytes, destructor)
end
function _M.bind_value(stmt, index, value)
return clib.sqlite3_bind_value(stmt, index, value)
end
function _M.bind_pointer(stmt, index, pointer, p_type, destructor)
return clib.sqlite3_bind_pointer(stmt, index, pointer, p_type, destructor)
end
ffi.cdef [[
int sqlite3_data_count(sqlite3_stmt *);
int sqlite3_column_count(sqlite3_stmt *);
const char *sqlite3_column_name(sqlite3_stmt *, int);
const char *sqlite3_column_decltype(sqlite3_stmt *, int);
]]
function _M.data_count(stmt)
return clib.sqlite3_data_count(stmt)
end
function _M.column_count(stmt)
return clib.sqlite3_column_count(stmt)
end
function _M.column_name(stmt, index)
return aux.wrap_string(clib.sqlite3_column_name(stmt, index))
end
function _M.column_decltype(stmt, index)
return aux.wrap_string(clib.sqlite3_column_decltype(stmt, index))
end
ffi.cdef [[
const void *sqlite3_column_blob(sqlite3_stmt*, int);
double sqlite3_column_double(sqlite3_stmt*, int);
int sqlite3_column_int(sqlite3_stmt*, int);
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int);
const char *sqlite3_column_text(sqlite3_stmt*, int);
sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int);
int sqlite3_column_bytes(sqlite3_stmt*, int);
int sqlite3_column_type(sqlite3_stmt*, int);
]]
function _M.column_blob(stmt, column)
return clib.sqlite3_column_blob(stmt, column)
end
function _M.column_double(stmt, column)
return clib.sqlite3_column_double(stmt, column)
end
function _M.column_int(stmt, column)
return clib.sqlite3_column_int(stmt, column)
end
function _M.column_int64(stmt, column)
return clib.sqlite3_column_int64(stmt, column)
end
function _M.column_text(stmt, column)
return aux.wrap_string(clib.sqlite3_column_text(stmt, column))
end
function _M.column_value(stmt, column)
return clib.sqlite3_column_value(stmt, column)
end
function _M.column_bytes(stmt, column)
return clib.sqlite3_column_bytes(stmt, column)
end
function _M.column_type(stmt, column)
return clib.sqlite3_column_type(stmt, column)
end
ffi.cdef [[
const char *sqlite3_sql(sqlite3_stmt*);
char *sqlite3_expanded_sql(sqlite3_stmt*);
const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
]]
function _M.sql(stmt)
return aux.wrap_string(clib.sqlite3_sql(stmt))
end
function _M.expanded_sql(stmt)
local cstr = clib.sqlite3_expanded_sql(stmt)
local lstr = ffi_str(cstr)
clib.sqlite3_free(cstr)
return lstr
end
function _M.normalized_sql(stmt)
return aux.wrap_string(clib.sqlite3_normalized_sql(stmt))
end
end
return setmetatable(_M, {
__call = init_mod
})
|
local Drop, Version = MakeSushi(7, 'Frame', 'DropdownFrame', nil, nil, SushiGroup)
if not Drop then
return
elseif not Version then
local function closeAll()
Drop:CloseAll()
end
hooksecurefunc('ToggleDropDownMenu', closeAll)
hooksecurefunc('CloseDropDownMenus', closeAll)
end
local function get(value, ...)
if type(value) == 'function' then
return value(...)
end
return value
end
--[[ Startup ]]--
function Drop:OnCreate()
SushiGroup.OnCreate(self)
self:SetOrientation('HORIZONTAL')
self:SetResizing('VERTICAL')
self:SetClampedToScreen(true)
self.bg = CreateFrame('Frame', nil, self)
self.bg:SetFrameLevel(self:GetFrameLevel())
self.bg:SetPoint('BOTTOMLEFT', 0, -11)
self.bg:SetPoint('TOPRIGHT', 0, 11)
end
function Drop:OnAcquire()
SushiCallHandler.OnAcquire(self)
self.lines = nil
self:SetMenu(false)
self:SetFrameStrata('FULLSCREEN_DIALOG')
self:SetCall('UpdateChildren', function()
self.width = 0
local lines = get(self.lines, self)
if lines then
for i, line in ipairs(lines) do
self:AddLine(line)
end
end
for button in self:IterateChildren() do
button:SetWidth(self.width + 25)
end
self:SetWidth(self.width + 52)
end)
end
--[[ API ]]--
function Drop:SetMenu(isMenu)
if isMenu then
self.bg:SetBackdrop {
bgFile = 'Interface/Tooltips/UI-Tooltip-Background',
edgeFile = 'Interface/Tooltips/UI-Tooltip-Border',
insets = {left = 5, right = 5, top = 5, bottom = 5},
edgeSize = 16, tileSize = 16, tile = true
}
self.bg:SetBackdropBorderColor(TOOLTIP_DEFAULT_COLOR.r, TOOLTIP_DEFAULT_COLOR.g, TOOLTIP_DEFAULT_COLOR.b)
self.bg:SetBackdropColor(TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, TOOLTIP_DEFAULT_BACKGROUND_COLOR.b)
else
self.bg:SetBackdrop {
bgFile = 'Interface/DialogFrame/UI-DialogBox-Background-Dark',
edgeFile = 'Interface/DialogFrame/UI-DialogBox-Border',
insets = {left = 11, right = 11, top = 11, bottom = 9},
edgeSize = 32, tileSize = 32, tile = true
}
end
end
function Drop:SetLines(lines)
self.lines = lines
self:UpdateChildren()
end
function Drop:AddLine(data)
local button = self:Create('DropdownButton')
button:SetTip(data.tooltipTitle, data.tooltipText)
button:SetChecked(get(data.checked, data))
button:SetRadio(data.isRadio)
button:SetText(data.text)
button:SetTitle(data.isTitle)
button:SetCheckable(not data.notCheckable)
button:SetCall('OnClick', function()
if not data.disabled or data.isTitle then
data.checked = button:GetChecked()
data:func()
self:SetShown(data.keepShownOnClick)
end
end)
self.width = max(self.width, button:GetTextWidth())
end
--[[ Static ]]--
function Drop:Toggle(...)
local n = select('#', ...)
local anchor = select(n < 4 and 1 or 2, ...)
if anchor ~= self.target then
self:Display(...)
else
CloseDropDownMenus()
end
PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON)
end
function Drop:Display(...)
local n = select('#', ...)
local anchor = select(n < 4 and 1 or 2, ...)
CloseDropDownMenus()
self.target = anchor
local frame = self(anchor)
if n < 4 then
frame:SetPoint('TOP', anchor, 'BOTTOM', 0, -5)
else
frame:SetPoint(...)
end
frame:SetMenu(select(n-1, ...))
frame:SetLines(select(n, ...))
end
function Drop:CloseAll()
for i, frame in ipairs(self.usedFrames) do
frame:Release()
end
self.target = nil
end
SushiDropFrame = Drop |
local Rule = require('nvim-autopairs.rule')
local cond = require('nvim-autopairs.conds')
local npairs = require('nvim-autopairs')
local ignored_next_char = string.gsub([[ [%w%%%[%.] ]],"%s+", "")
npairs.setup {
ignored_next_char = ignored_next_char
}
npairs.add_rule(
Rule('<', '>')
:with_pair(cond.not_after_regex(ignored_next_char))
:with_move(function(opts)
return opts.char == '>'
end)
:with_pair(cond.is_bracket_line())
)
-- (|) press space => ( | )
-- ( | ) press ) => ( )|
npairs.add_rules {
Rule(' ', ' ')
:with_pair(function (opts)
local pair = opts.line:sub(opts.col - 1, opts.col)
return vim.tbl_contains({ '()', '{}', '[]' }, pair)
end),
Rule('( ', ' )')
:with_pair(function() return false end)
:with_move(function(opts)
return opts.prev_char:match('.%)') ~= nil
end)
:use_key(')'),
Rule('{ ', ' }')
:with_pair(function() return false end)
:with_move(function(opts)
return opts.prev_char:match('.%}') ~= nil
end)
:use_key(')'),
Rule('[ ', ' ]')
:with_pair(function() return false end)
:with_move(function(opts)
return opts.prev_char:match('.%]') ~= nil
end)
:use_key(')'),
}
|
local awful = require("awful")
local gears = require("gears")
local wibox = require("wibox")
local beautiful = require("beautiful")
local dpi = beautiful.xresources.apply_dpi
local helpers = require('helpers')
local ram = wibox.widget.textbox("")
awesome.connect_signal("watches::ram", function(used, total)
local used_ram_percentage = string.format(
"%.1f%% ",
(used / total) * 100
)
ram.markup = helpers.colorize_text(used_ram_percentage, beautiful.xcolor1)
end)
return ram
|
loader.SetFillMode((loader.GetFillMode() + 1) % 2) -- SOLID / WIREFRAME
loader.SetWindMode((loader.GetWindMode() + 1) % 2) -- STRAIGHT / RADIAL
wind_speed = loader.GetWindSpeed()
loader.SetWindSpeed((wind_speed + 25.0) % 100.0)
wave_width = loader.GetWaveWidth()
loader.SetWaveWidth((wave_width + 6.0) % 20.0)
wind_strength = loader.GetWindStrength()
loader.SetWindStrength((wind_strength + 15.0) % 100.0)
math.randomseed( os.time() )
random_level = math.random(10)
loader.SetMaxTessellationLevel(random_level) |
local restserver = {}
local request = require("wsapi.request")
local response = require("wsapi.response")
local json = require("dkjson")
local unpack = unpack or table.unpack
local function add_resource(self, name, entries, authfunc)
for _, entry in ipairs(entries) do
local path = ("^/" .. name .. "/" .. entry.path):gsub("([^{]+)(%b{})", function (literal,pattern) return literal:gsub("%-", "%%-")..pattern end):gsub("/+", "/"):gsub("/$", "") .. "$"
entry.rest_path = path
entry.match_path = path:gsub("{[^:]*:([^}]*)}", "(%1)"):gsub("{[^}]*}", "([^/]+)")
-- set up auth (if not already present) for all entries of this resource
if not entry.auth and authfunc then entry.auth = authfunc end
path = path:gsub("{[^:]*:([^}]*)}", "%1"):gsub("{[^}]*}", "[^/]+")
local methods = self.config.paths[path]
if not methods then
methods = {}
self.config.paths[path] = methods
table.insert(self.config.path_list, path)
end
if methods[entry.method] then
local ui_path = "/" .. name .. "/" .. entry.path
error("A handler for method "..entry.method.." in path "..ui_path.." is already defined.")
end
methods[entry.method] = entry
end
end
local function set_error_handler(self, entry)
self.error_handler = function(_, code, msg)
return {
response = entry.handler(code, msg),
headers = { ["Content-Type"] = entry.produces or "text/plain" }
}
end
self.error_schema = entry.output_schema
end
local function type_check(tbl, schema)
for k, s in pairs(schema) do
if not tbl[k] then
if not s.optional then
return nil, "missing field '"..k.."'"
end
elseif type(tbl[k]) ~= s.type then
return nil, "in field '"..k.."', expected type "..s.type..", got "..type(tbl[k])
elseif s.array and next(tbl[k]) and not tbl[k][1] then
return nil, "in field '"..k.."', expected an array"
end
end
return true
end
local function decode(data, mimetype, schema)
if mimetype == "application/json" then
local tbl = json.decode(data)
if schema then
local ok, err = type_check(tbl, schema)
if not ok then
return nil, err
end
end
return tbl
elseif mimetype == "text/plain" then
return data or ""
elseif not mimetype or mimetype == "*/*" then
return data or ""
else
error("Mimetype "..mimetype.." not supported.")
end
end
local function encode(data, mimetype, schema)
if mimetype == "application/json" then
if schema then
local ok, err = type_check(data, schema)
if not ok then
return nil, err
end
end
return json.encode(data)
elseif mimetype == "text/plain" then
return data or ""
elseif not mimetype then
return data or ""
else
error("Mimetype "..mimetype.." not supported.")
end
end
local function get_error_response(self, code, msg, wreq)
local res = self.error_handler(wreq, code, msg)
res.headers = res.headers or { ["Content-Type"] = "text/plain" }
local output, err = encode(res.response, res.headers["Content-Type"], self.error_schema)
if not output then
return nil, err
end
res.content = output
return res
end
local function fail(self, wreq, code, msg)
local res, err = get_error_response(self, code, msg, wreq)
local wres = response.new(code, res.headers)
local output
if err then
wres = response.new(500, { ["Content-Type"] = "text/plain" })
output = "Internal Server Error - Server built a response that fails schema validation: "..err
else
output = res.content
end
wres:write(output)
return wres:finish()
end
local function match_path(self, path_info)
for _, path in ipairs(self.config.path_list) do
if path_info:match(path) then
return self.config.paths[path]
end
end
end
local function wsapi_handler_with_self(self, wsapi_env, rs_api)
local wreq = request.new(wsapi_env)
local input_path = wsapi_env.PATH_INFO:gsub("/$", "")
local methods = self.config.paths["^" .. input_path .. "$"] or match_path(self, wsapi_env.PATH_INFO)
local entry = methods and methods[wreq.method]
if not entry then
return fail(self, wreq, 405, "Method Not Allowed")
end
local input, err
if wreq.method == "POST" then
input, err = decode(wreq.POST.post_data, entry.consumes, entry.input_schema)
elseif wreq.method == "GET" then
input = wreq.GET
elseif wreq.method == "DELETE" then
input = ""
else
error("Other methods not implemented yet.")
end
if not input then
return fail(self, wreq, 400, "Bad Request - Your request fails schema validation: "..("" or err) )
end
local placeholder_matches = (entry.rest_path ~= entry.match_path) and { input_path:match(entry.match_path) } or {}
local ok, res
local handler
local pass_wreq = false
if rs_api == "0.3" then
handler = entry.handler
pass_wreq = true
elseif entry.handle_req then
handler = entry.handle_req
pass_wreq = true
else
handler = entry.handler
pass_wreq = false
end
local auth_result = entry.auth and entry.auth(wsapi_env) -- return { errorcode = 401|403, user = 'alice' } or nil
if auth_result and auth_result.errorcode then
return fail(self, wreq, auth_result.errorcode, "Authentication error: "..(auth_result.message or ""))
end
if pass_wreq then
if auth_result then
ok, res = pcall(handler, wreq, input, auth_result.user, unpack(placeholder_matches))
else
ok, res = pcall(handler, wreq, input, unpack(placeholder_matches))
end
else
if auth_result then
ok, res = pcall(handler, input, auth_result.user, unpack(placeholder_matches))
else
ok, res = pcall(handler, input, unpack(placeholder_matches))
end
end
if not ok then
return fail(self, wreq, 500, "Application error: "..res)
end
if not res then
return fail(self, wreq, 500, "Server failed to produce a response.")
end
local output, err = encode(res.config.entity, entry.produces, entry.output_schema)
if not output then
return fail(self, wreq, 500, "Server built a response that fails schema validation: "..err)
end
local headers = { ["Content-Type"] = entry.produces or "text/plain" }
if res.config.headers then
for k,v in pairs(res.config.headers) do
headers[k] = v
end
end
local wres = response.new(res.config.status,headers)
wres:write(output)
return wres:finish()
end
local function add_setter(self, var)
self[var] = function (self, val)
self.config[var] = val
return self
end
end
function restserver.new(rs_api)
local server = {
config = {
paths = {},
path_list = {},
},
enable = function(self, plugin_name)
local mod = require(plugin_name)
mod.extend(self)
return self
end,
add_resource = add_resource,
set_error_handler = set_error_handler,
get_error_response = get_error_response, -- To be used by server plugins
}
add_setter(server, "host")
add_setter(server, "port")
server.wsapi_handler = function(wsapi_env)
return wsapi_handler_with_self(server, wsapi_env, rs_api)
end
server.error_handler = function(wreq, code, msg)
return { response = tostring(code).." "..msg }
end
return server
end
function restserver.response()
local res = {
config = {},
}
add_setter(res, "status")
add_setter(res, "entity")
add_setter(res, "headers")
return res
end
return restserver
|
return {'vorderen','vordering','vorderingsrecht','vore','voren','vorenbedoeld','vorengenoemd','vorenstaand','vorig','vork','vorkbeen','vorken','vorkheftruck','vorm','vormbak','vormbehoud','vormcrisis','vormeis','vormelijk','vormelijkheid','vormeling','vormeloos','vormeloosheid','vormen','vormend','vormenrijkdom','vormenstoof','vormentaal','vormer','vormexperiment','vormfout','vormgebrek','vormgeefster','vormgeheugen','vormgeven','vormgever','vormgeving','vormgevingsbeleid','vormgevingsinstituut','vormgevingsprobleem','vormgevoel','vorming','vormingsactiviteit','vormingscentrum','vormingscursus','vormingsinstituut','vormingsklas','vormingsleider','vormingsleidster','vormingsonderwijs','vormingsproces','vormingstheater','vormingstoneel','vormingswerk','vormingswerker','vormingswerkster','vormkenmerk','vormleer','vormloos','vormloosheid','vormmachine','vormmeter','vormopmaker','vormpeter','vormpje','vormsel','vormtaal','vormvariant','vormvast','vormvastheid','vormverandering','vormverlies','vormzand','vorsen','vorser','vorst','vorstdag','vorstelijk','vorstelijkheid','vorstenbloed','vorstendom','vorstengunst','vorstenhuis','vorstenkroon','vorstenpaar','vorstentelg','vorstenzoon','vorstgevaar','vorstgevoelig','vorstgrens','vorstig','vorstin','vorstpan','vorstperiode','vorstschade','vorstverlet','vorstvrij','vort','vormbeheersing','vormverscheidenheid','vorstkam','vormtheorie','vorklift','vormdrift','vormherkenning','vormingsaanbod','vormpeil','vormbaar','vormbewustzijn','vormenwereld','vormfactor','vormingsdag','vormingsfonds','vormingspakket','vormingsplicht','vormingsprogramma','vormingsstation','vormkracht','vormovereenkomst','vormveld','vormvereiste','vormverzuim','vormvoorschrift','vormvrij','vormwereld','vormmerk','vorderingenstaat','vormingsmoment','vormingsperiode','vorden','vorselaar','vorsen','vorst','vorstenaar','vorsts','voragen','vording','vorster','vorenkamp','vorgers','vorder','vorderde','vorderden','vorderingen','vordert','vorenbedoelde','vorengenoemde','vorens','vorenstaande','vorentje','vorentjes','vorige','vorigen','vorkbenen','vorkheftrucks','vorkje','vorkjes','vormbakken','vormde','vormden','vormelijke','vormelijker','vormelijkheden','vormelingen','vormeloze','vormelozer','vormende','vormers','vormexperimenten','vormfouten','vormgeef','vormgeeft','vormgegeven','vormgevend','vormgevende','vormgevers','vormgevingskwesties','vormgevingsproblemen','vormingen','vormingscentra','vormingsleiders','vormingswerkers','vormkenmerken','vormloze','vormlozer','vormmachines','vormmeters','vormpeters','vormpjes','vormprincipes','vormstukken','vormt','vormveranderingen','vormvereisten','vors','vorstdagen','vorste','vorstelijke','vorstelijker','vorstelijkste','vorsten','vorstendommen','vorstendommetje','vorstendommetjes','vorstenhoven','vorstenhuizen','vorstenspiegels','vorstentelgen','vorstenzonen','vorstgrenzen','vorstige','vorstinnen','vorstinnetje','vorstpannen','vorstvrije','vorderende','vorkbeenderen','vormeisen','vormgaf','vormingsactiviteiten','vormingscursussen','vormingsinstituten','vormingsklassen','vormvarianten','vormvaste','vorsend','vorsers','vorstenkronen','vorstgevoelige','vorstkammen','vormingsdagen','vormingsmomenten','vormvoorschriften','vormvrije','vorstperiodes','vormgaven','vormingsprogrammas','vormkrachten','vorstperioden','vormgebreken','vormingspakketten','vormingsprocessen','vormfoutje','vormmerken','vormfactoren','vormingsstations','vordense'} |
-------------------------------------------------------------------------=---
-- Name: dialog.wx.lua
-- Purpose: Dialog wxLua sample, a temperature converter
-- Based on the C++ version by Marco Ghislanzoni
-- Author: J Winwood, John Labenski
-- Created: March 2002
-- Copyright: (c) 2001 Lomtick Software. All rights reserved.
-- Licence: wxWidgets licence
-------------------------------------------------------------------------=---
-- Load the wxLua module, does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit
package.cpath = package.cpath..";./?.dll;./?.so;../lib/?.so;../lib/vc_dll/?.dll;../lib/bcc_dll/?.dll;../lib/mingw_dll/?.dll;"
require("wx")
-- IDs of the controls in the dialog
ID_CELSIUS_BUTTON = 1 -- NOTE: We use the fact that the textctrl ids
ID_CELSIUS_TEXTCTRL = 2 -- are +1 fom the button ids.
ID_KELVIN_BUTTON = 3
ID_KELVIN_TEXTCTRL = 4
ID_FAHRENHEIT_BUTTON = 5
ID_FAHRENHEIT_TEXTCTRL = 6
ID_RANKINE_BUTTON = 7
ID_RANKINE_TEXTCTRL = 8
ID_ABOUT_BUTTON = 9
ID_CLOSE_BUTTON = 10
ID__MAX = 11 -- max of our window ids
-- Create the dialog, there's no reason why we couldn't use a wxFrame and
-- a frame would probably be a better choice.
dialog = wx.wxDialog(wx.NULL, wx.wxID_ANY, "wxLua Temperature Converter",
wx.wxDefaultPosition, wx.wxDefaultSize)
-- Create a wxPanel to contain all the buttons. It's a good idea to always
-- create a single child window for top level windows (frames, dialogs) since
-- by default the top level window will want to expand the child to fill the
-- whole client area. The wxPanel also gives us keyboard navigation with TAB key.
panel = wx.wxPanel(dialog, wx.wxID_ANY)
-- Layout all the buttons using wxSizers
local mainSizer = wx.wxBoxSizer(wx.wxVERTICAL)
local staticBox = wx.wxStaticBox(panel, wx.wxID_ANY, "Enter temperature")
local staticBoxSizer = wx.wxStaticBoxSizer(staticBox, wx.wxVERTICAL)
local flexGridSizer = wx.wxFlexGridSizer( 3, 3, 0, 0 )
flexGridSizer:AddGrowableCol(1, 0)
-- Make a function to reduce the amount of duplicate code.
function AddConverterControl(name_string, button_text, textCtrlID, buttonID)
local staticText = wx.wxStaticText( panel, wx.wxID_ANY, name_string)
local textCtrl = wx.wxTextCtrl( panel, textCtrlID, "000000.00000", wx.wxDefaultPosition, wx.wxDefaultSize, wx.wxTE_PROCESS_ENTER )
local button = wx.wxButton( panel, buttonID, button_text)
flexGridSizer:Add( staticText, 0, wx.wxALIGN_CENTER_VERTICAL+wx.wxALL, 5 )
flexGridSizer:Add( textCtrl, 0, wx.wxGROW+wx.wxALIGN_CENTER+wx.wxALL, 5 )
flexGridSizer:Add( button, 0, wx.wxGROW+wx.wxALIGN_CENTER+wx.wxALL, 5 )
return textCtrl
end
celsiusTextCtrl = AddConverterControl("Celsius", "From &Celsius", ID_CELSIUS_TEXTCTRL, ID_CELSIUS_BUTTON)
kelvinTextCtrl = AddConverterControl("Kelvin", "From &Kelvin", ID_KELVIN_TEXTCTRL, ID_KELVIN_BUTTON)
fahrenheitTextCtrl = AddConverterControl("Fahrenheit", "From &Fahrenheit", ID_FAHRENHEIT_TEXTCTRL, ID_FAHRENHEIT_BUTTON)
rankineTextCtrl = AddConverterControl("Rankine", "From &Rankine", ID_RANKINE_TEXTCTRL, ID_RANKINE_BUTTON)
--[[
NOTE: We've wrapped the creation of the controls into a function, but we could
have created them all separately this way.
local celsiusStaticText = wx.wxStaticText( panel, wx.wxID_ANY, "Celsius")
local celsiusTextCtrl = wx.wxTextCtrl( panel, ID_CELSIUS_TEXTCTRL, "", wx.wxDefaultPosition, wx.wxSize(80,-1), 0 )
local celsiusButton = wx.wxButton( panel, ID_CELSIUS_BUTTON, "C -> K && F")
flexGridSizer:AddWindow( celsiusStaticText, 0, wx.wxALIGN_CENTER_VERTICAL+wx.wxALL, 5 )
flexGridSizer:AddWindow( celsiusTextCtrl, 0, wx.wxGROW+wx.wxALIGN_CENTER+wx.wxALL, 5 )
flexGridSizer:AddWindow( celsiusButton, 0, wx.wxALIGN_CENTER+wx.wxALL, 5 )
]]
staticBoxSizer:Add( flexGridSizer, 0, wx.wxGROW+wx.wxALIGN_CENTER+wx.wxALL, 5 )
mainSizer:Add( staticBoxSizer, 1, wx.wxGROW+wx.wxALIGN_CENTER+wx.wxALL, 5 )
local buttonSizer = wx.wxBoxSizer( wx.wxHORIZONTAL )
local aboutButton = wx.wxButton( panel, ID_ABOUT_BUTTON, "&About")
local closeButton = wx.wxButton( panel, ID_CLOSE_BUTTON, "E&xit")
buttonSizer:Add( aboutButton, 0, wx.wxALIGN_CENTER+wx.wxALL, 5 )
buttonSizer:Add( closeButton, 0, wx.wxALIGN_CENTER+wx.wxALL, 5 )
mainSizer:Add( buttonSizer, 0, wx.wxALIGN_CENTER+wx.wxALL, 5 )
panel:SetSizer( mainSizer )
mainSizer:SetSizeHints( dialog )
-- ---------------------------------------------------------------------------
-- Calculate the temp conversions, input only one temp, set others to nil
-- Shows how to handle nil inputs and return multiple ones
function ConvertTemp( Tc, Tk, Tf, Tr )
if Tc or Tk then
Tc = Tc or (Tk - 273.15)
Tf = (Tc * 9/5) + 32
else -- Tf or Tr
Tf = Tf or (Tr - 459.67)
Tc = (Tf - 32) * 5/9
end
Tk = Tc + 273.15
Tr = Tf + 459.67
return Tc, Tk, Tf, Tr
end
-- ---------------------------------------------------------------------------
-- Connect a handler for pressing enter in the textctrls
dialog:Connect(wx.wxID_ANY, wx.wxEVT_COMMAND_TEXT_ENTER,
function(event)
-- Send "fake" button press to do calculation.
-- Button ids have been set to be -1 from textctrl ids.
dialog:ProcessEvent(wx.wxCommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, event:GetId()-1))
end)
-- ---------------------------------------------------------------------------
-- Connect a central event handler that responds to all button clicks.
-- NOTE: Since we Connect() the about and close buttons after this they will be
-- called first and unless we call event:Skip() in their handlers the
-- events will never reach this function. Therefore we don't need to
-- check that the ids are only from temp conversion buttons.
dialog:Connect(wx.wxID_ANY, wx.wxEVT_COMMAND_BUTTON_CLICKED,
function(event)
-- NOTE: A wxID_CANCEL event is sent when the close button on the
-- dialog is pressed.
if event:GetId() >= ID__MAX then
event:Skip()
return
end
-- We know that the textctrl window ids are +1 from the button ids
local T = tonumber(dialog:FindWindow(event:GetId()+1):DynamicCast("wxTextCtrl"):GetValue())
if T == nil then
wx.wxMessageBox("The input temperature is invalid, enter a number.",
"Error!",
wx.wxOK + wx.wxICON_EXCLAMATION + wx.wxCENTRE,
dialog)
else
-- Create a "case" type statement
local TempCase = {
[ID_CELSIUS_BUTTON] = function() return ConvertTemp(T, nil, nil, nil) end,
[ID_KELVIN_BUTTON] = function() return ConvertTemp(nil, T) end, -- don't need trailing nils
[ID_FAHRENHEIT_BUTTON] = function() return ConvertTemp(nil, nil, T) end,
[ID_RANKINE_BUTTON] = function() return ConvertTemp(nil, nil, nil, T) end
}
-- call the "case" statement
local Tc, Tk, Tf, Tr = TempCase[event:GetId()]()
celsiusTextCtrl:SetValue( string.format("%.3f", Tc))
kelvinTextCtrl:SetValue( string.format("%.3f", Tk))
fahrenheitTextCtrl:SetValue(string.format("%.3f", Tf))
rankineTextCtrl:SetValue( string.format("%.3f", Tr))
end
end)
--[[
-- NOTE: You can also attach single event handlers to each of the buttons and
-- handle them separately.
dialog:Connect(ID_CELSIUS_BUTTON, wx.wxEVT_COMMAND_BUTTON_CLICKED,
function(event)
local T = tonumber(celsiusTextCtrl:GetValue())
if T == nil then
wx.wxMessageBox("The Celsius temperature is invalid, enter a number.",
"Error!",
wx.wxOK + wx.wxICON_EXCLAMATION + wx.wxCENTRE,
dialog)
else
kelvinTextCtrl:SetValue(T + 273.15)
fahrenheitTextCtrl:SetValue((T * 9 / 5) + 32)
rankineTextCtrl:SetValue((T * 9 / 5) + 32 + 459.67)
end
end)
]]
-- ---------------------------------------------------------------------------
-- Attach an event handler to the Close button
dialog:Connect(ID_CLOSE_BUTTON, wx.wxEVT_COMMAND_BUTTON_CLICKED,
function(event) dialog:Destroy() end)
dialog:Connect(wx.wxEVT_CLOSE_WINDOW,
function (event)
dialog:Destroy()
event:Skip()
end)
-- ---------------------------------------------------------------------------
-- Attach an event handler to the About button
dialog:Connect(ID_ABOUT_BUTTON, wx.wxEVT_COMMAND_BUTTON_CLICKED,
function(event)
wx.wxMessageBox("Based on the C++ version by Marco Ghislanzoni.\n"..
wxlua.wxLUA_VERSION_STRING.." built with "..wx.wxVERSION_STRING,
"About wxLua Temperature Converter",
wx.wxOK + wx.wxICON_INFORMATION,
dialog)
end)
-- ---------------------------------------------------------------------------
-- Send a "fake" event to simulate a button press to update the textctrls
dialog:ProcessEvent(wx.wxCommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, ID_CELSIUS_BUTTON))
-- ---------------------------------------------------------------------------
-- Centre the dialog on the screen
dialog:Centre()
-- Show the dialog
dialog:Show(true)
-- Call wx.wxGetApp():MainLoop() last to start the wxWidgets event loop,
-- otherwise the wxLua program will exit immediately.
-- Does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit since the
-- MainLoop is already running or will be started by the C++ program.
wx.wxGetApp():MainLoop()
|
local _CreateConVar = CreateConVar
local _CurTime = CurTime
local _hook_Add = hook.Add
local _player_GetAll = player.GetAll
if !gAC.config.NEKO_LUA_CHECKS then return end
local Neko_Value = gAC.Encoder.stringrandom(8, true)
_CreateConVar("neko_exit", Neko_Value, { FCVAR_CHEAT, FCVAR_PROTECTED, FCVAR_NOT_CONNECTED, FCVAR_USERINFO, FCVAR_UNREGISTERED, FCVAR_REPLICATED, FCVAR_UNLOGGED, FCVAR_DONTRECORD, FCVAR_SPONLY } )
_CreateConVar("neko_list", Neko_Value, { FCVAR_CHEAT, FCVAR_PROTECTED, FCVAR_NOT_CONNECTED, FCVAR_USERINFO, FCVAR_UNREGISTERED, FCVAR_REPLICATED, FCVAR_UNLOGGED, FCVAR_DONTRECORD, FCVAR_SPONLY } )
--Like if you managed to receive all gAC files then he should be able to receive the next messages.
_hook_Add("gAC.CLFilesLoaded", "g-ACAntiNekoPlayerAuthed", function(plr)
plr.GAC_Neko = 0
plr.GAC_Neko_Checks = _CurTime() + 5
gAC.Network:Send("g-AC_antineko", Neko_Value, plr)
end)
gAC.Network:AddReceiver("g-AC_Neko",function(tabledata, ply)
if ply.GAC_NEKOG then return end
ply.GAC_NEKOG = true
gAC.AddDetection( ply, "Global 'neko' function detected [Code 112]", gAC.config.NEKO_LUA_RETRIVAL_PUNISHMENT, gAC.config.NEKO_LUA_RETRIVAL_BANTIME )
end)
_hook_Add("Tick", "gAC-CheckNeko", function()
local _IPAIRS_ = _player_GetAll()
for k=1, #_IPAIRS_ do
local ply =_IPAIRS_[k]
if ply:IsBot() then continue end
if !ply.GAC_Neko_Checks then continue end
if ply.GAC_Neko_Checks > _CurTime() then continue end
if ply:IsTimingOut() then continue end
if ply:GetInfo( "neko_exit" ) != Neko_Value || ply:GetInfo("neko_list") != Neko_Value then
if ply.GAC_Neko > 4 then
gAC.AddDetection( ply, "Anti-neko cvar response not returned [Code 114]", gAC.config.NEKO_LUA_RETRIVAL_PUNISHMENT, gAC.config.NEKO_LUA_RETRIVAL_BANTIME )
ply.GAC_Neko_Checks = nil
continue
end
ply.GAC_Neko = ply.GAC_Neko + 1
ply.GAC_Neko_Checks = _CurTime() + 15
continue
end
if ply.GAC_Neko != 0 then
ply.GAC_Neko = 0
end
ply.GAC_Neko_Checks = _CurTime() + 5
end
end ) |
pg = pg or {}
pg.medal_template = {
[10011] = {
target_num = 2000,
name = "海军优秀服役勋章",
explain2 = "表现优秀的指挥官",
type = 0,
count_inherit = 0,
desc = "该勋章授予在服役期间表现优秀的指挥官",
next = 10012,
icon = "2021",
target_type = 1022,
start = 0,
hide = 0,
label = "l_201",
condition = "舰队出征累积胜利2000次 ",
rank = 1,
id = 10011,
explain1 = "授予在服役期间",
target_id = "0"
},
[10012] = {
target_num = 4000,
name = "海军优秀服役勋章",
explain2 = "表现优秀的指挥官",
type = 0,
count_inherit = 0,
desc = "该勋章授予在服役期间表现优秀的指挥官",
next = 10013,
icon = "2022",
target_type = 1022,
start = 1,
hide = 0,
label = "l_201",
condition = "舰队出征累积胜利4000次 ",
rank = 2,
id = 10012,
explain1 = "授予在服役期间",
target_id = "0"
},
[10013] = {
target_num = 10000,
name = "海军优秀服役勋章",
explain2 = "表现优秀的指挥官",
type = 0,
count_inherit = 0,
desc = "该勋章授予在服役期间表现优秀的指挥官",
next = 10014,
icon = "2023",
target_type = 1022,
start = 1,
hide = 0,
label = "l_201",
condition = "舰队出征累积胜利10000次 ",
rank = 3,
id = 10013,
explain1 = "授予在服役期间",
target_id = "0"
},
[10014] = {
target_num = 20000,
name = "海军优秀服役勋章",
explain2 = "表现优秀的指挥官",
type = 0,
count_inherit = 0,
desc = "该勋章授予在服役期间表现优秀的指挥官",
next = 10015,
icon = "2024",
target_type = 1022,
start = 1,
hide = 0,
label = "l_201",
condition = "舰队出征累积胜利20000次 ",
rank = 4,
id = 10014,
explain1 = "授予在服役期间",
target_id = "0"
},
[10015] = {
target_num = 1,
name = "海军优秀服役勋章",
explain2 = "表现优秀的指挥官",
type = 0,
count_inherit = 0,
desc = "该勋章授予在服役期间表现优秀的指挥官",
next = 0,
icon = "2025",
target_type = 9999,
start = 1,
hide = 3,
label = "l_201",
condition = "尚未开放,敬请期待",
rank = 5,
id = 10015,
explain1 = "授予在服役期间",
target_id = "0"
},
[10021] = {
target_num = 100,
name = "恪尽职守勋章",
explain2 = "恪守职责的指挥官",
type = 0,
count_inherit = 10022,
desc = "该勋章授予在服役期间出色履行职责的指挥官",
next = 10022,
icon = "2051",
target_type = 91,
start = 0,
hide = 0,
label = "l_202",
condition = "累积完成每日任务100次",
rank = 1,
id = 10021,
explain1 = "授予在服役期间",
target_id = "0"
},
[10022] = {
target_num = 300,
name = "恪尽职守勋章",
explain2 = "恪守职责的指挥官",
type = 0,
count_inherit = 10023,
desc = "该勋章授予在服役期间出色履行职责的指挥官",
next = 10023,
icon = "2052",
target_type = 91,
start = 1,
hide = 0,
label = "l_202",
condition = "累积完成每日任务300次",
rank = 2,
id = 10022,
explain1 = "授予在服役期间",
target_id = "0"
},
[10023] = {
target_num = 800,
name = "恪尽职守勋章",
explain2 = "恪守职责的指挥官",
type = 0,
count_inherit = 10024,
desc = "该勋章授予在服役期间出色履行职责的指挥官",
next = 10024,
icon = "2053",
target_type = 91,
start = 1,
hide = 0,
label = "l_202",
condition = "累积完成每日任务800次",
rank = 3,
id = 10023,
explain1 = "授予在服役期间",
target_id = "0"
},
[10024] = {
target_num = 1600,
name = "恪尽职守勋章",
explain2 = "恪守职责的指挥官",
type = 0,
count_inherit = 10025,
desc = "该勋章授予在服役期间出色履行职责的指挥官",
next = 10025,
icon = "2054",
target_type = 91,
start = 1,
hide = 0,
label = "l_202",
condition = "累积完成每日任务1600次",
rank = 4,
id = 10024,
explain1 = "授予在服役期间",
target_id = "0"
},
[10025] = {
target_num = 3200,
name = "恪尽职守勋章",
explain2 = "恪守职责的指挥官",
type = 0,
count_inherit = 0,
desc = "该勋章授予在服役期间出色履行职责的指挥官",
next = 0,
icon = "2055",
target_type = 91,
start = 1,
hide = 0,
label = "l_202",
condition = "累积完成每日任务3200次",
rank = 5,
id = 10025,
explain1 = "授予在服役期间",
target_id = "0"
},
[10031] = {
target_num = 1,
name = "海洋探索者勋章",
explain2 = "持之以恒的指挥官",
type = 0,
count_inherit = 10032,
desc = "探索不总伴随有收获。该勋章授予拥有坚定信念并持之以恒的指挥官",
next = 10032,
icon = "2031",
target_type = 141,
start = 0,
hide = 0,
label = "l_203",
condition = "从关卡中累积掉落获得1名超稀有角色",
rank = 1,
id = 10031,
explain1 = "授予在信念坚定",
target_id = "5"
},
[10032] = {
target_num = 3,
name = "海洋探索者勋章",
explain2 = "持之以恒的指挥官",
type = 0,
count_inherit = 10033,
desc = "探索不总伴随有收获。该勋章授予拥有坚定信念并持之以恒的指挥官",
next = 10033,
icon = "2032",
target_type = 141,
start = 1,
hide = 0,
label = "l_203",
condition = "从关卡中累积掉落获得3名超稀有角色",
rank = 2,
id = 10032,
explain1 = "授予在信念坚定",
target_id = "5"
},
[10033] = {
target_num = 10,
name = "海洋探索者勋章",
explain2 = "持之以恒的指挥官",
type = 0,
count_inherit = 10034,
desc = "探索不总伴随有收获。该勋章授予拥有坚定信念并持之以恒的指挥官",
next = 10034,
icon = "2033",
target_type = 141,
start = 1,
hide = 0,
label = "l_203",
condition = "从关卡中累积掉落获得10名超稀有角色",
rank = 3,
id = 10033,
explain1 = "授予在信念坚定",
target_id = "5"
},
[10034] = {
target_num = 20,
name = "海洋探索者勋章",
explain2 = "持之以恒的指挥官",
type = 0,
count_inherit = 0,
desc = "探索不总伴随有收获。该勋章授予拥有坚定信念并持之以恒的指挥官",
next = 10035,
icon = "2034",
target_type = 141,
start = 1,
hide = 0,
label = "l_203",
condition = "从关卡中累积掉落获得20名超稀有角色",
rank = 4,
id = 10034,
explain1 = "授予在信念坚定",
target_id = "5"
},
[10035] = {
target_num = 1,
name = "海洋探索者勋章",
explain2 = "持之以恒的指挥官",
type = 0,
count_inherit = 0,
desc = "探索不总伴随有收获。该勋章授予拥有坚定信念并持之以恒的指挥官",
next = 0,
icon = "2035",
target_type = 9999,
start = 1,
hide = 3,
label = "l_203",
condition = "尚未开放,敬请期待",
rank = 5,
id = 10035,
explain1 = "授予在信念坚定",
target_id = "0"
},
[10041] = {
target_num = 3000,
name = "杰出服务勋章",
explain2 = "贡献杰出的指挥官",
type = 0,
count_inherit = 0,
desc = "家,甜蜜的家。该勋章授予在港区建设中作出杰出贡献的指挥官",
next = 10042,
icon = "2041",
target_type = 133,
start = 0,
hide = 0,
label = "l_204",
condition = "累积消耗家具币达到3000枚",
rank = 1,
id = 10041,
explain1 = "授予为港区建设",
target_id = "0"
},
[10042] = {
target_num = 7000,
name = "杰出服务勋章",
explain2 = "贡献杰出的指挥官",
type = 0,
count_inherit = 0,
desc = "家,甜蜜的家。该勋章授予在港区建设中作出杰出贡献的指挥官",
next = 10043,
icon = "2042",
target_type = 133,
start = 1,
hide = 0,
label = "l_204",
condition = "累积消耗家具币达到7000枚",
rank = 2,
id = 10042,
explain1 = "授予为港区建设",
target_id = "0"
},
[10043] = {
target_num = 15000,
name = "杰出服务勋章",
explain2 = "贡献杰出的指挥官",
type = 0,
count_inherit = 0,
desc = "家,甜蜜的家。该勋章授予在港区建设中作出杰出贡献的指挥官",
next = 10044,
icon = "2043",
target_type = 133,
start = 1,
hide = 0,
label = "l_204",
condition = "累积消耗家具币达到15000枚",
rank = 3,
id = 10043,
explain1 = "授予为港区建设",
target_id = "0"
},
[10044] = {
target_num = 30000,
name = "杰出服务勋章",
explain2 = "贡献杰出的指挥官",
type = 0,
count_inherit = 0,
desc = "家,甜蜜的家。该勋章授予在港区建设中作出杰出贡献的指挥官",
next = 10045,
icon = "2044",
target_type = 133,
start = 1,
hide = 0,
label = "l_204",
condition = "累积消耗家具币达到30000枚",
rank = 4,
id = 10044,
explain1 = "授予为港区建设",
target_id = "0"
},
[10045] = {
target_num = 60000,
name = "杰出服务勋章",
explain2 = "贡献杰出的指挥官",
type = 0,
count_inherit = 0,
desc = "家,甜蜜的家。该勋章授予在港区建设中作出杰出贡献的指挥官",
next = 0,
icon = "2045",
target_type = 133,
start = 1,
hide = 0,
label = "l_204",
condition = "累积消耗家具币达到60000枚",
rank = 5,
id = 10045,
explain1 = "授予为港区建设",
target_id = "0"
},
[10051] = {
target_num = 10,
name = "玫瑰誓约纪念章",
explain2 = "如玫瑰般绽放于心间 ",
type = 0,
count_inherit = 0,
desc = "点滴中耕耘的羁绊,如玫瑰般绽放于心间。 ",
next = 10052,
icon = "2061",
target_type = 1019,
start = 0,
hide = 0,
label = "l_205",
condition = "舰队中好感度大于等于100的舰船达到10艘",
rank = 1,
id = 10051,
explain1 = "点滴中耕耘的羁绊",
target_id = "10000"
},
[10052] = {
target_num = 20,
name = "玫瑰誓约纪念章",
explain2 = "如玫瑰般绽放于心间 ",
type = 0,
count_inherit = 0,
desc = "点滴中耕耘的羁绊,如玫瑰般绽放于心间。 ",
next = 10053,
icon = "2062",
target_type = 1019,
start = 1,
hide = 0,
label = "l_205",
condition = "舰队中好感度大于等于100的舰船达到20艘",
rank = 2,
id = 10052,
explain1 = "点滴中耕耘的羁绊",
target_id = "10000"
},
[10053] = {
target_num = 50,
name = "玫瑰誓约纪念章",
explain2 = "如玫瑰般绽放于心间 ",
type = 0,
count_inherit = 0,
desc = "点滴中耕耘的羁绊,如玫瑰般绽放于心间。 ",
next = 10054,
icon = "2063",
target_type = 1019,
start = 1,
hide = 0,
label = "l_205",
condition = "舰队中好感度大于等于100的舰船达到50艘",
rank = 3,
id = 10053,
explain1 = "点滴中耕耘的羁绊",
target_id = "10000"
},
[10054] = {
target_num = 100,
name = "玫瑰誓约纪念章",
explain2 = "如玫瑰般绽放于心间 ",
type = 0,
count_inherit = 0,
desc = "点滴中耕耘的羁绊,如玫瑰般绽放于心间。 ",
next = 10055,
icon = "2064",
target_type = 1019,
start = 1,
hide = 0,
label = "l_205",
condition = "舰队中好感度大于等于100的舰船达到100艘",
rank = 4,
id = 10054,
explain1 = "点滴中耕耘的羁绊",
target_id = "10000"
},
[10055] = {
target_num = 200,
name = "玫瑰誓约纪念章",
explain2 = "如玫瑰般绽放于心间 ",
type = 0,
count_inherit = 0,
desc = "点滴中耕耘的羁绊,如玫瑰般绽放于心间。 ",
next = 0,
icon = "2065",
target_type = 1019,
start = 1,
hide = 0,
label = "l_205",
condition = "舰队中好感度大于等于100的舰船达到200艘",
rank = 5,
id = 10055,
explain1 = "点滴中耕耘的羁绊",
target_id = "10000"
},
[10061] = {
target_type = 160,
name = "白鹰海军荣誉勋章",
hide = 0,
type = 0,
start = 0,
count_inherit = 0,
condition = "白鹰阵营120级舰船达到12艘,白鹰阵营舰船总好感达成2000点,使用白鹰舰船在任意关卡中获得经验200万点",
desc = "以白鹰之名,授予在白鹰阵营军事行动中作出最杰出贡献的海军指挥官",
label = "l_101",
icon = "1011",
next = 10062,
rank = 1,
id = 10061,
explain1 = "以白鹰之名授予",
target_num = 3,
explain2 = "最杰出的指挥官",
target_id = {
100611,
100621,
100631
}
},
[10062] = {
target_type = 160,
name = "白鹰海军荣誉勋章",
hide = 0,
type = 0,
start = 1,
count_inherit = 0,
condition = "白鹰阵营120级舰船达到24艘,白鹰阵营舰船总好感达成4000点,使用白鹰舰船在任意关卡中获得经验200万点",
desc = "以白鹰之名,授予在白鹰阵营军事行动中作出最杰出贡献的海军指挥官",
label = "l_101",
icon = "1012",
next = 10063,
rank = 2,
id = 10062,
explain1 = "以白鹰之名授予",
target_num = 3,
explain2 = "最杰出的指挥官",
target_id = {
100612,
100622,
100632
}
},
[10063] = {
target_num = 1,
name = "白鹰海军荣誉勋章",
explain2 = "最杰出的指挥官",
type = 0,
count_inherit = 0,
desc = "以白鹰之名,授予在白鹰阵营军事行动中作出最杰出贡献的海军指挥官",
next = 10064,
icon = "1013",
target_type = 9999,
start = 1,
hide = 3,
label = "l_101",
condition = "尚未开放,敬请期待",
rank = 3,
id = 10063,
explain1 = "以白鹰之名授予",
target_id = "0"
},
[10064] = {
target_num = 1,
name = "白鹰海军荣誉勋章",
explain2 = "最杰出的指挥官",
type = 0,
count_inherit = 0,
desc = "以白鹰之名,授予在白鹰阵营军事行动中作出最杰出贡献的海军指挥官",
next = 10065,
icon = "1014",
target_type = 9999,
start = 1,
hide = 3,
label = "l_101",
condition = "尚未开放,敬请期待",
rank = 4,
id = 10064,
explain1 = "以白鹰之名授予",
target_id = "0"
},
[10065] = {
target_num = 1,
name = "白鹰海军荣誉勋章",
explain2 = "最杰出的指挥官",
type = 0,
count_inherit = 0,
desc = "以白鹰之名,授予在白鹰阵营军事行动中作出最杰出贡献的海军指挥官",
next = 0,
icon = "1015",
target_type = 9999,
start = 1,
hide = 3,
label = "l_101",
condition = "尚未开放,敬请期待",
rank = 5,
id = 10065,
explain1 = "以白鹰之名授予",
target_id = "0"
},
[10071] = {
target_type = 160,
name = "皇家海军十字勋章",
hide = 0,
type = 0,
start = 0,
count_inherit = 0,
condition = "皇家阵营120级舰船达到12艘,皇家阵营舰船总好感达成2000点,使用皇家舰船在任意关卡中获得经验200万点",
desc = "以皇家之名,将该荣耀赠予在面对敌人时表现最英勇、最无畏的指挥官",
label = "l_102",
icon = "1021",
next = 10072,
rank = 1,
id = 10071,
explain1 = "以皇家之名赠予",
target_num = 3,
explain2 = "最英勇的指挥官",
target_id = {
100711,
100721,
100731
}
},
[10072] = {
target_type = 160,
name = "皇家海军十字勋章",
hide = 0,
type = 0,
start = 1,
count_inherit = 0,
condition = "皇家阵营120级舰船达到24艘,皇家阵营舰船总好感达成4000点,使用皇家舰船在任意关卡中获得经验200万点",
desc = "以皇家之名,将该荣耀赠予在面对敌人时表现最英勇、最无畏的指挥官",
label = "l_102",
icon = "1022",
next = 10073,
rank = 2,
id = 10072,
explain1 = "以皇家之名赠予",
target_num = 3,
explain2 = "最英勇的指挥官",
target_id = {
100712,
100722,
100732
}
},
[10073] = {
target_num = 1,
name = "皇家海军十字勋章",
explain2 = "最英勇的指挥官",
type = 0,
count_inherit = 0,
desc = "以皇家之名,将该荣耀赠予在面对敌人时表现最英勇、最无畏的指挥官",
next = 10074,
icon = "1023",
target_type = 9999,
start = 1,
hide = 3,
label = "l_102",
condition = "尚未开放,敬请期待",
rank = 3,
id = 10073,
explain1 = "以皇家之名赠予",
target_id = "0"
},
[10074] = {
target_num = 1,
name = "皇家海军十字勋章",
explain2 = "最英勇的指挥官",
type = 0,
count_inherit = 0,
desc = "以皇家之名,将该荣耀赠予在面对敌人时表现最英勇、最无畏的指挥官",
next = 10075,
icon = "1024",
target_type = 9999,
start = 1,
hide = 3,
label = "l_102",
condition = "尚未开放,敬请期待",
rank = 4,
id = 10074,
explain1 = "以皇家之名赠予",
target_id = "0"
},
[10075] = {
target_num = 1,
name = "皇家海军十字勋章",
explain2 = "最英勇的指挥官",
type = 0,
count_inherit = 0,
desc = "以皇家之名,将该荣耀赠予在面对敌人时表现最英勇、最无畏的指挥官",
next = 0,
icon = "1025",
target_type = 9999,
start = 1,
hide = 3,
label = "l_102",
condition = "尚未开放,敬请期待",
rank = 5,
id = 10075,
explain1 = "以皇家之名赠予",
target_id = "0"
},
[10081] = {
target_type = 160,
name = "重樱勋位大绶章",
hide = 0,
type = 0,
start = 0,
count_inherit = 0,
condition = "重樱阵营120级舰船达到12艘,重樱阵营舰船总好感达成2000点,使用重樱舰船在任意关卡中获得经验200万点",
desc = "以重樱之名,授予为重樱海军建设作出最卓越功绩的指挥官阁下",
label = "l_103",
icon = "1031",
next = 10082,
rank = 1,
id = 10081,
explain1 = "以重樱之名授予",
target_num = 3,
explain2 = "最卓越的指挥官",
target_id = {
100811,
100821,
100831
}
},
[10082] = {
target_type = 160,
name = "重樱勋位大绶章",
hide = 0,
type = 0,
start = 1,
count_inherit = 0,
condition = "重樱阵营120级舰船达到24艘,重樱阵营舰船总好感达成4000点,使用重樱舰船在任意关卡中获得经验200万点",
desc = "以重樱之名,授予为重樱海军建设作出最卓越功绩的指挥官阁下",
label = "l_103",
icon = "1032",
next = 10083,
rank = 2,
id = 10082,
explain1 = "以重樱之名授予",
target_num = 3,
explain2 = "最卓越的指挥官",
target_id = {
100812,
100822,
100832
}
},
[10083] = {
target_num = 1,
name = "重樱勋位大绶章",
explain2 = "最卓越的指挥官",
type = 0,
count_inherit = 0,
desc = "以重樱之名,授予为重樱海军建设作出最卓越功绩的指挥官阁下",
next = 10084,
icon = "1033",
target_type = 9999,
start = 1,
hide = 3,
label = "l_103",
condition = "尚未开放,敬请期待",
rank = 3,
id = 10083,
explain1 = "以重樱之名授予",
target_id = "0"
},
[10084] = {
target_num = 1,
name = "重樱勋位大绶章",
explain2 = "最卓越的指挥官",
type = 0,
count_inherit = 0,
desc = "以重樱之名,授予为重樱海军建设作出最卓越功绩的指挥官阁下",
next = 10085,
icon = "1034",
target_type = 9999,
start = 1,
hide = 3,
label = "l_103",
condition = "尚未开放,敬请期待",
rank = 4,
id = 10084,
explain1 = "以重樱之名授予",
target_id = "0"
},
[10085] = {
target_num = 1,
name = "重樱勋位大绶章",
explain2 = "最卓越的指挥官",
type = 0,
count_inherit = 0,
desc = "以重樱之名,授予为重樱海军建设作出最卓越功绩的指挥官阁下",
next = 0,
icon = "1035",
target_type = 9999,
start = 1,
hide = 3,
label = "l_103",
condition = "尚未开放,敬请期待",
rank = 5,
id = 10085,
explain1 = "以重樱之名授予",
target_id = "0"
},
[10091] = {
target_type = 160,
name = "铁血海军功勋勋章",
hide = 0,
type = 0,
start = 0,
count_inherit = 0,
condition = "铁血阵营120级舰船达到12艘,铁血阵营舰船总好感达成2000点,使用铁血舰船在任意关卡中获得经验200万点",
desc = "以铁血之名,奖励在作战中展现了杰出的指挥能力并取得了突出功绩的指挥官",
label = "l_104",
icon = "1041",
next = 10092,
rank = 1,
id = 10091,
explain1 = "以铁血之名奖励",
target_num = 3,
explain2 = "最出色的指挥官",
target_id = {
100911,
100921,
100931
}
},
[10092] = {
target_type = 160,
name = "铁血海军功勋勋章",
hide = 0,
type = 0,
start = 1,
count_inherit = 0,
condition = "铁血阵营120级舰船达到24艘,铁血阵营舰船总好感达成4000点,使用铁血舰船在任意关卡中获得经验200万点",
desc = "以铁血之名,奖励在作战中展现了杰出的指挥能力并取得了突出功绩的指挥官",
label = "l_104",
icon = "1042",
next = 10093,
rank = 2,
id = 10092,
explain1 = "以铁血之名奖励",
target_num = 3,
explain2 = "最出色的指挥官",
target_id = {
100912,
100922,
100932
}
},
[10093] = {
target_num = 1,
name = "铁血海军功勋勋章",
explain2 = "最出色的指挥官",
type = 0,
count_inherit = 0,
desc = "以铁血之名,奖励在作战中展现了杰出的指挥能力并取得了突出功绩的指挥官",
next = 10094,
icon = "1043",
target_type = 9999,
start = 1,
hide = 3,
label = "l_104",
condition = "尚未开放,敬请期待",
rank = 3,
id = 10093,
explain1 = "以铁血之名奖励",
target_id = "0"
},
[10094] = {
target_num = 1,
name = "铁血海军功勋勋章",
explain2 = "最出色的指挥官",
type = 0,
count_inherit = 0,
desc = "以铁血之名,奖励在作战中展现了杰出的指挥能力并取得了突出功绩的指挥官",
next = 10095,
icon = "1044",
target_type = 9999,
start = 1,
hide = 3,
label = "l_104",
condition = "尚未开放,敬请期待",
rank = 4,
id = 10094,
explain1 = "以铁血之名奖励",
target_id = "0"
},
[10095] = {
target_num = 1,
name = "铁血海军功勋勋章",
explain2 = "最出色的指挥官",
type = 0,
count_inherit = 0,
desc = "以铁血之名,奖励在作战中展现了杰出的指挥能力并取得了突出功绩的指挥官",
next = 0,
icon = "1045",
target_type = 9999,
start = 1,
hide = 3,
label = "l_104",
condition = "尚未开放,敬请期待",
rank = 5,
id = 10095,
explain1 = "以铁血之名奖励",
target_id = "0"
},
[10101] = {
target_num = 100,
name = "海军服役成就奖章 ",
explain2 = "有所建树的指挥官",
type = 0,
count_inherit = 0,
desc = "奖励致力于舰队扩大建设并有所建树的指挥官 ",
next = 10102,
icon = "2011",
target_type = 1044,
start = 0,
hide = 0,
label = "l_206",
condition = "图鉴中解锁100种不同舰船",
rank = 1,
id = 10101,
explain1 = "奖励在舰队扩大中",
target_id = "0"
},
[10102] = {
target_num = 200,
name = "海军服役成就奖章 ",
explain2 = "有所建树的指挥官",
type = 0,
count_inherit = 0,
desc = "奖励致力于舰队扩大建设并有所建树的指挥官 ",
next = 10103,
icon = "2012",
target_type = 1044,
start = 1,
hide = 0,
label = "l_206",
condition = "图鉴中解锁200种不同舰船",
rank = 2,
id = 10102,
explain1 = "奖励在舰队扩大中",
target_id = "0"
},
[10103] = {
target_num = 300,
name = "海军服役成就奖章 ",
explain2 = "有所建树的指挥官",
type = 0,
count_inherit = 0,
desc = "奖励致力于舰队扩大建设并有所建树的指挥官 ",
next = 10104,
icon = "2013",
target_type = 1044,
start = 1,
hide = 0,
label = "l_206",
condition = "图鉴中解锁300种不同舰船",
rank = 3,
id = 10103,
explain1 = "奖励在舰队扩大中",
target_id = "0"
},
[10104] = {
target_num = 1,
name = "海军服役成就奖章 ",
explain2 = "有所建树的指挥官",
type = 0,
count_inherit = 0,
desc = "奖励致力于舰队扩大建设并有所建树的指挥官 ",
next = 10105,
icon = "2014",
target_type = 9999,
start = 1,
hide = 3,
label = "l_206",
condition = "尚未开放,敬请期待",
rank = 4,
id = 10104,
explain1 = "奖励在舰队扩大中",
target_id = "0"
},
[10105] = {
target_num = 1,
name = "海军服役成就奖章 ",
explain2 = "有所建树的指挥官",
type = 0,
count_inherit = 0,
desc = "奖励致力于舰队扩大建设并有所建树的指挥官 ",
next = 0,
icon = "2015",
target_type = 9999,
start = 1,
hide = 3,
label = "l_206",
condition = "尚未开放,敬请期待",
rank = 5,
id = 10105,
explain1 = "奖励在舰队扩大中",
target_id = "0"
},
[100611] = {
target_type = 1042,
name = "白鹰阵营子勋章1",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "白鹰阵营120级的舰船达到12艘",
desc = "",
label = "",
icon = "",
next = 0,
rank = 1,
id = 100611,
explain1 = "",
target_num = 12,
explain2 = "",
target_id = {
{
1,
120
}
}
},
[100612] = {
target_type = 1042,
name = "白鹰阵营子勋章1",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "白鹰阵营120级的舰船达到24艘",
desc = "",
label = "",
icon = "",
next = 0,
rank = 2,
id = 100612,
explain1 = "",
target_num = 24,
explain2 = "",
target_id = {
{
1,
120
}
}
},
[100613] = {
target_num = 1,
name = "白鹰阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100613,
explain1 = "",
target_id = "0"
},
[100614] = {
target_num = 1,
name = "白鹰阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100614,
explain1 = "",
target_id = "0"
},
[100615] = {
target_num = 1,
name = "白鹰阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100615,
explain1 = "",
target_id = "0"
},
[100621] = {
target_num = 200000,
name = "白鹰阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 1043,
start = 1,
hide = 1,
label = "",
condition = "白鹰阵营总好感达成2000",
rank = 1,
id = 100621,
explain1 = "",
target_id = "1"
},
[100622] = {
target_num = 400000,
name = "白鹰阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 1043,
start = 1,
hide = 1,
label = "",
condition = "白鹰阵营总好感达成4000",
rank = 2,
id = 100622,
explain1 = "",
target_id = "1"
},
[100623] = {
target_num = 1,
name = "白鹰阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100623,
explain1 = "",
target_id = "0"
},
[100624] = {
target_num = 1,
name = "白鹰阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100624,
explain1 = "",
target_id = "0"
},
[100625] = {
target_num = 1,
name = "白鹰阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100625,
explain1 = "",
target_id = "0"
},
[100631] = {
target_type = 1041,
name = "白鹰阵营子勋章3",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "白鹰舰船出征获得经验200万点",
desc = "",
label = "",
icon = "",
next = 0,
rank = 1,
id = 100631,
explain1 = "",
target_num = 2000000,
explain2 = "",
target_id = {
{
1,
0
}
}
},
[100632] = {
target_type = 1041,
name = "白鹰阵营子勋章3",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "白鹰舰船出征获得经验200万点",
desc = "",
label = "",
icon = "",
next = 0,
rank = 2,
id = 100632,
explain1 = "",
target_num = 2000000,
explain2 = "",
target_id = {
{
1,
0
}
}
},
[100633] = {
target_num = 1,
name = "白鹰阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100633,
explain1 = "",
target_id = "0"
},
[100634] = {
target_num = 1,
name = "白鹰阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100634,
explain1 = "",
target_id = "0"
},
[100635] = {
target_num = 1,
name = "白鹰阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100635,
explain1 = "",
target_id = "0"
},
[100711] = {
target_type = 1042,
name = "皇家阵营子勋章1",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "皇家阵营120级的舰船达到12艘",
desc = "",
label = "",
icon = "",
next = 0,
rank = 1,
id = 100711,
explain1 = "",
target_num = 12,
explain2 = "",
target_id = {
{
2,
120
}
}
},
[100712] = {
target_type = 1042,
name = "皇家阵营子勋章1",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "皇家阵营120级的舰船达到24艘",
desc = "",
label = "",
icon = "",
next = 0,
rank = 2,
id = 100712,
explain1 = "",
target_num = 24,
explain2 = "",
target_id = {
{
2,
120
}
}
},
[100713] = {
target_num = 1,
name = "皇家阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100713,
explain1 = "",
target_id = "0"
},
[100714] = {
target_num = 1,
name = "皇家阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100714,
explain1 = "",
target_id = "0"
},
[100715] = {
target_num = 1,
name = "皇家阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100715,
explain1 = "",
target_id = "0"
},
[100721] = {
target_num = 200000,
name = "皇家阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 1043,
start = 1,
hide = 1,
label = "",
condition = "皇家阵营总好感达成2000",
rank = 1,
id = 100721,
explain1 = "",
target_id = "2"
},
[100722] = {
target_num = 400000,
name = "皇家阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 1043,
start = 1,
hide = 1,
label = "",
condition = "皇家阵营总好感达成4000",
rank = 2,
id = 100722,
explain1 = "",
target_id = "2"
},
[100723] = {
target_num = 1,
name = "皇家阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100723,
explain1 = "",
target_id = "0"
},
[100724] = {
target_num = 1,
name = "皇家阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100724,
explain1 = "",
target_id = "0"
},
[100725] = {
target_num = 1,
name = "皇家阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100725,
explain1 = "",
target_id = "0"
},
[100731] = {
target_type = 1041,
name = "皇家阵营子勋章3",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "皇家舰船出征获得经验200万点",
desc = "",
label = "",
icon = "",
next = 0,
rank = 1,
id = 100731,
explain1 = "",
target_num = 2000000,
explain2 = "",
target_id = {
{
2,
0
}
}
},
[100732] = {
target_type = 1041,
name = "皇家阵营子勋章3",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "皇家舰船出征获得经验200万点",
desc = "",
label = "",
icon = "",
next = 0,
rank = 2,
id = 100732,
explain1 = "",
target_num = 2000000,
explain2 = "",
target_id = {
{
2,
0
}
}
},
[100733] = {
target_num = 1,
name = "皇家阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100733,
explain1 = "",
target_id = "0"
},
[100734] = {
target_num = 1,
name = "皇家阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100734,
explain1 = "",
target_id = "0"
},
[100735] = {
target_num = 1,
name = "皇家阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100735,
explain1 = "",
target_id = "0"
},
[100811] = {
target_type = 1042,
name = "重樱阵营子勋章1",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "重樱阵营120级的舰船达到12艘",
desc = "",
label = "",
icon = "",
next = 0,
rank = 1,
id = 100811,
explain1 = "",
target_num = 12,
explain2 = "",
target_id = {
{
3,
120
}
}
},
[100812] = {
target_type = 1042,
name = "重樱阵营子勋章1",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "重樱阵营120级的舰船达到24艘",
desc = "",
label = "",
icon = "",
next = 0,
rank = 2,
id = 100812,
explain1 = "",
target_num = 24,
explain2 = "",
target_id = {
{
3,
120
}
}
},
[100813] = {
target_num = 1,
name = "重樱阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100813,
explain1 = "",
target_id = "0"
},
[100814] = {
target_num = 1,
name = "重樱阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100814,
explain1 = "",
target_id = "0"
},
[100815] = {
target_num = 1,
name = "重樱阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100815,
explain1 = "",
target_id = "0"
},
[100821] = {
target_num = 200000,
name = "重樱阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 1043,
start = 1,
hide = 1,
label = "",
condition = "重樱阵营总好感达成2000",
rank = 1,
id = 100821,
explain1 = "",
target_id = "3"
},
[100822] = {
target_num = 400000,
name = "重樱阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 1043,
start = 1,
hide = 1,
label = "",
condition = "重樱阵营总好感达成4000",
rank = 2,
id = 100822,
explain1 = "",
target_id = "3"
},
[100823] = {
target_num = 1,
name = "重樱阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100823,
explain1 = "",
target_id = "0"
},
[100824] = {
target_num = 1,
name = "重樱阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100824,
explain1 = "",
target_id = "0"
},
[100825] = {
target_num = 1,
name = "重樱阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100825,
explain1 = "",
target_id = "0"
},
[100831] = {
target_type = 1041,
name = "重樱阵营子勋章3",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "重樱舰船出征获得经验200万点",
desc = "",
label = "",
icon = "",
next = 0,
rank = 1,
id = 100831,
explain1 = "",
target_num = 2000000,
explain2 = "",
target_id = {
{
3,
0
}
}
},
[100832] = {
target_type = 1041,
name = "重樱阵营子勋章3",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "重樱舰船出征获得经验200万点",
desc = "",
label = "",
icon = "",
next = 0,
rank = 2,
id = 100832,
explain1 = "",
target_num = 2000000,
explain2 = "",
target_id = {
{
3,
0
}
}
},
[100833] = {
target_num = 1,
name = "重樱阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100833,
explain1 = "",
target_id = "0"
},
[100834] = {
target_num = 1,
name = "重樱阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100834,
explain1 = "",
target_id = "0"
},
[100835] = {
target_num = 1,
name = "重樱阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100835,
explain1 = "",
target_id = "0"
},
[100911] = {
target_type = 1042,
name = "铁血阵营子勋章1",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "铁血阵营120级的舰船达到12艘",
desc = "",
label = "",
icon = "",
next = 0,
rank = 1,
id = 100911,
explain1 = "",
target_num = 12,
explain2 = "",
target_id = {
{
4,
120
}
}
},
[100912] = {
target_type = 1042,
name = "铁血阵营子勋章1",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "铁血阵营120级的舰船达到24艘",
desc = "",
label = "",
icon = "",
next = 0,
rank = 2,
id = 100912,
explain1 = "",
target_num = 24,
explain2 = "",
target_id = {
{
4,
120
}
}
},
[100913] = {
target_num = 1,
name = "铁血阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100913,
explain1 = "",
target_id = "0"
},
[100914] = {
target_num = 1,
name = "铁血阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100914,
explain1 = "",
target_id = "0"
},
[100915] = {
target_num = 1,
name = "铁血阵营子勋章1",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100915,
explain1 = "",
target_id = "0"
},
[100921] = {
target_num = 200000,
name = "铁血阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 1043,
start = 1,
hide = 1,
label = "",
condition = "铁血阵营总好感达成2000",
rank = 1,
id = 100921,
explain1 = "",
target_id = "4"
},
[100922] = {
target_num = 400000,
name = "铁血阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 1043,
start = 1,
hide = 1,
label = "",
condition = "铁血阵营总好感达成4000",
rank = 2,
id = 100922,
explain1 = "",
target_id = "4"
},
[100923] = {
target_num = 1,
name = "铁血阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100923,
explain1 = "",
target_id = "0"
},
[100924] = {
target_num = 1,
name = "铁血阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100924,
explain1 = "",
target_id = "0"
},
[100925] = {
target_num = 1,
name = "铁血阵营子勋章2",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100925,
explain1 = "",
target_id = "0"
},
[100931] = {
target_type = 1041,
name = "铁血阵营子勋章3",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "铁血舰船出征获得经验200万点",
desc = "",
label = "",
icon = "",
next = 0,
rank = 1,
id = 100931,
explain1 = "",
target_num = 2000000,
explain2 = "",
target_id = {
{
4,
0
}
}
},
[100932] = {
target_type = 1041,
name = "铁血阵营子勋章3",
hide = 1,
type = 0,
start = 1,
count_inherit = 0,
condition = "铁血舰船出征获得经验200万点",
desc = "",
label = "",
icon = "",
next = 0,
rank = 2,
id = 100932,
explain1 = "",
target_num = 2000000,
explain2 = "",
target_id = {
{
4,
0
}
}
},
[100933] = {
target_num = 1,
name = "铁血阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 3,
id = 100933,
explain1 = "",
target_id = "0"
},
[100934] = {
target_num = 1,
name = "铁血阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 4,
id = 100934,
explain1 = "",
target_id = "0"
},
[100935] = {
target_num = 1,
name = "铁血阵营子勋章3",
explain2 = "",
type = 0,
count_inherit = 0,
desc = "",
next = 0,
icon = "",
target_type = 9999,
start = 1,
hide = 3,
label = "",
condition = "尚未开放,敬请期待",
rank = 5,
id = 100935,
explain1 = "",
target_id = "0"
},
all = {
10011,
10012,
10013,
10014,
10015,
10021,
10022,
10023,
10024,
10025,
10031,
10032,
10033,
10034,
10035,
10041,
10042,
10043,
10044,
10045,
10051,
10052,
10053,
10054,
10055,
10061,
10062,
10063,
10064,
10065,
10071,
10072,
10073,
10074,
10075,
10081,
10082,
10083,
10084,
10085,
10091,
10092,
10093,
10094,
10095,
10101,
10102,
10103,
10104,
10105,
100611,
100612,
100613,
100614,
100615,
100621,
100622,
100623,
100624,
100625,
100631,
100632,
100633,
100634,
100635,
100711,
100712,
100713,
100714,
100715,
100721,
100722,
100723,
100724,
100725,
100731,
100732,
100733,
100734,
100735,
100811,
100812,
100813,
100814,
100815,
100821,
100822,
100823,
100824,
100825,
100831,
100832,
100833,
100834,
100835,
100911,
100912,
100913,
100914,
100915,
100921,
100922,
100923,
100924,
100925,
100931,
100932,
100933,
100934,
100935
}
}
return
|
-- include useful files
u_execScript("utils.lua")
u_execScript("common.lua")
u_execScript("commonpatterns.lua")
u_execScript("nextpatterns.lua")
u_execScript("evolutionpatterns.lua")
-- onInit is an hardcoded function that is called when the level is first loaded
function onInit()
l_setSpeedMult(5.0)
l_setSpeedInc(0.0)
l_setRotationSpeed(0.0)
l_setRotationSpeedMax(0.0)
l_setRotationSpeedInc(0.0)
l_setDelayMult(1.35)
l_setDelayInc(0.0)
l_setFastSpin(71.0)
l_setSides(32)
l_setSidesMin(32)
l_setSidesMax(32)
l_setIncTime(10)
l_setWallSkewLeft(15)
l_setPulseMin(75)
l_setPulseMax(75)
l_setPulseSpeed(0)
l_setPulseSpeedR(0)
l_setPulseDelayMax(6.8)
l_setBeatPulseMax(20)
l_setBeatPulseDelayMax(26.1)
l_setSwapEnabled(true)
end
-- onLoad is an hardcoded function that is called when the level is started/restarted
function onLoad()
e_messageAdd("remember, swap with spacebar!", 120)
end
-- onStep is an hardcoded function that is called when the level timeline is empty
-- onStep should contain your pattern spawning logic
function onStep()
hmcSimpleBarrageSNeigh(getRandomSide(), 3, 0)
t_wait(getPerfectDelayDM(THICKNESS) * 6)
end
-- onIncrement is an hardcoded function that is called when the level difficulty is incremented
function onIncrement()
end
-- onUnload is an hardcoded function that is called when the level is closed/restarted
function onUnload()
end
-- onUpdate is an hardcoded function that is called every frame
function onUpdate(mFrameTime)
end
|
return nn.Sequential():add(nn.Linear(4096,config.nClasses)):add(nn.LogSoftMax()) |
object_tangible_holiday_empire_day_empire_day_space_station = object_tangible_holiday_empire_day_shared_empire_day_space_station:new {
}
ObjectTemplates:addTemplate(object_tangible_holiday_empire_day_empire_day_space_station, "object/tangible/holiday/empire_day/empire_day_space_station.iff")
|
WorldItem = {}Apartment = {}
Bank = {}
Business = {}
Carwash = {}
ClothingStore = {}
Dmv = {}
DriveThrough = {}
DrugProcessor = {}
Fbi = {}
Fishing = {}
FlightSchool = {}
Ganglands = {}
Garage = {}
Hospital = {}
House = {}
MechanicShop = {}
MoneyTruck = {}
Prison = {}
Simeons = {}
Store = {}
TattooParlor = {}
Taxi = {}
VehicleMarket = {}
VehicleRental = {} |
local function Cake()
a = "EAT THIS LAST"
print(a)
end
Cake() |
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BceLeaveHall_pb', package.seeall)
local BCELEAVEHALL = protobuf.Descriptor();
BCELEAVEHALL.name = "BceLeaveHall"
BCELEAVEHALL.full_name = ".com.xinqihd.sns.gameserver.proto.BceLeaveHall"
BCELEAVEHALL.nested_types = {}
BCELEAVEHALL.enum_types = {}
BCELEAVEHALL.fields = {}
BCELEAVEHALL.is_extendable = false
BCELEAVEHALL.extensions = {}
BceLeaveHall = protobuf.Message(BCELEAVEHALL)
_G.BCELEAVEHALL_PB_BCELEAVEHALL = BCELEAVEHALL
|
local ga = gajosframework
ga.MainMenu = classExtends(Controller, function(user)
self.user = user
self.model = ga.MainMenuModel.new(self, user)
self.view = ga.MainMenuView.new(user)
function self:setBackground(path, darkness)
self.model:setBackground(path)
if darkness then
self.model:setBackgroundColor(255 * (1 - darkness), 255 * (1 - darkness), 255 * (1 - darkness))
end
end
function self:show()
self.view:init()
self.view:showBackground(self.model.background)
self.view:drawNavItems(self.model.nav_items)
self:loadNavItem()
end
function self:hide()
self.view:hideBackground(self.model.background)
self.view:remove()
end
function self:showTutorial()
self.view:showTutorial()
end
function self:hideTutorial()
self.view:hideTutorial()
end
function self:setNavItems(items)
self.model:setNavItems(items)
end
function self:setPages(pages)
self.model:setPages(pages)
end
function self:loadNavItem()
local item = self.model.nav_items[self.view.current_nav_item]
self.view:loadNavItem(self.view.current_nav_item, item.name, item.onShow, true)
return true
end
end)
ga.GUI_Window.AddStyle('ga_mainmenu', {
width = 850,
height = 400,
})
ga.GUI_Button.AddStyle('ga_arrow', {
path = ga.DIR.gfx .. 'hud_arrow.bmp',
width = 32,
height = 32,
})
ga.GUI_Button.AddStyle('ga_slot', {
width = 32,
height = 32,
})
ga.GUI_Button.AddStyle('ga_bigslot', {
width = 50,
height = 50,
})
ga.GUI_Button.AddStyle('ga_nav_item', {
width = 80,
height = 25,
})
|
-----------------------------------
-- Area: Chateau d'Oraguille
-- NPC: Faurie
-- Chat Text and Zone Exit Menu
-----------------------------------
require("scripts/globals/settings");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:startEvent(506);
end;
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if (option == 0) then
player:setPos(0, 0, 100, 64, 231);
end;
end;
|
workspace "gperftools_test"
configurations { "Debug", "Release" }
platforms { "x64" }
targetdir "../bin/%{cfg.buildcfg}"
language "C++"
flags {
"C++11",
"StaticRuntime",
}
includedirs {
"../deps/include/",
}
libdirs {
"../deps/lib_win",
"../deps/lib_linux",
}
filter "configurations:Debug"
libdirs{
"../bin/Debug",
}
filter "configurations:Release"
libdirs{
"../bin/Release",
}
filter { }
filter "configurations:Debug"
defines { "_DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
filter { }
defines { "ENABLE_PROFILER" }
if os.is("windows") then
end
if os.is("linux") then
buildoptions { "-fPIC -static-libgcc -static-libstdc++" }
links{
"profiler",
"tcmalloc",
"pthread",
}
end
project "test"
kind "ConsoleApp"
targetname "test"
includedirs {
"../src",
}
files {
"../src/common/**",
"../src/test/**",
}
project "PProfGo"
kind "SharedLib"
targetname "PProfGo"
files {
"../src/common/**",
"../src/go/**",
}
|
local value = {
x = 0,
y = 0,
minvalue = 0,
maxvalue = 100,
value = 10,
w = 60,
h = 60,
background = { 255, 255, 255 },
buttons = { 200, 200, 200 },
foreground = { 21, 21, 21 },
valtimer = timer.new(0.3),
incriment = 1,
substate = "Main",
visible = true
}
value.__index = value
function value:new( data, parent )
local data = data or {}
local self = setmetatable( data, value )
self.font = data.font or ui.font( 16 )
self.parent = parent or error("Value object needs a parent!")
self.state = data.state or parent.state
table.insert( self.parent.children, self )
return self
end
function value:update( dt )
if ui.checkState( self ) then
local ax, ay = ui.getAbsPos( self )
if self.align == "center" then
ax = ui.getAbsX(self) + self.parent.w/2 - self.w/2
end
if love.mouse.isDown(1) then
if self.valtimer:update(dt) then
local mx, my = love.mouse.getPosition()
if mx >= ax and mx <= ax + self.w and my >= ay and my <= ay + self.h/3 then
--increase value
self.value = math.min(self.value + self.incriment, self.maxvalue)
elseif mx >= ax and mx <= ax + self.w and my >= ay + self.h*.66 and my <= ay + self.h then
--decrease value
self.value = math.max(self.minvalue, self.value - self.incriment)
end
self.valtimer:restart()
end
else
self.valtimer:stop()
end
end
end
function value:draw()
if ui.checkState( self ) then
local ax, ay = ui.getAbsPos( self )
if self.align == "center" then
ax = ui.getAbsX(self) + self.parent.w/2 - self.w/2
end
love.graphics.setColor( self.background )
love.graphics.rectangle("fill", ax, ay, self.w, self.h)
love.graphics.setColor( self.buttons )
love.graphics.rectangle("fill", ax, ay, self.w, self.h/3)
love.graphics.rectangle("fill", ax, ay+self.h*0.66, self.h/3)
love.graphics.setColor( self.foreground )
love.graphics.printf("v", ax, ay+self.h*0.66, self.w, "center")
love.graphics.printf("^", ax, ay, self.w, "center")
love.graphics.printf(tostring(self.value), ax, ay+self.h/3, self.w, "center")
love.graphics.setColor( 255, 255, 255 )
end
end
return value |
ATJ.lcm = {}
function ATJ.lcm.wait_fifo_empty()
while (bit32.band(HW.YUV2RGB.CTL.read(), 0x04) == 0) do
end
end
function ATJ.lcm.rs_command()
ATJ.lcm.wait_fifo_empty()
HW.YUV2RGB.CTL.write(0x802ae)
end
function ATJ.lcm.rs_data()
ATJ.lcm.wait_fifo_empty()
HW.YUV2RGB.CTL.write(0x902ae)
end
function ATJ.lcm.fb_data()
ATJ.lcm.rs_command()
HW.YUV2RGB.FIFODATA.write(0x22)
HW.YUV2RGB.CTL.write(0xa02ae)
end
function ATJ.lcm.init()
HW.CMU.DEVCLKEN.write(bit32.bor(HW.CMU.DEVCLKEN.read(), 0x102))
ATJ.gpio.muxsel("LCM")
hwstub.udelay(1)
ATJ.lcm.rs_command()
HW.YUV2RGB.CLKCTL.write(0x102)
end
|
local swap_next, swap_prev = (function()
local swap_objects = {
p = "@parameter.inner",
f = "@function.outer",
e = "@element",
}
local n, p = {}, {}
for key, obj in pairs(swap_objects) do
n[string.format("<M-l>%s", key)] = obj
p[string.format("<M-h>%s", key)] = obj
end
return n, p
end)()
require("nvim-treesitter.configs").setup({
ensure_installed = { "bash", "dockerfile", "go", "lua", "yaml" },
sync_install = false,
highlight = { enable = true },
indent = { enable = true, disable = { "yaml" } },
autopairs = { enable = true },
context_commentstring = { enable = true, enable_autocmd = false },
textobjects = {
select = {
enable = true,
lookahead = true,
keymaps = {
["af"] = "@function.outer",
["if"] = "@function.inner",
["ac"] = "@conditional.outer",
["ic"] = "@conditional.inner",
["aa"] = "@parameter.outer",
["ia"] = "@parameter.inner",
["av"] = "@variable.outer",
["iv"] = "@variable.inner",
},
},
move = {
enable = true,
set_jumps = true,
goto_next_start = {
["]p"] = "@parameter.inner",
["]m"] = "@function.outer",
["]]"] = "@class.outer",
},
goto_next_end = {
["]M"] = "@function.outer",
["]["] = "@class.outer",
},
goto_previous_start = {
["[p"] = "@parameter.inner",
["[m"] = "@function.outer",
["[["] = "@class.outer",
},
goto_previous_end = {
["[M"] = "@function.outer",
["[]"] = "@class.outer",
},
},
swap = {
enable = true,
swap_next = swap_next,
swap_previous = swap_prev,
},
},
})
|
-- Combat settings
-- NOTE: valid values for worldType are: "pvp", "no-pvp" and "pvp-enforced"
worldType = "pvp"
hotkeyAimbotEnabled = true
protectionLevel = 35
pzLocked = 50 * 1000
removeChargesFromRunes = true
removeChargesFromPotions = true
removeWeaponAmmunition = true
removeWeaponCharges = true
timeToDecreaseFrags = 24 * 60 * 60 * 1000
whiteSkullTime = 15 * 60 * 1000
stairJumpExhaustion = 2 * 1000
experienceByKillingPlayers = false
expFromPlayersLevelRange = 75
dayKillsToRedSkull = 3
weekKillsToRedSkull = 5
monthKillsToRedSkull = 10
redSkullDuration = 30
blackSkullDuration = 45
orangeSkullDuration = 7
-- Connection Config
-- NOTE: maxPlayers set to 0 means no limit
ip = "127.0.0.1"
bindOnlyGlobalAddress = false
loginProtocolPort = 7171
gameProtocolPort = 7172
statusProtocolPort = 7171
maxPlayers = 0
motd = "Welcome to The Wallera Global!"
onePlayerOnlinePerAccount = true
allowClones = false
serverName = "Wallera Global"
statusTimeout = 5 * 1000
replaceKickOnLogin = true
maxPacketsPerSecond = 25
-- Version Manual
clientVersionMin = 1100
clientVersionMax = 1157
clientVersionStr = "11.57"
-- Depot Limit
freeDepotLimit = 2000
premiumDepotLimit = 10000
depotBoxes = 17
-- GameStore
gamestoreByModules = true
-- Casting System
enableLiveCasting = true
liveCastPort = 7173
-- Expert Pvp Config
expertPvp = false
-- Deaths
-- NOTE: Leave deathLosePercent as -1 if you want to use the default
-- death penalty formula. For the old formula, set it to 10. For
-- no skill/experience loss, set it to 0.
deathLosePercent = -1
-- Houses
-- NOTE: set housePriceEachSQM to -1 to disable the ingame buy house functionality
housePriceEachSQM = 1000
houseRentPeriod = "daily"
-- Item Usage
timeBetweenActions = 200
timeBetweenExActions = 1000
-- Map
-- NOTE: set mapName WITHOUT .otbm at the end
mapName = "realmap"
mapAuthor = "Cipsoft"
-- Market
marketOfferDuration = 30 * 24 * 60 * 60
premiumToCreateMarketOffer = true
checkExpiredMarketOffersEachMinutes = 60
maxMarketOffersAtATimePerPlayer = 100
-- MySQL
mysqlHost = "194.5.156.1"
mysqlUser = "u410324573_otserv"
mysqlPass = "otserver"
mysqlDatabase = "u410324573_mortera"
mysqlPort = 3306
mysqlSock = ""
passwordType = "sha1"
-- Misc.
allowChangeOutfit = true
freePremium = true
kickIdlePlayerAfterMinutes = 15
idleWarningTime = 10 * 60 * 1000
idleKickTime = 15 * 60 * 1000
maxMessageBuffer = 4
emoteSpells = false
classicEquipmentSlots = false
allowWalkthrough = true
coinPacketSize = 1
coinImagesURL = "http://localhost/images/store/"
classicAttackSpeed = false
-- Rates
-- NOTE: rateExp is not used if you have enabled stages in data/XML/stages.xml
rateExp = 1
rateSkill = 50
rateLoot = 3
rateMagic = 25
rateSpawn = 1
-- Monster rates
rateMonsterHealth = 1.0
rateMonsterAttack = 1.0
rateMonsterDefense = 1.0
-- Monsters
deSpawnRange = 2
deSpawnRadius = 50
-- Stamina
staminaSystem = true
-- Scripts
warnUnsafeScripts = true
convertUnsafeScripts = true
-- Startup
-- NOTE: defaultPriority only works on Windows and sets process
-- priority, valid values are: "normal", "above-normal", "high"
defaultPriority = "high"
startupDatabaseOptimization = true
-- Status server information
ownerName = "ADM Kabo"
ownerEmail = "kabofloww@gmail.com"
url = "http://www.facebook.com/kaboflow18"
location = "Mexico"
|
local parser = require("moocscript.parser")
local compile = require("moocscript.compile")
describe("test success 1 #table", function()
local mnstr=[[
b = 9 + ...
a = {
--- 111
3,
4 = 3, --- 222
fn(){} = 4,
{fn(){}} = fn(){}, --[=[ 90123d ]=]
false = tonumber("10"),
class = 12,
c = 1 + ...,
=b,
d = b,
[b] = b
-- 999
}
a [ "d"] = 3
return a
]]
local ret, ast = parser.parse(mnstr)
it("should get ast", function()
assert.is_true(ret)
assert.is_true(type(ast) == "table")
end)
local ret, content = compile.compile({}, ast)
it("should get compiled lua", function()
assert.is_true(ret)
assert.is_true(type(content) == "string")
end)
local f = load(content, "test", "t")
it("should get function", function()
assert(type(f) == "function")
local t = f(10)
assert.is_equal(t.c, 11)
assert.is_equal(t.b, 19)
assert.is_equal(t.d, 3)
end)
end)
describe("test success 2 #table", function()
local mnstr=[[
b = 9 + ...
a = {
--- 111
3,
4 = 3, --- 222
fn(){} = 4,
{fn(){}} = fn(){}, --[=[ 90123d ]=]
false = tonumber("10"),
class = 12,
c = 1 + ...,
=b,
d = b,
[b] = b
-- 999
}
a [ "d"] = 3
return a
]]
local ret, ast = parser.parse(mnstr)
it("should get ast", function()
assert.is_true(ret)
assert.is_true(type(ast) == "table")
end)
local ret, content = compile.compile({}, ast)
it("should get compiled lua", function()
assert.is_true(ret)
assert.is_true(type(content) == "string")
end)
local f = load(content, "test", "t")
it("should get function", function()
assert(type(f) == "function")
local t = f(10)
assert.is_equal(t.c, 11)
assert.is_equal(t.b, 19)
assert.is_equal(t.d, 3)
end)
end)
describe("test comment #table", function()
local mnstr=[[
b = 9 + ...
a = {
--- 111
--- 222
3,
4 = 3, --- 222
--[=[ 1231232 ]=]
--[=[ 212312 ]=]
fn(){} = 4,
{fn(){}} = fn(){}, --[=[ 90123d ]=]
false = tonumber("10"),
class = 12,
c = 1 + ...,
=b,
d = b,
[b] = b
-- 999
-- 33
--[=[ 222 ]=]
}
c = {
-- 111
-- 222
--[=[ 12312 ]=]
}
a [ "d"] = 3
return a
]]
local ret, ast = parser.parse(mnstr)
it("should get ast", function()
assert.is_true(ret)
assert.is_true(type(ast) == "table")
end)
local ret, content = compile.compile({}, ast)
it("should get compiled lua", function()
assert.is_true(ret)
assert.is_true(type(content) == "string")
end)
local f = load(content, "test", "t")
it("should get function", function()
assert(type(f) == "function")
local t = f(10)
assert.is_equal(t.c, 11)
assert.is_equal(t.b, 19)
assert.is_equal(t.d, 3)
end)
end)
describe("test failed #table", function()
local mnstr=[[
return { a = a }
]]
local ret, ast = parser.parse(mnstr)
it("should get ast", function()
assert.is_true(ret)
end)
it("has error", function()
local ret, content = compile.compile({}, ast)
assert.is_false(ret)
assert.is_equal(content, "_:1: return { a = a } <undefined variable 'a'>")
end)
end) |
--[[
Sklepy z odzieza
@author Jakub 'XJMLN' Starzak <jack@pszmta.pl
@package PSZMTA.gracz-sklep_odziezowy
@copyright Jakub 'XJMLN' Starzak <jack@pszmta.pl>
Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie.
]]--
local s_active = nil
local i = 1
local sw, sh = guiGetScreenSize()
local tWidth = dxGetTextWidth("Wciśnij strzałkę w lewo lub prawo aby poruszać się po menu. Wciśńij klawisz ENTER aby zakończyć.")
local type1_skinlist = {
-- id, nazwa
{11,"Człowiek z maską"},
{14,"Joker"},
{18,"Człowiek 'Steve' "},
{20,"FBI"},
{24,"a chuj wie"},
{26,"nie wiem co tu wpisac lol"},
{32,"Lamar Davis"},
{33,"Brooke Scott"},
{40,"Kobieta"},
{51,"nie wiem co tu wpisac lol"},
{52,"nie wiem co tu wpisac lol"},
{53,"nie wiem co tu wpisac lol"},
{54,"nie wiem co tu wpisac lol"},
{59,"nie wiem co tu wpisac lol"},
{98,"nie wiem co tu wpisac lol"},
{100,"nie wiem co tu wpisac lol"},
{104,"nie wiem co tu wpisac lol"},
{105,"nie wiem co tu wpisac lol"},
{108,"nie wiem co tu wpisac lol"},
{123,"nie wiem co tu wpisac lol"},
{246,"nie wiem co tu wpisac lol"},
{254,"nie wiem co tu wpisac lol"},
{285,"nie wiem co tu wpisac lol"},
{288,"nie wiem co tu wpisac lol"},
}
local function renderMainMenu()
if (not s_active.active) then return end
dxDrawImage(0,sh-256, 256/2, 256/2, "i/a_left.png")
dxDrawImage(sw-256/2,sh-256, 256/2, 256/2, "i/a_right.png")
if getTickCount()-s_active.ts<15000 then
local alpha = 1
if (getTickCount()-s_active.ts>(5000-1000)) then
alpha = interpolateBetween(0,0,0,255,0,0,(getTickCount()-s_active.ts/500),"InQuad")
end
dxDrawText(s_active.descr,sw/2 - dxGetTextWidth(s_active.descr)/2,sh/2 - 50,250,250,tocolor(255,255,255,255*alpha))
end
dxDrawText("Wciśnij strzałkę w lewo lub prawo aby poruszać się po menu. Wciśnij klawisz ENTER aby zakończyć.",(sw/2 - tWidth/2), sh - 50,(sw/2 - tWidth/2), 50)
end
local function goRightSkin()
if i>=#type1_skinlist then return end
i=i+1
s_active = {active = true, descr = type1_skinlist[i][2], ts = getTickCount()}
setElementModel(getLocalPlayer(),type1_skinlist[i][1])
end
local function goLeftSkin()
if i == 0 or i == 1 then i = 1 return end
i=i-1
s_active = {active = true, descr = type1_skinlist[i][2], ts = getTickCount()}
setElementModel(getLocalPlayer(),type1_skinlist[i][1])
end
function onPlayerEndShopping(plr,sid)
if (not plr) then return end
unbindKey("arrow_r","down",goRightSkin)
unbindKey("arrow_l","down",goLeftSkin)
unbindKey("enter","down",acceptOwnedSkin)
removeEventHandler("onClientRender",root, renderMainMenu)
s_active = nil
i = 1
triggerServerEvent("onPlayerRequestEnd",localPlayer, plr, tonumber(sid))
end
local function acceptOwnedSkin()
if s_active and s_active.active then
local owned_skin = type1_skinlist[i][1]
local owned_skin_desc = type1_skinlist[i][2]
outputChatBox("Zmieniono wygląd postaci na "..owned_skin_desc..".",255,0,0)
setElementModel(getLocalPlayer(),owned_skin)
local c= getElementData(getLocalPlayer(),"character")
if (not c or not c.skin) then return end
c.skin = owned_skin
setElementData(getLocalPlayer(),"character",c)
fadeCamera(false)
setCameraTarget(getLocalPlayer())
setElementFrozen(getLocalPlayer(),false)
showChat(true)
showPlayerHudComponent("all",true)
toggleAllControls(true)
fadeCamera(true)
onPlayerEndShopping(getLocalPlayer(),owned_skin)
end
end
local function createChangeroomPerPlayer(plr)
if (not plr == getLocalPlayer()) then return end
fadeCamera(false)
setElementFrozen(plr,true)
showChat(false)
showPlayerHudComponent("all",false)
setElementPosition(plr,198.8,-127.64,1003.52)
setElementRotation(plr,0,0,180)
setElementDimension(plr,getElementData(plr,"id")*251)
setCameraMatrix(198.94,-130.48,1005.52,198.93,-127.29,1004,0,0)
toggleAllControls(false,true,true)
setElementModel(plr,11)
end
addEvent("onPlayerHitShopMarker", true)
addEventHandler("onPlayerHitShopMarker", getRootElement(), function(plr,type)
if (not plr == getLocalPlayer()) then return end
local c = getElementData(plr,"character")
if (not c or not c.skin) then return end
createChangeroomPerPlayer(plr)
setTimer(function()
bindKey("arrow_r","down",goRightSkin)
bindKey("arrow_l","down",goLeftSkin)
bindKey("enter","down",acceptOwnedSkin)
local sd = type1_skinlist[i][2]
s_active = {active = true, descr = sd, ts = getTickCount()}
addEventHandler("onClientRender", root, renderMainMenu)
fadeCamera(true)
end,1500,1)
end) |
object_tangible_component_clothing_trim_outbreak_prison_guard_jacket = object_tangible_component_clothing_shared_trim_outbreak_prison_guard_jacket:new {
}
ObjectTemplates:addTemplate(object_tangible_component_clothing_trim_outbreak_prison_guard_jacket, "object/tangible/component/clothing/trim_outbreak_prison_guard_jacket.iff")
|
setfenv(1, require "sysapi-ns")
ffi.cdef [[
typedef void VOID;
typedef signed char CCHAR, CHAR, INT8;
typedef unsigned char BYTE, UCHAR, UINT8, BOOLEAN;
typedef signed short SHORT, INT16;
typedef unsigned short WORD, USHORT, UINT16;
typedef signed int INT, INT32, BOOL;
typedef unsigned int UINT, UINT32;
typedef signed long LONG;
typedef unsigned long ULONG, DWORD;
typedef int64_t INT64;
typedef uint64_t UINT64;
typedef signed long long LONGLONG;
typedef unsigned long long ULONGLONG;
typedef intptr_t LONG_PTR;
typedef uintptr_t ULONG_PTR;
typedef size_t SIZE_T, *PSIZE_T;
typedef int errno_t;
typedef long HRESULT;
typedef const char *LPCSTR, *LPCCH, *PCCH;;
typedef CHAR *NPSTR, *LPSTR, *PSTR;
typedef PSTR *PZPSTR;
typedef const PSTR *PCZPSTR;
typedef const CHAR *LPCSTR, *PCSTR;
typedef PCSTR *PZPCSTR;
typedef const PCSTR *PCZPCSTR;
typedef wchar_t WCHAR, *PWCHAR, *PWCH, *PWSTR, *LPWSTR;
typedef WCHAR *PWCHAR, *LPWCH, *PWCH, *LMSTR;
typedef const wchar_t *LPCWSTR, *PCWSTR, *LPCTSTR;
typedef const WCHAR *LPCWCH, *PCWCH;
typedef VOID *PVOID, *LPVOID;
typedef const VOID* LPCVOID;
typedef CHAR *PCHAR, *LPSTR;
typedef void * __ptr64 PVOID64;
typedef UCHAR *PUCHAR;
typedef SHORT *PSHORT;
typedef USHORT *PUSHORT;
typedef INT *PINT;
typedef DWORD *PDWORD, *LPDWORD;
typedef UINT *PUINT;
typedef LONG *PLONG;
typedef ULONG *PULONG;
typedef LONGLONG *PLONGLONG;
typedef ULONGLONG *PULONGLONG;
typedef BOOL *PBOOL, *LPBOOL;
typedef BYTE *PBYTE, *LPBYTE;
typedef PVOID HANDLE, *PHANDLE, *LPHANDLE;
typedef PVOID HINSTANCE;
typedef HINSTANCE HMODULE;
typedef PVOID LPUNKNOWN;
typedef DWORD (*PTHREAD_START_ROUTINE)(
LPVOID lpThreadParameter
);
typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE;
typedef LONG KPRIORITY;
typedef struct _SECURITY_ATTRIBUTES {
DWORD nLength;
LPVOID lpSecurityDescriptor;
BOOL bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
typedef union _LARGE_INTEGER {
struct {
ULONG LowPart;
LONG HighPart;
} DUMMYSTRUCTNAME;
struct {
ULONG LowPart;
LONG HighPart;
} u;
LONGLONG QuadPart;
} LARGE_INTEGER, *PLARGE_INTEGER;
typedef union _ULARGE_INTEGER {
struct {
DWORD LowPart;
DWORD HighPart;
} DUMMYSTRUCTNAME;
struct {
DWORD LowPart;
DWORD HighPart;
} u;
ULONGLONG QuadPart;
} ULARGE_INTEGER;
typedef struct _STRING {
USHORT Length;
USHORT MaximumLength;
PCHAR Buffer;
} STRING, *PSTRING, ANSI_STRING, *PANSI_STRING, OEM_STRING, *POEM_STRING;
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWCH Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
typedef struct _GUID {
unsigned long Data1;
unsigned short Data2;
unsigned short Data3;
unsigned char Data4[8];
} GUID;
typedef PVOID PSID;
typedef struct _SID_AND_ATTRIBUTES {
PSID Sid;
DWORD Attributes;
} SID_AND_ATTRIBUTES, * PSID_AND_ATTRIBUTES;
]]
|
package.path="lualib/?.lua;"
local lproto = require "lproto"
local protDict = {}
local function registprot(p)
table.insert(protDict,p)
return #protDict
end
--[[
-- define protocol dict
--]]
local dp = {
user = "hanxi",
money = 100,
list = { -- it mean's array. the element is the table content.
a = 1,
b = "hao",
},
}
local test_prot_Id = registprot(dp)
prot = lproto.initprot(protDict)
-- 序列化
function serialize(obj,n)
if n==nil then n=1 end
local lua = ""
local t = type(obj)
if t == "number" then
lua = lua .. obj
elseif t == "boolean" then
lua = lua .. tostring(obj)
elseif t == "string" then
lua = lua .. string.format("%q", obj)
elseif t == "table" then
lua = lua .. "{\n"
for k, v in pairs(obj) do
lua = lua .. string.rep("\t",n) .. "[" .. serialize(k) .. "]=" .. serialize(v,n+1) .. ",\n"
end
local metatable = getmetatable(obj)
if metatable ~= nil and type(metatable.__index) == "table" then
for k, v in pairs(metatable.__index) do
lua = lua .. string.rep("\t",n) .."[" .. serialize(k) .. "]=" .. serialize(v,n+1) .. ",\n"
end
end
lua = lua .. string.rep("\t",n-1) .. "}"
elseif t == "nil" then
return nil
else
error("can not serialize a " .. t .. " type.")
end
return lua
end
--[[
-- the protocol will bu pack
--]]
local p = {
protId = 1,
user = "hanxi",
money = 0xffff0fffff,
list = {{a=1,b="h"},{a=2,b="s"}},
}
local fd = 1
print("pack protId=",test_prot_Id)
local sz,str = prot:pack(fd,test_prot_Id,p)
print("return : ",sz,str)
local ret,fd,protId,pp = prot:unpack(str,sz)
print("upacke protId=",protId)
print("return : ",ret,fd,protId,pp)
print(serialize(pp))
|
local status_ok, bufferline = pcall(require, 'bufferline')
if not status_ok then
return
end
bufferline.setup({
options = {
mode = 'buffers', -- set to 'tabs' to only show tabpages instead
close_command = 'bdelete! %d', -- can be a string | function, see 'Mouse actions'
right_mouse_command = 'bdelete! %d', -- can be a string | function, see 'Mouse actions'
left_mouse_command = 'buffer %d', -- can be a string | function, see 'Mouse actions'
middle_mouse_command = nil, -- can be a string | function, see 'Mouse actions'
-- NOTE: this plugin is designed with this icon in mind,
-- and so changing this is NOT recommended, this is intended
-- as an escape hatch for people who cannot bear it for whatever reason
indicator_icon = '▎',
buffer_close_icon = '',
modified_icon = '●',
close_icon = '',
left_trunc_marker = '',
right_trunc_marker = '',
--- name_formatter can be used to change the buffer's label in the bufferline.
--- Please note some names can/will break the
--- bufferline so use this at your discretion knowing that it has
--- some limitations that will *NOT* be fixed.
name_formatter = function(buf) -- buf contains a 'name', 'path' and 'bufnr'
-- remove extension from markdown files for example
if buf.name:match('%.md') then
return vim.fn.fnamemodify(buf.name, ':t:r')
end
end,
max_name_length = 18,
max_prefix_length = 15, -- prefix used when a buffer is de-duplicated
tab_size = 18,
diagnostics = 'nvim_lsp',
diagnostics_update_in_insert = false,
diagnostics_indicator = function(count, level)
local icon = level:match("error") and " " or " "
return " " .. icon .. count
end,
-- NOTE: this will be called a lot so don't do any heavy processing here
offsets = { { filetype = 'NvimTree', text = '', padding = 1 } },
color_icons = true, -- whether or not to add the filetype icon highlights
show_buffer_icons = true, -- disable filetype icons for buffers
show_buffer_close_icons = true,
show_buffer_default_icon = true, -- whether or not an unrecognised filetype should show a default icon
show_close_icon = false,
show_tab_indicators = true,
persist_buffer_sort = true, -- whether or not custom sorted buffers should persist
-- can also be a table containing 2 custom separators
-- [focused and unfocused]. eg: { '|', '|' }
separator_style = 'thick',
enforce_regular_tabs = false,
always_show_bufferline = true,
sort_by = 'insert_after_current'
}
})
|
local PANEL = {}
function PANEL:Init()
self:Receiver("impulseInv", self.OnDrop)
self:SetMouseInputEnabled(false)
self:SetSize(140, 140)
self:Hide()
end
function PANEL:SetItem(panel)
self.Item = panel
self:SetPos(gui.MouseX() + 6, gui.MouseY() - self:GetTall() - 6)
self.ItemName = panel.Item.Name
self.ItemColour = panel.Item.Colour or impulse.Config.MainColour
self.ItemDesc = panel.Item.Desc or ""
self.ItemRarity = 1
self.ItemIsIllegal = panel.Item.Illegal or false
self.ItemIsEquipped = panel.Item.Equipable or false
self.ItemIsRestricted = panel.Item.Restricted or false
surface.SetFont("Impulse-Elements18-Shadow")
local nameSize = surface.GetTextSize(self.ItemName)
surface.SetFont("Impulse-Elements16-Shadow")
local descSize = surface.GetTextSize(self.ItemDesc)
local wide
if descSize > nameSize and nameSize < 200 then
wide = math.Clamp(descSize, 140, 200)
else
wide = math.Clamp(nameSize, 140, 340)
end
local extraTall = 0
if descSize > 773 then
extraTall = 70
end
local extraMarkup = ""
if self.ItemIsIllegal then
extraMarkup = "<colour=255, 0, 0, 255>This item is contraband</colour>\n"
end
if self.ItemIsEquipped then
extraMarkup = extraMarkup.."<colour=0, 200, 0, 255>This item is equipped</colour>\n"
end
if self.ItemIsRestricted then
extraMarkup = extraMarkup.."<colour=255, 223, 0, 255>This item is restricted</colour>\n"
end
self.ItemDescMarkup = markup.Parse("<font=Impulse-Elements16-Shadow>"..extraMarkup.."<colour=255, 255, 255, 255>"..self.ItemDesc.."</colour></font>", wide)
self:SetSize(wide + 20, 140 + extraTall)
self:Show()
end
function PANEL:Think()
self:SetPos(gui.MouseX() + 6, gui.MouseY() - self:GetTall() - 2)
if self.Item and IsValid(self.Item) and self.Item.model:IsHovered() then
self:MoveToFront()
else
self:Remove()
end
end
local gradient = Material("vgui/gradient-r")
local outlineCol = Color(10, 10, 10, 255)
local darkCol = Color(80, 80, 80, 100)
local fullCol = Color(139, 0, 0, 15)
function PANEL:Paint(w,h)
impulse.blur(self, 10, 20, 255)
surface.SetDrawColor(darkCol)
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(outlineCol)
surface.DrawOutlinedRect(0, 0, w, h)
surface.SetFont("Impulse-Elements18-Shadow")
surface.SetTextColor(self.ItemColour)
surface.SetTextPos(10, 10)
surface.DrawText(self.ItemName)
self.ItemDescMarkup:Draw(10, 30)
end
vgui.Register("impulseInventoryHover", PANEL, "DPanel") |
<form action="." class="form-horizontal hidden-print" id="main" method="GET">
<div class="form-group">
<input type="hidden" name="database" value="<%= html.dbactive %>">
<input type="hidden" name="action" value="new_task">
<input type="hidden" name="tagid" value="<%= html.taglist[html.options.tag].id %>">
<div class="col-xs-10">
<input id="search" class="form-control" name="name" type="text" autocomplete="off" autofocus>
</div>
<div class="col-xs-2">
<button class="btn btn-default pull-right" type="submit"><%= html.img("note_add", 16) %></button>
</div>
</div>
</form>
<ul id="tasklist" class="list-group">
<li class="list-group-item active"><%= #html.tasklist %> Tarefas</li>
<% for i, v in pairs(html.tasklist) do %>
<li class="list-group-item">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<%= html.img(html.dueicon(v), 16) %>
<span class="caret"></span>
<%= v.name %>
</a>
<ul class="dropdown-menu">
<li><a href="?action=new_task&tagid=<%= html.taglist[html.options.tag].id %>&database=<%= html.dbactive %>"><%= html.img("note_add", 16) %> Nova tarefa</a></li>
<li><a href="?action=upd_task&id=<%= v.id %>&database=<%= html.dbactive %>"><%= html.img("note_edit", 16) %> Editar tarefa</a></li>
<% if v.recurrent == "1" then %>
<li><a href="?action=del_task&id=<%= v.id %>&name=<%= v.name %>&database=<%= html.dbactive %>"><%= html.img("note_delete", 16) %> Excluir tarefa</a></li>
<% else %>
<li><a href="?action=del_task&id=<%= v.id %>&name=<%= v.name %>&recurrent=<%= v.recurrent %>&database=<%= html.dbactive %>"><%= html.img("note_go", 16) %> Concluir tarefa</a></li>
<% end %>
<li class="divider"></li>
<li><a href="?action=set_date&date=today&id=<%= v.id %>&database=<%= html.dbactive %>"><%= html.img("flag_today", 16) %> Marcar para hoje</a></li>
<li><a href="?action=set_date&date=tomorrow&id=<%= v.id %>&database=<%= html.dbactive %>"><%= html.img("flag_tomorrow", 16) %> Marcar para amanhã</a></li>
<li><a href="?action=set_date&date=anytime&id=<%= v.id %>&database=<%= html.dbactive %>"><%= html.img("flag_anytime", 16) %> Deixar para qualquer dia</a></li>
</ul>
</li>
<% end %>
</ul>
<script>
$("#search").on("input", function(){
var r = new RegExp(this.value, "i");
$("#tasklist > li > a").each(function(i, e) {
if ($(e).text().match(r))
e.parentNode.style.display = "block"
else
e.parentNode.style.display = "none";
});
$("#tasklist > li.active").text($("#tasklist > li > a:visible").length + " Tarefas");
});
</script>
|
Outfitter.EquipmentUpdateCount = 0
----------------------------------------
Outfitter._EquipmentChanges = Outfitter:newClass()
----------------------------------------
function Outfitter._EquipmentChanges:construct()
end
function Outfitter._EquipmentChanges:addChange(change)
table.insert(self, change)
end
function Outfitter._EquipmentChanges:insertChange(index, change)
table.insert(self, index, change)
end
function Outfitter._EquipmentChanges:findChangeForSlot(slotName)
for index, change in ipairs(self) do
if not change and change.SlotName == slotName then
return change, index
end
end
-- Return nothing
end
function Outfitter._EquipmentChanges:addChangesToEquipOutfit(outfit, inventoryCache)
inventoryCache:ResetIgnoreItemFlags()
-- Remove items which are already in the correct slot from the outfit and from the
-- equippable items list
local items = outfit:GetItems()
for inventorySlot, outfitItem in pairs(items) do
local containsItem, item = inventoryCache:InventorySlotContainsItem(inventorySlot, outfitItem)
if containsItem then
outfit:RemoveItem(inventorySlot)
if item then
item.IgnoreItem = true
end
end
end
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugOutfitTable(outfit, "Remaining")
end
-- WoW has a bug with dual-spec where you can end up with dual 2H weapons equipped even
-- though you may no longer have Titan's Grip. To correct this, I detect the situation here
-- and insert an unequip operation for the 2H'er in the OH slot to restore the equipment
-- to a valid state.
local has2HGlitch
local secondaryHandItem = inventoryCache.InventoryItems.SecondaryHandSlot
if not Outfitter.CanDualWield2H
and secondaryHandItem
and secondaryHandItem.InvType == "INVTYPE_2HWEAPON" then
has2HGlitch = true
local change = Outfitter:New(Outfitter._EquipmentChange, "SecondaryHandSlot", secondaryHandItem.Name)
change.TGFix = true
self:addChange(change)
end
-- Scan the outfit using the Outfitter.cSlotNames array as an index so that changes
-- are executed in the specified order. The order is designed so that items with
-- durability values are unequipped first, followed by other items such as cloaks and rings
-- which have no durability. This makes unequipping before death (falling, raid/party wipe) more useful
-- since it'll reduce the cost of repairs
for _, inventorySlot in ipairs(Outfitter.cSlotNames) do
self:addSlot(outfit, inventoryCache, inventorySlot, has2HGlitch)
end -- for
if #self == 0 then
return nil
end
self:adjustUniqueEquipSwaps()
self:optimize()
end
function Outfitter._EquipmentChanges:addUnequipChangesForOutfit(outfit, inventoryCache)
local items = outfit:GetItems()
for inventorySlot, item in pairs(items) do
local inventoryItem, ignoredItem = inventoryCache:FindItemOrAlt(item, true)
if inventoryItem then
local change = Outfitter:New(Outfitter._EquipmentChange)
change.FromLocation = inventoryItem.Location
change.Item = inventoryItem
self:addChange(change)
end
end -- for
end
function Outfitter._EquipmentChanges:addSlot(outfit, inventoryCache, inventorySlot, has2HGlitch)
-- Get the item the outfit wants in the slot
local outfitItem = outfit:GetItem(inventorySlot)
-- Do nothing if the outfit isn't using that slot
if not outfitItem then
return
end
local slotID = Outfitter.cSlotIDs[inventorySlot]
local currentItemCodes, currentItemName = Outfitter:GetSlotIDLinkInfo(slotID)
local currentItemCode = currentItemCodes and currentItemCodes[1]
local equipmentChange = Outfitter:New(Outfitter._EquipmentChange, inventorySlot, outfitItem.Name)
-- If the item is a phantom, just ignore it
if Outfitter.PhantomItemIDs[outfitItem.Code] then
return
end
--
if has2HGlitch and inventorySlot == "SecondaryHandSlot" then
currentItemCode = nil -- Pretend there's nothing in the OH since we've queued an unequip for it
end
-- Empty the slot if it's supposed to be blank
if outfitItem.Code == 0 or outfitItem.Code == nil then
if not currentItemCode then
return -- Nothing to do if the slot is supposed to be empty and already is
end
else
-- Find the item
local item, ignoredItem = inventoryCache:FindItemOrAlt(outfitItem, true)
-- If the item wasn't found then show an appropriate error message and leave
if not item then
Outfitter:ShowEquipError(outfitItem, ignoredItem, inventorySlot)
return
end
-- Add the unique-equipped item counts for the item being equipped
equipmentChange:addLocationUniqueEquipTotals(item.Location)
-- Update the change with info for the item being equipped
equipmentChange.ItemMetaSlotName = item.MetaSlotName
equipmentChange.ItemLocation = item.Location
-- Treat the item as a 1H if they can dual wield it
if equipmentChange.ItemMetaSlotName == "TwoHandSlot"
and not Outfitter:ItemUsesBothWeaponSlots(outfitItem) then
equipmentChange.ItemMetaSlotName = "Weapon0Slot"
end
end -- else outfitItem.Code == 0 or outfitItem.Code == nil
-- Insert the change
self:addChange(equipmentChange)
end
function Outfitter._EquipmentChanges:adjustUniqueEquipSwaps()
-- Calculate the sort rank for each change. There are three sort ranks and they are determined by whether an change item increases, decreases, or both increases and decreases totals for unique-equip attributes
for index, change in ipairs(self) do
-- Calculate the initial sort rank
change.uniqueEquipOrderingRank = change:calcUniqueEquipOrderingRank()
-- Initially use the slot sort index as the second-order sort value
change.uniqueEquipOrderingRank2 = Outfitter.cSlotOrder[change.SlotName]
end
-- The algorithm is repeated for multiple passes until no entries are relocated during a pass. Keep track of the totals for each pass to determine whether it changed.
local previousRank1Count, previousRank2Count
-- Limit the number of iterations by using a for loop instead of an unconditional while
local uniqueEquipStartCounts
for iteration = 1, 20 do
-- Sort the changes using the two change rank fields
table.sort(self, Outfitter.CompareUniqueEquipOrderingRanks)
-- Sum up the ID counts in rank 1 entries and re-assign ranks
uniqueEquipStartCounts = Outfitter:RecycleTable(uniqueEquipStartCounts)
local rank1Count, rank2Count = 0, 0
for index, change in ipairs(self) do
-- Rank 1 doesn't change order, so simply total up the unique counts and set the uniqueEquipOrderingRank2 field to ensure the ordering is preserved
if change.uniqueEquipOrderingRank == 1 then
-- Track the totals for each type
for uniqueEquipID, uniqueEquipCount in pairs(change.uniqueEquipTotals) do
uniqueEquipStartCounts[uniqueEquipID] = (uniqueEquipStartCounts[uniqueEquipID] or 0) + uniqueEquipCount
end
-- Preserve the ordering by using the index as the second-order sort value
change.uniqueEquipOrderingRank2 = index
-- Track how many rank 1 entries were found
rank1Count = rank1Count + 1
-- Rank 2 changes increase the unique count of some categories while decreasing others. Swapping one unique-equipped item for another unique-equipped item of another type would do this for example.
elseif change.uniqueEquipOrderingRank == 2 then
-- If there's nothing in rank 1 then we're done
if rank1Count == 0 then
return
end
-- Calculate a new rank using the start counts. A change can be promoted to rank 1 if it now results in no change or a net decrease in counts
change.uniqueEquipOrderingRank = change:calcUniqueEquipOrderingRank(uniqueEquipStartCounts)
-- Adjust the rank for this change
if change.uniqueEquipOrderingRank == 1 then
rank1Count = rank1Count + 1
change.uniqueEquipOrderingRank2 = index
elseif change.uniqueEquipOrderingRank == 2 then
rank2Count = rank2Count + 1
else -- 3
change.uniqueEquipOrderingRank2 = index
end
-- Rank 3 changes increase the unique-equipped count of one or more types.
else
-- If there's nothing in rank 1 or 2 we're done
if rank1Count == 0
or rank2Count == 0 then
return
end
-- Preserve the ordering
change.uniqueEquipOrderingRank2 = index
end
end
-- If the counts don't change we're done
if previousRank1Count == rank1Count
and previousRank2Count == rank2Count then
break
end
-- The counts changed, so remember the new counts and do it again
previousRank1Count = rank1Count
previousRank2Count = rank2Count
end -- for
end
function Outfitter._EquipmentChanges:fixSlotSwapChange(changeIndex1, equipmentChange1, slotName1, changeIndex2, equipmentChange2, slotName2)
-- No problem if both slots will be emptied
if not equipmentChange1.ItemLocation
and not equipmentChange2.ItemLocation then
return
end
-- No problem if neither slot is being moved to the other one
local slot2ToSlot1 = equipmentChange1.ItemLocation ~= nil
and equipmentChange1.ItemLocation.SlotName == slotName2
local slot1ToSlot2 = equipmentChange2.ItemLocation ~= nil
and equipmentChange2.ItemLocation.SlotName == slotName1
-- No problem if the slots are swapping with each other
-- or not moving between each other at all
if slot2ToSlot1 == slot1ToSlot2 then
return
end
-- Slot 1 is moving to slot 2
if slot1ToSlot2 then
if equipmentChange1.ItemLocation then
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugMessage("FixSlotSwapChange: Rearranging so that %s can move to %s", slotName1, slotName2)
end
-- Swap change 1 and change 2 around
self[changeIndex1] = equipmentChange2
self[changeIndex2] = equipmentChange1
-- Insert a change to empty slot 2
local emptySlot2 = Outfitter:New(Outfitter._EquipmentChange, equipmentChange2.SlotName)
self:insertChange(changeIndex1, emptySlot2)
equipmentChange1.Optimized = true
equipmentChange2.Optimized = true
emptySlot2.Optimized = true
else
-- Slot 1 is going to be empty, so empty slot 2 instead
-- and then when slot 1 is moved it'll swap the empty space
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugMessage("FixSlotSwapChange: Emptying %s so that %s can move there", slotName2, slotName1)
end
equipmentChange1.SlotName = slotName2
equipmentChange1.SlotID = equipmentChange2.SlotID
equipmentChange1.ItemLocation = nil
equipmentChange1.Optimized = true
equipmentChange2.Optimized = true
end
-- Slot 2 is moving to slot 1
else
if equipmentChange2.ItemLocation then
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugMessage("FixSlotSwapChange: Rearranging so that %s can move to %s", slotName2, slotName1)
end
-- Insert a change to empty slot 1 first
local emptySlot1 = Outfitter:New(Outfitter._EquipmentChange, equipmentChange1.SlotName)
self:insertChange(changeIndex1, emptySlot1)
equipmentChange1.Optimized = true
equipmentChange2.Optimized = true
emptySlot1.Optimized = true
else
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugMessage("FixSlotSwapChange: Emptying %s so that %s can move there", slotName1, slotName2)
end
-- Slot 2 is going to be empty, so empty slot 1 instead
-- and then when slot 2 is moved it'll swap the empty space
equipmentChange2.SlotName = slotName1
equipmentChange2.SlotID = equipmentChange1.SlotID
equipmentChange2.ItemLocation = nil
-- Change the order so that slot 1 gets emptied before the move
self[changeIndex1] = equipmentChange2
self[changeIndex2] = equipmentChange1
equipmentChange1.Optimized = true
equipmentChange2.Optimized = true
end
end
end
function Outfitter._EquipmentChanges:optimize()
local didSlot = {}
local changeIndex = 1
local numChanges = #self
while changeIndex <= numChanges do
local equipmentChange = self[changeIndex]
-- Do nothing if this change has already been worked on
if equipmentChange.Optimized then
-- If this is the change for the Titan's Grip fix, put it at the very start
-- so it clears the state before any mainhand/offhand swaps happen
elseif equipmentChange.TGFix then
if changeIndex ~= 1 then
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugMessage("EquipmentChanges:optimize: Moving TGFix to the front of the list")
end
table.remove(self, changeIndex)
self:insertChange(1, equipmentChange)
end
elseif equipmentChange.SlotName == "SecondaryHandSlot" then
local equipmentChange2, changeIndex2 = self:findChangeForSlot("MainHandSlot")
-- If equipping an offhand item, make sure it's after equipping
-- a mainhand item or it will fail when the current mainhand
-- is a two-hander
if equipmentChange.ItemLocation ~= nil then
if changeIndex2 and changeIndex2 > changeIndex then
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugMessage("EquipmentChanges:optimize: Moving offhand swap to be after mainhand")
end
table.remove(self, changeIndex)
self:insertChange(changeIndex2, equipmentChange)
changeIndex = changeIndex - 1
end
-- If the off-hand slot is being emptied, then do that before handling the
-- main hand slot (fixes Titan's Grip problem with the Argent Lance)
elseif equipmentChange.ItemLocation == nil then
if changeIndex2 and changeIndex2 < changeIndex then
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugMessage("EquipmentChanges:optimize: Moving offhand swap to be before mainhand")
end
table.remove(self, changeIndex)
self:insertChange(changeIndex2, equipmentChange)
end
end
-- If a two-hand weapon is being equipped, remove the change event
-- for removing the offhand slot
elseif equipmentChange.ItemMetaSlotName == "TwoHandSlot" then
local equipmentChange2, changeIndex2 = self:findChangeForSlot("SecondaryHandSlot")
-- If there's a change for the offhand slot, remove it
if changeIndex2 then
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugMessage("EquipmentChanges:optimize: Removing offhand swap because of 2H being equipped")
end
table.remove(self, changeIndex2)
if changeIndex2 < changeIndex then
changeIndex = changeIndex - 1
end
numChanges = numChanges - 1
end
-- Insert a new change for the offhand slot to empty it ahead
-- of equipping the two-hand item
if Outfitter.Debug.EquipmentChanges then
Outfitter:DebugMessage("EquipmentChanges:optimize: Emptying offhand before 2H equip")
end
self:insertChange(changeIndex, Outfitter:New(Outfitter._EquipmentChange, "SecondaryHandSlot"))
-- Otherwise see if the change needs to be re-arranged so that slot
-- swapping works correctly (trinkets, rings, or weapon slots being swapped)
else
local swapSlot = Outfitter.SlotSwapList[equipmentChange.SlotName]
if swapSlot and not didSlot[equipmentChange.SlotName] then
local equipmentChange2, changeIndex2 = self:findChangeForSlot(swapSlot)
if changeIndex2 then
self:FixSlotSwapChange(changeIndex, equipmentChange, equipmentChange.SlotName, changeIndex2, equipmentChange2, swapSlot)
end
didSlot[equipmentChange.SlotName] = true
numChanges = #self
end
end
--
changeIndex = changeIndex + 1
end
end
function Outfitter._EquipmentChanges:execute(emptyBagSlots, expectedInventoryCache)
-- Disable sound effects during the swap
local savedEnabledSFXValue
if not Outfitter.Settings.EnableEquipSounds then
savedEnabledSFXValue = GetCVar("Sound_EnableSFX")
SetCVar("Sound_EnableSFX", "0")
end
-- Process each change
for changeIndex, equipmentChange in ipairs(self) do
local swapItems, emptyThenEquip
-- Determine if an in-place swap is possible (or even necessary)
if equipmentChange.ItemLocation then
swapItems = true
-- If the items are for different bag types, check to see if we need to
-- separate the swap operation into Empty then Equip
local equippedItemBagType = Outfitter:GetSlotIDItemBagType(equipmentChange.SlotID)
local newItemBagType = Outfitter:GetItemLocationBagType(equipmentChange.ItemLocation)
-- If the item being equipped is in a specialty bag already and the
-- current item can't go in that bag then we have to EmptyThenEquip
local newItemInBagType = equipmentChange.ItemLocation.BagIndex and Outfitter:GetBagType(equipmentChange.ItemLocation.BagIndex)
if equippedItemBagType
and newItemInBagType
and newItemInBagType ~= 0
and bit.band(newItemInBagType, equippedItemBagType) == 0 then
emptyThenEquip = true
-- Otherwise, if the item being unequipped has a specialty slot available, then we have to EmptyThenEquip
elseif equippedItemBagType and Outfitter:FindEmptySpecialtyBagSlot(equippedItemBagType, emptyBagSlots) then
emptyThenEquip = true
end
end
-- Swap the item in-place with the new item
if swapItems then
if emptyThenEquip then
Outfitter:UnequipSlotID(equipmentChange.SlotID, emptyBagSlots, expectedInventoryCache)
end
-- Make sure nothing is already being held
ClearCursor()
-- Pick up the item and equip it
Outfitter:PickupItemLocation(equipmentChange.ItemLocation)
EquipCursorItem(equipmentChange.SlotID)
-- Update the expected cache
if expectedInventoryCache then
expectedInventoryCache:SwapLocationWithInventorySlot(equipmentChange.ItemLocation, equipmentChange.SlotName)
end
-- Remove the item
else
Outfitter:UnequipSlotID(equipmentChange.SlotID, emptyBagSlots, expectedInventoryCache)
end
end
-- Make sure nothing is left behind on the cursor
ClearCursor()
-- Restore the sound effects setting
if savedEnabledSFXValue then
SetCVar("Sound_EnableSFX", savedEnabledSFXValue)
end
end
function Outfitter._EquipmentChanges:debug()
Outfitter:DebugMark()
Outfitter:DebugTable(self, "EquipmentChanges")
end
----------------------------------------
Outfitter._EquipmentChange = Outfitter:newClass()
----------------------------------------
function Outfitter._EquipmentChange:construct(inventorySlot, itemName)
self.SlotName = inventorySlot
self.SlotID = Outfitter.cSlotIDs[inventorySlot]
self.ItemName = itemName
self.uniqueEquipTotals = {}
-- Subtract the unique-equip totals to get starting values
self:subtractInventoryUniqueEquipTotals()
return change
end
function Outfitter._EquipmentChange:subtractInventoryUniqueEquipTotals()
-- Get the item
local itemInfo = Outfitter:GetSlotIDItemInfo(self.SlotID)
-- Leave if no item
if not itemInfo then
return
end
-- Get the unique-equip types
local uniqueEquipTypes = itemInfo:GetUniqueEquipTypes()
-- Done if there are no unique-equip types
if not uniqueEquipTypes then
return
end
-- Subtract the counts
for uniqueEquipType in pairs(uniqueEquipTypes) do
self.uniqueEquipTotals[uniqueEquipType] = (self.uniqueEquipTotals[uniqueEquipType] or 0) - 1
end
end
function Outfitter._EquipmentChange:addLocationUniqueEquipTotals(location)
-- Get the item
local itemInfo
if location.BagIndex then
itemInfo = Outfitter:GetBagItemInfo(location.BagIndex, location.BagSlotIndex)
else
itemInfo = Outfitter:GetSlotIDItemInfo(location.SlotID)
end
-- Leave if no item
if not itemInfo then
return
end
-- Get the unique-equip types
local uniqueEquipTypes = itemInfo:GetUniqueEquipTypes()
-- Done if there are no unique-equip types
if not uniqueEquipTypes then
return
end
-- Add the counts
for uniqueEquipType in pairs(uniqueEquipTypes) do
self.uniqueEquipTotals[uniqueEquipType] = (self.uniqueEquipTotals[uniqueEquipType] or 0) + 1
end
end
function Outfitter._EquipmentChange:calcUniqueEquipOrderingRank(uniqueEquipCountOffsets)
local hasNegative, hasPositive
-- Check each total
for uniqueID, uniqueCount in pairs(self.uniqueEquipTotals) do
if uniqueEquipCountOffsets then
uniqueCount = uniqueCount + (uniqueEquipCountOffsets[uniqueID] or 0)
end
if uniqueCount < 0 then
hasNegative = true
if hasPositive then
break
end
elseif uniqueCount > 0 then
hasPositive = true
if hasNegative then
break
end
end
end
-- Changes which increase and decrease totals are given second priority so that they’re done before changes which increase only
if hasNegative and hasPositive then
return 2
-- Changes which only increase totals are given the lowest priority so that they’re done last
elseif hasPositive then
return 3
end
-- Changes which don’t affect or decrease totals are the highest priority
return 1
end
----------------------------------------
-- Outfitter
----------------------------------------
function Outfitter:ShowEquipError(pOutfitItem, pIgnoredItem, pInventorySlot)
if self.Settings.DisableEquipErrors then
return
end
local vSlotDisplayName = self.cSlotDisplayNames[pInventorySlot]
if not vSlotDisplayName then
vSlotDisplayName = pInventorySlot or "nil"
end
if pOutfitItem.Name then
if pIgnoredItem then
self:ErrorMessage(format(self.cItemAlreadyUsedError, self:GenerateItemLink(pOutfitItem), vSlotDisplayName))
self:DebugMessage("item already used for slot %s", vSlotDisplayName)
else
self:ErrorMessage(format(self.cItemNotFoundError, self:GenerateItemLink(pOutfitItem), vSlotDisplayName))
self:DebugMessage("can't find item for slot %s", vSlotDisplayName)
end
else
self:ErrorMessage(format(self.cItemNotFoundError, "unknown", vSlotDisplayName))
end
end
function Outfitter:PickupItemLocation(pItemLocation)
if pItemLocation == nil then
self:ErrorMessage("nil location in PickupItemLocation")
return
end
if pItemLocation.BagIndex then
if CT_oldPickupContainerItem then
CT_oldPickupContainerItem(pItemLocation.BagIndex, pItemLocation.BagSlotIndex)
else
PickupContainerItem(pItemLocation.BagIndex, pItemLocation.BagSlotIndex)
end
elseif pItemLocation.SlotName then
PickupInventoryItem(self.cSlotIDs[pItemLocation.SlotName])
else
self:ErrorMessage("Unknown location in PickupItemLocation")
return
end
end
function Outfitter.CompareUniqueEquipOrderingRanks(change1, change2)
if change1.uniqueEquipOrderingRank ~= change2.uniqueEquipOrderingRank then
return change1.uniqueEquipOrderingRank < change2.uniqueEquipOrderingRank
end
return change1.uniqueEquipOrderingRank2 < change2.uniqueEquipOrderingRank2
end
Outfitter.SlotSwapList =
{
Finger0Slot = "Finger1Slot",
Trinket0Slot = "Trinket1Slot",
MainHandSlot = "SecondaryHandSlot",
}
function Outfitter:FindEmptySpecialtyBagSlot(pItemBagType, pEmptyBagSlots)
if not pEmptyBagSlots
or not pItemBagType then
return
end
for vSlotInfoIndex, vSlotInfo in ipairs(pEmptyBagSlots) do
if bit.band(vSlotInfo.BagType, pItemBagType) ~= 0 then
return vSlotInfo, vSlotInfoIndex
end
end
end
function Outfitter:UnequipSlotID(pSlotID, pEmptyBagSlots, pExpectedInventoryCache)
self:MoveLocationToEmptyBagSlot(pSlotID, pEmptyBagSlots, self.cBagsFullError, pExpectedInventoryCache)
end
function Outfitter:MoveLocationToEmptyBagSlot(pLocation, pEmptyBagSlots, pErrorMessage, pExpectedInventoryCache)
local vItemBagType
if type(pLocation) == "table" then
vItemBagType = self:GetItemLocationBagType(pLocation)
else
vItemBagType = self:GetSlotIDItemBagType(pLocation)
end
if not vItemBagType then
return -- Location is already empty
end
-- Find a bag slot for it
local vEmptySlotInfo
if pEmptyBagSlots then
-- First try for a specialized bag
if vItemBagType
and vItemBagType ~= self.cGeneralBagType then
local vSlotInfoIndex
vEmptySlotInfo, vSlotInfoIndex = self:FindEmptySpecialtyBagSlot(vItemBagType, pEmptyBagSlots)
if vEmptySlotInfo then
table.remove(pEmptyBagSlots, vSlotInfoIndex)
end
end
-- Try for a general purpose bag
if not vEmptySlotInfo then
for vSlotInfoIndex, vSlotInfo in ipairs(pEmptyBagSlots) do
if vSlotInfo.BagType == self.cGeneralBagType then
vEmptySlotInfo = vSlotInfo
table.remove(pEmptyBagSlots, vSlotInfoIndex)
break
end
end
end
end
--
if not vEmptySlotInfo then
local vItemLink
if type(pLocation) == "table" then
vItemLink = self:GetItemLocationLink(pLocation)
else
vItemLink = self:GetInventorySlotIDLink(pLocation)
end
self:ErrorMessage(format(pErrorMessage, tostring(vItemLink)))
else
ClearCursor() -- Make sure they aren't holding anything already or things get wonky
if type(pLocation) == "table" then
self:PickupItemLocation(pLocation)
else
PickupInventoryItem(pLocation)
end
self:PickupItemLocation(vEmptySlotInfo)
if pExpectedInventoryCache then
if type(pLocation) == "table" then
pExpectedInventoryCache:SwapLocations(pLocation, vEmptySlotInfo)
else
pExpectedInventoryCache:SwapLocationWithInventorySlot(pLocation, self.cSlotIDToInventorySlot[pLocation])
end
end
end
end
function Outfitter:BeginEquipmentUpdate()
self.EquipmentUpdateCount = self.EquipmentUpdateCount + 1
end
function Outfitter:EndEquipmentUpdate(pCallerName, pUpdateNow)
self.EquipmentUpdateCount = self.EquipmentUpdateCount - 1
if self.EquipmentUpdateCount == 0 then
if pUpdateNow then
if self.Debug.EquipmentChanges then
self:DebugMessage("EndEquipmentUpdate: updating now")
end
self:UpdateEquippedItems()
else
self:ScheduleEquipmentUpdate()
end
self:Update(false)
end
end
function Outfitter:UpdateEquippedItems()
if not self.EquippedNeedsUpdate then
if self.Debug.EquipmentChanges then
self:DebugMessage("UpdateEquippedItems: Nothing to update")
end
return
end
if self.Debug.EquipmentChanges then
self:DebugMessage("UpdateEquippedItems: updating equipment")
end
-- Delay all changes until they're alive or not casting a spell
if self.IsDead
or not self.InterruptCasting and (self.IsCasting or self.IsChanneling) then
if self.Debug.EquipmentChanges then
self:DebugMessage("UpdateEquippedItems: deferring while casting")
end
return
end
self.InterruptCasting = nil
local vCurrentTime = GetTime()
if vCurrentTime - self.LastEquipmentUpdateTime < self.cMinEquipmentUpdateInterval then
if self.Debug.EquipmentChanges then
self:DebugMessage("UpdateEquippedItems: deferring for min interval")
end
self:ScheduleEquipmentUpdate()
return
end
self.LastEquipmentUpdateTime = vCurrentTime
self.EquippedNeedsUpdate = false
-- Compile the outfit
local vInventoryCache = self:GetInventoryCache()
local vCompiledOutfit = self:GetCompiledOutfit()
if self.Debug.EquipmentChanges then
self:DebugOutfitTable(vCompiledOutfit, "CompiledOutfit0")
end
-- When in combat delay the outfit change until
-- combat ends
if self.InCombat or self.MaybeInCombat then
self.EquippedNeedsUpdate = true
self.MaybeInCombat = false
self:ScheduleEquipmentUpdate()
return
end
-- Equip it
local vEquipmentChangeList = Outfitter:New(Outfitter._EquipmentChanges)
vEquipmentChangeList:addChangesToEquipOutfit(vCompiledOutfit, vInventoryCache)
if vEquipmentChangeList then
-- local vExpectedInventoryCache = self:New(self._InventoryCache)
if self.Debug.EquipmentChanges then
self:DebugMessage("UpdateEquippedItems: Executing change list")
self:DebugTable(vEquipmentChangeList, "ChangeList")
end
vEquipmentChangeList:execute(self:GetEmptyBagSlotList(), vExpectedInventoryCache)
else
if self.Debug.EquipmentChanges then
self:DebugMessage("UpdateEquippedItems: No change list generated")
end
end
-- Update the outfit we're expecting to see on the player
local vItems = vCompiledOutfit:GetItems()
for vInventorySlot, vItem in pairs(vItems) do
self.ExpectedOutfit:SetItem(vInventorySlot, vItem)
end
if self.Debug.EquipmentChanges then
self:DebugOutfitTable(vCompiledOutfit, "CompiledOutfit")
end
self.MaybeInCombat = false
self:ScheduleEquipmentUpdate()
end
function Outfitter:DebugOutfitTable(pOutfit, pPrefix)
local vPrefix = pPrefix or pOutfit.Name or "unnamed"
local vItems = pOutfit:GetItems()
if not vItems then
self:DebugMessage("%s: No items", vPrefix)
return
end
for vInventorySlot, vItem in pairs(vItems) do
if vItem.Code == 0 then
self:DebugMessage("%s.%s: Empty slot", vPrefix, vInventorySlot)
else
self:DebugMessage("%s.%s: %s", vPrefix, vInventorySlot, tostring(vItem.Link))
end
end
end
function Outfitter:ScheduleEquipmentUpdate()
if not self.EquippedNeedsUpdate then
return
end
local vElapsed = GetTime() - self.LastEquipmentUpdateTime
local vDelay = self.cMinEquipmentUpdateInterval - vElapsed
if vDelay < 0.05 then
vDelay = 0.05
end
if self.Debug.EquipmentChanges then
self:DebugMessage("ScheduleEquipmentUpdate: updating in %d seconds", vDelay)
end
self.SchedulerLib:ScheduleUniqueTask(vDelay, self.UpdateEquippedItems, self)
end
----------------------------------------
-- Outfitter.OutfitStack
----------------------------------------
function Outfitter.OutfitStack:Initialize()
self:RestoreSavedStack()
end
function Outfitter.OutfitStack:RestoreSavedStack()
if not gOutfitter_Settings.LastOutfitStack then
gOutfitter_Settings.LastOutfitStack = {}
end
for vIndex, vOutfit in ipairs(gOutfitter_Settings.LastOutfitStack) do
if vOutfit.Name then
vOutfit = Outfitter:FindOutfitByName(vOutfit.Name)
else
setmetatable(vOutfit, Outfitter._OutfitMetaTable)
end
if vOutfit and vOutfit:GetItems() then
table.insert(self.Outfits, vOutfit)
end
end
Outfitter.ExpectedOutfit = Outfitter:GetCompiledOutfit()
Outfitter:UpdateTemporaryOutfit(Outfitter:GetNewItemsOutfit(Outfitter.ExpectedOutfit))
if gOutfitter_Settings.Options.ShowStackContents then
self:DebugOutfitStack("Restore saved stack")
end
end
function Outfitter.OutfitStack:AddOutfit(pOutfit, pLayerID)
local vFound, vIndex = self:FindOutfit(pOutfit)
-- If it's already the topmost outfit just ignore the request
if vFound and vIndex == #self.Outfits then
return
end
-- If it's already on then remove it from the stack
-- so it can be added to the end
if vFound then
table.remove(self.Outfits, vIndex)
table.remove(gOutfitter_Settings.LastOutfitStack, vIndex)
for vLayerID, vLayerIndex in pairs(gOutfitter_Settings.LayerIndex) do
if vIndex < vLayerIndex then
gOutfitter_Settings.LayerIndex[vLayerID] = vLayerIndex - 1
end
end
Outfitter:DispatchOutfitEvent("UNWEAR_OUTFIT", pOutfit:GetName(), pOutfit)
end
-- Figure out the position to insert at
local vStackLength = #self.Outfits
local vInsertIndex = vStackLength + 1
local vLayerIndex = gOutfitter_Settings.LayerIndex[pLayerID]
if vLayerIndex then
vInsertIndex = vLayerIndex
end
if pLayerID then
gOutfitter_Settings.LayerIndex[pLayerID] = vInsertIndex
end
-- Adjust the layer indices
for vLayerID, vLayerIndex in pairs(gOutfitter_Settings.LayerIndex) do
if vInsertIndex < vLayerIndex then
gOutfitter_Settings.LayerIndex[vLayerID] = vLayerIndex + 1
end
end
-- Add the outfit
table.insert(self.Outfits, vInsertIndex, pOutfit)
if pOutfit:GetName() then
table.insert(gOutfitter_Settings.LastOutfitStack, vInsertIndex, {Name = pOutfit:GetName()})
else
table.insert(gOutfitter_Settings.LastOutfitStack, vInsertIndex, pOutfit)
end
Outfitter.DisplayIsDirty = true
if gOutfitter_Settings.Options.ShowStackContents then
self:DebugOutfitStack("Add outfit")
end
if vFound then
self:CollapseTemporaryOutfits()
end
Outfitter:DispatchOutfitEvent("WEAR_OUTFIT", pOutfit:GetName(), pOutfit)
end
function Outfitter.OutfitStack:RemoveOutfit(pOutfit)
local vFound, vIndex = self:FindOutfit(pOutfit)
if not vFound then
return false
end
-- Remove the outfit
table.remove(self.Outfits, vIndex)
table.remove(gOutfitter_Settings.LastOutfitStack, vIndex)
self:CollapseTemporaryOutfits()
for vLayerID, vLayerIndex in pairs(gOutfitter_Settings.LayerIndex) do
if vIndex < vLayerIndex then
gOutfitter_Settings.LayerIndex[vLayerID] = vLayerIndex - 1
end
end
Outfitter.DisplayIsDirty = true
if gOutfitter_Settings.Options.ShowStackContents then
self:DebugOutfitStack("Remove outfit")
end
return true
end
function Outfitter.OutfitStack:FindOutfit(pOutfit)
for vIndex, vOutfit in ipairs(self.Outfits) do
if vOutfit == pOutfit then
return true, vIndex
end
end
return false, nil
end
function Outfitter.OutfitStack:FindOutfitByCategory(pCategoryID)
for vIndex, vOutfit in ipairs(self.Outfits) do
if vOutfit.CategoryID == pCategoryID then
return true, vIndex
end
end
return false, nil
end
function Outfitter.OutfitStack:Clear()
for vIndex, vOutfit in ipairs(self.Outfits) do
Outfitter:DispatchOutfitEvent("UNWEAR_OUTFIT", vOutfit:GetName(), vOutfit)
end
wipe(self.Outfits)
gOutfitter_Settings.LastOutfitStack = Outfitter:RecycleTable(gOutfitter_Settings.LastOutfitStack)
gOutfitter_Settings.LayerIndex = Outfitter:RecycleTable(gOutfitter_Settings.LayerIndex)
Outfitter.DisplayIsDirty = true
if gOutfitter_Settings.Options.ShowStackContents then
Outfitter:DebugMessage("Outfitter stack cleared")
end
end
function Outfitter.OutfitStack:ClearCategory(pCategoryID)
local vIndex = 1
local vStackLength = #self.Outfits
local vChanged = false
while vIndex <= vStackLength do
local vOutfit = self.Outfits[vIndex]
if vOutfit
and vOutfit.CategoryID == pCategoryID then
-- Remove the outfit from the stack
table.remove(self.Outfits, vIndex)
table.remove(gOutfitter_Settings.LastOutfitStack, vIndex)
vStackLength = vStackLength - 1
vChanged = true
-- Adjust the layer indices
for vLayerID, vLayerIndex in pairs(gOutfitter_Settings.LayerIndex) do
if vIndex < vLayerIndex then
gOutfitter_Settings.LayerIndex[vLayerID] = vLayerIndex - 1
end
end
Outfitter:DispatchOutfitEvent("UNWEAR_OUTFIT", vOutfit:GetName(), vOutfit)
else
vIndex = vIndex + 1
end
end
self:CollapseTemporaryOutfits()
if vChanged then
if gOutfitter_Settings.Options.ShowStackContents then
self:DebugOutfitStack("Clear category "..pCategoryID)
end
Outfitter.DisplayIsDirty = true
end
end
function Outfitter.OutfitStack:GetTemporaryOutfit()
local vStackSize = #self.Outfits
if vStackSize == 0 then
return nil
end
local vOutfit = self.Outfits[vStackSize]
if vOutfit:GetName() then
return nil
end
return vOutfit
end
function Outfitter.OutfitStack:CollapseTemporaryOutfits()
local vIndex = 1
local vStackLength = #self.Outfits
local vTemporaryOutfit1 = nil
while vIndex <= vStackLength do
local vOutfit = self.Outfits[vIndex]
if vOutfit
and vOutfit:GetName() == nil then
if vTemporaryOutfit1 then
-- Copy the items up
local vTemporaryItems = vTemporaryOutfit1:GetItems()
for vInventorySlot, vItem in pairs(vTemporaryItems) do
if not vOutfit:SlotIsEnabled(vInventorySlot) then
vOutfit:SetItem(vInventorySlot, vItem)
end
end
-- Remove the lower temp outfit
table.remove(self.Outfits, vIndex - 1)
vStackLength = vStackLength - 1
else
vIndex = vIndex + 1
end
vTemporaryOutfit1 = vOutfit
else
vTemporaryOutfit1 = nil
vIndex = vIndex + 1
end
end
end
function Outfitter.OutfitStack:IsTopmostOutfit(pOutfit)
local vStackLength = #self.Outfits
if vStackLength == 0 then
return false
end
return self.Outfits[vStackLength] == pOutfit
end
function Outfitter.OutfitStack:UpdateOutfitDisplay()
local vShowTitleID
for vIndex, vOutfit in ipairs(self.Outfits) do
if vOutfit.ShowTitleID ~= nil then
vShowTitleID = vOutfit.ShowTitleID
end
end -- for
if vShowTitleID ~= nil
and Outfitter.HasHWEvent then
SetCurrentTitle(vShowTitleID)
end
end
function Outfitter:TagOutfitLayer(pOutfit, pLayerID)
local vFound, vIndex = self.OutfitStack:FindOutfit(pOutfit)
if not vFound then
return
end
gOutfitter_Settings.LayerIndex[pLayerID] = vIndex
end
function Outfitter.OutfitStack:DebugOutfitStack(pOperation)
Outfitter:DebugMessage("Outfitter Stack Contents: "..pOperation)
for vIndex, vOutfit in ipairs(self.Outfits) do
if vOutfit:GetName() then
Outfitter:DebugMessage("Slot "..vIndex..": "..vOutfit:GetName())
else
Outfitter:DebugMessage("Slot "..vIndex..": Temporaray outfit")
end
end
Outfitter:DebugTable(gOutfitter_Settings.LayerIndex, "LayerIndex")
end
function Outfitter.OutfitStack:GetCurrentOutfitInfo()
local vStackLength = #self.Outfits
if vStackLength == 0 then
return "", nil
end
local vOutfit = self.Outfits[vStackLength]
if vOutfit and vOutfit:GetName() then
return vOutfit:GetName(), vOutfit
else
return Outfitter.cCustom, vOutfit
end
end
|
package.path = "../?.lua;"..package.path;
require("p5")
function setup()
rectMode(CORNER); -- Default rectMode is CORNER
fill(255); -- Set fill to white
rect(25, 25, 50, 50); -- Draw white rect using CORNER mode
rectMode(CORNERS); -- Set rectMode to CORNERS
fill(100); -- Set fill to gray
rect(25, 25, 50, 50); -- Draw gray rect using CORNERS mode
end
go({width=1024, height=768, title="test_p5_rectmode1"});
|
-- Snippets
vim.g.coc_snippet_next = '<C-j>'
vim.g.coc_snippet_prev = '<C-k>'
vim.cmd("autocmd CursorHold * silent call CocActionAsync('highlight')")
|
local M = {}
function M.setup(config)
local defaults = require 'flavours.defaults'
local cfg = vim.tbl_deep_extend('force', defaults, config or {})
vim.cmd 'hi clear'
if vim.fn.exists('syntax_on') then
vim.cmd 'syntax reset'
end
vim.o.background = cfg.background
vim.o.termguicolors = true
vim.g.colors_name = 'flavours'
require('flavours.highlights').setup(cfg)
require('flavours.terminal').setup(cfg)
end
return M
|
local K = require("game.constants")
local LG = love.graphics
local renderWindow = require('game.render.window')
local renderBoardGems = require('game.render.gems.bgem')
local function renderNext(nextColumn, coords)
renderWindow.render("Next!", coords, function(w, h)
local scale = h / ( K.GEM_SIZE * 3.25 )
local x, y = ( w / scale - K.GEM_SIZE ) / 2, ( h / scale - K.GEM_SIZE * 3 ) / 2
LG.push()
LG.scale(scale, scale)
for i, j, b in nextColumn.allCoordinates() do
renderBoardGems(b, x, y, 1, j)
end
LG.pop()
end)
end
return renderNext
|
return require("kong.plugins.pre-function.migrations._001_280_to_300")("pre-function")
|
--
---- Copyright (c) 2014, Facebook, Inc.
---- All rights reserved.
----
---- This source code is licensed under the Apache 2 license found in the
---- LICENSE file in the root directory of this source tree.
----
ok, cunn = pcall(require, 'fbcunn')
if not ok then
ok,cunn = pcall(require,'cunn')
if ok then
print("warning: fbcunn not found. Falling back to cunn")
LookupTable = nn.LookupTable
else
print("Could not find cunn or fbcunn. Either is required")
os.exit()
end
else
deviceParams = cutorch.getDeviceProperties(1)
cudaComputeCapability = deviceParams.major + deviceParams.minor/10
LookupTable = nn.LookupTable
end
-- Train 1 day and gives 82 perplexity.
--[[
params = {
batch_size=20,
seq_length=35,
layers=2,
decay=1.15,
rnn_size=1500,
dropout=0.65,
init_weight=0.04,
lr=1,
vocab_size=10000,
epochs_to_lr_decay=14,
max_epochs=55,
max_grad_norm=10,
use_default_opt=true
}
]]--
-- Trains 1h and gives test 115 perplexity.
-- params = {
-- batch_size=20,
-- seq_length=20,
-- layers=2,
-- decay=2,
-- rnn_size=200,
-- dropout=0,
-- init_weight=0.1,
-- lr=1,
-- vocab_size=10000,
-- epochs_to_lr_decay=4,
-- max_epochs=13,
-- max_grad_norm=5,
-- use_default_opt=true,
-- make_queryable_model=false,
-- model_granularity="word"
-- }
-- Parameters for sentence query model.
-- params = {
-- batch_size=20,
-- seq_length=20,
-- layers=2,
-- decay=2,
-- rnn_size=200,
-- dropout=0,
-- init_weight=0.1,
-- lr=1,
-- vocab_size=10000,
-- epochs_to_lr_decay=4,
-- max_epochs=13,
-- max_grad_norm=5,
-- use_default_opt=true,
-- make_queryable_model=true,
-- model_granularity="word"
-- }
-- Parameters for character query model.
params = {
batch_size=20,
seq_length=100,
layers=1,
decay=2,
rnn_size=400,
dropout=0,
init_weight=0.1,
lr=1,
vocab_size=50,
epochs_to_lr_decay=4,
max_epochs=13,
max_grad_norm=5,
use_default_opt=true,
make_queryable_model=true,
model_granularity="character"
}
require('nngraph')
require('base')
require('xlua')
ptb = require('data')
-- Ripped out the serialization functionality from run_model.lua and isolated it
-- so that we can quickly integrate it with this script.
require('serialization')
-- TODO: include this in the repository for submission.
--package.path = package.path .. ";./../../torch_utilities/?.lua"
--require "sopt"
model = {}
function transfer_data(x)
return x:cuda()
end
function perplexity(mean_nll)
if model.granularity == "word" then
return torch.exp(mean_nll)
else
return torch.exp(5.6 * mean_nll)
end
end
function lstm(i, prev_c, prev_h)
local function new_input_sum()
local i2h = nn.Linear(params.rnn_size, params.rnn_size)
local h2h = nn.Linear(params.rnn_size, params.rnn_size)
return nn.CAddTable()({i2h(i), h2h(prev_h)})
end
local in_gate = nn.Sigmoid()(new_input_sum())
local forget_gate = nn.Sigmoid()(new_input_sum())
local in_gate2 = nn.Tanh()(new_input_sum())
local next_c = nn.CAddTable()({
nn.CMulTable()({forget_gate, prev_c}),
nn.CMulTable()({in_gate, in_gate2})
})
local out_gate = nn.Sigmoid()(new_input_sum())
local next_h = nn.CMulTable()({out_gate, nn.Tanh()(next_c)})
return next_c, next_h
end
function create_network()
local x = nn.Identity()()
local y = nn.Identity()()
local prev_s = nn.Identity()()
local i = {[0] = LookupTable(params.vocab_size, params.rnn_size)(x)}
local next_s = {}
local split = {prev_s:split(2 * params.layers)}
for layer_idx = 1, params.layers do
local prev_c = split[2 * layer_idx - 1]
local prev_h = split[2 * layer_idx]
local dropped = nn.Dropout(params.dropout)(i[layer_idx - 1])
local next_c, next_h = lstm(dropped, prev_c, prev_h)
table.insert(next_s, next_c)
table.insert(next_s, next_h)
i[layer_idx] = next_h
end
local h2y = nn.Linear(params.rnn_size, params.vocab_size)
local dropped = nn.Dropout(params.dropout)(i[params.layers])
local pred = nn.LogSoftMax()(h2y(dropped))
local err = nn.ClassNLLCriterion()({pred, y})
local module = {}
if not params.make_queryable_model then
module = nn.gModule({x, y, prev_s}, {err, nn.Identity()(next_s)})
else
module = nn.gModule({x, y, prev_s}, {err, nn.Identity()(next_s),
nn.Identity()(pred)})
end
module:getParameters():uniform(-params.init_weight, params.init_weight)
return transfer_data(module)
end
function setup()
print("Creating a RNN LSTM network.")
if not model_info_loaded() then
local core_network = create_network()
paramx, paramdx = core_network:getParameters()
model.s = {}
model.ds = {}
model.start_s = {}
if params.make_queryable_model then
model.dummy_output_grads = transfer_data(
torch.zeros(params.batch_size, params.vocab_size))
end
for j = 0, params.seq_length do
model.s[j] = {}
for d = 1, 2 * params.layers do
model.s[j][d] = transfer_data(
torch.zeros(params.batch_size, params.rnn_size))
end
end
for d = 1, 2 * params.layers do
model.start_s[d] = transfer_data(
torch.zeros(params.batch_size, params.rnn_size))
model.ds[d] = transfer_data(
torch.zeros(params.batch_size, params.rnn_size))
end
model.core_network = core_network
model.rnns = g_cloneManyTimes(core_network, params.seq_length)
model.norm_dw = 0
model.err = transfer_data(torch.zeros(params.seq_length))
set_model_info(core_network, model)
else
local core_network, model_buffers = get_model_info()
paramx, paramdx = core_network:getParameters()
model = model_buffers
model.rnns = g_cloneManyTimes(core_network, params.seq_length)
end
end
function reset_state(state)
state.pos = 1
if model ~= nil and model.start_s ~= nil then
for d = 1, 2 * params.layers do
model.start_s[d]:zero()
end
end
end
function reset_ds()
for d = 1, #model.ds do
model.ds[d]:zero()
end
end
function clear_model_context()
dummy_state = {}
reset_state(dummy_state)
reset_ds()
for j = 0, params.seq_length do
for d = 1, 2 * params.layers do
model.s[j][d]:zero()
end
end
end
function fp(state)
g_replace_table(model.s[0], model.start_s)
if state.pos + params.seq_length > state.data:size(1) then
reset_state(state)
end
for i = 1, params.seq_length do
local x = state.data[state.pos]
local y = state.data[state.pos + 1]
local s = model.s[i - 1]
model.err[i], model.s[i] = unpack(model.rnns[i]:forward({x, y, s}))
state.pos = state.pos + 1
end
g_replace_table(model.start_s, model.s[params.seq_length])
return model.err:mean()
end
function bp(state)
paramdx:zero()
reset_ds()
for i = params.seq_length, 1, -1 do
state.pos = state.pos - 1
local x = state.data[state.pos]
local y = state.data[state.pos + 1]
local s = model.s[i - 1]
local derr = transfer_data(torch.ones(1))
local tmp = {}
if not params.make_queryable_model then
tmp = model.rnns[i]:backward({x, y, s}, {derr, model.ds})[3]
else
tmp = model.rnns[i]:backward({x, y, s}, {derr, model.ds,
model.dummy_output_grads})[3]
end
g_replace_table(model.ds, tmp)
cutorch.synchronize()
end
state.pos = state.pos + params.seq_length
model.norm_dw = paramdx:norm()
--if params.use_default_opt then
if model.norm_dw > params.max_grad_norm then
local shrink_factor = params.max_grad_norm / model.norm_dw
paramdx:mul(shrink_factor)
end
--end
if params.use_default_opt then
paramx:add(paramdx:mul(-params.lr))
end
end
function run_valid()
reset_state(state_valid)
g_disable_dropout(model.rnns)
local len = (state_valid.data:size(1) - 1) / (params.seq_length)
local perp = 0
for i = 1, len do
perp = perp + fp(state_valid)
end
perp = perplexity(perp / len)
save_test_progress(perp)
print("Validation set perplexity: " .. g_f3(perp))
g_enable_dropout(model.rnns)
end
function run_test()
reset_state(state_test)
g_disable_dropout(model.rnns)
local perp = 0
local len = state_test.data:size(1)
g_replace_table(model.s[0], model.start_s)
for i = 1, (len - 1) do
local x = state_test.data[i]
local y = state_test.data[i + 1]
perp_tmp, model.s[1] = unpack(model.rnns[1]:forward({x, y, model.s[0]}))
perp = perp + perp_tmp[1]
g_replace_table(model.s[0], model.s[1])
end
print("Test set perplexity : " .. g_f3(perplexity(perp / (len - 1))))
g_enable_dropout(model.rnns)
end
--
-- Clear the context of the network, and do a pass over the first n - 1 words in
-- the sentence.
--
function process_new_sentence(indices)
input = torch.Tensor(#indices, 1):float()
for i = 1, #indices do
input[i][1] = indices[i]
end
input = input:expand(#indices, params.batch_size)
transfer_data(input)
local perp = 0
clear_model_context()
for i = 1, #indices - 1 do
local x = input[i]:cuda()
local y = input[i + 1]:cuda()
perp_tmp, model.s[1] = unpack(model.rnns[1]:forward({x, y, model.s[0]}))
perp = perp + perp_tmp[1]
g_replace_table(model.s[0], model.s[1])
end
end
--
-- After we have done a forward pass over the first n - 1 words of the sentence,
-- we can use this function to predict consecutive words.
--
function predict_next_word(indices)
input = torch.Tensor(params.batch_size):float():fill(indices[#indices]):cuda()
transfer_data(input)
perp_tmp, model.s[1], preds = unpack(model.rnns[1]:forward({input, input, model.s[0]}))
g_replace_table(model.s[0], model.s[1])
return preds[1]
end
--
-- This function should only be used with character-level models.
--
function predict_next_char(index)
input = torch.Tensor(params.batch_size):float():fill(index):cuda()
transfer_data(input)
perp_tmp, model.s[1], preds = unpack(model.rnns[1]:forward({input, input, model.s[0]}))
g_replace_table(model.s[0], model.s[1])
return preds[1]
end
if opt.task ~= "evaluate" then
print("Configuration parameters:")
print(params)
print("")
g_init_gpu("" .. opt.device)
print("Loading training data.")
state_train = {data = transfer_data(ptb.traindataset(params.batch_size))}
print("Loading validation data.")
state_valid = {data = transfer_data(ptb.validdataset(params.batch_size))}
--print("Loading testing data.")
--state_test = {data = transfer_data(ptb.testdataset(params.batch_size))}
--local states = {state_train, state_valid, state_test}
local states = {state_train, state_valid}
for _, state in pairs(states) do
reset_state(state)
end
setup()
train_info = get_train_info()
-- I don't serialize this information right now, because I don't want to deal
-- with updating times and counts based on prior values.
total_cases = 0
start_time = torch.tic()
epoch_size = torch.floor(state_train.data:size(1) / params.seq_length)
print("\nStarting epoch " .. train_info.epoch .. ".")
if not params.use_default_opt and not train_info.opt_method then
train_info.opt_method = sopt.adadelta
train_info.opt_state = {
learning_rate = sopt.constant(1),
momentum = sopt.constant(0.95),
momentum_type = sopt.none
}
objective = function(x)
if x ~= paramx then
paramx:copy(x)
end
local perp = fp(state_train)
if train_info.perps == nil then
train_info.perps = torch.zeros(epoch_size):add(perp)
end
train_info.perps[train_info.iter % epoch_size + 1] = perp
bp(state_train)
return perp, paramdx
end
end
while true do
if params.use_default_opt then
perp = fp(state_train)
if train_info.perps == nil then
train_info.perps = torch.zeros(epoch_size):add(perp)
end
train_info.perps[train_info.iter % epoch_size + 1] = perp
bp(state_train)
else
train_info.opt_method(objective, paramx, train_info.opt_state)
end
total_cases = total_cases + params.seq_length * params.batch_size
xlua.progress(train_info.iter % epoch_size + 1, epoch_size)
train_info.iter = train_info.iter + 1
if train_info.iter % torch.round(epoch_size / 10) == 10 then
wps = torch.floor(total_cases / torch.toc(start_time))
since_beginning = g_d(torch.toc(start_time) / 60)
perp = perplexity(train_info.perps:mean())
save_train_progress(perp)
print('epoch = ' .. g_f3(train_info.epoch) ..
', train perp. = ' .. g_f3(perp) ..
', wps = ' .. wps ..
', dw:norm() = ' .. g_f3(model.norm_dw) ..
', lr = ' .. params.lr ..
', since last restart = ' .. since_beginning .. ' mins.')
end
if train_info.iter % epoch_size == 0 then
run_valid()
train_info.epoch = train_info.epoch + 1
if params.use_default_opt and train_info.epoch > params.epochs_to_lr_decay then
params.lr = params.lr / params.decay
end
xlua.progress(epoch_size, epoch_size)
print("\nStarting epoch " .. train_info.epoch .. ".")
end
if train_info.iter % 33 == 0 then
cutorch.synchronize()
collectgarbage()
end
end
-- run_test()
-- print("Training is over.")
else
print("Configuration parameters:")
print(params)
print("")
g_init_gpu("" .. opt.device)
print("Loading training data.")
state_train = {data = transfer_data(ptb.traindataset(params.batch_size))}
print("Loading validation data.")
state_valid = {data = transfer_data(ptb.validdataset(params.batch_size))}
--print("Loading testing data.")
--state_test = {data = transfer_data(ptb.testdataset(params.batch_size))}
--local states = {state_train, state_valid, state_test}
local states = {state_train, state_valid}
for _, state in pairs(states) do
reset_state(state)
end
setup()
g_disable_dropout(model.rnns)
end
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('StoryBit', {
ActivationEffects = {},
Category = "Tick_BeforeFounders",
Effects = {},
EnableChance = 40,
Enabled = true,
Image = "UI/Messages/Events/03_discussion.tga",
Prerequisites = {},
ScriptDone = true,
Text = T(525807588817, --[[StoryBit Boost2_DigDeep Text]] "The data seems correct, but our equipment wasn't calibrated to detect the sites. You congratulate your colleague for the discovery and decide on a further course of action.\n\n<effect>You have discovered several new deposits near the colony."),
TextReadyForValidation = true,
TextsDone = true,
Title = T(252027768740, --[[StoryBit Boost2_DigDeep Title]] "Dig Deep"),
VoicedText = T(417309031546, --[[voice:narrator]] "One of our Scientists has just re-analyzed the scan data and found traces of resource deposits that you didn’t know existed."),
group = "Pre-Founder Stage",
id = "Boost2_DigDeep",
qa_info = PlaceObj('PresetQAInfo', {
data = {
{
action = "Modified",
time = 1549880229,
user = "Momchil",
},
{
action = "Modified",
time = 1549966361,
user = "Kmilushev",
},
{
action = "Verified",
time = 1549966939,
user = "Kmilushev",
},
{
action = "Verified",
time = 1550059384,
user = "Kmilushev",
},
{
action = "Modified",
time = 1550489063,
user = "Blizzard",
},
{
action = "Modified",
time = 1551175391,
user = "Momchil",
},
{
action = "Modified",
time = 1551274292,
user = "Radomir",
},
{
action = "Modified",
time = 1551965696,
user = "Radomir",
},
},
}),
PlaceObj('StoryBitReply', {
'Text', T(540767662028, --[[StoryBit Boost2_DigDeep Text]] "Correct the search patterns."),
'OutcomeText', "custom",
'CustomOutcomeText', T(968824402245, --[[StoryBit Boost2_DigDeep CustomOutcomeText]] "gain discount on the Deep Scanning tech"),
'Prerequisite', PlaceObj('IsCommander', {
'CommanderProfile', "astrogeologist",
'Negate', true,
}),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Effects', {
PlaceObj('SpawnSubsurfaceDeposits', {
'ResourceAmount', 5000000,
'DepthLayer', 2,
}),
PlaceObj('SpawnSubsurfaceDeposits', {
'Resource', "Water",
'ResourceAmount', 5000000,
'DepthLayer', 2,
}),
PlaceObj('RewardTechBoost', {
'Field', "Physics",
'Research', "DeepScanning",
'Amount', 50,
}),
},
}),
PlaceObj('StoryBitReply', {
'Text', T(494623791079, --[[StoryBit Boost2_DigDeep Text]] "Improve the drilling technology."),
'OutcomeText', "custom",
'CustomOutcomeText', T(818223058478, --[[StoryBit Boost2_DigDeep CustomOutcomeText]] "reveals Deep Water Extraction and Deep Metal Extraction tech"),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Effects', {
PlaceObj('SpawnSubsurfaceDeposits', {
'ResourceAmount', 5000000,
'DepthLayer', 2,
}),
PlaceObj('SpawnSubsurfaceDeposits', {
'Resource', "Water",
'ResourceAmount', 5000000,
'DepthLayer', 2,
}),
PlaceObj('DiscoverTech', {
'Field', "Physics",
'Tech', "DeepWaterExtraction",
}),
PlaceObj('DiscoverTech', {
'Field', "Physics",
'Tech', "DeepMetalExtraction",
}),
},
}),
PlaceObj('StoryBitReply', {
'Text', T(262277117951, --[[StoryBit Boost2_DigDeep Text]] "Immediately exploit the new deposits."),
'OutcomeText', "custom",
'CustomOutcomeText', T(297703279807, --[[StoryBit Boost2_DigDeep CustomOutcomeText]] "additional resources in all of the new deposits"),
}),
PlaceObj('StoryBitOutcome', {
'Prerequisites', {},
'Effects', {
PlaceObj('SpawnSubsurfaceDeposits', {
'ResourceAmount', 20000000,
'Grade', "Very High",
}),
PlaceObj('SpawnSubsurfaceDeposits', {
'Resource', "Water",
'ResourceAmount', 20000000,
'Grade', "Very High",
}),
},
}),
})
|
-- local dbg = require("debugger")
-- dbg.auto_where = 2
local chunk = require'tools.string'.chunk
local subject
local function set_subject(str, spos, epos)
subject = chunk(str, spos, epos)
end
local function assert_chunk_is(string, startpos, endpos, chunk)
local chunk = chunk or string
it("has the correct string", function()
assert.is_equal(string, subject.string())
end)
it("has the correct starting positiion", function()
assert.is_equal(startpos, subject.startpos())
end)
it("has the correct end position", function()
assert.is_equal(endpos, subject.endpos())
end)
it("has the correct chunk", function()
assert.is_equal(chunk, subject.chunk())
end)
it("has a nice representation", function()
assert.are.same({str = string, spos = startpos, epos = endpos, chunk = chunk}, subject:to_s())
end)
end
local function assert_parts(pfx, sfx)
local pfx = pfx or ""
local sfx = sfx or ""
it("has correct prefix", function()
assert.is_equal(pfx, subject.prefix())
end)
it("has correct suffix", function()
assert.is_equal(sfx, subject.suffix())
end)
end
describe("chunks", function()
describe("empty", function()
set_subject("")
assert_chunk_is("", 1, 0)
assert_parts()
end)
describe("default positions", function()
set_subject("subject")
assert_chunk_is("subject", 1, 7)
assert_parts()
it("hence replace replaces all", function()
assert.is_equal("new", subject.replace("new").string())
assert.is_equal("subject", subject.string())
end)
describe("delete", function()
local deleted = subject.delete().string()
set_subject(deleted)
assert_chunk_is("", 1, 0, "")
end)
end)
describe("parts", function()
set_subject("abcdef", 2, 4)
assert_chunk_is("abcdef", 2, 4, "bcd")
assert_parts("a", "ef")
end)
end)
|
-- Copyright (c) 2020 Kirazy
-- Part of Bob's Logistics Belt Reskin
--
-- See LICENSE.md in the project directory for license information.
-- Create belt particles
if data.raw["transport-belt"]["basic-transport-belt"] then
beltReskin.createParticles("basic")
end
if data.raw["transport-belt"]["turbo-transport-belt"] then
beltReskin.createParticles("turbo")
end
if data.raw["transport-belt"]["ultimate-transport-belt"] then
beltReskin.createParticles("ultimate")
end |
-- This information tells other players more about the mod
name = "Monster Healthbars"
description = "Healthbar for enemies"
author = "nlight"
version = "1.2d"
forumthread = ""
-- This lets other players know if your mod is out of date, update it to match the current version in the game
api_version = 6
api_version_dst = 10
dont_starve_compatible = true
reign_of_giants_compatible = true
shipwrecked_compatible = true
-- DST stuff
dst_compatible = true
all_clients_require_mod = false
client_only_mod = true
configuration_options = {
{
name = "HealthbarSize",
label = "Healthbar size",
options = {
{ description = "Extra small", data = "xs" },
{ description = "Small", data = "small" },
{ description = "Medium (default)", data = "med" },
{ description = "Large", data = "large" }
},
default = "med"
},
{
name = "WideHealthbar",
label = "Healthbar width",
options = {
{ description = "Normal (default)", data = false },
{ description = "Wide", data = true }
},
default = false
},
{
name = "FontSize",
label = "Font size",
options = {
{ description = "Extra small", data = "xs" },
{ description = "Small", data = "small" },
{ description = "Medium (default)", data = "med" },
{ description = "Large", data = "large" }
},
default = "med"
},
{
name = "ShowHealthText",
label = "Show health values",
options = {
{ description = "No", data = false },
{ description = "Yes", data = true }
},
default = false
},
{
name = "ShowTraitsText",
label = "Show traits text",
options = {
{ description = "No", data = false },
{ description = "Yes", data = true }
},
default = true
}
}
|
inspect = require 'lib.inspect'
GameState = require 'lib.hump.gamestate'
HumpCamera = require 'lib.hump.camera'
Vector = require 'lib.hump.vector'
class = require 'lib.hump.class'
Timer = require 'lib.hump.timer'
anim8 = require 'lib.anim8'
bump = require 'lib.bump'
tiny = require 'lib.tiny'
_ = require 'lib.underscore'
animation = require 'systems.animation'
player = require 'systems.player'
librarycard = require 'systems.librarycard'
book = require 'systems.book'
collision = require 'systems.collision'
enemy = require 'systems.enemy'
collection = require 'systems.collection'
wingame = require 'systems.wingame'
losegame = require 'systems.losegame'
title = require 'systems.title'
level_gui = require 'systems.level_gui'
TileLayerRenderer = require 'systems.renderers.tilelayer'
LevelLoader = require 'levelloader'
Camera = require 'camera'
ecs = tiny.world()
physics = bump.newWorld()
camera = true
pause = false
change_state = false
function switch_state(st, ...)
change_state = {}
change_state.state = st
change_state.args = {...}
end
function state_refresh()
ecs = tiny.world()
physics = bump.newWorld()
end
function level_state(lvlid)
tiny.addSystem(ecs, TileLayerRenderer)
tiny.addSystem(ecs, animation.renderer)
tiny.addSystem(ecs, animation.system)
tiny.addSystem(ecs, player.controller)
tiny.addSystem(ecs, player.system)
tiny.addSystem(ecs, librarycard.system)
tiny.addSystem(ecs, book.system)
tiny.addSystem(ecs, enemy.system)
tiny.addSystem(ecs, enemy.teenager.system)
tiny.addSystem(ecs, collision.system)
tiny.addSystem(ecs, level_gui.system)
LevelLoader.load_level(lvlid)
--initialize the proper systems
end
function game_win_state()
tiny.addSystem(ecs, animation.renderer)
tiny.addSystem(ecs, animation.system)
tiny.addSystem(ecs, wingame.system)
camera = HumpCamera()
camera:lookAt(320,200)
tiny.addEntity(ecs, wingame.new())
end
function game_over_state(lvlid)
tiny.addSystem(ecs, animation.renderer)
tiny.addSystem(ecs, animation.system)
tiny.addSystem(ecs, losegame.system)
camera = HumpCamera()
camera:lookAt(320, 200)
tiny.addEntity(ecs, losegame.new(lvlid))
end
function title_screen_state()
tiny.addSystem(ecs, animation.renderer)
tiny.addSystem(ecs, animation.system)
tiny.addSystem(ecs, title.system)
camera = HumpCamera()
camera:lookAt(320, 200)
tiny.addEntity(ecs, title.new())
end
function love.load()
ecs = tiny.world()
physics = bump.newWorld()
switch_state(title_screen_state)
end
function love.update(dt)
if change_state then
state_refresh()
change_state.state(unpack(change_state.args))
change_state=nil
end
if not pause then
Timer.update(dt)
if camera.update then
camera:update(dt)
end
tiny.update(ecs, dt, tiny.rejectAny('draw', 'keyboard'))
end
end
function love.draw()
camera:attach()
tiny.update(ecs, 0, tiny.requireAll('draw', 'with_camera'))
camera:detach()
tiny.update(ecs, 0, tiny.requireAll('draw', 'after_camera'))
end
function love.keypressed(key)
tiny.update(ecs, {key=key, isDown=true}, tiny.requireAll('keyboard'))
if key == 'escape' then
love.event.quit()
end
if key=='p' then
pause = not pause
end
end
function love.keyreleased(key)
tiny.update(ecs, {key=key, isDown=false}, tiny.requireAll('keyboard'))
end
|
-- the standard cubemap
plates = {
{ { 0, 0, 1 }, { 0, 1, 0 }, 90 }, -- front
{ { 1, 0, 0 }, { 0, 1, 0 }, 90 }, -- right
{ { -1, 0, 0 }, { 0, 1, 0 }, 90 }, -- left
{ { 0, 0, -1 }, { 0, 1, 0 }, 90 }, -- back
{ { 0, 1, 0 }, { 0, 0, -1 }, 90 }, -- top
{ { 0, -1, 0 }, { 0, 0, 1 }, 90 } -- bottom
}
|
return {
PlaceObj('ModItemCode', {
'name', "ExtractorAvailableDepositScript",
'FileName', "Code/ExtractorAvailableDepositScript.lua",
}),
}
|
credits.settings = {}
local set = credits.settings
--[[ See your `minetest.conf` file after first run to change these settings
credits.settings.interest_rate = 0.05 -- Equates to 5% per in-game day (Only executed once)
credits.settings.bal_refresh_rate = 3 -- Every 3 seconds, updates the HUD and checks if interest can be performed
credits.settings.starting_balance = 100 -- New players who the mod did not see before will get 100 credits on join
credits.settings.allow_replication = false -- Do we allow credits in item_replicators? (could be duped)
if credits.settings.allow_replication then
credits.settings.replication_time = 15 -- Seconds it takes...
credits.settings.replication_amount = 1 -- To produce this many
end
credits.settings.online_get_interest = true -- Do player's online get interest or does every account get interest
credits.settings.max_interest = 250 -- Limit the max credits a player can earn to this amount (this means regardless of their balance)
-- If online_get_interest then
-- For each player online do
-- credits_interest(player)
-- Else
-- For every player with an account do
-- credits_interest(player_account)
-- End
]]
set.interest_rate = minetest.settings:get("credits.interest_rate")
set.bal_refresh_rate = minetest.settings:get("credits.hud_refresh_rate")
set.starting_balance = minetest.settings:get("credits.starting_balance")
set.allow_replication = minetest.settings:get_bool("credits.allow_replication")
set.replication_time = minetest.settings:get("credits.replication_time")
set.replication_amount= minetest.settings:get("credits.replication_amount")
set.online_get_interest = minetest.settings:get_bool("credits.online_get_interest")
set.max_interest = minetest.settings:get("credits.max_interest")
-- Auto generate if they didn't exist
if set.interest_rate == nil then
set.interest_rate = 0.05
minetest.settings:set("credits.interest_rate", set.interest_rate)
else
set.interest_rate = tonumber(set.interest_rate)
end
if set.bal_refresh_rate == nil then
set.bal_refresh_rate = 3.0
minetest.settings:set("credits.hud_refresh_rate", set.bal_refresh_rate)
else
set.bal_refresh_rate = tonumber(set.bal_refresh_rate)
end
if set.starting_balance == nil then
set.starting_balance = 100
minetest.settings:set("credits.starting_balance", set.starting_balance)
else
set.starting_balance = tonumber(set.starting_balance)
end
if set.allow_replication == nil then
set.allow_replication = false
minetest.settings:set_bool("credits.allow_replication", set.allow_replication)
end
if set.replication_time == nil then
set.replication_time = 60
minetest.settings:set("credits.replication_time", set.replication_time)
else
set.replication_time = tonumber(set.replication_time)
end
if set.replication_amount == nil then
set.replication_amount = 1
minetest.settings:set("credits.replication_amount", set.replication_amount)
else
set.replication_amount = tonumber(set.replication_amount)
end
if set.online_get_interest == nil then
set.online_get_interest = true
minetest.settings:set_bool("credits.online_get_interest", set.online_get_interest)
end
if set.max_interest == nil then
set.max_interest = 250
minetest.settings:set("credits.max_interest", set.max_interest)
else
set.max_interest = tonumber(set.max_interest)
end
minetest.log("action", "[credits] credits.interest_rate = '"..tostring(set.interest_rate).."'")
minetest.log("action", "[credits] credits.hud_refresh_rate = '"..tostring(set.bal_refresh_rate).."'")
minetest.log("action", "[credits] credits.starting_balance = '"..tostring(set.starting_balance).."'")
minetest.log("action", "[credits] credits.allow_replication = '"..tostring(set.allow_replication).."'")
minetest.log("action", "[credits] credits.replication_time = '"..tostring(set.replication_time).."'")
minetest.log("action", "[credits] credits.replication_amount = '"..tostring(set.replication_amount).."'")
minetest.log("action", "[credits] credits.online_get_interest = '"..tostring(set.online_get_interest).."'")
minetest.log("action", "[credits] credits.max_interest = '"..tostring(set.max_interest).."'")
|
--[[
© 2018 Thriving Ventures AB do not share, re-distribute or modify
without permission of its author (gustaf@thrivingventures.com).
]]
local plugin = plugin
plugin.name = "MOTD"
plugin.author = "`impulse"
plugin.version = "1.0"
plugin.description = "An MOTD that is displayed when a player joins the server."
plugin.permissions = {"Manage MOTD"}
plugin.toggled = false
plugin.config = {
{
uniqueID = "Unlock Type",
description = "Changes how the MOTD closes",
default = "slider"
},
{
uniqueID = "URL",
description = "The website to load when opened",
default = ""
},
{
uniqueID = "Delay",
description = "How long you need to wait before you can close the MOTD",
default = 0
}
} |
--[[
Copyright (c) 2019 igor725, scaledteam
released under The MIT license http://opensource.org/licenses/MIT
]]
local survBlocknames = {
'Stone', 'Grass', 'Dirt', 'Cobblestone',
'Planks', 'Sapling', 'Bedrock', 'Water',
'Water', 'Lava', 'Lava', 'Sand', 'Gravel',
'Gold ore', 'Iron ore', 'Coal ore', 'Log',
'Leaves', 'Sponge', 'Glass', 'Red wool',
'Orange wool', 'Yellow wool', 'Lime wool',
'Green wool', 'Teal wool', 'Aqua wool',
'Cyan wool', 'Blue wool', 'Indigo wool',
'Violet wool', 'Magenta wool', 'Pink wool',
'Black wool', 'Gray wool', 'White wool',
'Dandelion', 'Rose', 'Brown mushroom',
'Red mushroom', 'Gold block', 'Iron block',
'Double slab', 'Slab', 'Brick', 'TNT',
'Bookshelf', 'Mossy stone', 'Obsidian',
'Cobblestone slab', 'Rope', 'Sandstone',
'Snow', 'Fire', 'Light pink wool',
'Forest green wool', 'Brown wool',
'Deep blue', 'Turquoise wool', 'Ice',
'Ceramic tile', 'Magma', 'Pillar',
'Crate', 'Stone brick'
}
function survAddBlockName(id, name)
survBlocknames[id] = name
end
function survGetBlockName(id)
return survBlocknames[id]
or BlockDefinitions:getOpt(id, 'name')
or'Unknown block'
end
|
local screenWidth, screenHeight = guiGetScreenSize()
local phi, theta = false, false
local elem = false
local distance = false
local height = false
local sin = math.sin
local cos = math.cos
local pi = math.pi
local rad = math.rad
local function scale(factor, baseX, baseY, baseZ, x, y, z)
return baseX + factor*(x-baseX), baseY + factor*(y-baseY), baseZ + factor*(z-baseZ)
end
local function onRender()
if not elem then
return
end
local x, y, z = getElementPosition(elem)
local camX = x + distance*cos(phi)*cos(theta)
local camY = y + distance*sin(phi)*cos(theta)
local camZ = z + 0.4*height + distance/1.5*sin(theta)
local camLookZ = z + 0.5*height
local hit, hitX, hitY, hitZ = processLineOfSight(x, y, camLookZ, camX, camY, camZ, true, false, false)
if hit then
camX, camY, camZ = scale(0.9, x, y, camLookZ, hitX, hitY, hitZ)
end
setCameraMatrix(camX, camY, camZ, x, y, camLookZ)
end
local function onMouseMove(relX, relY, absX, absY)
if isMTAWindowActive() then
return
end
absX = absX - screenWidth/2
absY = absY - screenHeight/2
phi = (phi - 0.005*absX) % (2*pi)
theta = theta + 0.005*absY
if theta > 0.4*pi then
theta = 0.4*pi
elseif theta < -0.4*pi then
theta = -0.4*pi
end
end
function setMouseLook(target, h, dist)
if target then
elem = target
distance = dist
height = h
local rX, rY, rZ = getElementRotation(elem)
phi = rad(rZ + 90 + 180)
theta = 0
addEventHandler('onClientCursorMove', getRootElement(), onMouseMove)
addEventHandler('onClientRender', getRootElement(), onRender)
else
elem = false
distance = false
height = false
removeEventHandler('onClientCursorMove', getRootElement(), onMouseMove)
removeEventHandler('onClientRender', getRootElement(), onRender)
end
end
|
return {'mexicaan','mexicaans','mexicaanse','mexico','mex','mexx','mexicanen','mex','mexx'} |
print("main.lua start")
BAD_REQUEST=400
OK=200
powersave_flag = false
print("load config.lua")
dofile("config")
print("sda", sda, "scl", scl)
print("load util.lua")
dofile("util.lua")
function init_display(disp)
disp:setFlipMode(1)
disp:clearBuffer()
disp:setContrast(255)
disp:setFontMode(0)
disp:setDrawColor(1)
disp:setBitmapMode(0)
disp:sendBuffer()
end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- MAIN
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print('init I2C')
i2c.setup(id,sda,scl,i2c.SLOW)
if (false) then
print('I2C Scan')
for i=0,127 do
i2c.start(id)
resCode = i2c.address(id, i, i2c.TRANSMITTER)
i2c.stop(id)
if resCode == true then
print("We have a device on address 0x" .. string.format("%02x", i) .. " (" .. i ..")")
end
end
end
print("init display 1")
disp1 = u8g2.sh1106_i2c_128x64_noname(id, i2c_addr_1)
init_display(disp1)
if (i2c_addr_2 == -1) then
disp2 = nil
else
print("init display 2")
disp2 = u8g2.sh1106_i2c_128x64_noname(id, i2c_addr_2)
init_display(disp2)
end
print('load utilDisplay.lua')
dofile('utilDisplay.lua')
print("HTTP server start")
dofile('httpServer.lua')
httpServer:listen(80)
print('mdns start hostname=' .. mdns_name)
mdns.register(mdns_name, { description="dumb_display", service="http", port=80, location='Living Room' })
print('load handler*.lua')
dofile('handleBatch.lua')
dofile('handleClear.lua')
dofile('handleString.lua')
dofile('handleBrightness.lua')
dofile('handlePowersave.lua')
dofile('handleExample.lua')
print('load displayDemo.lua')
dofile('displayDemo.lua')
print('initialize done.')
ip = wifi.sta.getip()
display_demo(disp1, "display1", ip)
display_demo(disp2, "display2", ip)
print('ready.')
|
psAir={
getGravity=function()
if player.vel.y<0 then
return 0.015
else
return 0.01
end
end,
update=function()
pAirUpdate(psAir.getGravity())
end,
checkTransition=function()
if (btnp(btnWhip)) return psWhip
if (pAirFrames<6 and btnp(btnJump)) return psJump
if (pAirFrames==0) sfx(33) return psGround
end
}
setmetatable(psAir,ps) |
--[[
Main entry point for the mod.
This file holds all general event handlers.
]]--
if not todo then
todo = {}
end
-- features
require("todo/features/add_task")
require("todo/features/delete_task")
require("todo/features/details_view")
require("todo/features/edit_task")
require("todo/features/export_task")
require("todo/features/import_task")
require("todo/features/main_ui")
require("todo/features/mark_complete")
require("todo/features/mark_open")
require("todo/features/sort_tasks")
require("todo/features/subtasks")
require("todo/features/take_task")
-- UIs
require("todo/ui/helper")
require("todo/ui/add_dialog")
require("todo/ui/edit_dialog")
require("todo/ui/edit_subtask_dialog")
require("todo/ui/export_dialog")
require("todo/ui/import_dialog")
require("todo/ui/main_frame")
-- convenience
require("todo/helper")
require("todo/logging")
todo.base64 = require("lib/base64")
function todo.mod_init()
todo.log("setting up mod data.")
if not global.todo then
global.todo = { ["open"] = {}, ["done"] = {}, ["settings"] = {} }
else
for _, task in ipairs(global.todo.open) do
todo.init_ensure_task_fields(task)
end
for _, task in ipairs(global.todo.done) do
todo.init_ensure_task_fields(task)
end
end
for _, player in pairs(game.players) do
todo.create_maximize_button(player)
end
-- If there is an old gui, remove it
for _, player in pairs(game.players) do
local flow = mod_gui.get_frame_flow(player)
if flow.todo_main_frame then
flow.todo_main_frame.destroy()
end
end
end
function todo.init_ensure_task_fields(task)
if not task.id then
task.id = todo.next_task_id()
end
if not task.title then
task.title = string.match(task.task, "[^\r\n]+")
end
end
function todo.on_gui_click(event)
local player = game.players[event.player_index]
local element = event.element
if (element.name == "todo_maximize_button") then
todo.on_maximize_button_click(player)
elseif (element.name == "todo_minimize_button") then
todo.minimize_main_frame(player)
elseif (element.name == "todo_open_add_dialog_button") then
todo.create_add_task_dialog(player)
elseif (element.name == "todo_save_new_task_button") then
todo.on_save_new_task_click(player)
elseif (element.name == "todo_add_cancel_button") then
todo.on_add_cancel_click(player)
elseif (string.find(element.name, "todo_take_task_button_")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_take_task_button_")
todo.on_take_task_click(player, id)
elseif (string.find(element.name, "todo_open_edit_dialog_button_")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_open_edit_dialog_button_")
todo.create_edit_task_dialog(player, id)
elseif (string.find(element.name, "todo_main_task_title_")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_task_title_")
todo.on_main_task_title_click(player, id, event.button)
elseif (string.find(element.name, "todo_edit_save_changes_button_")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_edit_save_changes_button_")
todo.on_edit_save_changes_click(player, id)
elseif (element.name == "todo_edit_cancel_button") then
todo.on_edit_cancel_click(player)
elseif (string.find(element.name, "todo_edit_delete_button")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_edit_delete_button_")
todo.create_delete_confirmation_button(player, element, id)
elseif (string.find(element.name, "todo_edit_confirm_deletion_button")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_edit_confirm_deletion_button_")
todo.on_edit_confirm_delete_click(player, id)
elseif (string.find(element.name, "todo_main_task_mark_complete_checkbox_")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_task_mark_complete_checkbox_")
todo.on_mark_complete_click(id)
elseif (string.find(element.name, "todo_main_task_mark_open_checkbox_")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_task_mark_open_checkbox_")
todo.on_mark_open_click(id)
elseif (element.name == "todo_toggle_show_completed_button") then
todo.on_toggle_show_completed_click(player)
elseif (string.find(element.name, "todo_main_task_move_up")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_task_move_up_")
todo.on_main_move_up_click(id)
elseif (string.find(element.name, "todo_main_task_move_down")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_task_move_down_")
todo.on_main_move_down_click(id)
elseif (string.find(element.name, "todo_main_task_move_top")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_task_move_top_")
todo.on_main_move_top_click(id)
elseif (string.find(element.name, "todo_main_task_move_bottom")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_task_move_bottom_")
todo.on_main_move_bottom_click(id)
elseif (element.name == "todo_main_open_export_dialog_button") then
todo.create_export_dialog(player)
elseif (element.name == "todo_export_generate_export_string_button") then
todo.generate_and_show_export_string(player)
elseif (element.name == "todo_export_cancel_button") then
todo.on_export_cancel_click(player)
elseif (element.name == "todo_main_open_import_dialog_button") then
todo.create_import_dialog(player)
elseif (element.name == "todo_import_import_tasks_button") then
todo.on_import_tasks_click(player)
elseif (element.name == "todo_import_cancel_button") then
todo.on_import_cancel_click(player)
elseif (string.find(element.name, "todo_main_open_details_button_")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_open_details_button_")
todo.on_show_task_details_click(player, id)
elseif (string.find(element.name, "todo_main_close_details_button_")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_close_details_button_")
todo.on_hide_task_details_click(player, id)
elseif (string.find(element.name, "todo_main_subtask_save_new_button_")) then
local id = todo.get_task_id_from_element_name(element.name, "todo_main_subtask_save_new_button_")
todo.on_save_new_subtask_click(player, id)
elseif (string.find(element.name, "todo_main_subtask_edit_button_")) then
local task_id, subtask_id = todo.get_task_id_from_element_name(element.name, "todo_main_subtask_edit_button_")
todo.on_edit_subtask_click(player, task_id, subtask_id)
elseif (element.name == "todo_edit_subtask_cancel_button") then
todo.on_edit_subtask_cancel_click(player)
elseif (string.find(element.name, "todo_edit_subtask_save_button_")) then
local task_id, subtask_id = todo.get_task_id_from_element_name(element.name, "todo_edit_subtask_save_button_")
todo.on_edit_subtask_save_click(player, task_id, subtask_id)
elseif (string.find(element.name, "todo_main_subtask_checkbox_")) then
local task_id, subtask_id = todo.get_task_id_from_element_name(element.name, "todo_main_subtask_checkbox_")
todo.on_subtask_checkbox_click(task_id, subtask_id)
elseif (string.find(element.name, "todo_main_subtask_move_up_")) then
local task_id, subtask_id = todo.get_task_id_from_element_name(element.name, "todo_main_subtask_move_up_")
todo.on_main_subtask_move_up_click(task_id, subtask_id)
elseif (string.find(element.name, "todo_main_subtask_move_down_")) then
local task_id, subtask_id = todo.get_task_id_from_element_name(element.name, "todo_main_subtask_move_down_")
todo.on_main_subtask_move_down_click(task_id, subtask_id)
elseif (string.find(element.name, "todo_main_subtask_delete_button_")) then
local task_id, subtask_id = todo.get_task_id_from_element_name(element.name, "todo_main_subtask_delete_button_")
todo.on_subtask_delete_click(task_id, subtask_id)
elseif (string.find(element.name, "todo_")) then
todo.log("Unknown todo element name:" .. element.name)
end
end
function todo.on_lua_shortcut(event)
local player = game.players[event.player_index]
if (event.prototype_name == "todo-toggle-ui-shortcut") then
todo.toggle_main_frame(player)
elseif (event.prototype_name == "todo-add-task-shortcut") then
todo.create_add_task_dialog(player)
end
end
function todo.on_runtime_mod_setting_changed(player, key)
if (key == "todolist-show-button") then
todo.on_show_maximize_button_changed(player)
elseif (key == "todolist-show-log") then
todo.log("Updated logging settings for player " .. player.name)
elseif (key == "todolist-auto-assign") then
todo.log("Changed auto-assign...")
elseif (key == "todolist-click-edit-task") then
todo.log("Changed button click to open edit frame...")
elseif (key == "todolist-translation-mode") then
-- automatically redraw main frame on mode change
todo.toggle_main_frame(player)
todo.toggle_main_frame(player)
end
end
-- TODO: is this the right place?
function todo.on_show_maximize_button_changed(player)
if todo.should_show_maximize_button(player) then
todo.log("Showing minimized button.")
if not todo.get_maximize_button(player) then
todo.create_maximize_button(player)
end
else
todo.log("Hiding minimized button.")
local max_button = todo.get_maximize_button(player)
if max_button then
max_button.destroy()
end
end
end
|
---------------------
-- Local variables --
---------------------
local g_Wnd, g_Anim, g_Visible
local g_PosX, g_PosY = g_ScreenSize[1] - 260, (g_ScreenSize[2] - 280)/2
local g_Width = 250
local g_StatsView
--------------------------------
-- Local function definitions --
--------------------------------
local function SpInitGui()
local h = StatsView.getHeight() + 30
g_Wnd = guiCreateWindow(g_ScreenSize[1] + g_Width, g_PosY, g_Width, h, "Statistics", false)
guiSetAlpha(g_Wnd, 0.8)
guiSetVisible(g_Wnd, false)
g_StatsView = StatsView.create(g_SharedState.accountId or g_Me, g_Wnd, 10, 25, g_Width - 20, h - 35)
end
local function onAccountChange()
if(g_StatsView) then
g_StatsView:changeTarget(g_SharedState.accountId or g_Me)
end
end
local function SpInit()
addEventHandler('main.onAccountChange', g_ResRoot, onAccountChange)
addCommandHandler('StatsPanel', SpToggle, false, false)
local key = getKeyBoundToCommand('StatsPanel') or 'F1'
bindKey(key, 'down', 'StatsPanel')
-- Me: 270, RoadRunner: 225
--Debug.info('Height def-normal '..GUI.getFontHeight('default-normal')..' def-small '..GUI.getFontHeight('default-small')..' def-bold-small '..GUI.getFontHeight('default-bold-small')..' clear-norm '..GUI.getFontHeight('clear-normal')..' sa-hdr '..GUI.getFontHeight('sa-header'))
end
----------------------
-- Global functions --
----------------------
function SpToggle()
if(not g_Wnd) then
SpInitGui()
end
if(g_Anim) then
g_Anim:remove()
end
if(g_Visible) then -- hide panel
g_Anim = Animation.createAndPlay(g_Wnd,
Animation.presets.guiMoveEx(g_ScreenSize[1] + g_Width, g_PosY, 500, 'InQuad'),
Animation.presets.guiSetVisible(false))
g_StatsView:hide()
else -- show panel
guiSetVisible(g_Wnd, true)
g_Anim = Animation.createAndPlay(g_Wnd, Animation.presets.guiMoveEx(g_PosX, g_PosY, 500, 'InOutQuad'))
g_StatsView:show()
AchvActivate('Open Statistics Panel')
end
g_Visible = not g_Visible
end
addInitFunc(SpInit)
|
local keyboard = libs.keyboard;
--@help Lower volume
actions.volume_down = function()
toast();
keyboard.stroke("down");
end
--@help Raise volume
actions.volume_up = function()
toast();
keyboard.stroke("up");
end
--@help Rewind
actions.rewind = function()
keyboard.stroke("left");
end
--@help Fast forward
actions.fast_forward = function()
keyboard.stroke("right");
end
--@help Toggle fullscreen
actions.fullscreen = function()
keyboard.stroke("F");
end
--@help Exit fullscreen
actions.exit_fullscreen = function()
keyboard.stroke("esc");
end
--@help Toggle play/pause
actions.play_pause = function()
keyboard.stroke("space");
end
|
--[[
Modefied version of Direwolf20`s button API
http://pastebin.com/cK9wnj7X
]]
local mon = peripheral.wrap("right")
local button = {}
mon.setTextScale(1)
mon.setTextColor(colors.white)
mon.setBackgroundColor(colors.black)
function setTable(name, func, arg, xmin, xmax, ymin, ymax)
button[name] = {}
button[name]["func"] = func
button[name]["active"] = false
button[name]["arg"] = arg
button[name]["xmin"] = xmin
button[name]["ymin"] = ymin
button[name]["xmax"] = xmax
button[name]["ymax"] = ymax
end
--[[
function funcName()
print("You clicked buttonText")
end
function fillTable()
setTable("ButtonText", funcName, 5, 25, 4, 8)
end
]]
function clearTable()
button = {}
end
function screen()
local BColor
for name,data in pairs(button) do
if data["active"] == true then BColor = colors.lime else BColor = colors.red end
mon.setBackgroundColor(BColor)
local yspot = math.floor((data["ymin"] + data["ymax"]) /2)
local xspot = math.floor((data["xmax"] - data["xmin"] - string.len(name)) /2) +1
for j = data["ymin"], data["ymax"] do
mon.setCursorPos(data["xmin"], j)
if j == yspot then
for k = 0, data["xmax"] - data["xmin"] - string.len(name) +1 do
if k == xspot then mon.write(name) else mon.write(" ") end
end
else
for i = data["xmin"], data["xmax"] do
mon.write(" ")
end
end
end
mon.setBackgroundColor(colors.black)
end
end
function toggleButton(name)
button[name]["active"] = not button[name]["active"]
screen()
end
function flash(name)
toggleButton(name)
screen()
sleep(0.15)
toggleButton(name)
screen()
end
function checkxy(x, y)
for name, data in pairs(button) do
if y>=data["ymin"] and y <= data["ymax"] then
if x>=data["xmin"] and x<= data["xmax"] then
if data["arg"] == "" then
data["func"]()
else
data["func"](data["arg"])
end
return true
--print(name)
end
end
end
return false
end
function heading(text)
w, h = mon.getSize()
mon.setCursorPos((w-string.len(text))/2+1, 1)
mon.write(text)
end
function label(w, h, text)
mon.setCursorPos(w, h)
mon.write(text)
end |
--- 模块功能:Lua补丁
-- @module patch
-- @author openLuat
-- @license MIT
-- @copyright openLuat
-- @release 2017.10.21
require"pm"
module(..., package.seeall)
--[[
模块名称:Lua自带接口补丁
模块功能:补丁某些Lua自带的接口,规避调用异常时死机
模块最后修改时间:2017.02.14
]]
--保存Lua自带的os.time接口
local oldostime = os.time
--[[
函数名:safeostime
功能 :封装自定义的os.time接口
参数 :
t:日期表,如果没有传入,使用系统当前时间
返回值:t时间距离1970年1月1日0时0分0秒所经过的秒数
]]
function safeostime(t)
return oldostime(t) or 0
end
--Lua自带的os.time接口指向自定义的safeostime接口
os.time = safeostime
--保存Lua自带的os.date接口
local oldosdate = os.date
--[[
函数名:safeosdate
功能 :封装自定义的os.date接口
参数 :
s:输出格式
t:距离1970年1月1日0时0分0秒所经过的秒数
返回值:参考Lua自带的os.date接口说明
]]
function safeosdate(s, t)
if s == "*t" then
return oldosdate(s, t) or {year = 2012,
month = 12,
day = 11,
hour = 10,
min = 9,
sec = 0}
else
return oldosdate(s, t)
end
end
--Lua自带的os.date接口指向自定义的safeosdate接口
os.date = safeosdate
-- 对coroutine.resume加一个修饰器用于捕获协程错误
local rawcoresume = coroutine.resume
coroutine.resume = function(...)
local arg = { ... }
function wrapper(co,...)
local arg = { ... }
if not arg[1] then
local traceBack = debug.traceback(co) or "empty"
traceBack = (traceBack and traceBack~="") and ((arg[2] or "").."\r\n"..traceBack) or (arg[2] or "")
log.error("coroutine.resume",traceBack)
if errDump and type(errDump.appendErr)=="function" then
errDump.appendErr(traceBack)
end
if _G.COROUTINE_ERROR_RESTART then rtos.restart() end
end
return unpack(arg)
end
return wrapper(arg[1],rawcoresume(...))
end
os.clockms = function() return rtos.tick()/16 end
--保存Lua自带的json.decode接口
if json and json.decode then oldjsondecode = json.decode end
--- 封装自定义的json.decode接口
-- @string s,json格式的字符串
-- @return table,第一个返回值为解析json字符串后的table
-- @return boole,第二个返回值为解析结果(true表示成功,false失败)
-- @return string,第三个返回值可选(只有第二个返回值为false时,才有意义),表示出错信息
local function safeJsonDecode(s)
local result, info = pcall(oldjsondecode, s)
if result then
return info, true
else
return {}, false, info
end
end
--Lua自带的json.decode接口指向自定义的safeJsonDecode接口
if json and json.decode then json.decode = safeJsonDecode end
local oldUartWrite = uart.write
uart.write = function(...)
pm.wake("lib.patch.uart.write")
local result = oldUartWrite(...)
pm.sleep("lib.patch.uart.write")
return result
end
if i2c and i2c.write then
local oldI2cWrite = i2c.write
i2c.write = function(...)
pm.wake("lib.patch.i2c.write")
local result = oldI2cWrite(...)
pm.sleep("lib.patch.i2c.write")
return result
end
end
if i2c and i2c.send then
local oldI2cSend = i2c.send
i2c.send = function(...)
pm.wake("lib.patch.i2c.send")
local result = oldI2cSend(...)
pm.sleep("lib.patch.i2c.send")
return result
end
end
if spi and spi.send then
oldSpiSend = spi.send
spi.send = function(...)
pm.wake("lib.patch.spi.send")
local result = oldSpiSend(...)
pm.sleep("lib.patch.spi.send")
return result
end
end
if spi and spi.send_recv then
oldSpiSendRecv = spi.send_recv
spi.send_recv = function(...)
pm.wake("lib.patch.spi.send_recv")
local result = oldSpiSendRecv(...)
pm.sleep("lib.patch.spi.send_recv")
return result
end
end
|
local ca_pass = {}
function ca_pass:evaluation()
return 999980
end
function ca_pass:execution(cfg, data)
end
return ca_pass |
function mobs.on_step(self,dtime)
if self.type == "monster" and minetest.setting_getbool("only_peaceful_mobs") then
self.object:remove()
return
end
if self.lifetimer ~= false then
self.lifetimer = self.lifetimer - dtime
if self.lifetimer <= 0 and not self.tamed and self.type ~= "npc" then
local player_count = 0
for _,obj in ipairs(minetest.get_objects_inside_radius(self.object:getpos(), 10)) do
if obj:is_player() then
player_count = player_count+1
end
end
if player_count == 0 and self.state ~= "attack" then
minetest.log("action","lifetimer expired, removed mob "..self.name)
self.object:remove()
return
end
end
end
if self.object:getvelocity().y > 0.1 then
local yaw = self.object:getyaw()
if self.drawtype == "side" then
yaw = yaw+(math.pi/2)
end
local x = math.sin(yaw) * -2
local z = math.cos(yaw) * 2
self.object:setacceleration({x=x, y=-10, z=z})
else
self.object:setacceleration({x=0, y=-10, z=0})
end
if self.disable_fall_damage and self.object:getvelocity().y == 0 then
if not self.old_y then
self.old_y = self.object:getpos().y
else
local d = self.old_y - self.object:getpos().y
if d > 5 then
local damage = d-5
self.object:set_hp(self.object:get_hp()-damage)
if self.object:get_hp() == 0 then
self.object:remove()
end
end
self.old_y = self.object:getpos().y
end
end
-- if pause state then this is where the loop ends
-- pause is only set after a monster is hit
if self.pause_timer > 0 then
self.pause_timer = self.pause_timer - dtime
if self.pause_timer <= 0 then
self.pause_timer = 0
end
return
end
self.timer = self.timer+dtime
if self.state ~= "attack" then
if self.timer < 1 then
return
end
self.timer = 0
end
if self.sounds and self.sounds.random and self.state ~= "attack" then
if randomChance(self.random_freq) then
if ( self.type == "npc" and randomChance(65) ) or self.type ~= "npc" then
local maxhear = 50
local g = 1
if self.type == "npc" then
maxhear = 20
g = 0.7
end
minetest.sound_play(self.sounds.random, {object = self.object, max_hear_distance=maxhear, gain=g})
end
end
end
local do_env_damage = function(self)
local pos = self.object:getpos()
local n = minetest.get_node(pos)
if self.light_damage and self.light_damage ~= 0
and pos.y>0
and minetest.get_node_light(pos)
and minetest.get_node_light(pos) > 4
and minetest.get_timeofday() > 0.2
and minetest.get_timeofday() < 0.8
then
self.object:set_hp(self.object:get_hp()-self.light_damage)
if self.object:get_hp() == 0 then
self.object:remove()
end
end
if self.water_damage and self.water_damage ~= 0 and
minetest.get_item_group(n.name, "water") ~= 0
then
self.object:set_hp(self.object:get_hp()-self.water_damage)
if self.object:get_hp() == 0 then
self.object:remove()
end
end
if self.lava_damage and self.lava_damage ~= 0 and
minetest.get_item_group(n.name, "lava") ~= 0
then
self.object:set_hp(self.object:get_hp()-self.lava_damage)
if self.object:get_hp() == 0 then
self.object:remove()
end
end
end
self.env_damage_timer = self.env_damage_timer + dtime
if self.state == "attack" and self.env_damage_timer > 1 then
self.env_damage_timer = 0
do_env_damage(self)
elseif self.state ~= "attack" then
do_env_damage(self)
end
self:do_avoidance()
-- if they are attacking that should take priority over everything else so move it up here
if self.state == "attack" and self.attack_type == "dogfight" then
if not self.attack.player or not self.attack.player:getpos() then
self.state = "stand"
self:set_animation("stand")
return
end
local s = self.object:getpos()
local p = self.attack.player:getpos()
local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
if dist > self.view_range or self.attack.player:get_hp() <= 0 then
self.state = "stand"
self.v_start = false
self.set_velocity(self, 0)
self.attack = {player=nil, dist=nil}
self:set_animation("stand")
return
else
self.attack.dist = dist
end
local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z}
local yaw = math.atan(vec.z/vec.x)+math.pi/2
if self.drawtype == "side" then
yaw = yaw+(math.pi/2)
end
if p.x > s.x then
yaw = yaw+math.pi
end
self.object:setyaw(yaw)
if self.attack.dist > self.attack_range then
if not self.v_start then
self.v_start = true
self.set_velocity(self, self.run_velocity)
else
if self.jump == true and self.get_velocity(self) <= 0.5 and self.object:getvelocity().y == 0 then
local v = self.object:getvelocity()
v.y = 7
self.object:setvelocity(v)
end
self.set_velocity(self, self.run_velocity)
end
self:set_animation("run")
else
self.set_velocity(self, 0)
self:set_animation("punch")
self.v_start = false
if self.timer > 1 then
self.timer = 0
local p2 = p
local s2 = s
p2.y = p2.y + 1.5
s2.y = s2.y + 1.5
if minetest.line_of_sight(p2,s2) == true then
if self.sounds and self.sounds.attack then
minetest.sound_play(self.sounds.attack, {object = self.object})
end
if self.attack_function ~= nil then
self.attack_function(self,self.attack.player)
else
self.attack.player:punch(self.object, 1.0, {
full_punch_interval=1.0,
damage_groups = {fleshy=self.damage}
}, vec)
end
if self.attack.player:get_hp() <= 0 then
self.state = "stand"
self.v_start = false
self.set_velocity(self, 0)
self.attack = {player=nil, dist=nil}
self:set_animation("stand")
end
end
end
end
return
elseif self.state == "attack" and self.attack_type == "shoot" then
if not self.attack.player or not self.attack.player:is_player() then
self.state = "stand"
self:set_animation("stand")
return
end
local s = self.object:getpos()
local p = self.attack.player:getpos()
p.y = p.y - .5
s.y = s.y + .5
local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
if dist > self.view_range or self.attack.player:get_hp() <= 0 then
self.state = "stand"
self.v_start = false
self.set_velocity(self, 0)
if self.type ~= "npc" then
self.attack = {player=nil, dist=nil}
end
self:set_animation("stand")
return
else
self.attack.dist = dist
end
local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z}
local yaw = math.atan(vec.z/vec.x)+math.pi/2
if self.drawtype == "side" then
yaw = yaw+(math.pi/2)
end
if p.x > s.x then
yaw = yaw+math.pi
end
self.object:setyaw(yaw)
self.set_velocity(self, 0)
if self.timer > self.shoot_interval and math.random(1, 100) <= 60 then
self.timer = 0
self:set_animation("punch")
if self.sounds and self.sounds.attack then
minetest.sound_play(self.sounds.attack, {object = self.object})
end
local p = self.object:getpos()
p.y = p.y + self.arrow_offset
local obj = minetest.add_entity(p, self.arrow)
local amount = (vec.x^2+vec.y^2+vec.z^2)^0.5
local v = obj:get_luaentity().velocity
vec.y = vec.y
vec.x = vec.x*v/amount
vec.y = vec.y*v/amount
vec.z = vec.z*v/amount
obj:setvelocity(vec)
if obj:get_luaentity().drop_rate ~= nil then
obj:setacceleration({x=vec.x, y=obj:get_luaentity().drop_rate, z=vec.z})
end
end
return
end
-- FIND SOMEONE TO ATTACK
if ( self.type == "monster" or self.type == "barbarian" ) and minetest.setting_getbool("enable_damage") and self.state ~= "attack" then
if mobs.api_throttling(self) then return end
local s = self.object:getpos()
local inradius = minetest.get_objects_inside_radius(s,self.view_range)
local player = nil
local type = nil
for _,oir in ipairs(inradius) do
if oir:is_player() then
player = oir
type = "player"
else
local obj = oir:get_luaentity()
if obj then
player = obj.object
type = obj.type
end
end
if type == "player" or type == "npc" then
local s = self.object:getpos()
local p = player:getpos()
local sp = s
p.y = p.y + 1
sp.y = sp.y + 1 -- aim higher to make looking up hills more realistic
local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
--print("Dist "..tostring(dist) .. " < " .. tostring(self.view_range) .. " in_fov " .. tostring(self.in_fov(self,p)))
if dist < self.view_range and self.in_fov(self,p) then
if minetest.line_of_sight(sp,p,2) == true then
self.do_attack(self,player,dist)
break
else
--print("no line of site")
end
end
end
end
end
-- NPC FIND A MONSTER TO ATTACK
if self.type == "npc" and self.attacks_monsters and self.state ~= "attack" then
if mobs.api_throttling(self) then return end
local s = self.object:getpos()
local inradius = minetest.get_objects_inside_radius(s,self.view_range)
for _, oir in pairs(inradius) do
local obj = oir:get_luaentity()
if obj then
if obj.type == "monster" or obj.type == "barbarian" then
-- attack monster
local p = obj.object:getpos()
local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
self.do_attack(self,obj.object,dist)
break
end
end
end
end
if self.follow ~= nil and not self.following then
if mobs.api_throttling(self) then return end
for _,player in pairs(minetest.get_connected_players()) do
local s = self.object:getpos()
local p = player:getpos()
local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
if self.view_range and dist < self.view_range then
self.following = player
break
end
end
end
if self.following and self.following:is_player() then
if self.following:get_wielded_item():get_name() ~= self.follow then
self.following = nil
else
local s = self.object:getpos()
local p = self.following:getpos()
local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
if dist > self.view_range then
self.following = nil
self.v_start = false
else
local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z}
local yaw = math.atan(vec.z/vec.x)+math.pi/2
if self.drawtype == "side" then
yaw = yaw+(math.pi/2)
end
if p.x > s.x then
yaw = yaw+math.pi
end
self.object:setyaw(yaw)
if dist > 2 then
if not self.v_start then
self.v_start = true
self.set_velocity(self, self.walk_velocity)
else
if self.jump == true and self.get_velocity(self) <= 1.5 and self.object:getvelocity().y == 0 then
local v = self.object:getvelocity()
v.y = 6
self.object:setvelocity(v)
end
self.set_velocity(self, self.walk_velocity)
end
self:set_animation("walk")
else
self.v_start = false
self.set_velocity(self, 0)
self:set_animation("stand")
end
return
end
end
end
if self.state == "stand" then
-- randomly turn
math.randomseed(os.clock())
if math.random(1, 100) < self.activity_level then
if mobs.api_throttling(self) then return end
-- if there is a player nearby look at them
local lp = nil
local s = self.object:getpos()
if self.type == "npc" then
local o = minetest.get_objects_inside_radius(self.object:getpos(), 3)
local yaw = 0
for _,o in ipairs(o) do
if o:is_player() then
lp = o:getpos()
break
end
end
end
if lp ~= nil then
mobs:face_pos(self,lp)
else
local yaw = self.object:getyaw()+((math.random(0,360)-270)/180*math.pi)
self.object:setyaw(yaw)
end
end
self.set_velocity(self, 0)
self.set_animation(self, "stand")
if math.random(1, 100) <= self.activity_level and self.stationary == false then
self.set_velocity(self, self.walk_velocity)
self.state = "walk"
self.set_animation(self, "walk")
end
elseif self.state == "walk" or self.state == "path" then
if ( math.random(1, 100) <= 30 or ( self.get_velocity(self) < self.walk_velocity ) ) and self.state ~= "path" then
self.object:setyaw(self.object:getyaw()+((math.random(0,360)-270)/180*math.pi))
end
if self.jump == true and self.get_velocity(self) <= 0.5 and self.object:getvelocity().y == 0 then
local v = self.object:getvelocity()
v.y = 5
self.object:setvelocity(v)
end
self:set_animation("walk")
self.set_velocity(self, self.walk_velocity)
if math.random(1, 100) <= 30 and self.state ~= "path" then
self.set_velocity(self, 0)
self.state = "stand"
self:set_animation("stand")
end
if self.state == "path" then
self.leg_timer = self.leg_timer + dtime
self.check_path(self)
end
end
end
|
function torch.find(tensor, val, dim)
local i = 1
local indice = {}
if dim then
assert(tensor:dim() == 2, "torch.find dim arg only supports matrices for now")
assert(dim == 2, "torch.find only supports dim=2 for now")
local colSize, rowSize = tensor:size(1), tensor:size(2)
local rowIndice = {}
tensor:apply(function(x)
if x == val then
table.insert(rowIndice, i)
end
if i == rowSize then
i = 1
table.insert(indice, rowIndice)
rowIndice = {}
else
i = i + 1
end
end)
else
tensor:apply(function(x)
if x == val then
table.insert(indice, i)
end
i = i + 1
end)
end
return indice
end
|
ENT.Type = "ai"
ENT.Base = "base_ai"
ENT.PrintName = "Prison Warden"
ENT.Author = "Owain Owjo"
ENT.Category = "The XYZ Network Custom Stuff"
ENT.Spawnable = true
ENT.AdminSpawnable = true
|
local colors = require('colors')
local os = require('os')
local c = require('component')
local noop = function() end
local setPal = c and c.gpu and c.gpu.setPaletteColor or noop
if not setPal then
printError('Error: 99_color_palette.lua is unable to find the current gpu')
os.sleep(4)
end
-- Monokai theme
setPal(colors.white, 0xF8F8F2)
setPal(colors.black, 0x272822)
setPal(colors.yellow, 0xE6DB74)
setPal(colors.pink, 0xF92672)
setPal(colors.gray, 0x75715E)
setPal(colors.silver, 0x90908A)
setPal(colors.cyan, 0x66D9EF)
setPal(colors.purple, 0xAE81FF)
-- Basic other colors
setPal(colors.green, 0x00DB00)
setPal(colors.blue, 0x0049FF)
setPal(colors.lightblue, 0x0092FF)
setPal(colors.magenta, 0xFF24FF)
setPal(colors.orange, 0xFF6D00)
setPal(colors.lime, 0x00FF80)
setPal(colors.red, 0xFF0000)
setPal(colors.brown, 0x332400)
|
class("MapInstance" , MapEditor)
-- I borrowed this code from an ancient version of Racing, which was borrowed from when I was new at
-- Lua and playing around with tables. Let's hope me from 2 years ago wasn't an idiot.
MapEditor.MapInstance.CopyTable = function(t , copiedTables)
-- this will be returned as the copied table
local tCopy = {}
-- helps with tables that reference other tables
-- that reference the fist table, etc
-- key = old table that has been copied
-- value new table
if not copiedTables then copiedTables = {} end
copiedTables[t] = tCopy
for key , value in pairs(t) do
if type(value) == "table" then
if copiedTables[value] then
tCopy[key] = copiedTables[value]
else
tCopy[key] = MapEditor.MapInstance.CopyTable(value , copiedTables)
end
else
tCopy[key] = value
end
end
return tCopy
end
function MapEditor.MapInstance:__init(map)
self.map = map
-- Copy objects map to a more convenient type-to-object-array map.
-- Key: object type
-- Value: array of objects (with any object-type properties replaced with object ids)
self.objectTypeToObjects = {}
for prettySureThisIsNeverActuallyTheObjectId , object in pairs(self.map.objects) do
if self.objectTypeToObjects[object.type] == nil then
self.objectTypeToObjects[object.type] = {}
end
-- Eeeeuuuuuuurrrrrggghhh
-- Deep copy the object and change any object properties to use the object id instead. So it's
-- reverting part of the work of MapEditor.LoadFromMarshalledMap, but I don't know a nice way
-- of keeping the old data or something.
local copiedObject = self.CopyTable(object)
for propertyName , propertyValue in ipairs(copiedObject.properties) do
if type(propertyValue) == "table" then
if propertyValue.id ~= nil then
-- This property is an Object.
copiedObject.properties[propertyName] = propertyValue.id
elseif #propertyValue > 0 and propertyValue[1].id ~= nil then
-- This property is a table of Objects.
for index , object in ipairs(propertyValue) do
propertyValue[index] = object.id
end
end
end
end
-- Fix for Angle inaccuracy when sent to clients.
local a = copiedObject.angle
copiedObject.angle = {a.x , a.y , a.z , a.w}
table.insert(self.objectTypeToObjects[object.type] , copiedObject)
end
self.clientObjects = {}
for objectType , objects in pairs(self.objectTypeToObjects) do
if objects[1].isClientSide then
for index , object in ipairs(objects) do
table.insert(self.clientObjects , object)
end
end
end
self.players = {}
end
function MapEditor.MapInstance:Destroy()
-- Remove all of our players.
for index , player in ipairs(self.players) do
self:RemovePlayer(player)
end
end
function MapEditor.MapInstance:AddPlayer(player)
table.insert(self.players , player)
Network:Send(player , "InitializeMapInstance" , self.clientObjects)
end
function MapEditor.MapInstance:RemovePlayer(player)
local index = table.find(self.players , player)
if index == nil then
error("Cannot find player: "..tostring(player))
end
table.remove(self.players , index)
Network:Send(player , "TerminateMapInstance")
end
|
----------------------------
-- LORE Premake5 script --
----------------------------
targetdir "../bin/%{cfg.buildcfg}/Run"
objdir "../bin/%{cfg.buildcfg}/Obj"
debugdir "../bin/%{cfg.buildcfg}/Run"
includedirs { ".",
"%{prj.location}",
"%{sln.location}/External",
"%{sln.location}/External/assimp/include",
"%{sln.location}/External/freetype2",
"%{sln.location}/External/glm",
"%{sln.location}/External/imgui",
"%{sln.location}/External/rapidjson/include",
"%{sln.location}/Plugins/ThirdParty"
}
libdirs { "../lib/x64/%{cfg.buildcfg}" }
architecture "x86_64"
characterset ( "MBCS" )
--
-- Solution
solution "LORE"
configurations { "Debug", "Release" }
startproject "Sample3D"
--
-- Configurations
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
--
-- Systems
filter "system:MacOSX"
cppdialect "C++14"
--
-- Projects
project "LORE"
location "LORE"
kind "SharedLib"
language "C++"
defines { "__Lore_Exports__", "_HAS_CXX17", "_HAS_CXX20", "LORE_DEBUG_UI" }
buildoptions { "/std:c++latest" }
pchheader "_pch.h"
pchsource "LORE/_pch.cpp"
forceincludes { "_pch.h" }
files {
"LORE/**.h", "LORE/**.cpp", "LORE/**.inl",
"External/imgui/*.h", "External/imgui/*.cpp"
}
links { "assimp-vc142-mt" }
postbuildcommands { "{COPY} ../../lib/x64/%{cfg.buildcfg}/ ../../bin/%{cfg.buildcfg}/Run/" }
project "Plugin_OpenGL"
location "Plugins/OpenGL"
kind "SharedLib"
language "C++"
libdirs { "../bin/%{cfg.buildcfg}/Run" } -- Location of LORE.lib after build.
defines { "__LoreOpenGL_Exports__", "_HAS_CXX17", "_HAS_CXX20", "LORE_DEBUG_UI" }
buildoptions { "/std:c++latest" }
pchheader "_pch.h"
pchsource "Plugins/OpenGL/_pch.cpp"
forceincludes { "_pch.h" }
files {
"Plugins/OpenGL/**.h", "Plugins/OpenGL/**.cpp",
"External/imgui/*.h", "External/imgui/*.cpp"
}
links { "LORE", "glad", "freetype" }
-- OS-specific options
filter { "system:Windows" }
links { "glfw3dll" }
filter { "system:MacOSX" }
links { "glfw3" }
linkoptions { "-framework Cocoa -framework IOKit -framework CoreVideo -framework OpenGL" }
postbuildcommands { "{COPY} ../../../lib/x64/%{cfg.buildcfg}/ ../../../bin/%{cfg.buildcfg}/Run/" }
project "glad"
location "Plugins/ThirdParty/glad"
kind "StaticLib"
language "C"
files {
"Plugins/ThirdParty/glad/*.h", "Plugins/ThirdParty/glad/*.c"
}
--
-- Examples
project "Sample3D"
location "Samples/Sample3D"
kind "ConsoleApp"
language "C++"
defines { "_HAS_CXX17", "_HAS_CXX20" }
buildoptions { "/std:c++latest" }
files {
"Samples/Sample3D/**.h",
"Samples/Sample3D/**.cpp"
}
links { "LORE" }
project "Sample2D"
location "Samples/Sample2D"
kind "ConsoleApp"
language "C++"
defines { "_HAS_CXX17", "_HAS_CXX20" }
buildoptions { "/std:c++latest" }
files {
"Samples/Sample2D/**.h",
"Samples/Sample2D/**.cpp"
}
links { "LORE" }
--
-- Tests
project "Tests"
location "Tests"
kind "ConsoleApp"
language "C++"
defines { "_HAS_CXX17", "_HAS_CXX20" }
buildoptions { "/std:c++latest" }
forceincludes { "TestUtils.h" }
files {
"Tests/**.h", "Tests/**.hpp", "Tests/**.cpp", "Tests/**.json"
}
links { "LORE" }
|
-- internationalization boilerplate
local MP = minetest.get_modpath(minetest.get_current_modname())
local S, NS = dofile(MP.."/intllib.lua")
-- Note: diggers go in group 3 and have an execute_dig method.
local digger_nodebox = {
{-0.5, -0.5, 0, 0.5, 0.5, 0.4375}, -- Block
{-0.4375, -0.3125, 0.4375, 0.4375, 0.3125, 0.5}, -- Cutter1
{-0.3125, -0.4375, 0.4375, 0.3125, 0.4375, 0.5}, -- Cutter2
{-0.5, -0.125, -0.125, 0.5, 0.125, 0}, -- BackFrame1
{-0.125, -0.5, -0.125, 0.125, 0.5, 0}, -- BackFrame2
{-0.25, -0.25, -0.5, 0.25, 0.25, 0}, -- Drive
}
local dual_digger_nodebox = {
{-0.5, -0.4375, 0, 0.5, 0.5, 0.4375}, -- Block
{-0.4375, -0.3125, 0.4375, 0.4375, 0.3125, 0.5}, -- Cutter1
{-0.3125, -0.4375, 0.4375, 0.3125, 0.4375, 0.5}, -- Cutter2
{-0.5, 0, -0.125, 0.5, 0.125, 0}, -- BackFrame1
{-0.25, 0, -0.5, 0.25, 0.25, 0}, -- Drive
{-0.25, 0.25, -0.25, 0.25, 0.5, 0}, -- Upper_Drive
{-0.5, -0.4375, -0.5, 0.5, 0, 0.4375}, -- Lower_Block
{-0.3125, -0.5, -0.4375, 0.3125, -0.4375, 0.4375}, -- Lower_Cutter_1
{-0.4375, -0.5, -0.3125, 0.4375, -0.4375, 0.3125}, -- Lower_Cutter_2
}
local modpath_doc = minetest.get_modpath("doc")
local intermittent_formspec_string = default.gui_bg ..
default.gui_bg_img ..
default.gui_slots ..
"field[0.5,0.8;1,0.1;period;" .. S("Periodicity") .. ";${period}]" ..
"tooltip[period;" .. S("Digger will dig once every n steps.\nThese steps are globally aligned, all diggers with\nthe same period and offset will dig on the same location.") .. "]" ..
"field[1.5,0.8;1,0.1;offset;" .. S("Offset") .. ";${offset}]" ..
"tooltip[offset;" .. S("Offsets the start of periodicity counting by this amount.\nFor example, a digger with period 2 and offset 0 digs\nevery even-numbered block and one with period 2 and\noffset 1 digs every odd-numbered block.") .. "]" ..
"button_exit[2.2,0.5;1,0.1;set;" .. S("Save &\nShow") .. "]" ..
"tooltip[set;" .. S("Saves settings") .. "]"
if modpath_doc then
intermittent_formspec_string = "size[4.5,1]" .. intermittent_formspec_string ..
"button_exit[3.2,0.5;1,0.1;help;" .. S("Help") .. "]" ..
"tooltip[help;" .. S("Show documentation about this block") .. "]"
else
intermittent_formspec_string = "size[3.5,1]" .. intermittent_formspec_string
end
local intermittent_formspec = function(pos, meta)
return intermittent_formspec_string
end
local intermittent_on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", intermittent_formspec(pos, meta))
meta:set_int("period", 1)
meta:set_int("offset", 0)
end
local intermittent_on_receive_fields = function(pos, formname, fields, sender)
local meta = minetest.get_meta(pos)
local period = tonumber(fields.period)
local offset = tonumber(fields.offset)
if period and period > 0 then
meta:set_int("period", math.floor(period))
end
if offset then
meta:set_int("offset", math.floor(offset))
end
if fields.help and minetest.get_modpath("doc") then --check for mod in case someone disabled it after this digger was built
local node_name = minetest.get_node(pos).name
minetest.after(0.5, doc.show_entry, sender:get_player_name(), "nodes", node_name, true)
end
if fields.set then
digtron.show_offset_markers(pos, offset, period)
end
end,
-- Digs out nodes that are "in front" of the digger head.
minetest.register_node("digtron:digger", {
description = S("Digtron Digger Head"),
_doc_items_longdesc = digtron.doc.digger_longdesc,
_doc_items_usagehelp = digtron.doc.digger_usagehelp,
groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 3},
drop = "digtron:digger",
sounds = digtron.metal_sounds,
paramtype = "light",
paramtype2= "facedir",
is_ground_content = false,
drawtype="nodebox",
node_box = {
type = "fixed",
fixed = digger_nodebox,
},
-- Aims in the +Z direction by default
tiles = {
"digtron_plate.png^[transformR90",
"digtron_plate.png^[transformR270",
"digtron_plate.png",
"digtron_plate.png^[transformR180",
{
name = "digtron_digger_yb.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.0,
},
},
"digtron_plate.png^digtron_motor.png",
},
-- returns fuel_cost, item_produced
execute_dig = function(pos, protected_nodes, nodes_dug, controlling_coordinate, lateral_dig, player)
local facing = minetest.get_node(pos).param2
local digpos = digtron.find_new_pos(pos, facing)
if protected_nodes:get(digpos.x, digpos.y, digpos.z) then
return 0, {}
end
return digtron.mark_diggable(digpos, nodes_dug, player)
end,
damage_creatures = function(player, pos, controlling_coordinate)
local facing = minetest.get_node(pos).param2
digtron.damage_creatures(player, digtron.find_new_pos(pos, facing), 8)
end,
})
-- Digs out nodes that are "in front" of the digger head.
minetest.register_node("digtron:intermittent_digger", {
description = S("Digtron Intermittent Digger Head"),
_doc_items_longdesc = digtron.doc.intermittent_digger_longdesc,
_doc_items_usagehelp = digtron.doc.intermittent_digger_usagehelp,
_digtron_formspec = intermittent_formspec,
groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 3},
drop = "digtron:intermittent_digger",
sounds = digtron.metal_sounds,
paramtype = "light",
paramtype2= "facedir",
is_ground_content = false,
drawtype="nodebox",
node_box = {
type = "fixed",
fixed = digger_nodebox,
},
-- Aims in the +Z direction by default
tiles = {
"digtron_plate.png^[transformR90",
"digtron_plate.png^[transformR270",
"digtron_plate.png",
"digtron_plate.png^[transformR180",
{
name = "digtron_digger_yb.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.0,
},
},
"digtron_plate.png^digtron_intermittent.png^digtron_motor.png",
},
on_construct = intermittent_on_construct,
on_receive_fields = intermittent_on_receive_fields,
-- returns fuel_cost, item_produced
execute_dig = function(pos, protected_nodes, nodes_dug, controlling_coordinate, lateral_dig, player)
if lateral_dig == true then
return 0, {}
end
local facing = minetest.get_node(pos).param2
local digpos = digtron.find_new_pos(pos, facing)
if protected_nodes:get(digpos.x, digpos.y, digpos.z) then
return 0, {}
end
local meta = minetest.get_meta(pos)
if (digpos[controlling_coordinate] + meta:get_int("offset")) % meta:get_int("period") ~= 0 then
return 0, {}
end
return digtron.mark_diggable(digpos, nodes_dug, player)
end,
damage_creatures = function(player, pos, controlling_coordinate)
local facing = minetest.get_node(pos).param2
local targetpos = digtron.find_new_pos(pos, facing)
local meta = minetest.get_meta(pos)
if (targetpos[controlling_coordinate] + meta:get_int("offset")) % meta:get_int("period") == 0 then
digtron.damage_creatures(player, targetpos, 8)
end
end
})
-- A special-purpose digger to deal with stuff like sand and gravel in the ceiling. It always digs (no periodicity or offset), but it only digs falling_block nodes
minetest.register_node("digtron:soft_digger", {
description = S("Digtron Soft Material Digger Head"),
_doc_items_longdesc = digtron.doc.soft_digger_longdesc,
_doc_items_usagehelp = digtron.doc.soft_digger_usagehelp,
groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 3},
drop = "digtron:soft_digger",
sounds = digtron.metal_sounds,
paramtype = "light",
paramtype2= "facedir",
is_ground_content = false,
drawtype="nodebox",
node_box = {
type = "fixed",
fixed = digger_nodebox,
},
-- Aims in the +Z direction by default
tiles = {
"digtron_plate.png^[transformR90^[colorize:" .. digtron.soft_digger_colorize,
"digtron_plate.png^[transformR270^[colorize:" .. digtron.soft_digger_colorize,
"digtron_plate.png^[colorize:" .. digtron.soft_digger_colorize,
"digtron_plate.png^[transformR180^[colorize:" .. digtron.soft_digger_colorize,
{
name = "digtron_digger_yb.png^[colorize:" .. digtron.soft_digger_colorize,
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.0,
},
},
"digtron_plate.png^digtron_motor.png^[colorize:" .. digtron.soft_digger_colorize,
},
execute_dig = function(pos, protected_nodes, nodes_dug, controlling_coordinate, lateral_dig, player)
local facing = minetest.get_node(pos).param2
local digpos = digtron.find_new_pos(pos, facing)
if protected_nodes:get(digpos.x, digpos.y, digpos.z) then
return 0, {}
end
if digtron.is_soft_material(digpos) then
return digtron.mark_diggable(digpos, nodes_dug, player)
end
return 0, {}
end,
damage_creatures = function(player, pos, controlling_coordinate)
local facing = minetest.get_node(pos).param2
digtron.damage_creatures(player, digtron.find_new_pos(pos, facing), 4)
end,
})
minetest.register_node("digtron:intermittent_soft_digger", {
description = S("Digtron Intermittent Soft Material Digger Head"),
_doc_items_longdesc = digtron.doc.intermittent_soft_digger_longdesc,
_doc_items_usagehelp = digtron.doc.intermittent_soft_digger_usagehelp,
_digtron_formspec = intermittent_formspec,
groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 3},
drop = "digtron:intermittent_soft_digger",
sounds = digtron.metal_sounds,
paramtype = "light",
paramtype2= "facedir",
is_ground_content = false,
drawtype="nodebox",
node_box = {
type = "fixed",
fixed = digger_nodebox,
},
-- Aims in the +Z direction by default
tiles = {
"digtron_plate.png^[transformR90^[colorize:" .. digtron.soft_digger_colorize,
"digtron_plate.png^[transformR270^[colorize:" .. digtron.soft_digger_colorize,
"digtron_plate.png^[colorize:" .. digtron.soft_digger_colorize,
"digtron_plate.png^[transformR180^[colorize:" .. digtron.soft_digger_colorize,
{
name = "digtron_digger_yb.png^[colorize:" .. digtron.soft_digger_colorize,
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.0,
},
},
"digtron_plate.png^digtron_intermittent.png^digtron_motor.png^[colorize:" .. digtron.soft_digger_colorize,
},
on_construct = intermittent_on_construct,
on_receive_fields = intermittent_on_receive_fields,
execute_dig = function(pos, protected_nodes, nodes_dug, controlling_coordinate, lateral_dig, player)
if lateral_dig == true then
return 0, {}
end
local facing = minetest.get_node(pos).param2
local digpos = digtron.find_new_pos(pos, facing)
if protected_nodes:get(digpos.x, digpos.y, digpos.z) then
return 0, {}
end
local meta = minetest.get_meta(pos)
if (digpos[controlling_coordinate] + meta:get_int("offset")) % meta:get_int("period") ~= 0 then
return 0, {}
end
if digtron.is_soft_material(digpos) then
return digtron.mark_diggable(digpos, nodes_dug, player)
end
return 0, {}
end,
damage_creatures = function(player, pos, controlling_coordinate)
local meta = minetest.get_meta(pos)
local facing = minetest.get_node(pos).param2
local targetpos = digtron.find_new_pos(pos, facing)
if (targetpos[controlling_coordinate] + meta:get_int("offset")) % meta:get_int("period") == 0 then
digtron.damage_creatures(player, targetpos, 4)
end
end,
})
-- Digs out nodes that are "in front" of the digger head and "below" the digger head (can be rotated).
minetest.register_node("digtron:dual_digger", {
description = S("Digtron Dual Digger Head"),
_doc_items_longdesc = digtron.doc.dual_digger_longdesc,
_doc_items_usagehelp = digtron.doc.dual_digger_usagehelp,
groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 3},
drop = "digtron:dual_digger",
sounds = digtron.metal_sounds,
paramtype = "light",
paramtype2= "facedir",
is_ground_content = false,
drawtype="nodebox",
node_box = {
type = "fixed",
fixed = dual_digger_nodebox,
},
-- Aims in the +Z and -Y direction by default
tiles = {
"digtron_plate.png^digtron_motor.png",
{
name = "digtron_digger_yb.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.0,
},
},
"digtron_plate.png",
"digtron_plate.png^[transformR180",
{
name = "digtron_digger_yb.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.0,
},
},
"digtron_plate.png^digtron_motor.png",
},
-- returns fuel_cost, items_produced
execute_dig = function(pos, protected_nodes, nodes_dug, controlling_coordinate, lateral_dig, player)
local facing = minetest.get_node(pos).param2
local digpos = digtron.find_new_pos(pos, facing)
local digdown = digtron.find_new_pos_downward(pos, facing)
local items = {}
local cost = 0
if protected_nodes:get(digpos.x, digpos.y, digpos.z) ~= true then
local forward_cost, forward_items = digtron.mark_diggable(digpos, nodes_dug, player)
for _, item in pairs(forward_items) do
table.insert(items, item)
end
cost = cost + forward_cost
end
if protected_nodes:get(digdown.x, digdown.y, digdown.z) ~= true then
local down_cost, down_items = digtron.mark_diggable(digdown, nodes_dug, player)
for _, item in pairs(down_items) do
table.insert(items, item)
end
cost = cost + down_cost
end
return cost, items
end,
damage_creatures = function(player, pos, controlling_coordinate)
local facing = minetest.get_node(pos).param2
digtron.damage_creatures(player, digtron.find_new_pos(pos, facing), 8)
digtron.damage_creatures(player, digtron.find_new_pos_downward(pos, facing), 8)
end,
})
-- Digs out soft nodes that are "in front" of the digger head and "below" the digger head (can be rotated).
minetest.register_node("digtron:dual_soft_digger", {
description = S("Digtron Dual Soft Material Digger Head"),
_doc_items_longdesc = digtron.doc.dual_soft_digger_longdesc,
_doc_items_usagehelp = digtron.doc.dual_soft_digger_usagehelp,
groups = {cracky = 3, oddly_breakable_by_hand=3, digtron = 3},
drop = "digtron:dual_soft_digger",
sounds = digtron.metal_sounds,
paramtype = "light",
paramtype2= "facedir",
is_ground_content = false,
drawtype="nodebox",
node_box = {
type = "fixed",
fixed = dual_digger_nodebox,
},
-- Aims in the +Z and -Y direction by default
tiles = {
"digtron_plate.png^digtron_motor.png^[colorize:" .. digtron.soft_digger_colorize,
{
name = "digtron_digger_yb.png^[colorize:" .. digtron.soft_digger_colorize,
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.0,
},
},
"digtron_plate.png^[colorize:" .. digtron.soft_digger_colorize,
"digtron_plate.png^[transformR180^[colorize:" .. digtron.soft_digger_colorize,
{
name = "digtron_digger_yb.png^[colorize:" .. digtron.soft_digger_colorize,
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.0,
},
},
"digtron_plate.png^digtron_motor.png^[colorize:" .. digtron.soft_digger_colorize,
},
-- returns fuel_cost, items_produced
execute_dig = function(pos, protected_nodes, nodes_dug, controlling_coordinate, lateral_dig, player)
local facing = minetest.get_node(pos).param2
local digpos = digtron.find_new_pos(pos, facing)
local digdown = digtron.find_new_pos_downward(pos, facing)
local items = {}
local cost = 0
if protected_nodes:get(digpos.x, digpos.y, digpos.z) ~= true and digtron.is_soft_material(digpos) then
local forward_cost, forward_items = digtron.mark_diggable(digpos, nodes_dug, player)
for _, item in pairs(forward_items) do
table.insert(items, item)
end
cost = cost + forward_cost
end
if protected_nodes:get(digdown.x, digdown.y, digdown.z) ~= true and digtron.is_soft_material(digdown) then
local down_cost, down_items = digtron.mark_diggable(digdown, nodes_dug, player)
for _, item in pairs(down_items) do
table.insert(items, item)
end
cost = cost + down_cost
end
return cost, items
end,
damage_creatures = function(player, pos, controlling_coordinate)
local facing = minetest.get_node(pos).param2
digtron.damage_creatures(player, digtron.find_new_pos(pos, facing), 4)
digtron.damage_creatures(player, digtron.find_new_pos_downward(pos, facing), 4)
end,
}) |
function getTableKeys(tab)
local keyset = {}
for k,v in pairs(tab) do
keyset[#keyset + 1] = k
end
return keyset
end
FsmMachine = {}
function FsmMachine:New(opts)
opts = opts or {}
self.__index = self
local o = setmetatable({}, self)
o.states = {}
o.curState = nil
o.debug = opts["debug"]
return o
end
-- Current state
function FsmMachine:GetCurrent()
return self.curState.stateName
end
-- Available actions
function FsmMachine:GetActions()
return getTableKeys(self.curState.transitions)
end
-- Add state
function FsmMachine:AddState(stateName, callbacks)
local state = BaseState:New(stateName)
self.states[stateName] = state
if callbacks then
self:Listen(stateName, callbacks)
end
if not self.curState then
self:AddInitState(stateName)
end
end
-- default initialization
function FsmMachine:AddInitState(stateName)
self.curState = self.states[stateName]
end
-- connect
function FsmMachine:Connect(opts)
local to = opts["to"]
local message = opts["message"]
local toState = self.states[to]
local fromOrFroms = opts["from"]
local froms = nil
if type(fromOrFroms) == "table" then
froms = fromOrFroms
else
froms = { fromOrFroms }
end
for i, from in ipairs(froms) do
local fromState = self.states[from]
fromState:Connect(message, toState)
end
end
function FsmMachine:Listen(toStateName, callbacks)
local state = self.states[toStateName]
local onEnter = callbacks["onEnter"]
if onEnter then
state:ListenToOnEnter(onEnter)
end
local onLeave = callbacks["onLeave"]
if onLeave then
state:ListenToOnLeave(onLeave)
end
end
-- switching state
function FsmMachine:Switch(message)
local shouldTransition = false
local destState = nil
if self.curState.transitions[message] then
shouldTransition = true
destState = self.curState.transitions[message]
end
if shouldTransition then
if self.debug then print("FsmMachine: [" .. message .. "] message received") end
self.curState:OnLeave()
self.curState = destState
self.curState:OnEnter()
else
if self.debug then print("FsmMachine: Unknown message [" .. message .. "] for state [" .. self.curState.stateName .. "]") end
end
end
BaseState = {}
function BaseState:New(stateName)
self.__index = self
local o = setmetatable({}, self)
o.stateName = stateName
o.onLeaves = {}
o.onEnters = {}
o.transitions = {}
return o
end
-- Connect
function BaseState:Connect(message, destState)
self.transitions[message] = destState
end
-- Listen to onEnter
function BaseState:ListenToOnEnter(onEnter)
table.insert(self.onEnters, onEnter)
end
-- Listen to onLeave
function BaseState:ListenToOnLeave(onLeave)
table.insert(self.onLeaves, onLeave)
end
-- Enter state
function BaseState:OnEnter()
for i, onEnter in ipairs(self.onEnters) do
onEnter()
end
end
-- leave the state
function BaseState:OnLeave()
for i, onLeave in ipairs(self.onLeaves) do
onLeave()
end
end
return FsmMachine
|
--[[
Author: Noya
Date: April 5, 2015
Get a point at a distance in front of the caster
]]
function GetFrontPoint( event )
local caster = event.caster
local fv = caster:GetForwardVector()
local origin = caster:GetAbsOrigin()
local distance = event.Distance
local front_position = origin + fv * distance
local result = {}
table.insert(result, front_position)
return result
end
-- Set the units looking at the same point of the caster
function SetUnitsMoveForward( event )
local caster = event.caster
local target = event.target
local fv = caster:GetForwardVector()
local origin = caster:GetAbsOrigin()
target:SetForwardVector(fv)
end
--[[
Author: Noya
Date: 16.01.2015.
Levels up the ability_name to the same level of the ability that runs this
]]
function LevelUpAbility( event )
local caster = event.caster
local this_ability = event.ability
local this_abilityName = this_ability:GetAbilityName()
local this_abilityLevel = this_ability:GetLevel()
-- The ability to level up
local ability_name = event.ability_name
local ability_handle = caster:FindAbilityByName(ability_name)
local ability_level = ability_handle:GetLevel()
-- Check to not enter a level up loop
if ability_level ~= this_abilityLevel then
ability_handle:SetLevel(this_abilityLevel)
end
end |
--ZFUNC-clamp-v1
local function clamp( num, min, max ) --> res
if num < min then return min
elseif num > max then return max
else return num
end
end
return clamp
|
monitoring.wrap_global({"minetest", "set_node"}, "set_node")
|
-- vshard.util
local log = require('log')
local fiber = require('fiber')
local lerror = require('vshard.error')
local lversion = require('vshard.version')
local lmsgpack = require('msgpack')
local MODULE_INTERNALS = '__module_vshard_util'
local M = rawget(_G, MODULE_INTERNALS)
if not M then
--
-- The module is loaded for the first time.
--
M = {
-- Latest versions of functions.
reloadable_fiber_main_loop = nil,
}
rawset(_G, MODULE_INTERNALS, M)
end
local tnt_version = lversion.parse(_TARANTOOL)
--
-- Extract parts of a tuple.
-- @param tuple Tuple to extract a key from.
-- @param parts Array of index parts. Each part must contain
-- 'fieldno' attribute.
--
-- @retval Extracted key.
--
local function tuple_extract_key(tuple, parts)
local key = {}
for _, part in ipairs(parts) do
table.insert(key, tuple[part.fieldno])
end
return key
end
--
-- Wrapper to run a func in infinite loop and restart it on
-- errors and module reload.
-- This loop executes the latest version of itself in case of
-- reload of that module.
-- See description of parameters in `reloadable_fiber_create`.
--
local function reloadable_fiber_main_loop(module, func_name, data)
log.info('%s has been started', func_name)
local func = module[func_name]
::restart_loop::
local ok, err = pcall(func, data)
-- yield serves two purposes:
-- * makes this fiber cancellable
-- * prevents 100% cpu consumption
fiber.yield()
if not ok then
log.error('%s has been failed: %s', func_name, err)
if func == module[func_name] then
goto restart_loop
end
-- There is a chance that error was raised during reload
-- (or caused by reload). Perform reload in case function
-- has been changed.
log.error('reloadable function %s has been changed', func_name)
end
log.info('module is reloaded, restarting')
-- luajit drops this frame if next function is called in
-- return statement.
return M.reloadable_fiber_main_loop(module, func_name, data)
end
--
-- Create a new fiber which runs a function in a loop. This loop
-- is aware of reload mechanism and it loads a new version of the
-- function in that case.
-- To handle module reload and run new version of a function
-- in the module, the function should just return.
-- @param fiber_name Name of a new fiber. E.g.
-- "vshard.rebalancer".
-- @param module Module which can be reloaded.
-- @param func_name Name of a function to be executed in the
-- module.
-- @param data Data to be passed to the specified function.
-- @retval New fiber.
--
local function reloadable_fiber_create(fiber_name, module, func_name, data)
assert(type(fiber_name) == 'string')
local xfiber = fiber.create(reloadable_fiber_main_loop, module, func_name,
data)
xfiber:name(fiber_name, {truncate = true})
return xfiber
end
--
-- Wrap a given function to check that self argument is passed.
-- New function returns an error in case one called a method
-- like object.func instead of object:func.
-- Returning wrapped function to a user and using raw functions
-- inside of a module improves speed.
-- This function can be used only in case the second argument is
-- not of the "table" type or has different metatable.
-- @param obj_name Name of the called object. Used only for error
-- message construction.
-- @param func_name Name of the called function. Used only for an
-- error message construction.
-- @param mt Meta table of self argument.
-- @param func A function which is about to be wrapped.
--
-- @retval Wrapped function.
--
local function generate_self_checker(obj_name, func_name, mt, func)
return function (self, ...)
if getmetatable(self) ~= mt then
local fmt = 'Use %s:%s(...) instead of %s.%s(...)'
error(string.format(fmt, obj_name, func_name, obj_name, func_name))
end
return func(self, ...)
end
end
-- Update latest versions of function
M.reloadable_fiber_main_loop = reloadable_fiber_main_loop
local function sync_task(delay, task, ...)
if delay then
fiber.sleep(delay)
end
task(...)
end
--
-- Run a function without interrupting current fiber.
-- @param delay Delay in seconds before the task should be
-- executed.
-- @param task Function to be executed.
-- @param ... Arguments which would be passed to the `task`.
--
local function async_task(delay, task, ...)
assert(delay == nil or type(delay) == 'number')
fiber.create(sync_task, delay, task, ...)
end
--
-- Check if Tarantool version is >= that a specified one.
--
local function version_is_at_least(...)
return tnt_version >= lversion.new(...)
end
if not version_is_at_least(1, 10, 1) then
error("VShard supports only Tarantool >= 1.10.1")
end
--
-- Copy @a src table. Fiber yields every @a interval keys copied. Does not give
-- any guarantees on what is the result when the source table is changed during
-- yield.
--
local function table_copy_yield(src, interval)
local res = {}
-- Time-To-Yield.
local tty = interval
for k, v in pairs(src) do
res[k] = v
tty = tty - 1
if tty <= 0 then
fiber.yield()
tty = interval
end
end
return res
end
--
-- Remove @a src keys from @a dst if their values match. Fiber yields every
-- @a interval iterations. Does not give any guarantees on what is the result
-- when the source table is changed during yield.
--
local function table_minus_yield(dst, src, interval)
-- Time-To-Yield.
local tty = interval
for k, srcv in pairs(src) do
if dst[k] == srcv then
dst[k] = nil
end
tty = tty - 1
if tty <= 0 then
fiber.yield()
tty = interval
end
end
return dst
end
local function fiber_cond_wait_xc(cond, timeout)
-- Handle negative timeout specifically - otherwise wait() will throw an
-- ugly usage error.
-- Don't trust this check to the caller's code, because often it just calls
-- wait many times until it fails or the condition is met. Code looks much
-- cleaner when it does not need to check the timeout sign. On the other
-- hand, perf is not important here - anyway wait() yields which is slow on
-- its own, but also breaks JIT trace recording which makes pcall() in the
-- non-xc version of this function inconsiderable.
if timeout < 0 or not cond:wait(timeout) then
-- Don't use the original error if cond sets it. Because it sets
-- TimedOut error. It does not have a proper error code, and may not be
-- detected by router as a special timeout case if necessary. Or at
-- least would complicate the handling in future. Instead, try to use a
-- unified timeout error where possible.
error(lerror.timeout())
end
-- Still possible though that the fiber is canceled and cond:wait() throws.
-- This is why the _xc() version of this function throws even the timeout -
-- anyway pcall() is inevitable.
end
--
-- Exception-safe cond wait with unified errors in vshard format.
--
local function fiber_cond_wait(cond, timeout)
local ok, err = pcall(fiber_cond_wait_xc, cond, timeout)
if ok then
return true
end
return nil, lerror.make(err)
end
--
-- Exception-safe way to check if the current fiber is canceled.
--
local function fiber_is_self_canceled()
return not pcall(fiber.testcancel)
end
--
-- Dictionary of supported core features on the given instance. Try to use it
-- in all the other code rather than direct version check.
--
local feature = {
msgpack_object = lmsgpack.object ~= nil,
netbox_return_raw = version_is_at_least(2, 10, 0, 'beta', 2, 86),
}
return {
tuple_extract_key = tuple_extract_key,
reloadable_fiber_create = reloadable_fiber_create,
generate_self_checker = generate_self_checker,
async_task = async_task,
internal = M,
version_is_at_least = version_is_at_least,
table_copy_yield = table_copy_yield,
table_minus_yield = table_minus_yield,
fiber_cond_wait = fiber_cond_wait,
fiber_is_self_canceled = fiber_is_self_canceled,
feature = feature,
}
|
#!/usr/bin/env lua
require "ex"
for e in assert(os.dir(".")) do
print(string.format("%.3s %9d %s", e.type or 'Unknown', e.size or -1, e.name))
end
--[[
local f,s,i = assert(os.dir(".."))
print(f,s,i)
i=assert(f(s,i))
for e in f,s,i do
print(e.name,e.type,e.size)
end
--]]
|
require "model"
-- Make sure that model exists
assert(model, "Model namespace does not exist")
-- Create a sample user model with username, password, and usgn
User = model{
"user", -- Table name, lowercase
username = model.CharField{max_length = 10, null = false, unique = true},
password = model.CharField{max_length = 10, null = false},
usgn = model.IntegerField{null = true, unique = true}
}
-- Make sure that User is created
assert(User, "Cannot create model User")
-- Create a user
lee = User{username = "lee", password = "confidential"}
-- Check that lee exists
assert(lee, "Cannot create user lee")
-- Check that lee's password is too long
assert(not lee.password, "confidential is somehow less than 10 letters long.")
-- Check that lee doesn't have an id yet.
assert(not lee.id, "Object lee has been tempered with")
-- Assign a usgn to lee and validate
lee.usgn = 146
-- Assign a valid password
lee.password = "demo"
-- Validate usgn
assert(lee.usgn == 146, "Object lee's USGN is incorrect")
-- Create a sample clan model with clan_name and tag fields
Clan = model{
"clan",
clan_name = model.CharField{unique = true},
tag = model.CharField{null = true}
}
-- Create a nice looking tostring of Clan
function Clan.on_string(self)
return self.tag or "[NaN]"
end
-- Make sure that Clan is created
assert(Clan, "Cannot create model Clan")
-- Create a clan
TGV = Clan{clan_name = "TGV", tag = "[TGV]"}
-- Check TGV
assert(TGV, "Cannot create clan TGV")
-- Create a userproxy to connect user to clan
UserClan = model{
"userclan",
clan = model.ForeignKey{to = "clan", null = false},
user = model.ForeignKey{to = "user", null = false}
}
-- Create a nice looking tostring method of UserClan
function UserClan.on_string(self)
return "%s%s"%{self.clan.tag or "[No Clan]", self.user.username}
end
-- Make sure that UserClan exists
assert(UserClan, "UserClan Proxy model cannot be created")
Model3 = model{"model3",data = model.CharField{}}
-- Create Proxies and go from there...
p = UserClan{user=lee,clan=TGV}
p:save()
aj = User{username = "aj", password = "aj"}
p2 = UserClan{user=aj,clan=TGV}
p2:save()
jack = User{username = "jack", password = "jack"}
jack:save()
-- Creates a query-set that finds all UserClan objects where clan.clan_name equals "TGV"
q = UserClan.objects.all():where{clan__clan_name = "TGV"}
-- Check that the queryset is constructed correctly
assert(q, "Queryset cannot be constructed")
-- Make sure that the Queryset can be evaluted
q()
q = User.objects.all():where{userclan__clan = TGV}
q()
-- Cleanup
p:delete()
p2:delete()
TGV:delete()
lee:delete()
aj:delete()
jack:delete()
sql:close()
-- Generated SQL:
--[[--
>lua -e "io.stdout:setvbuf 'no'" "test.lua"
SELECT * FROM sqlite_master WHERE tbl_name = "user_model";
SELECT * FROM sqlite_master WHERE tbl_name = "clan_model";
SELECT * FROM sqlite_master WHERE tbl_name = "userclan_model";
INSERT INTO user_model (username,usgn,password) VALUES ("lee",146,"demo");
SELECT id FROM user_model ORDER BY id DESC
INSERT INTO clan_model (clan_name,tag) VALUES ("TGV","[TGV]");
SELECT id FROM clan_model ORDER BY id DESC
INSERT INTO userclan_model (user,clan) VALUES (1,1);
SELECT id FROM userclan_model ORDER BY id DESC
INSERT INTO user_model (password,username) VALUES ("aj","aj");
SELECT id FROM user_model ORDER BY id DESC
INSERT INTO userclan_model (user,clan) VALUES (2,1);
SELECT id FROM userclan_model ORDER BY id DESC
INSERT INTO user_model (password,username) VALUES ("jack","jack");
SELECT id FROM user_model ORDER BY id DESC
SELECT * FROM clan_model WHERE ( "clan_name" = "TGV" )
SELECT * FROM userclan_model WHERE ( "clan" = 1 )
SELECT * FROM clan_model WHERE ( "id" = 1 ) LIMIT 1
SELECT * FROM user_model WHERE ( "id" = 1 ) LIMIT 1
SELECT * FROM clan_model WHERE ( "id" = 1 ) LIMIT 1
SELECT * FROM user_model WHERE ( "id" = 2 ) LIMIT 1
SELECT user AS id FROM userclan_model WHERE ( "clan" LIKE 1 ESCAPE '\' )
SELECT * FROM user_model WHERE ( "id" = 1 ) LIMIT 1
SELECT * FROM user_model WHERE ( "id" = 2 ) LIMIT 1
DELETE FROM userclan_model WHERE id=1
DELETE FROM userclan_model WHERE id=2
DELETE FROM clan_model WHERE id=1
DELETE FROM user_model WHERE id=1
DELETE FROM user_model WHERE id=2
DELETE FROM user_model WHERE id=3
>Exit code: 0
--]]--
|
import "darkroom"
(terralib.loadfile("test.t"))()
width = 584
height = 388
--local frame1 = orion.image(orion.type.uint(8),width,height)
local frame1 = testinput
im vectorField(x,y) [uint8[3]]( {frame1(x,y),frame1(x,y)+3,0} ) end
test({vectorField, im(x,y) [uint8[3]]( {(frame1(x,y))*50+128, (frame1(x,y))*50+12,0}) end}) |
--[[--
h1. four.Effect
An effect defines either a configuration of the graphics pipeline
or a list of Effects for rendering a Geometry object.
--]]--
local lub = require 'lub'
local four = require 'four'
local lib = lub.class 'four.Effect'
local Color = four.Color
local Effect = lib
-- Meta table to detect shader source changes. Allows the renderer to
-- dynamically recompile the GPU program.
local isShaderKey = { vertex = true, geometry = true, fragment = true }
function lib.__index(t, k)
if k == "shaders" then return rawget(t, k)
elseif isShaderKey[k] then return t.shaders[k]
else return lib[k] end
end
function lib.__newindex(t, k, v)
if isShaderKey[k] then
local shaders = t.shaders
shaders[k] = v
t.program_changed = true
else
rawset(t, k, v)
end
end
setmetatable(lib, { __call = function(lib, ...) return lib.new(...) end})
-- h2. Render states
--[[--
h3. Rasterization state
*Note*. Faces with a counter clock-wise orientation are front faces.
Rasterization state is described by a table with the following keys:
* @face_cull@, faces to cull (defaults to @CULL_NONE@).
--]]--
function lib.defaultRasterization ()
return { cull_face = lib.CULL_NONE }
end
lib.CULL_NONE = 1
lib.CULL_FRONT = 2
lib.CULL_BACK = 3
--[[--
h3. Depth state
*Note.* Depth clearing and depth range are specified by the Camera object.
Depth state is described by a table with the following keys:
* @test@, @true@ if z-test should be performed (defaults to @true@)
* @func@, comparison function (defaults to @DEPTH_FUNC_LEQUAL@)
* @write@, @true@ if z buffer should be written to (default to @true@)
* @offset@, depth offset (defaults to @{ factor = 0, units = 0 }@),
see doc of glPolygonOffset.
--]]--
function lib.defaultDepth()
return { test = true, func = lib.DEPTH_FUNC_LEQUAL, write = true,
offset = { factor = 0, units = 0 } }
end
lib.DEPTH_FUNC_NEVER = 1
lib.DEPTH_FUNC_LESS = 2
lib.DEPTH_FUNC_EQUAL = 3
lib.DEPTH_FUNC_LEQUAL = 4
lib.DEPTH_FUNC_GREATER = 5
lib.DEPTH_FUNC_NOTEQUAL = 6
lib.DEPTH_FUNC_GEQUAL = 7
lib.DEPTH_FUNC_ALWAYS = 8
-- h2. Constructor
--[[--
@Effect(def)@ is a new effect object. @def@ keys:
* @default_uniforms@, key/value table, defining default values for uniforms.
* @uniform@, uniform lookup function invoked before rendering a renderable.
defaults to @function(self, cam, renderable, name) = return
renderable[name]@. If the function returns @nil@, @default_uniforms@ is
used.
* @vertex@, vertex shader source.
* @geometry@, geometry shader source (optional).
* @fragment@, fragment shader source.
* @depth@, depth state keys to override the defaults (see Depth state).
* @rasterization@, rasterization state keys to override the defaults
(see Rasterization state).
* @opaque@, defines whether the effect is opaque. Renderables with
opaque effects are rendered before non-opaque ones.
--]]--
function lib.new(def)
local self =
{ default_uniforms = {},
uniform = function(e, cam, renderable, name) return renderable[name] end,
shaders =
{ vertex = lib.Shader [[void main() {}]],
geometry = nil, -- optional
fragment = lib.Shader [[void main() {}]]},
program_changed = true, -- The renderer sets this to false once it got
-- the new program.
opaque = true,
rasterization = lib.defaultRasterization(),
depth = lib.defaultDepth() }
setmetatable(self, lib)
if def then self:set(def) end
return self
end
function lib:set(def)
if def.default_uniforms ~= nil then
self.default_uniforms = def.default_uniforms
end
if def.uniform ~= nil then self.uniform = def.uniform end
if def.vertex ~= nil then self.vertex = def.vertex end
if def.geometry ~= nil then self.geometry = def.geometry end
if def.fragment ~= nil then self.fragment = def.fragment end
if def.rasterization ~= nil then
if def.rasterization.cull_face ~= nil then
self.rasterization.cull_face = def.rasterization.cull_face
end
end
if def.depth ~= nil then
if def.depth.test ~= nil then self.depth.test = def.depth.test end
if def.depth.func ~= nil then self.depth.func = def.depth.func end
if def.depth.write ~= nil then self.depth.write = def.depth.write end
if def.depth.offset ~= nil then self.depth.offset = def.depth.offset end
end
if def.opaque ~= nil then self.opaque = def.opaque end
end
-- h2. Shader constructor
function lib.Shader(src)
local trace = lub.split(debug.traceback(),'\n\t')[3]
local file, last_line = string.match(trace, '^([^:]+):([^:]+):')
local src_line_count = #lub.split(src, '\n')
return { file = file, line = last_line - src_line_count, fragment = src }
end
-- h2. Special uniform values
lib.MODEL_TO_WORLD = { special_uniform = true }
lib.MODEL_TO_CAMERA = { special_uniform = true }
lib.MODEL_TO_CLIP = { special_uniform = true }
lib.MODEL_NORMAL_TO_CAMERA = { special_uniform = true }
lib.WORLD_TO_CAMERA = { special_uniform = true }
lib.WORLD_TO_CLIP = { special_uniform = true }
lib.CAMERA_TO_CLIP = { special_uniform = true }
lib.CAMERA_RESOLUTION = { special_uniform = true }
lib.RENDER_FRAME_START_TIME = { special_uniform = true }
-- h2. Effect shaders
local function makeSource(preamble, src)
local frags = src.fragment and { src } or src
local src = { preamble }
local files = {}
for i, f in ipairs(frags) do
src[i + 1] = string.format("#line %d %d\n%s", f.line, i, f.fragment)
files[i] = f.file
end
if #files == 0 then -- TODO can we do something better here ?
error ("A shader source contains no fragments or a nil")
end
return { src = table.concat(src,"\n"), files = files }
end
function lib:vertexShaderSource(pre) return makeSource(pre, self.vertex) end
function lib:fragmentShaderSource(pre) return makeSource(pre, self.fragment) end
function lib:geometryShaderSource(pre)
return self.geometry and makeSource(pre, self.geometry) or nil
end
-- h2. Predefined Effects
--[[--
@Wireframe(def)@ renders triangle geometry as wireframe. @def@ keys:
* @fill_color@, a Color defining the triangle fill color (defaults
to Color.white ()).
* @wire_color@, a Color defining the wireframe color (default to Color.red().
* @wire_only@, draw only the wire frame.
* @ajdacency@, @true@ to apply the geometry primitive to
Geometry.TRIANGLES_ADJACENCY.
* All other @Effect@ @def@ key apply.
Effect adapted from http://cgg-journal.com/2008-2/06/index.html.
--]]--
-- TODO use discard ?
function lib.Wireframe(def)
local adjacency = def and def.adjacency or false
local geometry = adjacency and Effect.Shader [[
layout(triangles_adjacency) in;
layout(triangle_strip, max_vertices=3) out;
uniform vec2 resolution;
noperspective out vec3 dist;
void main(void)
{
vec2 p0 = resolution * gl_in[0].gl_Position.xy/gl_in[0].gl_Position.w;
vec2 p1 = resolution * gl_in[2].gl_Position.xy/gl_in[2].gl_Position.w;
vec2 p2 = resolution * gl_in[4].gl_Position.xy/gl_in[4].gl_Position.w;
vec2 v0 = p2 - p1;
vec2 v1 = p2 - p0;
vec2 v2 = p1 - p0;
float area = abs(v1.x * v2.y - v1.y * v2.x);
dist = vec3(area / length(v0), 0, 0);
gl_Position = gl_in[0].gl_Position;
EmitVertex();
dist = vec3(0, area / length(v1), 0);
gl_Position = gl_in[2].gl_Position;
EmitVertex();
dist = vec3(0, 0, area / length(v2));
gl_Position = gl_in[4].gl_Position;
EmitVertex();
EndPrimitive();
}
]] or Effect.Shader [[
layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;
uniform vec2 resolution;
noperspective out vec3 dist;
void main(void)
{
vec2 p0 = resolution * gl_in[0].gl_Position.xy/gl_in[0].gl_Position.w;
vec2 p1 = resolution * gl_in[1].gl_Position.xy/gl_in[1].gl_Position.w;
vec2 p2 = resolution * gl_in[2].gl_Position.xy/gl_in[2].gl_Position.w;
vec2 v0 = p2 - p1;
vec2 v1 = p2 - p0;
vec2 v2 = p1 - p0;
float area = abs(v1.x * v2.y - v1.y * v2.x);
dist = vec3(area / length(v0), 0, 0);
gl_Position = gl_in[0].gl_Position;
EmitVertex();
dist = vec3(0, area / length(v1), 0);
gl_Position = gl_in[1].gl_Position;
EmitVertex();
dist = vec3(0, 0, area / length(v2));
gl_Position = gl_in[2].gl_Position;
EmitVertex();
EndPrimitive();
}
]]
return Effect
{
rasterization = def and def.rasterization,
depth = def and def.depth,
opaque = def and def.opaque,
default_uniforms =
{ model_to_clip = Effect.MODEL_TO_CLIP,
resolution = Effect.CAMERA_RESOLUTION,
fill_color = def and def.fill_color or Color.white(),
wire_color = def and def.wire_color or Color.black(),
wire_width = def and def.wire_width or 1.0,
wire_only = def and def.wire_only or false },
vertex = def and def.vertex or Effect.Shader [[
uniform mat4 model_to_clip;
in vec4 vertex;
out vec4 v_vertex;
void main() { gl_Position = model_to_clip * vertex; }
]],
geometry = def and def.geometry or geometry,
fragment = def and def.fragment or Effect.Shader [[
uniform bool wire_only;
uniform float wire_width;
uniform vec4 wire_color;
uniform vec4 fill_color;
noperspective in vec3 dist;
out vec4 color;
void main(void)
{
float d = min(dist[0],min(dist[1],dist[2]));
float I = exp2(-(2 / wire_width) * d * d);
if (wire_only)
{
color = I * wire_color;
} else {
color = vec4(I * wire_color.rgb + (1.0 - I) * fill_color.rgb,
fill_color.a);
}
}
]]
}
end
--[[--
@Normals(def)@ renders the normals of geometry.
* @normal_scale@, a scale factor to apply to the normals.
* @normal_color_start@, color at the starting point of the vector.
* @normal_color_end@, color at the end of vector.
--]]--
function lib.Normals(def)
return Effect
{
rasterization = def and def.rasterization,
depth = def and def.depth,
opaque = def and def.opaque,
default_uniforms =
{ model_to_cam = Effect.MODEL_TO_CAMERA,
normal_to_cam = Effect.MODEL_NORMAL_TO_CAMERA,
cam_to_clip = Effect.CAMERA_TO_CLIP,
normal_scale = def and def.normal_scale or 0.1,
normal_color_start = def and def.normal_color_start or Color.black(),
normal_color_end = def and def.normal_color_end or Color.white() },
vertex = def and def.vertex or Effect.Shader [[
uniform mat4 model_to_cam;
uniform mat3 normal_to_cam;
uniform float normal_scale;
in vec3 vertex;
in vec3 normal;
out vec4 v_position;
out vec3 v_snormal;
void main()
{
v_position = model_to_cam * vec4(vertex, 1.0);
v_snormal = normal_scale * normalize(normal_to_cam * normal);
}
]],
geometry = def and def.geometry or Effect.Shader [[
uniform mat4 cam_to_clip;
uniform vec4 normal_color_start;
uniform vec4 normal_color_end;
layout(triangles) in;
layout(line_strip, max_vertices = 6) out;
in vec4 v_position[3];
in vec3 v_snormal[3];
out vec4 g_color;
void main()
{
for (int i = 0; i < 3; i++)
{
gl_Position = cam_to_clip * v_position[i];
g_color = normal_color_start;
EmitVertex();
gl_Position = cam_to_clip * (v_position[i] + vec4(v_snormal[i], 0.0));
g_color = normal_color_end;
EmitVertex();
EndPrimitive();
}
}
]],
fragment = def and def.fragment or Effect.Shader [[
in vec4 g_color;
out vec4 f_color;
void main(void) { f_color = g_color; }
]]
}
end
return lib
|
if (CLIENT) then
net.Receive("GPM.Where_Are_You?", function()
net.Start( "GPM.Where_Are_You?" )
net.WriteString( system.GetCountry():lower() )
net.SendToServer()
end)
end
local default_language = "gb"
local cvar = GetConVar( "default_language" )
if (cvar) then
default_language = cvar:GetString()
end
local PLAYER = FindMetaTable("Player")
do
function PLAYER:Country()
return self:GetNWString( "GPM.Where_Am_I", default_language )
end
end
if (SERVER) then
function PLAYER:SetCountry( country_code )
return self:SetNWString( "GPM.Where_Am_I", country_code or default_language )
end
util.AddNetworkString( "GPM.Where_Are_You?" )
hook.Add("PlayerInitialized", "GPM.Where_Are_You?", function( ply )
net.Start( "GPM.Where_Are_You?" )
net.Send( ply )
end)
local net_ReadString = net.ReadString
net.Receive("GPM.Where_Are_You?", function( len, ply )
if IsValid( ply ) and (ply:GetNWString( "GPM.Where_Am_I", false ) == false) then
ply:SetCountry( net_ReadString() )
end
end)
end
|
-- Bahama Mamas: -1388.0013, -618.41967, 30.819599
exports('GetBahamaMamasObject', function()
return BahamaMamas
end)
BahamaMamas = {
ipl = "hei_sm_16_interior_v_bahama_milo_",
Enable = function(state)
EnableIpl(BahamaMamas.ipl, state)
end
}
|
local lu = require('luaunit')
print( lu.EPS )
local pi_div_6_deg_expected, pi_div_6_deg_calculated, pi_div_3_deg_expected, pi_div_3_deg_calculated
pi_div_6_deg_calculated = math.deg(math.pi/6)
pi_div_6_deg_expected = 30
pi_div_3_deg_calculated = math.deg(math.pi/3)
pi_div_3_deg_expected = 60
print( (pi_div_6_deg_expected - pi_div_6_deg_calculated) / lu.EPS ) -- prints: 16
print( (pi_div_3_deg_expected - pi_div_3_deg_calculated) / lu.EPS ) -- prints: 32
-- Better use relative error:
print( ( (pi_div_6_deg_expected - pi_div_6_deg_calculated) / pi_div_6_deg_expected) / lu.EPS ) -- prints: 0.53333
print( ( (pi_div_3_deg_expected - pi_div_3_deg_calculated) / pi_div_3_deg_expected) / lu.EPS ) -- prints: 0.53333
-- relative error is constant. Assertion can take the form of:
lu.assertAlmostEquals( (pi_div_6_deg_expected - pi_div_6_deg_calculated) / pi_div_6_deg_expected, 0, lu.EPS )
lu.assertAlmostEquals( (pi_div_3_deg_expected - pi_div_3_deg_calculated) / pi_div_3_deg_expected, 0, lu.EPS ) |
local function GetInserterImage(path)
return "__MomoPyTweak__/graphics/entity/inserter/" .. path .. ".png"
end
local function ConvertSpriteToOnlyHR(sprite)
if (sprite.hr_version) then
sprite.filename = sprite.hr_version.filename
sprite.width = sprite.hr_version.width
sprite.height = sprite.hr_version.height
end
end
local function ConvertSheetToOnlyHR(sheet)
if (sheet.hr_version) then
sheet.filename = sheet.hr_version.filename
sheet.width = sheet.hr_version.width
sheet.height = sheet.hr_version.height
sheet.shift = sheet.shift
end
end
function momoPyTweak.Inserter()
local prototype = {}
-- express
momoPyTweak.item.inserter = momoIRTweak.item.NewItemFixedSize("momo-express-inserter", 32, "inserter", 50)
momoPyTweak.item.inserter.order = "zz1"
momoPyTweak.item.inserter.place_result = "momo-express-inserter"
prototype = momoIRTweak.DeepCopy(data.raw.inserter["fast-inserter"])
prototype.icon_size = 32
prototype.icon = momoPyTweak.item.inserter.icon
prototype.name = "momo-express-inserter"
prototype.max_health = 600
prototype.energy_per_movement = "10KJ"
prototype.energy_per_rotation = "10KJ"
prototype.energy_source.drain = "0.7kW"
prototype.extension_speed = 0.14
prototype.rotation_speed = 0.08
prototype.minable.result = "momo-express-inserter"
prototype.hand_base_picture.hr_version.filename = GetInserterImage("express/hr-hand-base")
ConvertSpriteToOnlyHR(prototype.hand_base_picture)
prototype.hand_closed_picture.hr_version.filename = GetInserterImage("express/hr-hand-closed")
ConvertSpriteToOnlyHR(prototype.hand_closed_picture)
prototype.hand_open_picture.hr_version.filename = GetInserterImage("express/hr-hand-open")
ConvertSpriteToOnlyHR(prototype.hand_open_picture)
prototype.platform_picture.sheet.hr_version.filename = GetInserterImage("express/hr-platform")
ConvertSheetToOnlyHR(prototype.platform_picture.sheet)
data:extend({prototype})
--- express filter
momoPyTweak.item.filterInserter = momoIRTweak.item.NewItemFixedSize("momo-express-filter-inserter", 32, "inserter", 50)
momoPyTweak.item.filterInserter.order = "zz2"
momoPyTweak.item.filterInserter.place_result = "momo-express-filter-inserter"
prototype = momoIRTweak.DeepCopy(data.raw.inserter["filter-inserter"])
prototype.icon_size = 32
prototype.icon = momoPyTweak.item.filterInserter.icon
prototype.name = "momo-express-filter-inserter"
prototype.max_health = 600
prototype.energy_per_movement = "12KJ"
prototype.energy_per_rotation = "12KJ"
prototype.energy_source.drain = "1kW"
prototype.extension_speed = 0.14
prototype.rotation_speed = 0.08
prototype.minable.result = "momo-express-filter-inserter"
prototype.hand_base_picture.hr_version.filename = GetInserterImage("express-filter/hr-hand-base")
ConvertSpriteToOnlyHR(prototype.hand_base_picture)
prototype.hand_closed_picture.hr_version.filename = GetInserterImage("express-filter/hr-hand-closed")
ConvertSpriteToOnlyHR(prototype.hand_closed_picture)
prototype.hand_open_picture.hr_version.filename = GetInserterImage("express-filter/hr-hand-open")
ConvertSpriteToOnlyHR(prototype.hand_open_picture)
prototype.platform_picture.sheet.hr_version.filename = GetInserterImage("express-filter/hr-platform")
ConvertSheetToOnlyHR(prototype.platform_picture.sheet)
data:extend({prototype})
-- stack express
momoPyTweak.item.stackInserter = momoIRTweak.item.NewItemFixedSize("momo-express-stack-inserter", 32, "inserter", 50)
momoPyTweak.item.stackInserter.order = "zz3"
momoPyTweak.item.stackInserter.place_result = "momo-express-stack-inserter"
prototype = momoIRTweak.DeepCopy(data.raw.inserter["stack-inserter"])
prototype.icon_size = 32
prototype.icon = momoPyTweak.item.stackInserter.icon
prototype.name = "momo-express-stack-inserter"
prototype.max_health = 600
prototype.energy_per_movement = "30KJ"
prototype.energy_per_rotation = "30KJ"
prototype.energy_source.drain = "1kW"
prototype.extension_speed = 0.14
prototype.rotation_speed = 0.08
prototype.minable.result = "momo-express-stack-inserter"
prototype.hand_base_picture.hr_version.filename = GetInserterImage("express-stack/hr-hand-base")
ConvertSpriteToOnlyHR(prototype.hand_base_picture)
prototype.hand_closed_picture.hr_version.filename = GetInserterImage("express-stack/hr-hand-closed")
ConvertSpriteToOnlyHR(prototype.hand_closed_picture)
prototype.hand_open_picture.hr_version.filename = GetInserterImage("express-stack/hr-hand-open")
ConvertSpriteToOnlyHR(prototype.hand_open_picture)
prototype.platform_picture.sheet.hr_version.filename = GetInserterImage("express-stack/hr-platform")
ConvertSheetToOnlyHR(prototype.platform_picture.sheet)
data:extend({prototype})
-- stack express filter
momoPyTweak.item.stackFilterInserter = momoIRTweak.item.NewItemFixedSize("momo-express-stack-filter-inserter", 32, "inserter", 50)
momoPyTweak.item.stackFilterInserter.order = "zz4"
momoPyTweak.item.stackFilterInserter.place_result = "momo-express-stack-filter-inserter"
prototype = momoIRTweak.DeepCopy(data.raw.inserter["stack-filter-inserter"])
prototype.icon_size = 32
prototype.icon = momoPyTweak.item.stackFilterInserter.icon
prototype.name = "momo-express-stack-filter-inserter"
prototype.max_health = 600
prototype.energy_per_movement = "31KJ"
prototype.energy_per_rotation = "31KJ"
prototype.energy_source.drain = "1kW"
prototype.extension_speed = 0.14
prototype.rotation_speed = 0.08
prototype.minable.result = "momo-express-stack-filter-inserter"
prototype.hand_base_picture.hr_version.filename = GetInserterImage("express-stack-filter/hr-hand-base")
ConvertSpriteToOnlyHR(prototype.hand_base_picture)
prototype.hand_closed_picture.hr_version.filename = GetInserterImage("express-stack-filter/hr-hand-closed")
ConvertSpriteToOnlyHR(prototype.hand_closed_picture)
prototype.hand_open_picture.hr_version.filename = GetInserterImage("express-stack-filter/hr-hand-open")
ConvertSpriteToOnlyHR(prototype.hand_open_picture)
prototype.platform_picture.sheet.hr_version.filename = GetInserterImage("express-stack-filter/hr-platform")
ConvertSheetToOnlyHR(prototype.platform_picture.sheet)
data:extend({prototype})
end
function momoPyTweak.updates.Inserter()
local ITEM = momoIRTweak.FastItem
local item = momoPyTweak.item
momoIRTweak.recipe.NewRecipe("crafting", item.inserter.name, 1, {
ITEM("fast-inserter", 1),
ITEM("processing-unit", 5),
ITEM("super-alloy", 10),
ITEM("small-parts-02", 5)
}, 30)
momoIRTweak.recipe.NewRecipe("crafting", item.filterInserter.name, 1, {
ITEM("filter-inserter", 1),
ITEM("advanced-circuit", 10),
ITEM("processing-unit", 5),
ITEM("super-alloy", 10),
ITEM("small-parts-02", 5)
}, 30)
momoIRTweak.recipe.NewRecipe("crafting", item.stackInserter.name, 1, {
ITEM("stack-inserter", 1),
ITEM("processing-unit", 10),
ITEM("super-alloy", 5),
ITEM("super-steel", 5),
ITEM("small-parts-02", 5)
}, 30)
momoIRTweak.recipe.NewRecipe("crafting", item.stackFilterInserter.name, 1, {
ITEM("stack-filter-inserter", 1),
ITEM("processing-unit", 10),
ITEM("advanced-circuit", 10),
ITEM("super-alloy", 5),
ITEM("super-steel", 5),
ITEM("small-parts-02", 5)
}, 30)
end
function momoPyTweak.updates.InserterTechnology()
local tech = momoIRTweak.technology
local item = momoPyTweak.item
local prototype = tech.ClonePrototype("fast-inserter", "momo-inserter")
tech.SetPrerequirePrototype(prototype, {"stack-inserter", "fine-electronics"})
tech.ClearEffects(prototype)
tech.SetUnit(prototype, {
{momoPyTweak.science.pack1, 1},
{momoPyTweak.science.pack2, 1},
{momoPyTweak.science.pack3, 1}
}, 60, 300)
data:extend({prototype})
momoPyTweak.technology.inserter = data.raw.technology["momo-inserter"]
if (momoPyTweak.settings.inserter) then
momoPyTweak.technology.inserter.enabled = true
tech.AddUnlockEffect("momo-inserter", item.inserter.name)
tech.AddUnlockEffect("momo-inserter", item.filterInserter.name)
tech.AddUnlockEffect("momo-inserter", item.stackInserter.name)
tech.AddUnlockEffect("momo-inserter", item.stackFilterInserter.name)
else
momoPyTweak.technology.inserter.enabled = false
end
end
|
-- Settings, Using Global Variables
-- Apple
gapple_apple = "default:apple"
-- Exteriors
gapple_gold = "default:gold_ingot"
gapple_steel = "default:steel_ingot"
gapple_copper = "default:copper_ingot"
gapple_diamond = "default:diamond"
gapple_mese = "default:mese_crystal"
gapple_obsidian = "default:obsidian_block"
-- Values, every 2 hit points equals 1 full heart
gapple_value_gold = 12
gapple_value_steel = 10
gapple_value_copper = 14
gapple_value_diamond = 16
gapple_value_obsidian = 18
gapple_value_mese = 20
-- End of settings
-- The order is the best to least from top to bottom
dofile(minetest.get_modpath("gapple") .. "/mese_crystal.lua")
dofile(minetest.get_modpath("gapple") .. "/obsidian.lua")
dofile(minetest.get_modpath("gapple") .. "/diamond.lua")
dofile(minetest.get_modpath("gapple") .. "/copper.lua")
dofile(minetest.get_modpath("gapple") .. "/golden.lua")
dofile(minetest.get_modpath("gapple") .. "/steel.lua")
|
local teleports = {
[2150] = {text = 'Entering Ushuriel\'s ward.', newPos = Position(33158, 31728, 11), storage = 0, alwaysSetStorage = true}, -- to ushuriel ward
[2151] = {text = 'Entering the Crystal Caves.', bossStorage = 200, newPos = Position(33069, 31782, 13), storage = 1}, -- from ushuriel ward
[2152] = {text = 'Escaping back to the Retreat.', newPos = Position(33165, 31709, 14)}, -- from crystal caves
[2153] = {text = 'Entering the Crystal Caves.', newPos = Position(33069, 31782, 13), storage = 1}, -- to crystal caves
[2154] = {text = 'Entering the Sunken Caves.', newPos = Position(33169, 31755, 13)}, -- to sunken caves
[2155] = {text = 'Entering the Mirror Maze of Madness.', newPos = Position(33065, 31772, 10)}, -- from sunken caves
[2156] = {text = 'Entering Zugurosh\'s ward.', newPos = Position(33124, 31692, 11)}, -- to zugurosh ward
[2157] = {text = 'Entering the Blood Halls.', bossStorage = 201, newPos = Position(33372, 31613, 14), storage = 2}, -- from zugurosh ward
[2158] = {text = 'Escaping back to the Retreat.', newPos = Position(33165, 31709, 14)}, -- from blood halls
[2159] = {text = 'Entering the Blood Halls.', newPos = Position(33372, 31613, 14), storage = 2}, -- to blood halls
[2160] = {text = 'Entering the Foundry.', newPos = Position(33356, 31589, 11)}, -- to foundry
[2161] = {text = 'Entering Madareth\'s ward.', newPos = Position(33197, 31767, 11)}, -- to madareth ward
[2162] = {text = 'Entering the Vats.', bossStorage = 202, newPos = Position(33153, 31782, 12), storage = 3}, -- from madareth ward
[2163] = {text = 'Escaping back to the Retreat.', newPos = Position(33165, 31709, 14)}, -- from vats
[2164] = {text = 'Entering the Vats.', newPos = Position(33153, 31782, 12), storage = 3}, -- to vats
[2165] = {text = 'Entering the Battlefield.', newPos = Position(33250, 31632, 13)}, -- to battlefield
[2166] = {text = 'Entering the Vats.', newPos = Position(33233, 31758, 12)}, -- from battlefield
[2167] = {text = 'Entering the Demon Forge.', newPos = Position(33232, 31733, 11)}, -- to brothers ward
[2168] = {text = 'Entering the Arcanum.', bossStorage = 203, newPos = Position(33038, 31753, 15), storage = 4}, -- from demon forge
[2169] = {text = 'Escaping back to the Retreat.', newPos = Position(33165, 31709, 14)}, -- from arcanum
[2170] = {text = 'Entering the Arcanum.', newPos = Position(33038, 31753, 15), storage = 4}, -- to arcanum
[2171] = {text = 'Entering the Soul Wells.', newPos = Position(33093, 31575, 11)}, -- to soul wells
[2172] = {text = 'Entering the Arcanum.', newPos = Position(33186, 31759, 15)}, -- from soul wells
[2173] = {text = 'Entering the Annihilon\'s ward.', newPos = Position(33197, 31703, 11)}, -- to annihilon ward
[2174] = {text = 'Entering the Hive.', bossStorage = 204, newPos = Position(33199, 31686, 12), storage = 5}, -- from annihilon ward
[2175] = {text = 'Escaping back to the Retreat.', newPos = Position(33165, 31709, 14)}, -- from hive
[2176] = {text = 'Entering the Hive.', newPos = Position(33199, 31686, 12), storage = 5}, -- to hive
[2177] = {text = 'Entering the Hellgorak\'s ward.', newPos = Position(33104, 31734, 11)}, -- to hellgorak ward
[2178] = {text = 'Entering the Shadow Nexus. Abandon all Hope.', bossStorage = 205, newPos = Position(33110, 31682, 12), storage = 6}, -- from hellgorak ward
[2179] = {text = 'Escaping back to the Retreat.', newPos = Position(33165, 31709, 14)}, -- from shadow nexus
[2180] = {text = 'Entering the Blood Halls.', newPos = Position(33357, 31589, 12)} -- from foundry to blood halls
}
function onStepIn(creature, item, position, fromPosition)
local player = creature:getPlayer()
if not player then
return true
end
local teleport = teleports[item.uid]
if teleport.alwaysSetStorage and player:getStorageValue(Storage.TheInquisition.EnterTeleport) < teleport.storage then
player:setStorageValue(Storage.TheInquisition.EnterTeleport, teleport.storage)
end
if teleport.bossStorage then
if Game.getStorageValue(teleport.bossStorage) == 2 then
if player:getStorageValue(Storage.TheInquisition.EnterTeleport) < teleport.storage then
player:setStorageValue(Storage.TheInquisition.EnterTeleport, teleport.storage)
end
else
player:teleportTo(Position(33165, 31709, 14))
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
player:say('Escaping back to the Retreat.', TALKTYPE_MONSTER_SAY)
return true
end
elseif teleport.storage and player:getStorageValue(Storage.TheInquisition.EnterTeleport) < teleport.storage then
player:teleportTo(fromPosition)
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
player:say('You don\'t have enough energy to enter this portal', TALKTYPE_MONSTER_SAY)
return true
end
player:teleportTo(teleport.newPos)
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
player:say(teleport.text, TALKTYPE_MONSTER_SAY)
return true
end
|
local S = aurum.get_translator()
gemai.register_action("aurum_npcs:avatar_caligula_attack_modify", function(self)
local nearby = math.max(1, aurum.mobs.helper_nearby_players(self))
self.data.regen_rate = nearby * 10
end)
aurum.mobs.register("aurum_npcs:avatar_caligula", {
description = S"Avatar of Caligula",
herd = "aurum:servitors",
longdesc = S"Lord of the Dead City.",
box = {-0.35, -0.35, -0.35, 0.35, 0.85, 0.35},
initial_properties = {
visual = "sprite",
textures = {"aurum_npcs_avatar_caligula.png"},
visual_size = {x = 1, y = 2},
hp_max = 100,
},
pathfinder = aurum.mobs.DEFAULT_FLY_PATHFINDER,
initial_data = {
habitat_nodes = {"group:dirt", "group:stone", "group:clay", "group:clay_brick"},
xmana = 100,
movement = "fly",
hunt_prey = {"player"},
regen_rate = 1,
attack = b.t.combine(aurum.mobs.initial_data.attack, {
damage = {chill = 10, psyche = 10, impact = 10},
}),
base_speed = 1,
},
entity_def = {
_mob_init = function(self)
self._data.gemai.drops = {"aurum_fear:ultimus " .. math.random(1, 3)}
end,
},
armor_groups = {chill = 0, psyche = 0},
gemai = {
global_actions = {
"aurum_mobs:physics",
"aurum_mobs:environment",
"aurum_mobs:regen",
},
global_events = {
punch = "go_fight",
interact = "",
herd_alerted = "go_fight",
lost = "roam",
stuck = "roam",
},
states = {
init = {
events = {
init = "roam",
},
},
roam = {
actions = {
"aurum_mobs:find_prey",
"aurum_mobs:find_habitat",
"aurum_mobs:find_random",
},
events = {
found_prey = "go_fight",
found_habitat = "go",
found_random = "go",
},
},
go = {
actions = {
"aurum_mobs:find_prey",
"aurum_mobs:teleport",
},
events = {
found_prey = "go_fight",
reached = "roam",
},
},
go_fight = {
actions = {
"aurum_mobs:teleport",
"aurum_mobs:alert_herd",
"aurum_mobs:timeout",
},
events = {
reached = "fight",
},
},
fight = {
actions = {
"aurum_mobs:adrenaline",
"aurum_mobs:alert_herd",
"aurum_mobs:attack",
},
events = {
noreach = "go_fight",
},
},
},
},
})
|
--[[ Copyright (C) 2018-2019 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
]]
local property_helpers = require 'common.property_helpers'
local asserts = require 'testing.asserts'
local test_runner = require 'testing.test_runner'
local tests = {}
local RESULT = property_helpers.RESULT
function tests.headTailSplit()
local headTailSplit = property_helpers.headTailSplit
asserts.tablesEQ({headTailSplit('aaa.bbb.ccc')}, {'aaa', 'bbb.ccc'})
asserts.tablesEQ({headTailSplit('aaa')}, {'aaa', nil})
asserts.tablesEQ({headTailSplit('10.12')}, {10, '12'})
end
function tests.readProperty()
local readProperty = property_helpers.readProperty
asserts.EQ(readProperty({abc = {a = 1, b = 2, c = 3}}, 'abc.b'), '2')
asserts.EQ(readProperty({abc = {a = 1, b = 2, c = 3}}, 'abc.d'),
RESULT.NOT_FOUND)
asserts.EQ(readProperty({abc = {'a', 'b', 'c'}}, 'abc.2'), 'b')
asserts.EQ(readProperty({abc = {'a', 'b', 'c'}}, 'abc.0'), RESULT.NOT_FOUND)
local params = {abc = function(listKeys) return listKeys .. listKeys end}
asserts.EQ(readProperty(params, 'abc.hello'), 'hellohello')
end
function tests.writeProperty()
local writeProperty = property_helpers.writeProperty
local params = {abc = {a = '1', b = 2, c = true}}
asserts.EQ(writeProperty(params, 'abc.a', '11'), RESULT.SUCCESS)
asserts.tablesEQ(params, {abc = {a = '11', b = 2, c = true}})
asserts.EQ(writeProperty(params, 'abc.b', '22'), RESULT.SUCCESS)
asserts.tablesEQ(params, {abc = {a = '11', b = 22, c = true}})
asserts.EQ(writeProperty(params, 'abc.c', 'false'), RESULT.SUCCESS)
asserts.tablesEQ(params, {abc = {a = '11', b = 22, c = false}})
local params2 = {}
params2.abc = {
add = function(key, value)
params2.abc[key] = value
return RESULT.SUCCESS
end
}
asserts.EQ(writeProperty(params2, 'abc.add.newKey', 'newValue'),
RESULT.SUCCESS)
asserts.EQ(params2.abc.newKey, 'newValue')
end
function tests.addProperty()
local addProperty = property_helpers.addProperty
local params = {}
asserts.EQ(addProperty(params, 'abc.b', 2), true)
asserts.tablesEQ(params, {abc = {b = 2}})
asserts.EQ(addProperty(params, 'abc.a', '1'), true)
asserts.tablesEQ(params, {abc = {a = '1', b = 2}})
asserts.EQ(addProperty(params, 'abc.a', '11'), false)
asserts.tablesEQ(params, {abc = {a = '1', b = 2}})
asserts.EQ(addProperty(params, 'abc.c', {'c1', 'c2', 'c3'}), true)
asserts.tablesEQ(params, {abc = {a = '1', b = 2, c = {'c1', 'c2', 'c3'}}})
end
function tests.removeProperty()
local removeProperty = property_helpers.removeProperty
local params = {abc = {a = '1', b = 2, c = {'c1', 'c2', 'c3'}}}
asserts.EQ(removeProperty(params, 'abc.b'), true)
asserts.tablesEQ(params, {abc = {a = '1', c = {'c1', 'c2', 'c3'}}})
asserts.EQ(removeProperty(params, 'abc.a'), true)
asserts.tablesEQ(params, {abc = {c = {'c1', 'c2', 'c3'}}})
asserts.EQ(removeProperty(params, 'abc.c.2'), true)
asserts.tablesEQ(params, {abc = {c = {[1] = 'c1', [3] = 'c3'}}})
asserts.EQ(removeProperty(params, 'abc'), true)
asserts.tablesEQ(params, {})
end
return test_runner.run(tests)
|
--Make sure the commonjs loader pattern is in
require '../node-resolve'
--Make sure you `npm install luadash` first
local __ = require 'luadash'
local input = {1, 2, 3}
print("in: ", table.concat(input, ", "))
function double (value)
return value * 2
end
print("out: ", table.concat(__.map(double, input), ", "))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.