content stringlengths 5 1.05M |
|---|
-- Custom Extensions to the God-Controller
local God = {}
God.onBuiltEntityFilters = {
{ filter = "type", type = "tile-ghost" },
{ filter = "type", type = "entity-ghost" },
{ filter = "type", type = "item-request-proxy" },
}
-- Whether the Entity or Tile is a Ghost (can be revived)
function God.IsCreatable(entity)
return entity.valid
and (entity.type == "tile-ghost"
or entity.type == "entity-ghost"
or entity.type == "item-request-proxy")
end
-- Immediately destroy an Entity (and perhaps related Entities)
function God.Destroy(entity)
if entity.valid
and entity.can_be_destroyed()
and entity.to_be_deconstructed()
then
-- If the Entity has Transport Lines, also delete any Items on it
if entity.prototype.belt_speed ~= nil then
for i = 1, entity.get_max_transport_line_index() do
entity.get_transport_line(i).clear()
end
end
-- If the Entity represents a Hidden Tile underneath
if entity.type == "deconstructible-tile-proxy" then
local hiddenTile = entity.surface.get_hidden_tile(entity.position)
entity.surface.set_tiles {
{
name = hiddenTile,
position = entity.position,
}
}
end
entity.destroy({ raise_destroy = true })
end
end
-- Immediately Insert an Entity's Requests
function God.InsertRequests(entity)
if entity.valid
and entity.type == "item-request-proxy"
and entity.proxy_target then
-- Insert any Requested Items (like Modules, Fuel)
for name, count in pairs(entity.item_requests) do
entity.proxy_target.insert({
name = name,
count = count,
})
end
entity.destroy()
end
end
-- Immediately Revive a Ghost Entity
function God.Create(entity)
if entity.valid then
if entity.type == "tile-ghost" then
-- Tiles are simple Revives
entity.silent_revive({ raise_revive = true })
elseif entity.type == "item-request-proxy" then
-- Requests are simple
God.InsertRequests(entity)
elseif entity.type == "entity-ghost" then
-- Entities might also want Items after Reviving
local _, revived, request = entity.silent_revive({
return_item_request_proxy = true,
raise_revive = true
})
if not revived or not request then return end
God.InsertRequests(request)
end
end
end
-- Immediately turn one Entity into another
function God.Upgrade(entity)
if entity.valid
and entity.to_be_upgraded()
then
local target = entity.get_upgrade_target()
local direction = entity.get_upgrade_direction()
local options = {
name = target.name,
position = entity.position,
direction = direction or entity.direction,
force = entity.force,
fast_replace = true,
spill = false,
raise_built = true,
}
-- Otherwise it fails to place "output" sides (it defaults to "input")
if entity.type == "underground-belt" then
options.type = entity.belt_to_ground_type
end
local result = entity.surface.create_entity(options)
if result == nil then
Debug.log("Upgrade Failed, Cancelling: " .. entity.name)
entity.cancel_upgrade(entity.force)
end
end
end
-- Ensure the God's Inventory is kept in-sync
function God.OnInventoryChanged(event)
local player = game.players[event.player_index]
local playerData = global.players[event.player_index]
if playerData.insideSandbox ~= nil then
Inventory.Prune(player)
playerData.sandboxInventory = Inventory.Persist(
player.get_main_inventory(),
playerData.sandboxInventory
)
end
end
-- Ensure newly-crafted Items are put into the Cursor for use
function God.OnPlayerCraftedItem(event)
local player = game.players[event.player_index]
local playerData = global.players[event.player_index]
if playerData.insideSandbox ~= nil
and player.cursor_stack
and player.cursor_stack.valid
and event.item_stack.valid
and event.item_stack.valid_for_read
and event.recipe.valid
and (
#event.recipe.products == 1
or (
event.recipe.prototype.main_product
and event.recipe.prototype.main_product.name == event.item_stack.name
)
)
and player.mod_settings[Settings.craftToCursor].value
then
event.item_stack.count = event.item_stack.prototype.stack_size
player.cursor_stack.clear()
player.cursor_stack.transfer_stack(event.item_stack)
end
end
function God.HandlerWrapper(setting, surfaceGroup, handler, entity)
surfaceGroup[entity.surface.name].hasRequests = true
if settings.global[setting].value == 0 then
handler(entity)
end
end
-- Ensure new Orders are handled
function God.OnMarkedForDeconstruct(event)
-- Debug.log("Entity Deconstructing: " .. event.entity.unit_number .. " " .. event.entity.type)
if Lab.IsLab(event.entity.surface) then
God.HandlerWrapper(
Settings.godAsyncDeleteRequestsPerTick,
global.labSurfaces,
God.Destroy,
event.entity
)
elseif SpaceExploration.IsSandbox(event.entity.surface) then
God.HandlerWrapper(
Settings.godAsyncDeleteRequestsPerTick,
global.seSurfaces,
God.Destroy,
event.entity
)
end
end
-- Ensure new Orders are handled
function God.OnMarkedForUpgrade(event)
-- Debug.log("Entity Upgrading: " .. event.entity.unit_number .. " " .. event.entity.type)
if Lab.IsLab(event.entity.surface) then
God.HandlerWrapper(
Settings.godAsyncUpgradeRequestsPerTick,
global.labSurfaces,
God.Upgrade,
event.entity
)
elseif SpaceExploration.IsSandbox(event.entity.surface) then
God.HandlerWrapper(
Settings.godAsyncUpgradeRequestsPerTick,
global.seSurfaces,
God.Upgrade,
event.entity
)
end
end
-- Ensure new Ghosts are handled
function God.OnBuiltEntity(event)
-- Debug.log("Entity Creating: " .. event.created_entity.unit_number .. " " .. event.created_entity.type)
if Lab.IsLab(event.created_entity.surface) then
God.HandlerWrapper(
Settings.godAsyncCreateRequestsPerTick,
global.labSurfaces,
God.Create,
event.created_entity
)
elseif SpaceExploration.IsSandbox(event.created_entity.surface) then
God.HandlerWrapper(
Settings.godAsyncCreateRequestsPerTick,
global.seSurfaces,
God.Create,
event.created_entity
)
end
end
-- For each known Sandbox Surface, handle any async God functionality
function God.HandleSandboxRequests(surfaces)
local createRequestsPerTick = settings.global[Settings.godAsyncCreateRequestsPerTick].value
local upgradeRequestsPerTick = settings.global[Settings.godAsyncUpgradeRequestsPerTick].value
local deleteRequestsPerTick = settings.global[Settings.godAsyncDeleteRequestsPerTick].value
for surfaceName, surfaceData in pairs(surfaces) do
if surfaceData.hasRequests then
local surface = game.surfaces[surfaceName]
local requestsHandled = 0
local requestedDeconstructions = surface.find_entities_filtered({
to_be_deconstructed = true,
limit = deleteRequestsPerTick,
})
for _, request in pairs(requestedDeconstructions) do
requestsHandled = requestsHandled + 1
God.Destroy(request)
end
local requestedUpgrades = surface.find_entities_filtered({
to_be_upgraded = true,
limit = upgradeRequestsPerTick,
})
for _, request in pairs(requestedUpgrades) do
requestsHandled = requestsHandled + 1
God.Upgrade(request)
end
local requestedRevives = surface.find_entities_filtered({
type = "entity-ghost",
limit = createRequestsPerTick,
})
for _, request in pairs(requestedRevives) do
requestsHandled = requestsHandled + 1
God.Create(request)
end
requestedRevives = surface.find_entities_filtered({
type = "tile-ghost",
limit = createRequestsPerTick,
})
for _, request in pairs(requestedRevives) do
requestsHandled = requestsHandled + 1
God.Create(request)
end
local requestedInserts = surface.find_entities_filtered({
type = "item-request-proxy",
limit = createRequestsPerTick,
})
for _, request in pairs(requestedInserts) do
requestsHandled = requestsHandled + 1
God.Create(request)
end
if requestsHandled == 0 then
surfaceData.hasRequests = false
end
end
end
end
-- Wrapper for Event Handlers
function God.HandleAllSandboxRequests(event)
God.HandleSandboxRequests(global.labSurfaces)
God.HandleSandboxRequests(global.seSurfaces)
end
-- Charts each Sandbox that a Player is currently inside of
function God.ChartAllOccupiedSandboxes()
if settings.global[Settings.scanSandboxes].value then
local charted = {}
for _, player in pairs(game.players) do
local hash = player.force.name .. player.surface.name
if Sandbox.IsSandbox(player.surface) and not charted[hash] then
player.force.chart_all(player.surface)
charted[hash] = true
end
end
end
end
return God
|
ITEM.name = "12.7×40mm M228 SAP-HP"
ITEM.model = "models/Items/BoxSRounds.mdl"
ITEM.ammo = "pistol" -- type of the ammo
ITEM.ammoAmount = 240 -- amount of the ammo
ITEM.description = "M228 Semi-Armor-Piercing High-Penetration ammunition used in the M6C/SOCOM."
|
return {'ulo','uloschool','uloscholen'} |
-- Create a standard Solar2D newText display object and reveal it character by character.
local function newRollingText( text, x, y, font, fontSize, revealTime )
if type( text ) == "string" then
local length = text:len()
if length > 0 then
local object = display.newText( "", x or 0, y or 0, font or native.systemFont, fontSize or 18 )
object.anchorX, object.anchorY = 0, 0
local time = revealTime and revealTime/length
if time then
local n = 1
timer.performWithDelay( time, function()
object.text = text:sub(1,n)
n = n+1
end, length )
else
object.text = text
end
return object
end
end
end
local sampleText = newRollingText( "Here's a cool rolling text sample:\n\nHello world!", 40, 80, native.systemFont, 24, 1200 ) |
local AddonName, AddonTable = ...
AddonTable.skinning = {
110609, -- Raw Beast Hide
110610, -- Raw Beast Hide Scraps
}
|
local F, G, V = unpack(select(2, ...))
function F.rebackdrop(frame)
frame:SetBackdrop(nil)
frame:SetBackdrop({
bgFile = [[Interface\Buttons\WHITE8x8]],
edgeFile = [[Interface\Buttons\WHITE8x8]],
edgeSize = 1,
})
frame:SetBackdropColor(unpack(G.colors.base))
frame:SetBackdropBorderColor(unpack(G.colors.border))
end
function F.rebackdroplight(frame)
frame:SetBackdrop(nil)
frame:SetBackdrop({
bgFile = [[Interface\Buttons\WHITE8x8]],
edgeFile = [[Interface\Buttons\WHITE8x8]],
edgeSize = 1,
})
frame:SetBackdropColor(G.colors.base[1] + 0.05, G.colors.base[2] + 0.05, G.colors.base[3] + 0.05, G.colors.base[4])
frame:SetBackdropBorderColor(unpack(G.colors.border))
end |
function onCreate()
setProperty('timeTxt.text', 'Target');
end |
local PixelShuffle, parent = torch.class("nn.PixelShuffle", "nn.Module")
-- Shuffles pixels after upscaling with a ESPCNN model
-- Converts a [batch x channel*r^2 x m x p] tensor to [batch x channel x r*m x r*p]
-- tensor, where r is the upscaling factor.
-- @param upscaleFactor - the upscaling factor to use
function PixelShuffle:__init(upscaleFactor)
parent.__init(self)
self.upscaleFactor = upscaleFactor
self.upscaleFactorSquared = self.upscaleFactor * self.upscaleFactor
end
-- Computes the forward pass of the layer i.e. Converts a
-- [batch x channel*r^2 x m x p] tensor to [batch x channel x r*m x r*p] tensor.
-- @param input - the input tensor to be shuffled of size [b x c*r^2 x m x p]
-- @return output - the shuffled tensor of size [b x c x r*m x r*p]
function PixelShuffle:updateOutput(input)
self._intermediateShape = self._intermediateShape or torch.LongStorage(6)
self._outShape = self.outShape or torch.LongStorage()
self._shuffleOut = self._shuffleOut or input.new()
local batched = false
local batchSize = 1
local inputStartIdx = 1
local outShapeIdx = 1
if input:nDimension() == 4 then
batched = true
batchSize = input:size(1)
inputStartIdx = 2
outShapeIdx = 2
self._outShape:resize(4)
self._outShape[1] = batchSize
else
self._outShape:resize(3)
end
--input is of size h/r w/r, rc output should be h, r, c
local channels = input:size(inputStartIdx) / self.upscaleFactorSquared
local inHeight = input:size(inputStartIdx + 1)
local inWidth = input:size(inputStartIdx + 2)
self._intermediateShape[1] = batchSize
self._intermediateShape[2] = channels
self._intermediateShape[3] = self.upscaleFactor
self._intermediateShape[4] = self.upscaleFactor
self._intermediateShape[5] = inHeight
self._intermediateShape[6] = inWidth
self._outShape[outShapeIdx] = channels
self._outShape[outShapeIdx + 1] = inHeight * self.upscaleFactor
self._outShape[outShapeIdx + 2] = inWidth * self.upscaleFactor
local inputView = torch.view(input, self._intermediateShape)
self._shuffleOut:resize(inputView:size(1), inputView:size(2), inputView:size(5),
inputView:size(3), inputView:size(6), inputView:size(4))
self._shuffleOut:copy(inputView:permute(1, 2, 5, 3, 6, 4))
self.output = torch.view(self._shuffleOut, self._outShape)
return self.output
end
-- Computes the backward pass of the layer, given the gradient w.r.t. the output
-- this function computes the gradient w.r.t. the input.
-- @param input - the input tensor of shape [b x c*r^2 x m x p]
-- @param gradOutput - the tensor with the gradients w.r.t. output of shape [b x c x r*m x r*p]
-- @return gradInput - a tensor of the same shape as input, representing the gradient w.r.t. input.
function PixelShuffle:updateGradInput(input, gradOutput)
self._intermediateShape = self._intermediateShape or torch.LongStorage(6)
self._shuffleIn = self._shuffleIn or input.new()
local batchSize = 1
local inputStartIdx = 1
if input:nDimension() == 4 then
batchSize = input:size(1)
inputStartIdx = 2
end
local channels = input:size(inputStartIdx) / self.upscaleFactorSquared
local height = input:size(inputStartIdx + 1)
local width = input:size(inputStartIdx + 2)
self._intermediateShape[1] = batchSize
self._intermediateShape[2] = channels
self._intermediateShape[3] = height
self._intermediateShape[4] = self.upscaleFactor
self._intermediateShape[5] = width
self._intermediateShape[6] = self.upscaleFactor
local gradOutputView = torch.view(gradOutput, self._intermediateShape)
self._shuffleIn:resize(gradOutputView:size(1), gradOutputView:size(2), gradOutputView:size(4),
gradOutputView:size(6), gradOutputView:size(3), gradOutputView:size(5))
self._shuffleIn:copy(gradOutputView:permute(1, 2, 4, 6, 3, 5))
self.gradInput = torch.view(self._shuffleIn, input:size())
return self.gradInput
end
function PixelShuffle:clearState()
nn.utils.clear(self, {
"_intermediateShape",
"_outShape",
"_shuffleIn",
"_shuffleOut",
})
return parent.clearState(self)
end
|
return {
load="viewer/load.lua",
doInitSDL=true,
}
|
local lzug = require('luftzug')
vim.api.nvim_buf_set_keymap(0, 'n', '<Plug>LzugAddReference', "<cmd>call v:lua.lzug_add_reference()<CR>", { noremap = true})
vim.api.nvim_buf_set_keymap(0, 'n', '<Plug>LzugFollowFootnoteOrLink', "<cmd>call v:lua.lzug_handle_tab()<CR>", { noremap = true})
vim.api.nvim_buf_set_keymap(0, 'n', '<Plug>LzugAddLink', "<cmd>call v:lua.lzug_add_link()<CR>", { noremap = true})
if vim.g.luftzug_follow_link_keymap then
vim.api.nvim_buf_set_keymap(0, 'n', vim.g.luftzug_follow_link_keymap, "<Plug>LzugFollowFootnoteOrLink", { noremap = false })
end
-- vim.cmd([[command! -buffer LuftzugFormatBuffer :lua require'luftzug'.format_buffer()]])
-- vim.cmd([[autocmd BufWritePre <buffer> :LuftzugFormatBuffer]])
vim.cmd([[command! -nargs=* -buffer LzugAddFootnote :lua require'luftzug'.add_footnote(<q-args>)]])
|
local p2p_discovery = require "defnet.p2p_discovery"
local udp = require "defnet.udp"
local trickle = require "game.trickle"
local M = {}
local P2P_PORT = 50000
local UDP_SERVER_PORT = 9192
local STATE_LISTENING = "STATE_LISTENING"
local STATE_JOINED_GAME = "STATE_JOINED_GAME"
local STATE_HOSTING_GAME = "STATE_HOSTING_GAME"
local function generate_unique_id()
return tostring(socket.gettime()) .. tostring(os.clock()) .. tostring(math.random(99999,10000000))
end
local mp = {
id = nil,
state = nil,
clients = {},
message_signatures = {},
message_handlers = {},
stream = trickle.create(),
}
M.HEARTBEAT = "HEARTBEAT"
M.JOIN_SERVER = "JOIN_SERVER"
M.PLAYER_ACTION = "PLAYER_ACTION"
local join_server_signature = {
{ "id", "string" },
}
local heartbeat_signature = {
{ "id", "string" },
}
local player_action_signature = {
{ "id", "string" },
{ "action", "string" },
}
local function create_join_server_message(id)
assert(id, "You must provide an id")
local message = trickle.create()
message:writeString(M.JOIN_SERVER)
message:pack({ id = id }, join_server_signature)
return tostring(message)
end
local function create_heartbeat_message(id)
assert(id, "You must provide an id")
local message = trickle.create()
message:writeString(M.HEARTBEAT)
message:pack({ id = id }, heartbeat_signature)
return tostring(message)
end
local function create_player_action_message(id, action)
assert(id, "You must provide an id")
local message = trickle.create()
message:writeString(M.PLAYER_ACTION)
message:pack({ id = id, action = action }, player_action_signature)
return tostring(message)
end
function M.register_message(message_type, message_signature)
assert(message_type, "You must provide a message type")
assert(message_signature, "You must provide a message signature")
mp.message_signatures[message_type] = message_signature
end
function M.register_handler(message_type, handler_fn)
assert(message_type, "You must provide a message type")
assert(handler_fn, "You must provide a handler function")
mp.message_handlers[message_type] = mp.message_handlers[message_type] or {}
table.insert(mp.message_handlers[message_type], handler_fn)
end
local function handle_message(message_type, stream, from_ip, from_port)
assert(message_type, "You must provide a message type")
assert(stream, "You must provide a stream")
print("handle_message", message_type)
if mp.message_handlers[message_type] and mp.message_signatures[message_type] then
local message = stream:unpack(mp.message_signatures[message_type])
for _,handler in ipairs(mp.message_handlers[message_type]) do
handler(message, from_ip, from_port)
end
end
end
---
-- Add a client to the list of clients
-- Can be called multiple times without risking duplicates
-- @param ip Client ip
-- @param port Client port
-- @param id Client id
local function add_client(ip, port, id)
assert(ip, "You must provide an ip")
assert(port, "You must provide a port")
assert(id, "You must provide an id")
mp.clients[id] = { ip = ip, port = port, ts = socket.gettime(), id = id }
end
--- Update the timestamp for a client
-- @param id
local function refresh_client(id)
assert(id, "You must provide an id")
if mp.clients[id] then
mp.clients[id].ts = socket.gettime()
end
end
--- Send a message to all clients
-- @param message The message to send
local function send_to_clients(message)
assert(message, "You must provide a message")
for _,client in pairs(mp.clients) do
mp.udp_client.send(message, client.ip, client.port)
end
end
function M.send_player_action(action)
assert(mp.state == STATE_JOINED_GAME, "Wrong state")
mp.udp_client.send(create_player_action_message(mp.id, action), mp.host_ip, UDP_SERVER_PORT)
end
function M.server(on_player_action)
assert(on_player_action)
mp.id = generate_unique_id()
mp.p2p_broadcast = p2p_discovery.create(P2P_PORT)
M.register_message(M.JOIN_SERVER, join_server_signature)
M.register_message(M.PLAYER_ACTION, player_action_signature)
M.register_message(M.HEARTBEAT, heartbeat_signature)
M.register_handler(M.HEARTBEAT, function(message, from_ip, from_port)
refresh_client(message.id)
end)
M.register_handler(M.JOIN_SERVER, function(message, from_ip, from_port)
add_client(from_ip, from_port, message.id)
end)
M.register_handler(M.PLAYER_ACTION, function(message, from_ip, from_port)
on_player_action(message, from_ip, from_port)
end)
coroutine.wrap(function()
mp.state = STATE_HOSTING_GAME
mp.host_ip = "127.0.0.1"
-- incoming message handler
mp.udp_server = udp.create(function(data, ip, port)
local stream = trickle.create(data)
local message_type = stream:readString()
while message_type and message_type ~= "" do
handle_message(message_type, stream, ip, port)
message_type = stream:readString()
end
end, UDP_SERVER_PORT)
-- start broadcasting server existence
print("BROADCAST")
mp.p2p_broadcast.broadcast("findme")
timer.repeating(1, function()
-- check for clients that haven't sent a heartbeat for a while
-- and consider those clients disconnected
for k,client in pairs(mp.clients) do
if (socket.gettime() - client.ts) > 5 then
print("removing client", k)
mp.clients[k] = nil
end
end
end)
end)()
end
function M.client(on_connected)
assert(on_connected)
mp.id = generate_unique_id()
mp.p2p_listen = p2p_discovery.create(P2P_PORT)
coroutine.wrap(function()
-- create our UDP connection
-- we use this to communicate with the server
mp.udp_client = udp.create(function(data, ip, port)
local stream = trickle.create(data)
local message_type = stream:readString()
handle_message(message_type, stream, ip, port)
end)
-- let's start by listening if there's someone already looking for players
-- wait for a while and if we don't find a server we start broadcasting
print("LISTEN")
mp.state = STATE_LISTENING
mp.p2p_listen.listen("findme", function(ip, port)
print("Found server", ip, port)
mp.state = STATE_JOINED_GAME
mp.host_ip = ip
mp.p2p_listen.stop()
-- send join message to server
print("sending to server")
mp.udp_client.send(create_join_server_message(mp.id), mp.host_ip, UDP_SERVER_PORT)
on_connected(mp.id)
end)
-- send client heartbeat
timer.repeating(1, function()
if mp.state == STATE_JOINED_GAME then
print("sending heartbeat")
mp.udp_client.send(create_heartbeat_message(mp.id), mp.host_ip, UDP_SERVER_PORT)
end
end)
end)()
end
--- Stop the multiplayer module and all underlying systems
function M.stop()
if mp.p2p_listen then
mp.p2p_listen.stop()
end
if mp.p2p_broadcast then
mp.p2p_broadcast.stop()
end
if mp.udp_server then
mp.udp_server.destroy()
end
if mp.udp_client then
mp.udp_client.destroy()
end
end
--- Update the multiplayer module and all underlying systems
-- Any data added to the stream will be sent at this time and the
-- stream will be cleared
-- @param dt
function M.update(dt)
if mp.p2p_listen then
mp.p2p_listen.update()
end
if mp.p2p_broadcast then
mp.p2p_broadcast.update()
end
if mp.udp_server then
mp.udp_server.update()
end
if mp.udp_client then
mp.udp_client.update()
end
end
return M |
-- Copyright (c) 2021, The Pallene Developers
-- Pallene is licensed under the MIT license.
-- Please refer to the LICENSE and AUTHORS files for details
-- SPDX-License-Identifier: MIT
local util = require "pallene.util"
local typedecl = require "pallene.typedecl"
local types = require "pallene.types"
local ast = require "pallene.ast"
local checker = require "pallene.checker"
local converter = {}
--
-- ASSIGNMENT CONVERSION
-- ======================
-- This Compiler pass handles mutable captured variables inside nested closures by
-- transforming AST Nodes that reference or re-assign to them. All captured variables
-- are 'boxed' inside records. For example, consider this code:
-- ```
-- function m.foo()
-- local x: integer = 10
-- local set_x: (integer) -> () = function (y)
-- x = y
-- end
-- local get_x: () -> integer = function () return x end
-- end
--```
-- The AST representation of the above snippet, will be converted in this pass to
-- something like the following:
-- ```
-- record $T
-- value: integer
-- end
--
-- function m.foo()
-- local x: $T = { value = 10 }
-- local set_x: (integer) -> () = function (y)
-- x.value = y
-- end
-- local get_x: () -> integer = function () return x.value end
-- end
-- ```
local Converter = util.Class()
function converter.convert(prog_ast)
local conv = Converter.new()
conv:visit_prog(prog_ast)
-- transform the AST Nodes for captured vars.
conv:apply_transformations()
-- add the upvalue box record types to the AST
for _, node in ipairs(conv.box_records) do
table.insert(prog_ast.tls, node)
end
return prog_ast
end
-- Encapsulates an update to an AST Node.
-- `node`: The AST we will replace (we use it's location)
-- `update_fn`: A `node -> ()` function that is used to update the node.
local function NodeUpdate(node, update_fn)
return {
node = node,
update_fn = update_fn,
}
end
function Converter:init()
self.update_ref_of_decl = {} -- { ast.Decl => list of NodeUpdate }
-- The `func_depth_of_decl` maps a decl to the depth of the function where it appears.
-- This helps distinguish between mutated variables that are locals and globals from those
-- that are captured upvalues and need to be transformed to a different kind of node.
self.func_depth_of_decl = {} -- { ast.Decl => integer }
self.update_init_exp_of_decl = {} -- { ast.Decl => NodeUpdate }
self.mutated_decls = {} -- { ast.Decl }
self.captured_decls = {} -- { ast.Decl }
self.box_records = {} -- list of ast.Toplevel.Record
self.lambda_of_param = {} -- { ast.Decl => ast.Lambda }
-- Variables that are not initialized upon declaration can still be captured as
-- upvalues. In order to facilitate this, we add an `ast.Exp.UpvalueRecord` node
-- to the corresponding ast.Decl node.
self.add_init_exp_to_decl = {} -- { ast.Decl => NodeUpdate }
-- used to assign unique names to subsequently generated record types
self.typ_counter = 0
-- Depth of current function's nesting.
-- This does not take into account block scopes like `do...end`.
self.func_depth = 1
end
-- generates a unique type name each time
function Converter:type_name(var_name)
self.typ_counter = self.typ_counter + 1
return "$T_"..var_name.."_"..self.typ_counter
end
function Converter:add_box_type(loc, typ)
local dummy_node = ast.Toplevel.Record(loc, types.tostring(typ), {})
dummy_node._type = typ
table.insert(self.box_records, dummy_node)
return dummy_node
end
function Converter:register_decl(decl)
if not self.update_ref_of_decl[decl] then
self.update_ref_of_decl[decl] = {}
self.func_depth_of_decl[decl] = self.func_depth
end
end
function Converter:visit_prog(prog_ast)
assert(prog_ast._tag == "ast.Program.Program")
for _, tl_node in ipairs(prog_ast.tls) do
if tl_node._tag == "ast.Toplevel.Stats" then
for _, stat in ipairs(tl_node.stats) do
self:visit_stat(stat)
end
else
-- skip record declarations and type aliases
assert(typedecl.match_tag(tl_node._tag, "ast.Toplevel"))
end
end
end
function Converter:visit_stats(stats)
for _, stat in ipairs(stats) do
self:visit_stat(stat)
end
end
-- Goes over all the ast.Decls inside the AST that have been captured by some nested
-- function, transforms the decl node itself and all the references made to it.
function Converter:apply_transformations()
local proxy_var_of_param = {} -- { ast.Decl => ast.Decl }
local proxy_stats_of_lambda = {} -- { ast.Lambda => list of ast.Stat.Decl }
for decl in pairs(self.mutated_decls) do
if self.captured_decls[decl] then
assert(not decl._exported_as)
-- 1. Create a record type `$T` to hold this captured var.
-- 2. Transform node from `local x = value` to `local x: $T = { value = value }`
-- 3. Transform all references to the var from `ast.Var.Name` to ast.Var.Dot
local typ = types.T.Record(
self:type_name(decl.name),
{ "value" },
{ value = decl._type },
true
)
self:add_box_type(decl.loc, typ)
local is_param = self.lambda_of_param[decl]
local init_exp_update = self.update_init_exp_of_decl[decl]
if init_exp_update then
local old_exp = init_exp_update.node
decl._type = typ
local update = init_exp_update.update_fn
local new_node = ast.Exp.InitList(old_exp.loc, {{ name = "value", exp = old_exp }})
new_node._type = typ
update(new_node)
elseif is_param then
--- Function parameters that are captured are implementing by "proxy"-ing them.
--- Consider the following function that returns a closure:
--- ```
--- function m.foo(n: integer)
--- -- capture n
--- end
--- ```
--- Since we cannot transform the declaration node of a function parameter,
--- we create a variable to represent the boxed parameter which can be captured.
--- ```
--- function m.foo(n: integer)
--- local $n: $T = { value = n }
--- -- capture and mutate $n
--- end
local param = ast.Exp.Var(decl.loc, ast.Var.Name(decl.loc, decl.name))
param.var._def = checker.Def.Variable(decl)
param.var._type = assert(decl._type)
param._type = decl._type
local decl_lhs = ast.Decl.Decl(decl.loc, "$"..decl.name, false)
local decl_rhs = ast.Exp.InitList(decl.loc, {{ name = "value", exp = param }})
decl_rhs._type = typ
decl_lhs._type = typ
local stat = ast.Stat.Decl(decl.loc, { decl_lhs }, { decl_rhs })
local lambda = self.lambda_of_param[decl]
if not proxy_stats_of_lambda[lambda] then
proxy_stats_of_lambda[lambda] = {}
end
table.insert(proxy_stats_of_lambda[lambda], stat)
proxy_var_of_param[decl] = decl_lhs
else
-- Capturing uninitialized decls as mutable upvalues
decl._type = typ
local ast_update = assert(self.add_init_exp_to_decl[decl])
local update = ast_update.update_fn
local new_node = ast.Exp.UpvalueRecord(decl.loc)
new_node._type = typ
update(new_node)
end
--- Update all references made to the mutable upvalue. Replace all `ast.Var` nodes
--- with `ast.Dot` nodes.
for _, node_update in ipairs(self.update_ref_of_decl[decl]) do
local old_var = node_update.node
local loc = old_var.loc
local update = node_update.update_fn
local dot_exp
local proxy_decl = proxy_var_of_param[decl]
if proxy_decl then
-- references to captured parameters get replaced by references to `value` field of
-- their proxy variables.
local proxy_var = ast.Var.Name(old_var.loc, "$"..decl.name)
proxy_var._def = checker.Def.Variable(proxy_decl)
dot_exp = ast.Exp.Var(loc, proxy_var)
else
dot_exp = ast.Exp.Var(loc, old_var)
end
local new_node = ast.Var.Dot(old_var.loc, dot_exp, "value")
new_node.exp._type = typ
update(new_node)
end
end
end
-- insert all the parameter proxy declarations
for lambda, stats in pairs(proxy_stats_of_lambda) do
for _, stat in ipairs(lambda.body.stats) do
table.insert(stats, stat)
end
lambda.body.stats = stats
end
end
function Converter:visit_lambda(lambda)
self.func_depth = self.func_depth + 1
for _, arg in ipairs(lambda.arg_decls) do
self:register_decl(arg)
self.lambda_of_param[arg] = lambda
end
self:visit_stats(lambda.body.stats)
assert(self.func_depth > 1)
self.func_depth = self.func_depth - 1
end
function Converter:visit_func(func)
assert(func._tag == "ast.FuncStat.FuncStat")
local lambda = func.value
assert(lambda and lambda._tag == "ast.Exp.Lambda")
self:visit_lambda(lambda)
end
function Converter:visit_stat(stat)
local tag = stat._tag
if tag == "ast.Stat.Functions" then
for _, func in ipairs(stat.funcs) do
self:register_decl(func)
self:visit_func(func)
end
elseif tag == "ast.Stat.Return" then
for _, exp in ipairs(stat.exps) do
self:visit_exp(exp)
end
elseif tag == "ast.Stat.Decl" then
for i, decl in ipairs(stat.decls) do
self:register_decl(decl)
if i > #stat.exps then
-- Uninitialized decls might be captured as upvalues.
local update_decl = function (new_exp)
stat.exps[i] = new_exp
end
self.add_init_exp_to_decl[decl] = NodeUpdate(decl, update_decl)
end
end
for i, exp in ipairs(stat.exps) do
self:visit_exp(exp)
-- do not register extra values on RHS
if i <= #stat.decls then
-- update the initializer expression of this decl in case it's being captured
-- and mutated.
local update_init = function (new_exp)
stat.exps[i] = new_exp
end
self.update_init_exp_of_decl[stat.decls[i]] = NodeUpdate(stat.exps[i], update_init)
end
end
elseif tag == "ast.Stat.Block" then
self:visit_stats(stat.stats)
elseif tag == "ast.Stat.While" or tag == "ast.Stat.Repeat" then
self:visit_stats(stat.block.stats)
self:visit_exp(stat.condition)
elseif tag == "ast.Stat.If" then
self:visit_exp(stat.condition)
self:visit_stats(stat.then_.stats)
if stat.else_ then
self:visit_stat(stat.else_)
end
elseif tag == "ast.Stat.ForNum" then
self:visit_exp(stat.start)
self:visit_exp(stat.limit)
self:visit_exp(stat.step)
self:register_decl(stat.decl)
self:visit_stats(stat.block.stats)
elseif tag == "ast.Stat.ForIn" then
for _, decl in ipairs(stat.decls) do
self:register_decl(decl)
end
for _, exp in ipairs(stat.exps) do
self:visit_exp(exp)
end
self:visit_stats(stat.block.stats)
elseif tag == "ast.Stat.Assign" then
for i, var in ipairs(stat.vars) do
self:visit_var(var, function (new_var)
stat.vars[i] = new_var
end)
if var._tag == "ast.Var.Name" and not var._exported_as then
if var._def._tag == "checker.Def.Variable" then
local decl = assert(var._def.decl)
self.mutated_decls[decl] = true
end
end
end
for _, exp in ipairs(stat.exps) do
self:visit_exp(exp)
end
elseif tag == "ast.Stat.Decl" then
for _, decl in ipairs(stat.decls) do
self:register_decl(decl)
end
for _, exp in ipairs(stat.exps) do
self:visit_exp(exp)
end
elseif tag == "ast.Stat.Call" then
self:visit_exp(stat.call_exp)
elseif tag == "ast.Stat.Break" then
-- empty
else
typedecl.tag_error(tag)
end
end
-- This function takes an `ast.Var` node and a callback that should replace the reference to the
-- var at the call site with a transformed AST node, provided the new AST node as an argument.
-- If it is found out later that `var` is being captured and mutated somewhere then `update_fn`
-- is called to transform it to an `ast.Var.Dot` Node.
--
-- @param var The `ast.Var` node.
-- @param update_fn An `(ast.Var) -> ()` function that should update an `ast.Var.Name` node
-- to a new `ast.Var.Dot` node by assigning it's argument to an appropriate location in the AST
function Converter:visit_var(var, update_fn)
local vtag = var._tag
if vtag == "ast.Var.Name" and not var._exported_as then
if var._def._tag == "checker.Def.Variable" then
local decl = assert(var._def.decl)
assert(self.update_ref_of_decl[decl])
local depth = self.func_depth_of_decl[decl]
-- depth == 1 when the decl is that of a global
if depth < self.func_depth then
self.captured_decls[decl] = true
end
table.insert(self.update_ref_of_decl[decl], NodeUpdate(var, update_fn))
end
elseif vtag == "ast.Var.Dot" then
self:visit_exp(var.exp)
elseif vtag == "ast.Var.Bracket" then
self:visit_exp(var.t)
self:visit_exp(var.k)
end
end
-- If necessary, transforms `exp` or one of it's subexpression nodes in case they
-- reference a mutable upvalue.
-- Recursively visits all sub-expressions and applies an `ast.Var.Name => ast.Var.Dot`
-- transformation wherever necessary.
function Converter:visit_exp(exp)
local tag = exp._tag
if tag == "ast.Exp.InitList" then
for _, field in ipairs(exp.fields) do
self:visit_exp(field.exp)
end
elseif tag == "ast.Exp.Lambda" then
self:visit_lambda(exp)
elseif tag == "ast.Exp.CallFunc" or tag == "ast.Exp.CallMethod" then
self:visit_exp(exp.exp)
for _, arg in ipairs(exp.args) do
self:visit_exp(arg)
end
elseif tag == "ast.Exp.Var" then
self:visit_var(exp.var, function (new_var) exp.var = new_var end)
elseif tag == "ast.Exp.Unop"
or tag == "ast.Exp.Cast"
or tag == "ast.Exp.ToFloat"
or tag == "ast.Exp.Paren" then
self:visit_exp(exp.exp)
elseif tag == "ast.Exp.Binop" then
self:visit_exp(exp.lhs)
self:visit_exp(exp.rhs)
elseif not typedecl.match_tag(tag, "ast.Exp") then
typedecl.tag_error(tag)
end
end
return converter
|
object_tangible_holiday_empire_day_component_dh17_cartridge_grips = object_tangible_holiday_empire_day_component_shared_dh17_cartridge_grips:new {
}
ObjectTemplates:addTemplate(object_tangible_holiday_empire_day_component_dh17_cartridge_grips, "object/tangible/holiday/empire_day/component/dh17_cartridge_grips.iff")
|
object_tangible_quest_frn_all_security_terminal_wall_03 = object_tangible_quest_shared_frn_all_security_terminal_wall_03:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_frn_all_security_terminal_wall_03, "object/tangible/quest/frn_all_security_terminal_wall_03.iff")
|
dziendziecka = true
local dzien_dziecka_loc = {
--{2240.42,-72.21,26.50,359,id=218,2240.23,-70.06,25.6}, -- PC cmentarz
--{-2273.89,533.18,35.02,270, id=219, -2271.82,533.16,34.3}, -- SF stacja
--{389.39,-1525.02,32.27,38.4, id=220, 388.27,-1524.06,31.3}, -- LS Rodeo
--{2322.61,2394.16,10.82,92.7, id=221, 2320.14,2394.15,10}, -- LV komi
}
for i,v in ipairs(dzien_dziecka_loc) do
v.obj = createObject(3533, v[1],v[2],v[3]-5)
setElementFrozen(v.obj,true)
v.ped = createPed(v.id,v[1],v[2],v[3]+1,v[4])
setElementFrozen(v.ped,true)
setElementData(v.ped,"npc",true)
setElementData(v.ped,"name","Ukryty skin")
v.blip = createBlip(v[1],v[2],v[3],12,2,255,0,0,255,0,99999)
v.marker = createMarker(v[5],v[6],v[7],"cylinder",1, 255,255,255,120)
setElementData(v.marker,"marker:halloween",true)
setElementData(v.marker,"skin:id",v.id)
v.t3d = createElement('text')
setElementPosition(v.t3d,v[5],v[6],v[7]+1.5)
setElementData(v.t3d, "text","Skin świąteczny")
end
addEventHandler("onMarkerHit",resourceRoot,function(hitElement,matchingDimension)
if (getElementType(hitElement)~="player") then return end
if (not matchingDimension) then return end
if (getElementInterior(hitElement)~=getElementInterior(source)) then return end
if (getPedOccupiedVehicle(hitElement)) then return end
if getElementData(source,"marker:halloween") then
local sid = getElementData(source,"skin:id")
setElementModel(hitElement,sid)
local uid = getElementData(hitElement,"auth:uid")
if (not uid) then return end
exports['psz-mysql']:zapytanie(string.format("UPDATE psz_postacie SET skin=%d WHERE userid=%d LIMIT 1",sid,uid))
outputChatBox("Odebrałeś specjalny skin, na mapie są ukryte jeszcze inne skiny - znajdź je. :-)",hitElement,0,255,120)
end
end)
--[[
addEvent("onPlayerHitMarkerEvent",true)
addEventHandler("onPlayerHitMarkerEvent",root,function(uid)
if (not uid) then return end
local q = string.format("SELECT type FROM psz_eventy WHERE uid=%d",uid)
local wynik = exports['psz-mysql']:pobierzWyniki(q)
if (wynik and wynik.type and wynik.type~=3) then
outputChatBox("Odebrałeś już nagrodę.",source,255,0,0)
elseif(wynik and wynik.type and wynik.type==3) then
outputChatBox("Odebrano pojazd RC Baron, miłej zabawy! :-)",source,0,255,120)
for i,v in ipairs(getElementsByType("vehicle")) do
if getElementModel(v) == 464 and getElementData(v,"event:rc") == source then
destroyElement(v)
end
end
local veh = createVehicle(464,-87.01,1075.54,19.74)
setElementData(veh,"event:rc",source)
warpPedIntoVehicle(source,veh)
elseif(not wynik) then
triggerClientEvent(source,"onServerReturnData",resourceRoot,true)
end
end)
addEvent("onPlayerTakeThing",true)
addEventHandler("onPlayerTakeThing",root,function(type)
local uid = getElementData(source,"auth:uid") or 0
if (not uid) then return end
local q
q = string.format("SELECT type FROM psz_eventy WHERE uid=%d",uid)
local wynik = exports['psz-mysql']:pobierzWyniki(q)
if (wynik and wynik.type) then outputChatBox("Odebrałeś już prezent!",source,255,0,0) return end
--if type == 1 then
--q = string.format("UPDATE psz_players SET vip = IF(vip>NOW(),vip,NOW())+INTERVAL 7 DAY WHERE id=%d",uid)
--exports['psz-mysql']:zapytanie(q)
---q = string.format("INSERT INTO psz_eventy SET uid=%d, type=1, ts=NOW()",uid)
--exports['psz-mysql']:zapytanie(q)
--local pz = getElementData(source,"PZ")
--pz = pz + 20
--setElementData(source,"PZ",pz)
--setElementData(source,"vip",true)
--outputChatBox("Twoje konto VIP zostało przedłużone",source)
if type == 2 then
q = string.format("INSERT INTO psz_eventy SET uid=%d, type=2, ts=NOW()",uid)
exports['psz-mysql']:zapytanie(q)
local pz = getElementData(source,"PZ")
pz = pz + 20
setElementData(source,"PZ",pz)
givePlayerMoney(source,1000)
outputChatBox("Otrzymałeś $1000.",source)
elseif type == 3 then
q = string.format("INSERT INTO psz_eventy SET uid=%d, type=3, ts=NOW()", uid)
exports['psz-mysql']:zapytanie(q)
local pz = getElementData(source,"PZ")
pz = pz + 20
setElementData(source,"PZ",pz)
for i,v in ipairs(getElementsByType("vehicle")) do
if getElementModel(v) == 464 and getElementData(v,"event:rc") == source then
destroyElement(v)
end
end
local veh = createVehicle(464,-87.01,1075.54,19.74)
setElementData(veh,"event:rc",source)
warpPedIntoVehicle(source,veh)
outputChatBox("Odebrano pojazd RC Baron, miłej zabawy! :-)",source,0,255,120)
outputChatBox("Wróć tutaj aby odebrać ponownie pojazd.",source,0,255,120)
end
end)
]]-- |
-- require particle
_ichor.add('particle_system', {
init = function(this)
this.particles = {}
end,
add = function(this, particle)
particle.system = this
add(this.particles, particle)
particle:init()
end,
del = function(this, particle)
del(this.particles, particle)
particle:destroy()
end,
update = function(this)
this:all('update')
end,
draw = function(this)
this:all('draw')
end,
all = function(this, key)
for particle in all(this.particles) do
particle[key](particle,key)
end
end
})
|
CommonGameScene2 = class(CommonScene);
-- 一些界面控件的index
CommonGameScene2.s_controls =
{
commonView_01 = ToolKit.getIndex();
commonView_02 = ToolKit.getIndex();
commonView_03 = ToolKit.getIndex();
commonView_04 = ToolKit.getIndex();
bgImage = ToolKit.getIndex();
gameLogoView = ToolKit.getIndex();
gameLogoDivider = ToolKit.getIndex();
gameLogoImage = ToolKit.getIndex();
commonRoomId = ToolKit.getIndex();
antiCheatingImg = ToolKit.getIndex();
--房间装饰图的配置
decorate_01 = ToolKit.getIndex();
decorate_02 = ToolKit.getIndex();
decorate_03 = ToolKit.getIndex();
decorate_04 = ToolKit.getIndex();
reconnect = ToolKit.getIndex();
};
-- 指令
CommonGameScene2.s_cmds =
{
receiveStateFun = ToolKit.getIndex();
receiveActionFun = ToolKit.getIndex();
ceatView = ToolKit.getIndex();
updatePrivateRoom = ToolKit.getIndex();
gameLevelUpdate = ToolKit.getIndex();
};
-- 构造器
CommonGameScene2.ctor = function(self, viewConfig, controller, childGameConfig)
-- 新老房间存在相同的commonRoomTimer文件,进入房间前重新require,并且清空监听
require("games/common2/tools/commonRoomTimer");
CommonRoomTimer.getInstance():clean();
self:resetPublicData();
--先进行common的初始化
self.m_isHandleCommonInit = false;
self:initBaseView(childGameConfig);
end
CommonGameScene2.resetPublicData = function(self)
require("games/common2/module/players/playerSeat");
require("games/common2/module/players/gamePlayerManager2");
require("games/common2/data/gameProcessManager2");
end
--@override
CommonGameScene2.resume = function(self)
CommonScene.resume(self);
self:commonInit();
end
--@override
--@brief 延迟加载layer,让大厅跳转房间更加流畅
CommonGameScene2.__onDelayResumeScene = function(self)
CommonScene.__onDelayResumeScene(self);
if not self.m_hasEnter then
self.m_hasEnter = true;
self:addLayer();
MsgProcessTools.getInstance():startProcess();
self:requestCtrlCmd(CommonGameController2.s_cmds.requestEnterRoom);
end
end
--@override
CommonGameScene2.pause = function(self)
CommonScene.pause(self);
end
--@override
CommonGameScene2.stop = function(self)
CommonScene.stop(self);
end
--@override
CommonGameScene2.run = function(self)
CommonScene.run(self);
end
-- 析构器
CommonGameScene2.dtor = function(self)
CommonScene.dtor(self);
for k,v in pairs(self.m_commonViewMap) do
v:removeAllChildren(true);
end
self.m_commonViewMap = {};
GameProcessManager2.releaseInstance();
GamePlayerManager2.releaseInstance();
PlayerSeat.releaseInstance();
DialogLogic.releaseInstance();
CommonRoomTimer2.releaseInstance();
AnimManager.getInstance():releaseAll();
end
CommonGameScene2.initBaseView = function(self, childGameConfig)
self.m_commonViewMap = {};
--初始化view层次
self.m_commonViewMap[1] = self:findViewById(CommonGameScene2.s_controls.commonView_01); --背景层
self.m_commonViewMap[2] = self:findViewById(CommonGameScene2.s_controls.commonView_02); --游戏私有层,专属子类
self.m_commonViewMap[3] = self:findViewById(CommonGameScene2.s_controls.commonView_03); -- 游戏公共层,动画神马的可以在此层做处理,子类可以直接访问
self.m_commonViewMap[4] = self:findViewById(CommonGameScene2.s_controls.commonView_04); --弹框层
-- 初始化桌面单击事件、双击事件
self.m_commonViewMap[2]:setEventTouch(self, self.onDesktopClick);
self.m_commonViewMap[2]:setEventDoubleClick(self, self.onDesktopDoubleClick);
self.m_reconnectBtn = self:findViewById(CommonGameScene2.s_controls.reconnect);
self.m_reconnectBtn:setEventTouch(self, self.onReconnectTouch);
self.m_reconnectBtn:setFile("isolater/btns/btn_green_164x89_l25_r25_t25_b25.png");
end
CommonGameScene2.onDesktopClick = function ( self, finger_action, x, y, drawing_id_first, drawing_id_current )
-- body
self:requestCtrlCmd(CommonGameController2.s_cmds.clickDesktop);
end
CommonGameScene2.onDesktopDoubleClick = function ( self, finger_action, x, y, drawing_id_first, drawing_id_current )
-- body
self:requestCtrlCmd(CommonGameController2.s_cmds.doubleClickDesktop);
end
--父类用的初始化
CommonGameScene2.commonInit = function(self)
if self.m_isHandleCommonInit then
return;
end
self:getScreenScale();
self:getCommonBaseView();
self:initCommonConfig();
self:initAntiCheatingInfo();
local viewCommonConfig = self:getCommonConfig();
if table.isEmpty(viewCommonConfig) then
Log.e("m_viewCommonConfig-child game must has this config in child's folder");
else
self:initGamePlayerManager(viewCommonConfig.playerNumer);
self:initRoomBg(viewCommonConfig.backgroundFile);
self:initRoomDecorate(viewCommonConfig.decorateConfig);
self:initAudioConfig(viewCommonConfig.soundConfig);
self:initAnimConfig(viewCommonConfig.animDefs);
self:initLogoArea(viewCommonConfig.logoConfig);
end
-- 子游戏的debug开关打开时,在房间内会显示当前子游戏的版本号
local gameId = GameInfoIsolater.getInstance():getCurGameId() or "";
local packageName = GameInfoIsolater.getInstance():getGamePackageName(gameId) or "";
if _G[packageName .. "_debug_for_update"] then
local gameVersion = "版本号:" .. GameInfoIsolater.getInstance():getGameVersion(gameId) or 0;
local gameVersionTx = UIFactory.createText(gameVersion, 32, 100, 32, kAlignCenter, 0, 0, 0);
self:addChild(gameVersionTx);
gameVersionTx:setAlign(kAlignCenter);
end
self.m_isHandleCommonInit = true;
end
CommonGameScene2.getScreenScale = function(self)
self.m_scaleWidth = System.getScreenScaleWidth();
self.m_scaleHeight = System.getScreenScaleHeight();
end
CommonGameScene2.getCommonBaseView = function(self)
--初始化背景图片
self.m_commonBgImage = self:findViewById(CommonGameScene2.s_controls.bgImage);
self.m_commonGameLogoDivider = self:findViewById(CommonGameScene2.s_controls.gameLogoDivider);
self.m_commonGameLogoImage = self:findViewById(CommonGameScene2.s_controls.gameLogoImage);
self.m_commonGameLogoView = self:findViewById(CommonGameScene2.s_controls.gameLogoView);
self.m_commonRoomIdText = self:findViewById(CommonGameScene2.s_controls.commonRoomId);
self:findViewById(CommonGameScene2.s_controls.reconnect):setVisible(_DEBUG);
self.m_decorateView = {};
self.m_decorateView[1] = self:findViewById(CommonGameScene2.s_controls.decorate_01);
self.m_decorateView[2] = self:findViewById(CommonGameScene2.s_controls.decorate_02);
self.m_decorateView[3] = self:findViewById(CommonGameScene2.s_controls.decorate_03);
self.m_decorateView[4] = self:findViewById(CommonGameScene2.s_controls.decorate_04);
self.m_antiCheatingImg = self:findViewById(CommonGameScene2.s_controls.antiCheatingImg);
end
-- 初始化游戏log
CommonGameScene2.initLogoArea = function(self, logoConfig)
--初始化游戏图标
logoConfig = table.verify(logoConfig);
local logoFile = logoConfig.file;
local x = logoConfig.x;
local y = logoConfig.y;
local align = logoConfig.align;
local isNeedDivider = logoConfig.needDivider;
local isNeedCombine = logoConfig.needCombine;
if string.isEmpty(logoFile) then
self.m_commonGameLogoView:setVisible(false);
else
self.m_commonGameLogoImage:setFile(logoFile)
local w, h = self.m_commonGameLogoImage.m_res.m_width, self.m_commonGameLogoImage.m_res.m_height;
self.m_commonGameLogoImage:setSize(w, h);
self.m_commonGameLogoImage:setAlign(kAlignLeft);
local logoView_w = w;
if isNeedCombine and not self.m_companyLogo then
self.m_companyLogo = UIFactory.createImage("games/common/company_logo.png");
self.m_commonGameLogoView:addChild(self.m_companyLogo);
self.m_companyLogo:setAlign(kAlignLeft);
local company_w, company_h = self.m_companyLogo:getSize();
local space = 5;
logoView_w = logoView_w + company_w + space;
self.m_commonGameLogoImage:setPos(company_w + space, nil);
end
self.m_commonGameLogoView:setVisible(true);
self.m_commonGameLogoView:setSize(logoView_w, nil);
self.m_commonGameLogoView:setAlign(align);
self.m_commonGameLogoView:setPos(x,y);
self.m_commonGameLogoDivider:setVisible(isNeedDivider);
end
local level = RoomLevelConfig.getInstance():getLevel("layer2","level1");
self.m_commonGameLogoView:setLevel(level);
end
-- 初始化游戏配置信息
CommonGameScene2.initCommonConfig = function(self)
--初始化配置
local commonGameData = GameInfoIsolater.getInstance();
local curPkgName = commonGameData:getGamePackageName(commonGameData:getCurGameId());
local viewCommonConfig = -1;
if not string.isEmpty(curPkgName) then
viewCommonConfig = ToolKit.safeRequire(string.format("games/%s/%sConfig", curPkgName, curPkgName));
end
if not string.isEmpty(viewCommonConfig) and type(viewCommonConfig) == "table" then
GameProcessManager2.getInstance():setGameConfig(viewCommonConfig);
end
end
--初始化背景
CommonGameScene2.initRoomBg = function(self,bgFile)
local str = string.trim(bgFile);
if string.isEmpty(str) then
bgFile = "games/common/room/room_bg.jpg";
end
self.m_commonBgImage:setFile(bgFile);
end
CommonGameScene2.initRoomDecorate = function(self,decorateConfig)
decorateConfig = table.verify(decorateConfig);
local count = #self.m_decorateView;
for i = 1, count do
local decorateView = self.m_decorateView[i];
local decorateFile = decorateConfig[i];
if string.isEmpty(decorateFile) then
decorateView:setVisible(false);
else
decorateView:setVisible(true);
decorateView:setFile(decorateFile);
local w, h = decorateView.m_res.m_width, decorateView.m_res.m_height;
decorateView:setSize(w, h);
end
end
end
CommonGameScene2.initAntiCheatingInfo = function(self)
local commonGameData = GameInfoIsolater.getInstance();
local gameId = commonGameData:getCurGameId();
local levelId = commonGameData:getCurRoomLevelId();
if self.m_antiCheatingImg then
if GameInfoIsolater.getInstance():isRoomAntiCheating(gameId, levelId) then
self.m_antiCheatingImg:setVisible(true);
self.m_antiCheatingImg:setPos(0, 80);
else
self.m_antiCheatingImg:setVisible(false);
end
end
end
CommonGameScene2.initAudioConfig = function(self,audioConfig)
kSoundModule:preload(audioConfig);
end
CommonGameScene2.initAnimConfig = function(self,animDefs)
if not table.isEmpty(animDefs) then
AnimDefs = CombineTables(AnimDefs or {}, animDefs or {});
AnimManager.getInstance():setAnimDefs(AnimDefs);
end
end
--protect
--获取通用配置
CommonGameScene2.getCommonConfig = function(self)
return table.verify(GameProcessManager2.getInstance():getGameConfig());
end
-- 设置玩家人数
CommonGameScene2.initGamePlayerManager = function(self,playerNumer)
PlayerSeat.getInstance():setCurGamePlayerMaxCount(number.valueOf(playerNumer,1));
end
------------------------------------------------game layer init start------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------
-- 添加功能层到scene
CommonGameScene2.addLayer = function(self)
-- ======================================= view 1
self:creatGameLayer();
self:creatBankrupt();
self:creatRecharge();
self:creatReadyLayer();
self:creatHeadLayer(); -- view1
self:creatFriendLayer();
self:creatAnimLayer();
self:creatClockLayer(); -- view2
self:creatChatRealTimeLayer();
self:creatTaskLayer();
self:creatSystemInfoLayer();
self:createSilverLayer();
self:creatToolBarLayer();
self:creatPlayerLayer();
-- ======================================= view 1
self:createRoomInfo();
self:createHeadToolbarLayer();
-- ======================================= view 4
self:creatExtraBtnLayer(); --view4
-- self:creatBroadcastLayer(); -- view4
self:creatRecruitLayer();
self:creatChatLayer();
self:crateInviteLayer();
self:creatChatWndLayer();
self:createReadyDegradeLayer();
self:createPrivateJiFenLayers();
self:createOnlookerSpinnerLayer();
end
CommonGameScene2.onCeatView = function(self,seat,uid,info,isFast)
if info and info.viewName then
if info.viewName == GameMechineConfig.VIEW_GAMEOVERWND then
if PrivateRoomIsolater.getInstance():isInJiFenRoom() then
return;
end
self:creatGameOverLayer();
elseif info.viewName == GameMechineConfig.VIEW_BROADCAST then
self:creatBroadcastLayer();
elseif info.viewName == GameMechineConfig.VIEW_SAFEBOX then
self:createSafebox();
elseif info.viewName == GameMechineConfig.VIEW_SETTING then
self:createSettingLayer();
elseif info.viewName == GameMechineConfig.VIEW_REPORT then
self:createReportLayer();
elseif info.viewName == GameMechineConfig.VIEW_CHAT then
self:creatChatWndLayer();
elseif info.viewName == GameMechineConfig.VIEW_BOXVIEW then
self:creatBoxTaskLayer();
end
end
end
CommonGameScene2.creatGameLayer = function(self)
-- 子游戏层
end
CommonGameScene2.creatGameOverLayer = function(self)
end
CommonGameScene2.createReadyDegradeLayer = function(self)
if not self.m_readyDegradeLayer then
local ReadyDegradeLayer = require("games/common2/module/readyDegrade/readyDegradeLayer");
self.m_readyDegradeLayer = new(ReadyDegradeLayer);
self.m_commonViewMap[4]:addChild(self.m_readyDegradeLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level2");
self.m_readyDegradeLayer:setLevel(level);
end
end
CommonGameScene2.creatBankrupt = function(self)
if not self.m_bankrupt then
local bankruptLayer = require("games/common2/module/bankrupt/bankruptLayer");
self.m_bankrupt = new(bankruptLayer);
self.m_commonViewMap[4]:addChild(self.m_bankrupt);
end
end
CommonGameScene2.creatRecharge = function(self)
if not self.m_recharge then
local rechargeLayer = require("games/common2/module/recharge/rechargeLayer");
self.m_recharge = new(rechargeLayer);
self.m_recharge:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_recharge);
end
end
CommonGameScene2.creatReadyLayer = function(self)
if not self.m_readyLayer then
local readyLayer = require("games/common2/module/ready/readyLayer");
self.m_readyLayer = new(readyLayer);
self.m_readyLayer:setDelegate(self);
self.m_commonViewMap[3]:addChild(self.m_readyLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer3","level1");
self.m_readyLayer:setLevel(level);
end
end
CommonGameScene2.creatHeadLayer = function(self)
if not self.m_headLayer then
local headLayer = require("games/common2/module/head/headLayer");
self.m_headLayer = new(headLayer);
self.m_headLayer:setDelegate(self);
self.m_commonViewMap[2]:addChild(self.m_headLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer2","level9");
self.m_headLayer:setLevel(level);
end
end
CommonGameScene2.creatChatLayer = function(self)
if not self.m_chatLayer then
local chatLayer = require("games/common2/module/chat/chatLayer");
self.m_chatLayer = new(chatLayer);
self.m_chatLayer:setDelegate(self);
self.m_commonViewMap[2]:addChild(self.m_chatLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer2","level9");
self.m_chatLayer:setLevel(level);
end
end
CommonGameScene2.creatChatWndLayer = function(self)
if not self.m_chatWndLayer then
local chatwndlayer = require("games/common2/module/chatWnd/chatwndlayer");
self.m_chatWndLayer = new(chatwndlayer);
self.m_chatWndLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_chatWndLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level2");
self.m_chatWndLayer:setLevel(level);
end
end
CommonGameScene2.creatPlayerLayer = function(self)
if not self.m_playerLayer then
local playerLayout = require("games/common2/module/playerInfo/playerLayout");
self.m_playerLayer = new(playerLayout);
self.m_playerLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_playerLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level2");
self.m_playerLayer:setLevel(level);
end
end
CommonGameScene2.creatSystemInfoLayer = function(self)
if not self.m_systemInfoLayer then
local systemInfoLayer = require("games/common2/module/systemInfo/systemInfoLayer");
self.m_systemInfoLayer = new(systemInfoLayer);
self.m_systemInfoLayer:setDelegate(self);
self.m_commonViewMap[1]:addChild(self.m_systemInfoLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer1","level3");
self.m_systemInfoLayer:setLevel(level);
end
end
CommonGameScene2.creatToolBarLayer = function(self)
if not self.m_roomMenuBarLayer then
local menuBarLayer = require("games/common2/module/roomMenuBar/roomMenuBarLayer");
self.m_roomMenuBarLayer = new(menuBarLayer);
self.m_roomMenuBarLayer:setDelegate(self);
self.m_commonViewMap[3]:addChild(self.m_roomMenuBarLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer3","level4");
self.m_roomMenuBarLayer:setLevel(level);
end
end
CommonGameScene2.creatFriendLayer = function(self)
if not self.m_friendLayer then
local roomFriendLayer = require("games/common2/module/friend/roomFriendLayer");
self.m_friendLayer = new(roomFriendLayer);
self.m_friendLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_friendLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level8");
self.m_friendLayer:setLevel(level);
end
end
CommonGameScene2.creatAnimLayer = function(self)
if not self.m_animLayer then
local animLayer = require("games/common2/module/anim/roomAnimLayer");
self.m_animLayer = new(animLayer);
self.m_animLayer:setDelegate(self);
self.m_commonViewMap[3]:addChild(self.m_animLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer3","level3");
self.m_animLayer:setLevel(level);
end
end
CommonGameScene2.creatTaskLayer = function(self)
if not self.m_taskLayer then
local taskLayer = require("games/common2/module/roomTask/roomTaskLayer");
self.m_taskLayer = new(taskLayer);
self.m_taskLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_taskLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer2","level2");
self.m_taskLayer:setLevel(level);
self.m_taskLayer:setFillParent(true,true);
end
end
CommonGameScene2.creatBoxTaskLayer = function(self)
if not self.m_taskBoxLayer then
local roomTaskRewardLayer = require("games/common2/module/roomtaskreward/roomTaskRewardLayer");
self.m_taskBoxLayer = new(roomTaskRewardLayer);
self.m_taskBoxLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_taskBoxLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level5");
self.m_taskBoxLayer:setLevel(level);
self.m_taskBoxLayer:setFillParent(true,true);
end
end
CommonGameScene2.creatClockLayer = function(self)
if not self.m_clockLayer then
local clockLayer = require("games/common2/module/clock/clockLayer");
self.m_clockLayer = new(clockLayer);
self.m_clockLayer:setDelegate(self);
self.m_commonViewMap[2]:addChild(self.m_clockLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer2","level4");
self.m_clockLayer:setLevel(level);
end
end
-- 实时对讲
CommonGameScene2.creatChatRealTimeLayer = function(self)
local gameId = GameInfoIsolater.getInstance():getCurGameId();
local roomInfo = table.verify(PrivateRoomIsolater.getInstance():getCurPrivateRoomInfo());
local talbeType = table.verify(roomInfo).tableType;
if PrivateRoomIsolater.getInstance():isInPrivateRoom() and talbeType and
PrivateRoomIsolater.getInstance():isOpenVideo(gameId, talbeType) then
if not self.m_chatRealTimeLayer then
local chatRealTimeLayer = require("games/common2/module/chatRealTime/chatRealTimeLayer");
self.m_chatRealTimeLayer = new(chatRealTimeLayer);
self.m_chatRealTimeLayer:setDelegate(self);
self.m_commonViewMap[2]:addChild(self.m_chatRealTimeLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer2","level11");
self.m_chatRealTimeLayer:setLevel(level);
end
end
end
-- 招募玩家
CommonGameScene2.creatRecruitLayer = function(self)
if PrivateRoomIsolater.getInstance():isInPrivateRoom()
and (not PrivateRoomIsolater.getInstance():isInJiFenRoom()) then
if not self.m_recruitLayer then
local recruitlayer = require("games/common2/module/recruit/recruitLayer");
self.m_recruitLayer = new(recruitlayer);
self.m_recruitLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_recruitLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level2");
self.m_recruitLayer:setLevel(level);
end
end
end
-- 邀请好友
CommonGameScene2.crateInviteLayer = function(self)
local tableId = kGameManager:getCurShortTableId();
if PrivateRoomIsolater.getInstance():isInPrivateRoom() and tableId and tableId > 0 then
if not self.m_inviteLayer then
local inviteLayer = require("games/common2/module/invite2/inviteLayer2");
self.m_inviteLayer = new(inviteLayer);
self.m_inviteLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_inviteLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level2");
self.m_inviteLayer:setLevel(level);
end
end
end
-- 扩展按钮
CommonGameScene2.creatExtraBtnLayer = function(self)
if not self.m_extraBtnLayer then
local extralayer = require("games/common2/module/extraBtn/extraBtnLayer");
self.m_extraBtnLayer = new(extralayer);
self.m_extraBtnLayer:setDelegate(self);
self.m_commonViewMap[2]:addChild(self.m_extraBtnLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer2","level5");
self.m_extraBtnLayer:setLevel(level);
end
end
-- 广播
CommonGameScene2.creatBroadcastLayer = function(self)
if not self.m_broadcastLayer then
local broadcastLayer = require("games/common2/module/broadcast/roomBroadcastLayer");
self.m_broadcastLayer = new(broadcastLayer);
self.m_broadcastLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_broadcastLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level8");
self.m_broadcastLayer:setLevel(level);
end
end
-- 房间信息
CommonGameScene2.createRoomInfo = function(self)
if PrivateRoomIsolater.getInstance():isInPrivateRoom() then
if not self.m_roomInfoLayer then
local roomInfoLayer = require("games/common2/module/roomInfo/roomInfoLayer");
self.m_roomInfoLayer = new(roomInfoLayer);
self.m_roomInfoLayer:setDelegate(self);
self.m_commonViewMap[2]:addChild(self.m_roomInfoLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer2","level10");
self.m_roomInfoLayer:setLevel(level);
end
end
end
-- 保险箱
CommonGameScene2.createSafebox = function(self)
if not self.m_safebox then
local safeboxLayer = require("games/common2/module/safebox/safeboxLayer");
self.m_safebox = new(safeboxLayer);
self.m_safebox:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_safebox);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level2");
self.m_safebox:setLevel(level);
end
end
-- 设置
CommonGameScene2.createSettingLayer = function(self)
if not self.m_settingLayer then
local settingLayer = require("games/common2/module/setting/settingLayer");
self.m_settingLayer = new(settingLayer);
self.m_settingLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_settingLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level2");
self.m_settingLayer:setLevel(level);
end
end
-- 举报
CommonGameScene2.createReportLayer = function(self)
if not self.m_reportLayer then
local report = require("games/common2/module/reportwnd/reportLayer");
self.m_reportLayer = new(report);
self.m_reportLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_reportLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level3");
self.m_reportLayer:setLevel(level);
end
end
-- 头像背景
CommonGameScene2.createHeadToolbarLayer = function ( self )
if not self.m_headToolbarLayer then
local toolbarlayer = require("games/common2/module/headToolbar/headToolbarLayer");
self.m_headToolbarLayer = new(toolbarlayer);
self.m_headToolbarLayer:setDelegate(self);
self.m_commonViewMap[1]:addChild(self.m_headToolbarLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer1","level1");
self.m_headToolbarLayer:setLevel(level);
end
end
CommonGameScene2.createSilverLayer = function ( self )
if not self.m_silverLayer then
local SilverLayer = require("games/common2/module/silver/silverLayer");
self.m_silverLayer = new(SilverLayer);
self.m_silverLayer:setDelegate(self);
self.m_commonViewMap[3]:addChild(self.m_silverLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer3","level4");
self.m_silverLayer:setLevel(level);
end
end
CommonGameScene2.createPrivateJiFenLayers = function(self)
if PrivateRoomIsolater.getInstance():isInJiFenRoom() then
self:createJiFenExtraBtnLayer();
self:createJiFenHeadLayer();
self:createJiFenChangeTipsLayer();
self:createJiFenRecordLayer();
self:createJifenFinishLayer();
end
end
CommonGameScene2.createJiFenExtraBtnLayer = function(self)
if not self.m_jifenExtraBtnLayer then
local JiFenExtraBtnLayer = require("games/common2/module/jifen/jifenExtraBtn/jifenExtraBtnLayer");
self.m_jifenExtraBtnLayer = new(JiFenExtraBtnLayer);
self.m_jifenExtraBtnLayer:setDelegate(self);
self.m_commonViewMap[2]:addChild(self.m_jifenExtraBtnLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer2","level8");
self.m_jifenExtraBtnLayer:setLevel(level);
end
end
CommonGameScene2.createJiFenHeadLayer = function(self)
if not self.m_jifenHeadLayer then
local JiFenHeadLayer = require("games/common2/module/jifen/jifenHead/jifenHeadLayer");
self.m_jifenHeadLayer = new(JiFenHeadLayer);
self.m_jifenHeadLayer:setDelegate(self);
self.m_commonViewMap[2]:addChild(self.m_jifenHeadLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer2","level9");
self.m_jifenHeadLayer:setLevel(level);
end
end
CommonGameScene2.createJiFenChangeTipsLayer = function(self)
if not self.m_jifenChangeTipsLayer then
local JiFenChangeTipsLayer = require("games/common2/module/jifen/jifenChangeTips/jifenChangeTipsLayer");
self.m_jifenChangeTipsLayer = new(JiFenChangeTipsLayer);
self.m_jifenChangeTipsLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_jifenChangeTipsLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level3");
self.m_jifenChangeTipsLayer:setLevel(level);
end
end
CommonGameScene2.createJiFenRecordLayer = function(self)
if not self.m_jifenRecordLayer then
local JiFenRecordLayer = require("games/common2/module/jifen/jifenRecord/jifenRecordLayer");
self.m_jifenRecordLayer = new(JiFenRecordLayer);
self.m_jifenRecordLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_jifenRecordLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level4");
self.m_jifenRecordLayer:setLevel(level);
end
end
CommonGameScene2.createJifenFinishLayer = function(self)
if not self.m_jifenFinishLayer then
local JiFenFinishLayer = require("games/common2/module/jifen/jifenFinish/jiFenFinishLayer");
self.m_jifenFinishLayer = new(JiFenFinishLayer);
self.m_jifenFinishLayer:setDelegate(self);
self.m_commonViewMap[4]:addChild(self.m_jifenFinishLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer4","level4");
self.m_jifenFinishLayer:setLevel(level);
end
end
CommonGameScene2.checkIsSupportOnlooker = function(self)
return false;
end
CommonGameScene2.createOnlookerSpinnerLayer = function(self)
if not self:checkIsSupportOnlooker() then
return;
end
if not self.m_onlookerSpinnerLayer then
local OnlookerSpinnerLayer = require("games/common2/onlooker/module/onlookerSpinner/onlookerSpinnerLayer");
self.m_onlookerSpinnerLayer = new(OnlookerSpinnerLayer);
self.m_onlookerSpinnerLayer:setDelegate(self);
self.m_commonViewMap[3]:addChild(self.m_onlookerSpinnerLayer);
local level = RoomLevelConfig.getInstance():getLevel("layer3","level4");
self.m_onlookerSpinnerLayer:setLevel(level);
end
end
------------------------------------------------game layer init end----------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------------------
-- ------------- toolbar ------------------------
-- CommonGameScene2.onToolbarShopClick = function(self)
-- self:requestRecharge();
-- end
--private
--请求充值
CommonGameScene2.requestRecharge = function(self,param,isOnlySupportSMS,goodInfo)
local _param = {
scene = PayIsolater.eGoodsListId.RoomPay,
gameid = GameInfoIsolater.getInstance():getCurGameId(),
level = GameInfoIsolater.getInstance():getCurRoomLevelId()
};
param = param or _param;
self:pushOtherState(States.ShortCutRecharge, nil, true, PayIsolater.eGoodsListId.RoomPay, param, goodInfo, isOnlySupportSMS);
end
CommonGameScene2.onToolbarExitClick = function(self)
if PrivateRoomIsolater.getInstance():isInJiFenRoom() then
self:requestCtrlCmd(CommonGameController2.s_cmds.requestExitJiFenRoom);
else
self:requestCtrlCmd(CommonGameController2.s_cmds.requestExitRoom);
end
end
CommonGameScene2.onToolbarSettingClick = function(self)
end
CommonGameScene2.onToolbarRobotClick = function(self)
end
CommonGameScene2.onToolbarRechargelick = function(self)
end
CommonGameScene2.onToolbarQuKuanClick = function(self)
end
CommonGameScene2.pushOtherState = function(self,...)
self:requestCtrlCmd(CommonGameController2.s_cmds.pushOtherState,...);
end
------------- toolbar ------------------------
-----------------------------------layer delegate callBack end---------------------------------------------------------------------------------------
----------------------- common map -----------------------------------------------------
----------------------control func-------------------------------
-- 点击桌面背景
CommonGameScene2.onCommonBgTouch = function(self, finger_action, x, y, drawing_id_first, drawing_id_current)
if finger_action == kFingerDown then
elseif finger_action == kFingerMove then
else
--此处关闭弹框
if self.m_recruitBtn then
self.m_recruitBtn:hideDetail();
end
EventDispatcher.getInstance():dispatch(kClosePopupWindows);
end
end
CommonGameScene2.onReceiveStateFun = function(self,state,...)
if CommonGameScene2.stateConfig[state] then
CommonGameScene2.stateConfig[state](self,...);
end
end
CommonGameScene2.onRefreshPrivateRoom = function (self)
self:creatChatRealTimeLayer();
self:creatRecruitLayer();
self:createPrivateJiFenLayers();
self:crateInviteLayer();
end
CommonGameScene2.onReconnectTouch = function(self, finger_action, x, y, drawing_id_first, drawing_id_current, event_time)
if finger_action == kFingerDown then
self.m_startx, self.m_starty = self.m_reconnectBtn:getAbsolutePos();
self.m_reconnectBtnMove = false;
elseif finger_action == kFingerMove then
if math.abs(x - self.m_startx) > 100 or math.abs(y - self.m_starty) > 100 then
local w,h = self.m_reconnectBtn:getSize();
self.m_reconnectBtn:setPos(x - w/2,y - h/2);
self.m_reconnectBtnMove = true;
end
elseif finger_action == kFingerUp then
if not self.m_reconnectBtnMove then
self:onTestReconnect();
end
self.m_reconnectBtnMove = false;
end
end
CommonGameScene2.onTestReconnect = function(self)
if not self.m_moreInfoTest then
local roommoreinfotest = require("games/common2/room/roommoreinfotest");
self.m_moreInfoTest = new(roommoreinfotest);
self:addChild(self.m_moreInfoTest);
self.m_moreInfoTest:setFillParent(true,true);
end
local btnX, btnY = self.m_reconnectBtn:getAbsolutePos();
local btnW, btnH = self.m_reconnectBtn:getSize();
self.m_moreInfoTest:refreshPos(btnX - btnW / 2 + 10, btnY + btnH - 10);
self.m_moreInfoTest:showView();
end
-- 游戏图层的层级发生变化,需要刷新
CommonGameScene2.onGameLevelUpdate = function(self,layerName)
local layers = {};
if layerName == "layer1" then
layers = {
{self.m_headToolbarLayer,"level1"}, {self.m_systemInfoLayer,"level3"},
};
elseif layerName == "layer2" then
layers = {
{self.m_commonGameLogoView,"level1"}, {self.m_taskLayer,"level2"}, {self.m_clockLayer,"level4"},
{self.m_extraBtnLayer,"level5"}, {self.m_jifenExtraBtnLayer,"level5"},
{self.m_chatLayer,"level9"}, {self.m_headLayer,"level9"},{self.m_jifenHeadLayer,"level9"},
{self.m_roomInfoLayer,"level10"}, {self.m_chatRealTimeLayer,"level11"},
};
elseif layerName == "layer3" then
layers = {
{self.m_readyLayer,"level1"}, {self.m_roomMenuBarLayer,"level4"}, {self.m_animLayer,"level3"},
{self.m_onlookerSpinnerLayer,"level4"},
};
elseif layerName == "layer4" then
layers = {
{self.m_chatWndLayer,"level2"},{self.m_playerLayer,"level2"},{self.m_recruitLayer,"level2"},
{self.m_inviteLayer,"level2"},{self.m_safebox,"level2"},{self.m_settingLayer,"level2"},{self.m_readyDegradeLayer,"level2"},
{self.m_reportLayer,"level3"},{self.m_jifenChangeTipsLayer,"level3"},
{self.m_jifenRecordLayer,"level4"},{self.m_jifenFinishLayer,"level4"},{self.m_broadcastLayer,"level8"},{self.m_friendLayer,"level8"},
};
end
for k,v in pairs(layers) do
if v[1] and v[2] and v[1].setLevel then
local level = RoomLevelConfig.getInstance():getLevel(layerName,v[2]);
if level > 0 then
v[1]:setLevel(level);
end
end
end
self:onRefreshOtherLayerLevel(layerName);
end
-- 用于之类重写
CommonGameScene2.onRefreshOtherLayerLevel = function(self,layerName)
end
-- 控件的配置信息
CommonGameScene2.s_controlConfig =
{
-- [CommonGameScene2.s_controls.backBtn] = {"head_area","btn_back"},
[CommonGameScene2.s_controls.commonView_01] = {"commonView1"},
[CommonGameScene2.s_controls.commonView_02] = {"commonView2"},
[CommonGameScene2.s_controls.commonView_03] = {"commonView3"},
[CommonGameScene2.s_controls.commonView_04] = {"commonView4"},
[CommonGameScene2.s_controls.bgImage] = {"commonView1", "bg"},
[CommonGameScene2.s_controls.gameLogoView] = {"commonView1", "gameLogoView"},
[CommonGameScene2.s_controls.gameLogoImage] = {"commonView1", "gameLogoView", "gameLogo"},
[CommonGameScene2.s_controls.gameLogoDivider] = {"commonView1", "gameLogoView", "gameLogoDivider"},
[CommonGameScene2.s_controls.commonRoomId] = {"commonView1", "privateRoomId"};
[CommonGameScene2.s_controls.decorate_01] = {"commonView1", "decorate_1"};
[CommonGameScene2.s_controls.decorate_02] = {"commonView1", "decorate_2"};
[CommonGameScene2.s_controls.decorate_03] = {"commonView1", "decorate_3"};
[CommonGameScene2.s_controls.decorate_04] = {"commonView1", "decorate_4"};
[CommonGameScene2.s_controls.antiCheatingImg] = {"commonView1", "antiCheatingImg"};
[CommonGameScene2.s_controls.reconnect] = {"reconnect"};
};
-- 控件的方法配置
CommonGameScene2.s_controlFuncMap =
{
[CommonGameScene2.s_controls.bgImage] = CommonGameScene2.onCommonBgTouch,
[CommonGameScene2.s_controls.reconnect] = CommonGameScene2.onTestReconnect,
};
-- 指令的方法配置
CommonGameScene2.s_cmdConfig =
{
[CommonGameScene2.s_cmds.receiveStateFun] = CommonGameScene2.onReceiveStateFun,
[CommonGameScene2.s_cmds.receiveActionFun] = CommonGameScene2.onReceiveActionFun,
[CommonGameScene2.s_cmds.ceatView] = CommonGameScene2.onCeatView,
[CommonGameScene2.s_cmds.updatePrivateRoom] = CommonGameScene2.onRefreshPrivateRoom,
[CommonGameScene2.s_cmds.gameLevelUpdate] = CommonGameScene2.onGameLevelUpdate,
};
CommonGameScene2.stateConfig = {
};
--游戏层可用的控件配置表
--此类只在集成了 CommonGameScene2 的类才会有
--事件需要自己集成
CommonGameScene2.s_gameControlConfig =
{
};
|
description 'FoRa_noobpack'
version '1.0.2'
server_scripts {
"@mysql-async/lib/MySQL.lua",
'@es_extended/locale.lua',
'server/server.lua'
}
client_scripts {
'client/client.lua'
}
|
--[[
# Pandoc filters
--]]
-- #T# Table of contents
-- #C# Basic usage
-- #C# Terminology and synonyms
-- #C# Pandoc AST
-- #C# Elements
-- #C# - Parts of an element
-- #C# - Types of elements
-- #C# - Other functions and methods
-- #T# Beginning of content
-- #C# Basic usage
-- # |-------------------------------------------------------------
-- #T# the pandoc module for Lua comes embedded in Pandoc, so it's not necessary to import the pandoc module
-- #T# the pandoc module can be treated as an associative array table, it's functions, variables, constants, etcetera, can be accessed as keys of said table
-- #T# filters work by filtering the elements of the input document, and when a filter is able to modify an element, the element is modified in whichever way determined by the filter
-- #T# the following filter is used to filter elements of bold (strong) font, and then to apply a small capitalization font to the contents of these elements
function Strong(element1)
return pandoc.SmallCaps(element1.content)
end
-- #T# the element1 is the element being filtered, which is a table that stores the contents of the element in element1.content, the Strong function filters elements of type Strong, and the SmallCaps function applies the small capitalization to its argument
-- #T# the following filter returns the element as a plain string, without the bold font
function Strong(element1)
return pandoc.Str(element1.content[1].text)
end
-- #T# the return value of a filter function can be
-- #T# nil, which doesn't change the filtered element
-- #T# a single new element that replaces the filtered element, if the filtered element is inline or block, the new element must be inline or block respectively
-- #T# an array table of elements that replaces the filtered element, if the filtered element is inline of block, each element in the array table must be inline or block respectively
function Strong(element1)
return nil
end
function Strong(element1)
return pandoc.SmallCaps(element1.content)
end
function Strong(element1)
return {pandoc.SmallCaps(element1.content), pandoc.Str(element1.content[1].text)}
end
-- # |-------------------------------------------------------------
-- #C# Terminology and synonyms
-- # |-------------------------------------------------------------
-- #T# Lua's array tables are refered here as lists
-- #T# a function that is named the same as a Pandoc's AST element, is called a filter
-- # |-------------------------------------------------------------
-- #C# Pandoc AST
-- # |-------------------------------------------------------------
-- #T# AST stands for Abstract Syntax Tree
-- #T# filters modify the Pandoc AST, so the Pandoc AST must be studied to know how to create a filter that achieves a desired result
-- #T# to see the Pandoc AST of a document, execute `pandoc file1.md -t native`
-- #T# the native format is for Pandoc AST native representation
-- #T# the content of an element in the AST is enclosed in square brackets after the type of the element
-- #T# having as input a Markdown file named file1.md with `word1 word2 word3`, executing `pandoc file1.md -t native` the AST output is `[Para [Str "word1",Space,Str "word2",Space,Str "word3"]]`
-- #T# the whole document is enclosed in square brackets. The contents of the Para element are enclosed in square brackets: `[Str "word1",Space,Str "word2",Space,Str "word3"]`, each word becomes an element of type Str, and each space is an element of type Space
-- #T# there are elements that have more information apart from its content, elements that have metadata have it stored apart from the content. Elements with a link target have the link information stored apart from the content
-- #T# a Markdown file named file1.md with `[in span1]{#id1 .c1 .c2 k1='v1' k2='v2'}`, executing `pandoc file1.md -t native` the AST output is `[Para [Span ("id1",["c1","c2"],[("k1","v1"),("k2","v2")]) [Str "in",Space,Str "span1"]]]`, the metadata of the Span element is enclosed in parentheses before the content
-- # |-------------------------------------------------------------
-- #C# Elements
-- # |-------------------------------------------------------------
-- #T# when an element is filtered, the resulting new element is not filtered by subsequent filters
function Emph(element1)
return pandoc.Strong(element1.content)
end
function Strong(element1)
return pandoc.SmallCaps(element1.content)
end
-- #| with these filters, an Emph element is turned into a Strong element, but that resulting Strong element is not converted into a SmallCaps element, it remains as a Strong element
-- #C# - Parts of an element
-- # |-----
-- #T# an element is a table, so its contents can be inspected as a regular table
function Strong(element1)
print(element1) -- # table: 0x7fd82c0fdd30
for k1, v1 in pairs(element1) do
print(k1, "|-|", v1) -- # content |-| table: 0x7fac16ba5cb0
end
for k1, v1 in pairs(element1.content) do
print(k1, "|-|", v1) -- # 1 |-| table: 0x7f8752cd4500
end
for k1, v1 in pairs(element1.content[1]) do
print(k1, "|-|", v1) -- # text |-| line1
end
print(element1.content[1].text) -- # line1
end
-- #T# an element is an associative array table, it's keys depend on the type of the element, for example a Strong element has the content key
-- #T# in a Strong element, the value of the content key is an array table, the value in content[1] is a table with the text key whose value is the text of the element
-- #T# the parts of an Strong element can be summarized as element1.content[1].text
-- # |-----
-- #C# - Types of elements
-- # |-----
-- #T# the type of an element is one of the pandoc types, the pandoc types make the set of possible elements with which filters can work
-- #T# the Inlines filter takes an Inlines type as argument, this argument is the list of inlines inside a given filtered block of the input document
function Inlines(inlines1)
print(inlines1[1].text)
return inlines1
end
-- #| this filter prints the text in the first inline element of each block
-- #T# the Blocks filter takes a Blocks type as argument, this argument is the list of blocks of the input document
function Blocks(blocks1)
print(blocks1[6].content[1].text)
return blocks1
end
-- #| this filter prints the text of the first content of the block number 6
-- #T# Lists are a type of element, Inlines are a type of List, so the List methods can be used with Inlines
-- #T# the insert method of Lists is used to insert an element at a given index in a list
-- # SYNTAX List1:insert(int1, value1)
-- #T# value1 is inserted at position int1 from List1
-- #T# the remove method of Lists is used to remove the element at a given index in a list
-- # SYNTAX List1:remove(int1)
-- #T# the element at position int1 from List1 is removed
function Inlines(inlines1)
if (inlines1[1].text == "A" and inlines1[2].tag == "Space") then
inlines1:remove(1)
inlines1:insert(1, pandoc.Str("B"))
end
return inlines1
end
-- #T# This filter replaces any string "A " that starts a block, for "B "
-- #T# the Str type is the basic inline type, it represents a string, for example 'word1' in Markdown
-- #T# the Space type represents a whitespace, for example ' ' in Markdown
-- #T# the Str filter takes a Str type as argument, this argument is the Str element being filtered
function Str(content1)
return pandoc.Str(content1.text.."Suffix text")
end
-- #T# the LineBreak type represents a newline
function LineBreak()
return {pandoc.LineBreak(), pandoc.LineBreak()}
end
-- #| this filter replaces every LineBreak element with two LineBreak elements
-- #T# the Para type is the basic block type, it represents a paragraph
-- #T# the Para filter takes a Para type as argument, this argument is the Para element being filtered
function Para(element1)
print(element1.tag)
print(element1.content[1].content[1].text)
return pandoc.Para(element1.content)
end
-- #T# this filter prints the tag attribute of the Para element, which is the string 'Para', and using a Markdown file with `*word1*` this filter prints 'word1'
-- #T# the tag attribute is common to many types, is contains a string with the name of the type itself
-- #T# the Pandoc type is the basic document type, it represents a document
-- #T# a Markdown file containing `word1 *word2 word3*` produces the native AST `[Para [Str "word1",Space,Emph [Str "word2",Space,Str "word3"]]]`, the following filter is applied to it
-- #T# the Pandoc filter takes a Pandoc type as argument, this argument is the Pandoc element being filtered
function Pandoc(document1)
print(document1.blocks[1].content[3].content[3].text) -- # word3
print(document1.meta) -- #| no output
return nil
end
-- #T# the reason for which there is no output for `print(document1.meta)`, is that `document.meta` is a table with no elements, because there is no metadata for this example
-- #T# the Span type represents a <span> tag, so it can have metadata
-- #| the Mardown file for the following filter contains `[in span1]{#id1 .c1 .c2 k1='v1' k2='v2'}`
-- #T# the Span filter takes a Span type as argument, this argument is the Span element being filtered
function Span(element1)
print(element1.identifier) -- # id1
print(element1.classes[1]) -- # c1
print(element1.classes[2]) -- # c2
print(element1.attributes.k1) -- # v1
print(element1.attributes.k2) -- # v2
return element1
end
-- #T# the identifier attribute is a string with the identifier in the metadata of the Span element
-- #T# the classes attribute is a list with the classes in the metadata of the Span element
-- #T# the attributes attribute is a table with the attribute value pairs in the metadata of the Span element
-- # |-----
-- #C# - Other functions and methods
-- # |-----
-- #T# the walk_block function is used to apply a given filter to a particular block
-- # SYNTAX pandoc.walk_block(block_element1, filter1)
-- #| for the following example, the Markdown file contains `word1 word2 word3`
function Para(element1)
return pandoc.walk_block(element1, { Str = function(element1) return pandoc.Str("replacement") end })
end
-- #| this filter takes Para elements and replaces their Str elements for the string "replacement". In this example, from walk_block(block_element1, filter1), filter1 is defined as an anonymous function, because otherwise the Str filter would apply to all Str elements in the document.
-- #T# the pandoc.walk_inline function is used to apply a given filter to a particular inline
-- # SYNTAX pandoc.walk_inline(inline_element1, filter1)
-- #| for the following example, the Markdown file contains `word1 *word2 word3*`
function Emph(element1)
return pandoc.walk_inline(element1, { Str = function(element1) return pandoc.Strong(element1) end })
end
-- #| this filter takes Emph elements and places their Str elements into Strong elements. In this example, from walk_inline(inline_element, filter1), filter1 is defined as an anonymous function, because otherwise the Str filter would apply to all Str elements in the document.
-- #T# the pandoc.read function is used to read a string as a document from a given language
-- # SYNTAX pandoc.read(document_string1, language_string1)
-- #T# the pandoc.read function returns a Pandoc document created from reading document_string1 written in language_string1
-- #| the following filter can be used on any Markdown file
function Pandoc(document1)
return pandoc.read("**only this**", "markdown")
end
-- #| this filter converts any Markdown file into `**only this**`
-- #T# the pandoc.pipe function is used to pipe into an external command and pipe back into the filter
-- # SYNTAX pandoc.pipe(command_string1, {arg_string1, arg_string2, arg_stringN}, input_string1)
-- #T# command_string1 is executed in the operating system, using the list of arguments as arguments for the command, and receiving input_string1 as if it was input from stdin
-- #| the Markdown file for this example contains `text1 text2`
function Str(content1)
return pandoc.Str(pandoc.pipe("sed", {"-e", "s/text/Text/"}, content1.text))
end
-- #| the Markdown output is `Text1 Text2`
-- #T# the clone method can be used on Pandoc objects to create copies of them
-- # syntax pandoc_element1:clone()
-- #T# pandoc_element1 is any Pandoc object that is non read-only
-- #| the Markdown file for this example contains `text **TEXT** text`
function Strong(element1)
emph1 = pandoc.Emph(element1.content)
emph2 = emph1:clone()
return {emph1, emph2}
end
-- #| the Markdown output is `text *TEXTTEXT* text`, the emph1 object is cloned in emph2, and then both objects are returned in a list
-- # |-----
-- # |------------------------------------------------------------- |
require "../lua/init"
require "../lua/third_party_project"
third_party_project( "xGL", "StaticLib" )
files
{
"%{prj.name}/src/xgl.cpp",
"%{prj.name}/src/xgl.h"
}
defines
{
"_CRT_SECURE_NO_WARNINGS"
}
includedirs
{
"%{prj.name}/src/**.h"
}
filter "system:windows"
systemversion "latest"
filter "system:linux"
systemversion "latest"
filter "system:macosx"
systemversion "11"
filter "configurations:Debug"
runtime "Debug"
symbols "on"
filter "configurations:Release"
runtime "Release"
optimize "on" |
require'indent_blankline'.setup {
char_list = {'|', '¦', '┆', '┊'},
-- context_patterns = {'class', 'function', 'method', 'if', 'foreach'},
-- show_current_context = true,
-- show_current_context_start = true,
show_trailing_blankline_indent = false,
use_treesitter = true,
}
|
dofile_once("data/scripts/lib/utilities.lua")
dofile_once("data/scripts/perks/perk.lua")
function death( damage_type_bit_field, damage_message, entity_thats_responsible, drop_items )
-- kill self
local entity_id = GetUpdatedEntityID()
local pos_x, pos_y = EntityGetTransform( entity_id )
local perk_id = perk_spawn( pos_x, pos_y, "EXTRA_HP" )
-- do some kind of an effect? throw some particles into the air?
EntityLoad( "data/entities/items/pickup/heart.xml", pos_x - 16, pos_y )
EntityLoad( "data/entities/items/wand_unshuffle_06.xml", pos_x + 16, pos_y )
if( perk_id ~= nil ) then
EntityAddComponent( perk_id, "VariableStorageComponent",
{
name = "perk_dont_remove_others",
value_bool = "1",
} )
end
AddFlagPersistent( "miniboss_dragon" )
--EntityKill( entity_id )
end |
local i = 0
return function(func)
local t = {}
local n = func()
while n ~= 10 do
table.insert(t,n)
n = func()
end
return t
end,{function() i = i+1 return i end},{{1,2,3,4,5,6,7,8,9}}
|
--虚拟大陆 每个玩家拥有一个
local skynet = require "skynet"
local util = require "util"
local json = require "cjson"
require "skynet.manager"
--大陆上的据点 (简化版城市)
local STRONGHOLD = {}
--大陆上的怪物
local MONSTER = {}
--数据持久化服务
local db_game
local db_guild
local arg = table.pack(...)
assert(arg.n == 1)
local player_id = tonumber(arg[1])
local player = {}
local tavern = {}
local monster = {}
local PROP = {}
local EQUIP = {}
local SHOP_ITEM = {}
local UNIT = {}
--指令集
local CMD = {}
--初始化虚拟大陆
function CMD.Init(player_data)
skynet.error("初始化玩家", player_id, "的虚拟大陆")
player = player_data
player.seat_0 = json.decode(player.seat_0)
player.seat_1 = json.decode(player.seat_1)
player.seat_2 = json.decode(player.seat_2)
player.seat_3 = json.decode(player.seat_3)
player.seat_4 = json.decode(player.seat_4)
STRONGHOLD = skynet.call(db_game, "lua", "LoadStrongholdList", player_id)
tavern = skynet.call(db_game, "lua", "LoadTavernList", player_id)
for k, v in pairs(tavern) do
tavern[k].seat_0 = json.decode(v.seat_0)
tavern[k].seat_1 = json.decode(v.seat_1)
tavern[k].seat_2 = json.decode(v.seat_2)
tavern[k].seat_3 = json.decode(v.seat_3)
tavern[k].seat_4 = json.decode(v.seat_4)
end
monster = skynet.call(db_game, "lua", "LoadMonsterList", player_id)
EQUIP = skynet.call(db_game, "lua", "LoadEquipList", player_id)
PROP = skynet.call(db_game, "lua", "LoadPropList", player_id)
UNIT = skynet.call(db_game, "lua", "LoadUnitList", player_id)
VCITY = skynet.call(db_game, "lua", "LoadCityList", player_id)
return true
end
function CMD.GetStronghold()
skynet.error("返回要塞数据")
return STRONGHOLD
end
function CMD.GetPlayer()
skynet.error("返回玩家数据")
return player
end
function CMD.GetTavern()
skynet.error("返回酒馆数据")
return tavern
end
function CMD.GetProp()
skynet.error("返回道具数据")
return PROP
end
function CMD.GetEquip()
skynet.error("返回装备数据")
return EQUIP
end
function CMD.GetUnit()
skynet.error("返回部队数据")
return UNIT
end
skynet.init(function()
skynet.error("为玩家", player_id, "创建虚拟大陆")
db_guild = skynet.queryservice("db_guild")
db_game = skynet.queryservice("db_game")
end)
skynet.start(function()
skynet.dispatch("lua", function(session, address, cmd, ...)
skynet.error("虚拟大陆服务 " .. player_id .. "收到" .. cmd .. "指令")
if CMD[cmd] ~= nil then
skynet.ret(skynet.pack(CMD[cmd](...)))
else
skynet.error("虚拟大陆服务没有定义 " .. cmd .. " 操作")
end
end)
-- skynet.register("vland" .. player_id)
end) |
print("Running editor.lua!")
setdefaultfont("Menlo", 15)
function hook(s)
removeattribute("NSColor", makerange(1, #s))
local i, j = 0, 0
while true do
i, j = s:find('hi!', i + 1)
if i == nil then break end
addattribute("NSColor", makecolor("orangeColor"),
makerange(i, j - i + 1))
end
end
|
-- Copyright (C) Miracle
-- Copyright (C) OpenWAF
local _M = {
_VERSION = "0.0.2"
}
local twaf_func = require "lib.twaf.inc.twaf_func"
local twaf_conf = require "lib.twaf.twaf_conf"
_M.api = {}
_M.help = {}
_M.api.rules = {}
-- get rules, e.g: GET /api/rules/{rule_id}
_M.api.rules.get = function(_twaf, log, u)
local conf = _twaf.config
if not u[2] then
log.result = conf.rules
return
end
if not conf.rules_id[u[2]] then
log.success = 0
log.reason = "no rule id: "..u[2]
return
end
for phase, rules in pairs(conf.rules) do
for _, r in pairs(rules) do
if r.id == u[2] then
log.result = r
return
end
end
end
if not log.result then
log.success = 0
log.reason = "no rule id: "..u[2]
return
end
end
-- post rules, e.g: POST /api/rules
-- post rules, e.g: POST /api/rules/checking
_M.api.rules.post = function(_twaf, log, u)
-- check request body
local data = twaf_func.api_check_json_body(log)
if not data then
return
end
if type(data.config) ~= "table" then
log.success = 0
log.reason = "rules: table expected, got "..type(data.config)
return
end
if #data.config == 0 then
data.config = {data.config}
end
-- check rules
local back = {}
local conf = _twaf.config
for _, r in ipairs(data.config) do
local res, err = twaf_func:check_rules(conf, r)
if res == true then
table.insert(back, r.id)
conf.rules_id[r.id] = 1
else
if log.reason then
table.insert(log.reason, err)
else
log.success = 0
log.reason = {}
table.insert(log.reason, err)
end
end
end
if log.success == 0 then
for _, v in ipairs(back) do
conf.rules_id[v] = nil
end
return
end
log.result = data.config
if u[2] and u[2]:lower() == "checking" then
for _, v in ipairs(back) do
conf.rules_id[v] = nil
end
return
end
-- add to conf.rules
if not conf.rules then
conf.rules = {}
end
twaf_conf:rule_group_phase(conf.rules, data.config)
end
-- update rules, e.g: PUT /api/rules
_M.api.rules.put = function(_twaf, log, u)
-- check request body
local data = twaf_func.api_check_json_body(log)
if not data then
return
end
if type(data.config) ~= "table" then
log.success = 0
log.reason = "rules: table expected, got "..type(data.config)
return
end
if #data.config == 0 then
data.config = {data.config}
end
local conf = _twaf.config
if type(conf.rules) ~= "table" then
log.success = 0
log.reason = "No system rules"
return
end
for _, r in ipairs(data.config) do
if type(r.id) ~= "string" then
log.success = 0
log.reason = "No key 'id' in rules"
return
end
if not conf.rules_id[r.id] then
log.success = 0
log.reason = "System rules no rule id '"..r.id.."'"
return
end
end
-- check rules
local back = {}
for _, r in ipairs(data.config) do
local res, err = twaf_func:check_rules(conf, r)
if type(err) == "table" then
for k, v in pairs(err) do
if ngx.re.find(v, "^ID.*duplicate$") then
table.remove(err, k)
end
end
if #err == 0 then
res = true
end
end
if res == true then
table.insert(back, r.id)
conf.rules_id[r.id] = 1
else
if log.reason then
table.insert(log.reason, err)
else
log.success = 0
log.reason = {}
table.insert(log.reason, err)
end
end
end
if log.success == 0 then
for _, v in ipairs(back) do
conf.rules_id[v] = nil
end
return
end
log.result = data.config
-- add to conf.rules
for _, r in ipairs(data.config) do
local phase = r.phase
if type(phase) ~= "table" then
phase = {phase}
end
for _, p in pairs(phase) do
repeat
if not conf.rules[p] then
conf.rules[p] = {}
table.insert(conf.rules[p], r)
break
end
for i, rule in ipairs(conf.rules[p]) do
if r.id == rule.id then
conf.rules[p][i] = r
break
end
end
table.insert(conf.rules[p], r)
until true
end
end
if not log.result then
log.success = 0
log.reason = "No rule id '"..u[3].."' in policy uuid '"..u[2].."'"
end
return
end
-- delete rules, e.g: DELETE /api/rules/{rule_id}
_M.api.rules.delete = function(_twaf, log, u)
end
_M.help.rules = {
"GET /api/rules",
"GET /api/rules/{rule_id}",
"POST /api/rules",
"POST /api/rules/checking",
"PUT /api/rules"
}
return _M |
-- Copyright (C) 2017 josephzeng <josephzeng36@gmail.com>
--
-- Distributed under terms of the MIT license.
--
local M = {}
M.environment = 0
M.mysql_ini = {
host = "127.0.0.1",
port = 3306,
database = "zsq_game",
user = "root",
password = "123456",
max_packet_size = 1024 * 1024
--on_connect = on_connect
}
M.redis_ini = {
host = "127.0.0.1",
port = 6379,
db = 0
}
M.msg = {
[101] = "登录失败",
[102] = "登录成功",
[901] = "数据包长度不够",
[902] = "数据包解包失败",
[903] = "服务CMD不存在",
[903] = "验证不通过",
[905] = "服务返回错误",
}
return M
|
--
-- Copyright (c) 2010 Ted Unangst <ted.unangst@gmail.com>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
--
-- Lua version ported/copied from the C version, copyright as follows.
--
-- Copyright (c) 2000 by Jef Poskanzer <jef@mail.acme.com>.
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
--
--
-- Usage is pretty obvious. bigint(n) constructs a bigint. n can be
-- a number or a string. The regular operators are all overridden via
-- metatable, and also generally work with regular numbers too.
-- Note that comparisons between bigints and numbers *don't* work.
-- bigint() uses a small cache, so bigint(constant) should be fast.
--
-- Only the basic operations are here. No gcd, factorial, prime test, ...
--
-- Technical notes:
-- Primary difference from the C version is the obvious 1 indexing, this
-- shows up in a variety of ways and places, along with slightly different
-- handling of pre-allocated comps arrays.
-- I made a brief effort to sync some of the comments, but you're better
-- off just reading the C code.
-- C version homepage: http://www.acme.com/software/bigint/
--
if isbigintreq then
return bigint
end
isbigintreq = true
-- two functions to help make Lua act more like C
local function fl(x)
if x < 0 then
return math.ceil(x) + 0 -- make -0 go away
else
return math.floor(x)
end
end
local function cmod(a, b)
local x = a % b
if a < 0 and x > 0 then
x = x - b
end
return x
end
local radix = 2^24 -- maybe up to 2^26 is safe?
local radix_sqrt = fl(math.sqrt(radix))
local bigintmt -- forward decl
local function conv(bi)
local ret = 0
for k=#bi.comps, 1, -1 do
ret = ret * radix + bi.comps[k]
end
return ret
end
local function alloc()
local bi = {}
setmetatable(bi, bigintmt)
bi.comps = {}
bi.sign = 1;
bi.conv = conv
return bi
end
local function clone(a)
local bi = alloc()
bi.sign = a.sign
local c = bi.comps
local ac = a.comps
for i = 1, #ac do
c[i] = ac[i]
end
return bi
end
local function normalize(bi, notrunc)
local c = bi.comps
local v
-- borrow for negative components
for i = 1, #c - 1 do
v = c[i]
if v < 0 then
c[i+1] = c[i+1] + fl(v / radix) - 1
v = cmod(v, radix)
if v ~= 0 then
c[i] = v + radix
else
c[i] = v
c[i+1] = c[i+1] + 1
end
end
end
-- is top component negative?
if c[#c] < 0 then
-- switch the sign and fix components
bi.sign = -bi.sign
for i = 1, #c - 1 do
v = c[i]
c[i] = radix - v
c[i+1] = c[i+1] + 1
end
c[#c] = -c[#c]
end
-- carry for components larger than radix
for i = 1, #c do
v = c[i]
if v > radix then
c[i+1] = (c[i+1] or 0) + fl(v / radix)
c[i] = cmod(v, radix)
end
end
-- trim off leading zeros
if not notrunc then
for i = #c, 2, -1 do
if c[i] == 0 then
c[i] = nil
else
break
end
end
end
-- check for -0
if #c == 1 and c[1] == 0 and bi.sign == -1 then
bi.sign = 1
end
end
local function negate(a)
local bi = clone(a)
bi.sign = -bi.sign
return bi
end
local function compare(a, b)
local ac, bc = a.comps, b.comps
local as, bs = a.sign, b.sign
if ac == bc then
return 0
elseif as > bs then
return 1
elseif as < bs then
return -1
elseif #ac > #bc then
return as
elseif #ac < #bc then
return -as
end
for i = #ac, 1, -1 do
if ac[i] > bc[i] then
return as
elseif ac[i] < bc[i] then
return -as
end
end
return 0
end
local function lt(a, b)
return compare(a, b) < 0
end
local function eq(a, b)
return compare(a, b) == 0
end
local function le(a, b)
return compare(a, b) <= 0
end
local function addint(a, n)
local bi = clone(a)
if bi.sign == 1 then
bi.comps[1] = bi.comps[1] + n
else
bi.comps[1] = bi.comps[1] - n
end
normalize(bi)
return bi
end
local function add(a, b)
if type(a) == "number" then
return addint(b, a)
elseif type(b) == "number" then
return addint(a, b)
end
local bi = clone(a)
local sign = bi.sign == b.sign
local c = bi.comps
for i = #c + 1, #b.comps do
c[i] = 0
end
local bc = b.comps
for i = 1, #bc do
local v = bc[i]
if sign then
c[i] = c[i] + v
else
c[i] = c[i] - v
end
end
normalize(bi)
return bi
end
local function sub(a, b)
if type(b) == "number" then
return addint(a, -b)
elseif type(a) == "number" then
a = bigint(a)
end
return add(a, negate(b))
end
local function mulint(a, b)
local bi = clone(a)
if b < 0 then
b = -b
bi.sign = -bi.sign
end
local bc = bi.comps
for i = 1, #bc do
bc[i] = bc[i] * b
end
normalize(bi)
return bi
end
local function multiply(a, b)
local bi = alloc()
local c = bi.comps
local ac, bc = a.comps, b.comps
for i = 1, #ac + #bc do
c[i] = 0
end
for i = 1, #ac do
for j = 1, #bc do
c[i+j-1] = c[i+j-1] + ac[i] * bc[j]
end
-- keep the zeroes
normalize(bi, true)
end
normalize(bi)
if bi ~= bigint(0) then
bi.sign = a.sign * b.sign
end
return bi
end
local function kmul(a, b)
local ac, bc = a.comps, b.comps
local an, bn = #a.comps, #b.comps
local bi, bj, bk, bl = alloc(), alloc(), alloc(), alloc()
local ic, jc, kc, lc = bi.comps, bj.comps, bk.comps, bl.comps
local n = fl((math.max(an, bn) + 1) / 2)
for i = 1, n do
ic[i] = (i + n <= an) and ac[i+n] or 0
jc[i] = (i <= an) and ac[i] or 0
kc[i] = (i + n <= bn) and bc[i+n] or 0
lc[i] = (i <= bn) and bc[i] or 0
end
normalize(bi)
normalize(bj)
normalize(bk)
normalize(bl)
local ik = bi * bk
local jl = bj * bl
local mid = (bi + bj) * (bk + bl) - ik - jl
local mc = mid.comps
local ikc = ik.comps
local jlc = jl.comps
for i = 1, #ikc + n*2 do -- fill it up
jlc[i] = jlc[i] or 0
end
for i = 1, #mc do
jlc[i+n] = jlc[i+n] + mc[i]
end
for i = 1, #ikc do
jlc[i+n*2] = jlc[i+n*2] + ikc[i]
end
jl.sign = a.sign * b.sign
normalize(jl)
return jl
end
local kthresh = 12
local function mul(a, b)
if type(a) == "number" then
return mulint(b, a)
elseif type(b) == "number" then
return mulint(a, b)
end
if #a.comps < kthresh or #b.comps < kthresh then
return multiply(a, b)
end
return kmul(a, b)
end
local function divint(numer, denom)
local bi = clone(numer)
if denom < 0 then
denom = -denom
bi.sign = -bi.sign
end
local r = 0
local c = bi.comps
for i = #c, 1, -1 do
r = r * radix + c[i]
c[i] = fl(r / denom)
r = cmod(r, denom)
end
normalize(bi)
return bi
end
local function multi_divide(numer, denom)
local n = #denom.comps
local approx = divint(numer, denom.comps[n])
for i = n, #approx.comps do
approx.comps[i - n + 1] = approx.comps[i]
end
for i = #approx.comps, #approx.comps - n + 2, -1 do
approx.comps[i] = nil
end
local rem = approx * denom - numer
if rem < denom then
quotient = approx
else
quotient = approx - multi_divide(rem, denom)
end
return quotient
end
local function multi_divide_wrap(numer, denom)
-- we use a successive approximation method, but it doesn't work
-- if the high order component is too small. adjust if needed.
if denom.comps[#denom.comps] < radix_sqrt then
numer = mulint(numer, radix_sqrt)
denom = mulint(denom, radix_sqrt)
end
return multi_divide(numer, denom)
end
local function div(numer, denom)
if type(denom) == "number" then
if denom == 0 then
error("divide by 0", 2)
end
return divint(numer, denom)
elseif type(numer) == "number" then
numer = bigint(numer)
end
-- check signs and trivial cases
local sign = 1
local cmp = compare(denom, bigint(0))
if cmp == 0 then
error("divide by 0", 2)
elseif cmp == -1 then
sign = -sign
denom = negate(denom)
end
cmp = compare(numer, bigint(0))
if cmp == 0 then
return bigint(0)
elseif cmp == -1 then
sign = -sign
numer = negate(numer)
end
cmp = compare(numer, denom)
if cmp == -1 then
return bigint(0)
elseif cmp == 0 then
return bigint(sign)
end
local bi
-- if small enough, do it the easy way
if #denom.comps == 1 then
bi = divint(numer, denom.comps[1])
else
bi = multi_divide_wrap(numer, denom)
end
if sign == -1 then
bi = negate(bi)
end
return bi
end
local function intrem(bi, m)
if m < 0 then
m = -m
end
local rad_r = 1
local r = 0
local bc = bi.comps
for i = 1, #bc do
local v = bc[i]
r = cmod(r + v * rad_r, m)
rad_r = cmod(rad_r * radix, m)
end
if bi.sign < 1 then
r = -r
end
return r
end
local function intmod(bi, m)
local r = intrem(bi, m)
if r < 0 then
r = r + m
end
return r
end
local function rem(bi, m)
if type(m) == "number" then
return bigint(intrem(bi, m))
elseif type(bi) == "number" then
bi = bigint(bi)
end
return bi - ((bi / m) * m)
end
local function mod(a, m)
local bi = rem(a, m)
if bi.sign == -1 then
bi = bi + m
end
return bi
end
local printscale = 10000000
local printscalefmt = string.format("%%.%dd", math.log10(printscale))
local function makestr(bi, s)
if bi >= bigint(printscale) then
makestr(divint(bi, printscale), s)
end
table.insert(s, string.format(printscalefmt, intmod(bi, printscale)))
end
local function biginttostring(bi)
local s = {}
if bi < bigint(0) then
bi = negate(bi)
table.insert(s, "-")
end
makestr(bi, s)
s = table.concat(s):gsub("^0*", "")
if s == "" then s = "0" end
return s
end
bigintmt = {
__add = add,
__sub = sub,
__mul = mul,
__div = div,
__mod = mod,
__unm = negate,
__eq = eq,
__lt = lt,
__le = le,
__tostring = biginttostring
}
local cache = {}
local ncache = 0
local function bigint(n)
if cache[n] then
return cache[n]
end
if type(n) == 'table' then
return clone(n)
end
local bi
if type(n) == "string" then
local digits = { n:byte(1, -1) }
for i = 1, #digits do
digits[i] = string.char(digits[i])
end
local start = 1
local sign = 1
if digits[i] == '-' then
sign = -1
start = 2
end
bi = bigint(0)
for i = start, #digits do
bi = addint(mulint(bi, 10), tonumber(digits[i]))
end
bi = mulint(bi, sign)
else
bi = alloc()
bi.comps[1] = n
normalize(bi)
end
if ncache > 100 then
cache = {}
ncache = 0
end
cache[n] = bi
ncache = ncache + 1
return bi
end
_G.bigint = bigint
return bigint |
local UID = KEYS[1]
local record = redis.call('zscore', 'rec', UID)
return record |
--[[
Falling from the Sky
-- SeaStuff Class --
Author: Yoru Sung
https://github.com/spero61/falling-from-the-sky
SeaStuff vibrates at the top of the game window for a couple of seconds
upon creation of its object. Then falls faster than other 'stuff's.
]]
SeaStuff = Class{__includes = Stuff}
function SeaStuff:init()
local index = love.math.random(1, 20)
local imagePrefix = "sea"
if index < 10 then
imagePrefix = imagePrefix .. "0"
end
local filename = imagePrefix .. tostring(index) .. ".png"
---@diagnostic disable-next-line: missing-parameter
self.image = love.graphics.newImage("image/seaStuff/" .. filename)
self.scale = seaStuffScale
self.width = self.image:getWidth() * self.scale
self.height = self.image:getHeight() * self.scale
self.x = love.math.random(0, gameWidth - self.width)
self.speed = seaStuffSpeed
self.score = seaScore
self.dead = false
-- for seaStuff specific behavior
self.vibrateTimer = vibrateTimer
end
function SeaStuff:update(dt)
if self.vibrateTimer > 0 then
self.y = love.math.random(15, 20)
end
self.vibrateTimer = self.vibrateTimer - dt
if self.vibrateTimer <= 0 then
-- twice faster than a normal one
self.y = self.y + self.speed * dt
end
if self.y - self.height > gameHeight and self.dead == false then
scoreSea:play()
self.dead = true
end
end
function SeaStuff:render()
love.graphics.draw(self.image, self.x, self.y, 0, self.scale, self.scale)
end |
Route = {}
Route.active = {}
Route.SetGps = function(route)
ClearGpsMultiRoute()
StartGpsMultiRoute(8, true, false)
for _, s in pairs(route.stops) do
AddPointToGpsMultiRoute(s.x+.0, s.y+.0, s.z+.0)
end
SetGpsMultiRouteRender(true)
end
-- Show the blips for all the stops we plan to make
Route.ShowBlips = function(route)
for _, s in pairs(route.stops) do
BusStop.ShowBlip(s)
end
end
-- Hides all the blips in the route
Route.HideBlips = function(route)
for _, s in pairs(route.stops) do
BusStop.HideBlip(s)
end
end
Route.RegisterEvents = function(ESX)
--TODO: Implement this functionality
--[[
RegisterNetEvent(E.RouteActive)
AddEventHandler(E.RouteActive, Route.ActivateRoute)
RegisterNetEvent(E.RouteDeactive)
AddEventHandler(E.RouteDeactive, Route.DeactivateRoute)
]]
end |
ESX = nil
kontrol = 2000
kontrol2 = 2000
kazma = false
local zone = nil
local sayac = 60
local anliktoken = 0
local alabilir = false
local var = false
local vehicle = nil
sesler = { "rockhit1", "rockhit2", "rockhit3", "rockhit4"}
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
end)
-- Create Blips
Citizen.CreateThread(function()
for k,v in pairs(Config.Blips) do
v.blip = AddBlipForCoord(v.Location, v.Location, v.Location)
SetBlipSprite(v.blip, v.id)
SetBlipAsShortRange(v.blip, true)
BeginTextCommandSetBlipName("STRING")
SetBlipColour(v.blip, 0)
AddTextComponentString(v.name)
EndTextCommandSetBlipName(v.blip)
end
end)
-- Display markers
Citizen.CreateThread(function()
while true do
Citizen.Wait(kontrol) -- bozulursa 0 yap
local coords = GetEntityCoords(PlayerPedId())
for k,v in pairs(Config.Zones) do
if(v.Type ~= -1 and GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < Config.DrawDistance) then
kontrol = 0
DrawMarker(v.Type, v.Pos.x, v.Pos.y, v.Pos.z, 0.0, 0.0, 0.0, 0, 180.0, 0.0, v.Size.x, v.Size.y, v.Size.z, Config.MarkerColor.r, Config.MarkerColor.g, Config.MarkerColor.b, 100, false, true, 2, false, false, false, false)
else
kontrol = 1000
end
end
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(kontrol2) -- bozulursa 0 yap
local coords = GetEntityCoords(PlayerPedId())
for k,v in pairs(Config.Zones2) do
if(v.Type ~= -1 and GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < 85.0) then
kontrol2 = 0
DrawMarker(v.Type, v.Pos.x, v.Pos.y, v.Pos.z, 0.0, 0.0, 0.0, 0, 180.0, 0.0, v.Size.x, v.Size.y, v.Size.z, Config.MarkerColor.r, Config.MarkerColor.g, Config.MarkerColor.b, 100, false, true, 2, false, false, false, false)
else
kontrol2 = 2000
end
end
end
end)
-- Enter / Exit marker events
Citizen.CreateThread(function()
while true do
Citizen.Wait(kontrol)
local coords = GetEntityCoords(PlayerPedId())
local isInMarker = false
local currentZone = nil
for k,v in pairs(Config.Zones) do
if GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < 3.0 then
kontrol = 0
isInMarker = true
currentZone = k
end
end
for k,v in pairs(Config.Zones2) do
if GetDistanceBetweenCoords(coords, v.Pos.x, v.Pos.y, v.Pos.z, true) < 1.5 then
kontrol2 = 0
isInMarker = true
currentZone = k
end
end
if (isInMarker and not HasAlreadyEnteredMarker) or (isInMarker and LastZone ~= currentZone) then
HasAlreadyEnteredMarker = true
LastZone = currentZone
TriggerEvent('thd_maden:hasEnteredMarker', currentZone)
end
if not isInMarker and HasAlreadyEnteredMarker then
HasAlreadyEnteredMarker = false
TriggerEvent('thd_maden:hasExitedMarker', LastZone)
end
end
end)
function OpenMenu()
local elements = {
{label = "Araç al", value = 'aracal'},
{label = "Token Sat", value = 'tokensat'},
{label = "Araç koy", value = 'arackoy'}
}
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'Madencilik', {
title = "Madencilik",
align = 'top-left',
elements = elements
}, function(data, menu)
if data.current.value == 'tokensat' then
TokenVerMenu()
elseif data.current.value == 'aracal' then
AracOlustur()
elseif data.current.value == 'arackoy' then
AracSil()
end
end, function(data, menu)
menu.close()
end)
end
RegisterNetEvent('thd_maden:eleKazma')
AddEventHandler('thd_maden:eleKazma', function()
eleKazma()
end)
function eleKazma()
if kazma == false then
kazma = CreateObject(GetHashKey("prop_tool_pickaxe"), 0, 0, 0, true, true, true)
AttachEntityToEntity(kazma, PlayerPedId(), GetPedBoneIndex(PlayerPedId(), 57005), 0.09, 0.03, -0.02, -78.0, 13.0, 28.0, false, false, false, false, 1, true)
SetCurrentPedWeapon(PlayerPedId(), GetHashKey('WEAPON_UNARMED'))
TriggerEvent('thd_maden:vuramaz')
TriggerEvent('thd_maden:vuramaz2')
kazma = true
else
DetachEntity(kazma, 1, true)
DeleteObject(kazma)
SetCurrentPedWeapon(PlayerPedId(), GetHashKey('WEAPON_UNARMED'))
TriggerEvent('thd_maden:vuramaz')
TriggerEvent('thd_maden:vuramaz2')
kazma = false
end
end
function AracOlustur()
if vehicle == nil then
TriggerServerEvent('thd_maden:arac')
else
exports['mythic_notify']:SendAlert('error', 'Zaten bir aracın var.', 5000)
end
end
RegisterNetEvent('thd_maden:AracOlustur')
AddEventHandler('thd_maden:AracOlustur', function ()
if vehicle == nil then
local modelHash = GetHashKey("Rebel")
RequestModel(modelHash)
local isLoaded = HasModelLoaded(modelHash)
while isLoaded == false do
Citizen.Wait(100)
end
vehicle = CreateVehicle(modelHash, Config.AracSpawnCords, 145.50, 1, 0)
plate = GetVehicleNumberPlateText(vehicle)
exports['mythic_notify']:SendAlert('success', 'Araç kiralandı.', 5000)
else
exports['mythic_notify']:SendAlert('error', 'Zaten bir aracın var.', 5000)
end
end)
function AracSil()
if vehicle ~= nil then
if plate == GetVehicleNumberPlateText(GetVehiclePedIsIn(PlayerPedId(), true)) then
DeleteEntity(vehicle)
DeleteVehicle(vehicle)
ESX.Game.DeleteVehicle(vehicle)
vehicle = nil
exports['mythic_notify']:SendAlert('success', 'Araç teslim edildi.', 5000)
TriggerServerEvent('thd_maden:paraver')
else
exports['mythic_notify']:SendAlert('inform', 'Araca binip tekrardan deneyin.', 5000)
end
end
end
RegisterNetEvent('thd_maden:vuramaz')
AddEventHandler('thd_maden:vuramaz', function()
Citizen.CreateThread(function()
while kazma do
Citizen.Wait(0)
DisablePlayerFiring(PlayerPedId(), true)
if IsControlJustPressed(1, 346) then
FreezeEntityPosition(PlayerPedId(), true)
if currentBar ~= nil then
ESX.Streaming.RequestAnimDict("melee@large_wpn@streamed_core", function()
TaskPlayAnim(PlayerPedId(), "melee@large_wpn@streamed_core", "ground_attack_on_spot", 1.0, -1.0, 1000, 49, 1, false, false, false)
EnableControlAction(0, 32, true) -- w
EnableControlAction(0, 34, true) -- a
EnableControlAction(0, 8, true) -- s
EnableControlAction(0, 9, true) -- d
EnableControlAction(0, 22, true) -- space
EnableControlAction(0, 36, true) -- ctrl
EnableControlAction(0, 21, true) -- SHIFT
TriggerEvent('InteractSound_CL:PlayOnOne', sesler[ math.random( #sesler ) ], 0.3)
Citizen.Wait(1500)
DisablePlayerFiring(PlayerPedId(), true)
FreezeEntityPosition(PlayerPedId(), false)
DisablePlayerFiring(PlayerPedId(), true)
BarEkle()
end)
else
DisablePlayerFiring(PlayerPedId(), true)
FreezeEntityPosition(PlayerPedId(), false)
exports['mythic_notify']:SendAlert('error', 'Yakında taş yok.', 5000)
end
end
end
end)
end)
RegisterNetEvent('thd_maden:vuramaz2')
AddEventHandler('thd_maden:vuramaz2', function()
Citizen.CreateThread(function()
while kazma do
Citizen.Wait(0)
DisablePlayerFiring(PlayerPedId(), true)
end
end)
end)
loadModel = function(model)
while not HasModelLoaded(model) do Wait(0) RequestModel(model) end
return model
end
function TokenVerMenu()
ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'Token Satma', {
title = "Satılacak Token Miktarı",
}, function (data2, menu)
local tokenMik = tonumber(data2.value)
if tokenMik < 0 or tokenMik == nil then
exports['mythic_notify']:SendAlert('error', 'Aynen şuan buga soktun.', 5000)
else
TriggerServerEvent('thd_maden:givePara', tokenMik, tokenMik * Config.BirTokenFiyat)
menu.close()
end
end, function (data2, menu)
menu.close()
end)
end
function mesajGoster(msg, action)
Citizen.CreateThread(function()
while currentBar ~= nil do
Citizen.Wait(0)
SetTextComponentFormat('STRING')
AddTextComponentString(msg)
DisplayHelpTextFromStringLabel(0, 0, 1, -1)
if IsControlJustPressed(1, 38) then
if action == "tokenal" then
if var == true then
if alabilir == true then
alabilir = false
TriggerServerEvent('thd_maden:giveToken', anliktoken)
anliktoken = 0
var = false
else
exports['mythic_notify']:SendAlert('inform', "Tokenleri almak için " .. sayac .. " saniye beklemen lazım", 5000)
end
else
exports['mythic_notify']:SendAlert('error', 'Eritilen taş yok.', 5000)
end
elseif action == "kayaver" then
ESX.Streaming.RequestAnimDict("amb@prop_human_bum_bin@idle_a", function()
TaskPlayAnim(PlayerPedId(), "amb@prop_human_bum_bin@idle_a", "idle_a", 1.0, -1.0, 5000, 0, 1, true, true, true)
EnableControlAction(0, 32, true) -- w
EnableControlAction(0, 34, true) -- a
EnableControlAction(0, 8, true) -- s
EnableControlAction(0, 9, true) -- d
EnableControlAction(0, 22, true) -- space
EnableControlAction(0, 36, true) -- ctrl
Citizen.Wait(5000)
DisablePlayerFiring(PlayerPedId(), true)
FreezeEntityPosition(PlayerPedId(), false)
DisablePlayerFiring(PlayerPedId(), true)
end)
TriggerServerEvent('thd_maden:kayalariver')
elseif action == "tokensat" then
OpenMenu()
end
end
end
end)
end
RegisterNetEvent('thd_maden:verchance')
AddEventHandler('thd_maden:verchance', function(bool)
var = bool
end)
RegisterNetEvent('thd_maden:tokensayac')
AddEventHandler('thd_maden:tokensayac', function(itemsayi)
sayac = Config.KayaEritmeSuresi
while sayac > 0 do
sayac = sayac - 1
Citizen.Wait(1000)
end
exports['mythic_notify']:SendAlert('success', 'Tokenler alınmaya hazır.', 5000)
anliktoken = itemsayi + anliktoken
alabilir = true
end)
AddEventHandler('thd_maden:hasEnteredMarker', function(zone)
currentBar = zone
if (zone ~= "tokenal" and zone ~= "kayaver" and zone ~= "tokensat") then
SetDisplay(zone, "block")
kontrol = 0
else
for k,v in pairs(Config.Zones2) do
if zone == k then
mesajGoster(v.Message, k)
end
end
kontrol2 = 0
end
end)
AddEventHandler('thd_maden:hasExitedMarker', function(zone)
closeAll()
currentBar = nil
end)
RegisterNUICallback("kaya", function(data)
if data.kaya then
TriggerServerEvent('thd_maden:givekaya')
end
end)
function SetDisplay(bar, bool)
--SetNuiFocus(bool, bool)
SendNUIMessage({
type = bar,
status = bool,
})
end
function BarEkle(zonee)
SendNUIMessage({
type = "ekle",
bar = currentBar,
})
end
function closeAll()
SendNUIMessage({
type = "bar1",
status = "none",
})
SendNUIMessage({
type = "bar2",
status = "none",
})
SendNUIMessage({
type = "bar3",
status = "none",
})
SendNUIMessage({
type = "bar4",
status = "none",
})
SendNUIMessage({
type = "bar5",
status = "none",
})
SendNUIMessage({
type = "bar6",
status = "none",
})
end |
--[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
--[[lit-meta
name = "luvit/timer"
version = "2.0.2"
dependencies = {
"luvit/core@2.0.0",
"luvit/utils@2.1.0",
}
license = "Apache 2"
homepage = "https://github.com/luvit/luvit/blob/master/deps/timer.lua"
description = "Javascript style setTimeout and setInterval for luvit"
tags = {"luvit", "timer"}
]]
local uv = require('uv')
local Object = require('core').Object
local bind = require('utils').bind
local assertResume = require('utils').assertResume
-------------------------------------------------------------------------------
local Timer = Object:extend()
function Timer:initialize()
self._handle= uv.new_timer()
self._active = false
end
function Timer:_update()
self._active = uv.is_active(self._handle)
end
-- Timer:start(timeout, interval, callback)
function Timer:start(timeout, interval, callback)
uv.timer_start(self._handle, timeout, interval, callback)
self:_update()
end
-- Timer:stop()
function Timer:stop()
uv.timer_stop(self._handle)
self:_update()
end
-- Timer:again()
function Timer:again()
uv.timer_again(self._handle)
self:_update()
end
-- Timer:close()
function Timer:close()
uv.close(self._handle)
self:_update()
end
-- Timer:setRepeat(interval)
Timer.setRepeat = uv.timer_set_repeat
-- Timer:getRepeat()
Timer.getRepeat = uv.timer_get_repeat
-- Timer.now
Timer.now = uv.now
------------------------------------------------------------------------------
local function sleep(delay, thread)
thread = thread or coroutine.running()
local timer = uv.new_timer()
uv.timer_start(timer, delay, 0, function ()
uv.timer_stop(timer)
uv.close(timer)
return assertResume(thread)
end)
return coroutine.yield()
end
local function setTimeout(delay, callback, ...)
local timer = uv.new_timer()
local args = {...}
uv.timer_start(timer, delay, 0, function ()
uv.timer_stop(timer)
uv.close(timer)
callback(unpack(args))
end)
return timer
end
local function setInterval(interval, callback, ...)
local timer = uv.new_timer()
uv.timer_start(timer, interval, interval, bind(callback, ...))
return timer
end
local function clearInterval(timer)
if uv.is_closing(timer) then return end
uv.timer_stop(timer)
uv.close(timer)
end
local checker = uv.new_check()
local idler = uv.new_idle()
local immediateQueue = {}
local function onCheck()
local queue = immediateQueue
immediateQueue = {}
for i = 1, #queue do
queue[i]()
end
-- If the queue is still empty, we processed them all
-- Turn the check hooks back off.
if #immediateQueue == 0 then
uv.check_stop(checker)
uv.idle_stop(idler)
end
end
local function setImmediate(callback, ...)
-- If the queue was empty, the check hooks were disabled.
-- Turn them back on.
if #immediateQueue == 0 then
uv.check_start(checker, onCheck)
uv.idle_start(idler, onCheck)
end
immediateQueue[#immediateQueue + 1] = bind(callback, ...)
end
------------------------------------------------------------------------------
local lists = {}
local function init(list)
list._idleNext = list
list._idlePrev = list
end
local function peek(list)
if list._idlePrev == list then
return nil
end
return list._idlePrev
end
local function remove(item)
if item._idleNext then
item._idleNext._idlePrev = item._idlePrev
end
if item._idlePrev then
item._idlePrev._idleNext = item._idleNext
end
item._idleNext = nil
item._idlePrev = nil
end
local function append(list, item)
remove(item)
item._idleNext = list._idleNext
list._idleNext._idlePrev = item
item._idlePrev = list
list._idleNext = item
end
local function isEmpty(list)
return list._idleNext == list
end
local expiration
expiration = function(timer, msecs)
return function()
local now = Timer.now()
while peek(timer) do
local elem = peek(timer)
local diff = now - elem._idleStart;
if ((diff + 1) < msecs) == true then
timer:start(msecs - diff, 0, expiration(timer, msecs))
return
else
remove(elem)
if elem.emit then
elem:emit('timeout')
end
end
end
-- Remove the timer if it wasn't already
-- removed by unenroll
local list = lists[msecs]
if list and isEmpty(list) then
list:stop()
list:close()
lists[msecs] = nil
end
end
end
local function _insert(item, msecs)
item._idleStart = Timer.now()
item._idleTimeout = msecs
if msecs < 0 then return end
local list
if lists[msecs] then
list = lists[msecs]
else
list = Timer:new()
init(list)
list:start(msecs, 0, expiration(list, msecs))
lists[msecs] = list
end
append(list, item)
end
local function unenroll(item)
remove(item)
local list = lists[item._idleTimeout]
if list and isEmpty(list) then
-- empty list
list:stop()
list:close()
lists[item._idleTimeout] = nil
end
item._idleTimeout = -1
end
-- does not start the timer, just initializes the item
local function enroll(item, msecs)
if item._idleNext then
unenroll(item)
end
item._idleTimeout = msecs
init(item)
end
-- call this whenever the item is active (not idle)
local function active(item)
local msecs = item._idleTimeout
if msecs and msecs >= 0 then
local list = lists[msecs]
if not list or isEmpty(list) then
_insert(item, msecs)
else
item._idleStart = Timer.now()
append(lists[msecs], item)
end
end
end
return {
sleep = sleep,
setTimeout = setTimeout,
setInterval = setInterval,
clearInterval = clearInterval,
clearTimeout = clearInterval,
clearTimer = clearInterval, -- Luvit 1.x compatibility
setImmediate = setImmediate,
unenroll = unenroll,
enroll = enroll,
active = active,
}
|
object_tangible_loot_creature_loot_collections_space_reactor_mark_03_incom = object_tangible_loot_creature_loot_collections_space_shared_reactor_mark_03_incom:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_space_reactor_mark_03_incom, "object/tangible/loot/creature/loot/collections/space/reactor_mark_03_incom.iff")
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
-----------------------------------------
-- Guild Finder List Panel Gamepad Behavior --
-----------------------------------------
ZO_GuildFinder_ListPanel_GamepadBehavior = ZO_Object.MultiSubclass(ZO_GuildFinder_Panel_GamepadBehavior, ZO_GamepadInteractiveSortFilterList)
function ZO_GuildFinder_ListPanel_GamepadBehavior:New(...)
return ZO_GuildFinder_Panel_GamepadBehavior.New(self, ...)
end
function ZO_GuildFinder_ListPanel_GamepadBehavior:Initialize(control)
ZO_GamepadInteractiveSortFilterList.Initialize(self, control)
ZO_GuildFinder_Panel_GamepadBehavior.Initialize(self, control)
local scrollData = ZO_ScrollList_GetDataList(self.list)
ZO_GamepadInteractiveSortFilterList:SetMasterList(scrollData)
end
function ZO_GuildFinder_ListPanel_GamepadBehavior:InitializeKeybinds()
ZO_GuildFinder_Panel_GamepadBehavior.InitializeKeybinds(self)
ZO_GamepadInteractiveSortFilterList.InitializeKeybinds(self)
end
function ZO_GuildFinder_ListPanel_GamepadBehavior:CanBeActivated()
return ZO_ScrollList_HasVisibleData(self.list)
end
function ZO_GuildFinder_ListPanel_GamepadBehavior:Activate()
ZO_GamepadInteractiveSortFilterList.Activate(self)
ZO_GuildFinder_Panel_GamepadBehavior.Activate(self)
end
function ZO_GuildFinder_ListPanel_GamepadBehavior:Deactivate()
ZO_GamepadInteractiveSortFilterList.Deactivate(self)
ZO_GuildFinder_Panel_GamepadBehavior.Deactivate(self)
self:EndSelection()
end
function ZO_GuildFinder_ListPanel_GamepadBehavior:CommitScrollList()
ZO_GamepadInteractiveSortFilterList.CommitScrollList(self)
self:OnCommitComplete()
end
function ZO_GuildFinder_ListPanel_GamepadBehavior:GetBackKeybindCallback()
return function()
PlaySound(SOUNDS.GAMEPAD_MENU_BACK)
self:EndSelection()
end
end
function ZO_GuildFinder_ListPanel_GamepadBehavior:OnCommitComplete()
-- To be overridden
end |
local drawableSprite = require("structs.drawable_sprite")
local cassetteCassette = {}
local colors = {
{73 / 255, 170 / 255, 240 / 255},
{240 / 255, 73 / 255, 190 / 255},
{252 / 255, 220 / 255, 58 / 255},
{56 / 255, 224 / 255, 78 / 255},
}
local depth = -1000000
local colorNames = {
["Blue"] = 0,
["Rose"] = 1,
["Bright Sun"] = 2,
["Malachite"] = 3
}
cassetteCassette.name = "brokemiahelper/cassetteCassette"
cassetteCassette.nodeLineRenderType = "line"
cassetteCassette.nodeLimits = {2, 2}
cassetteCassette.fieldInformation = {
index = {
fieldType = "integer",
options = colorNames,
editable = false
}
}
cassetteCassette.placements = {}
for i, _ in ipairs(colors) do
cassetteCassette.placements[i] = {
name = string.format("cassette_cassette_%s", i - 1),
data = {
index = i - 1,
tempo = 1.0,
width = 16,
height = 16
}
}
end
function cassetteCassette.sprite(room, entity)
local index = entity.index or 0
local color = colors[index + 1] or colors[1]
local sprite = drawableSprite.fromTexture("collectables/cassette/idle00", entity)
sprite:setColor(color)
sprite.depth = depth
return sprite
end
return cassetteCassette |
#!/usr/bin/env lua
local fin = assert(io.open(arg[1], "rb"))
local data = {}
local sum = -25
local chSum = 0
repeat
local inStr = fin:read(4096)
for c in (inStr or ''):gmatch"." do
data[#data+1] = c:byte()
end
until not inStr
fin:close()
for i=1, #data do
if i > 0x134 and i <= 0x14d then
sum = sum - data[i]
end
if not (i == 0x14f or i == 0x150) then
chSum = chSum + data[i]
end
end
data[0x14e] = sum % 256
data[0x14f] = math.floor(chSum / 256) % 256
data[0x150] = chSum % 256
local outStr = ''
for i=1, #data do
outStr = outStr..string.char(data[i])
end
local fout = assert(io.open(arg[1], "wb"))
fout:write(outStr)
fout:close()
|
local plugin_name = vim.split((...):gsub("%.", "/"), "/", true)[1]
local helper = require("vusted.helper")
helper.root = helper.find_plugin_root(plugin_name)
function helper.before_each()
require("piemenu.view.background").Background._click = function() end
end
function helper.after_each()
helper.cleanup()
helper.cleanup_loaded_modules(plugin_name)
print(" ")
end
function helper.set_lines(lines)
vim.api.nvim_buf_set_lines(0, 0, -1, false, vim.split(lines, "\n"))
end
local asserts = require("vusted.assert").asserts
asserts.create("filetype"):register_eq(function()
return vim.bo.filetype
end)
asserts.create("window_count"):register_eq(function()
return vim.fn.tabpagewinnr(vim.fn.tabpagenr(), "$")
end)
asserts.create("exists_message"):register(function(self)
return function(_, args)
local expected = args[1]
self:set_positive(("`%s` not found message"):format(expected))
self:set_negative(("`%s` found message"):format(expected))
local messages = vim.split(vim.api.nvim_exec("messages", true), "\n")
for _, msg in ipairs(messages) do
if msg:match(expected) then
return true
end
end
return false
end
end)
asserts.create("exists_highlighted_window"):register(function(self)
return function(_, args)
local expected = args[1]
self:set_positive(("window highlighted `%s` is not found"):format(expected))
self:set_negative(("window highlighted `%s` is found"):format(expected))
for _, window_id in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
local hls = vim.tbl_filter(function(hl)
return vim.startswith(hl, "Normal:")
end, vim.split(vim.wo[window_id].winhighlight, ",", true))
for _, hl in ipairs(hls) do
local _, v = unpack(vim.split(hl, ":", true))
if v == expected then
return true
end
end
end
return false
end
end)
return helper
|
local ByteArray = require("ByteArray")
ProtoBasePack = class("ProtoBasePack")
function ProtoBasePack:ctor()
self._byteData = ByteArray.new()
self._byteData:setEndian(ByteArray.ENDIAN_BIG)
end
function ProtoBasePack:clear()
self._byteData:clear()
end
ProtoBaseUnpack = class("ProtoBaseUnpack")
function ProtoBaseUnpack:ctor()
self._byteData = ByteArray.new()
self._byteData:setEndian(ByteArray.ENDIAN_BIG)
end
--[[
配置数据解析
]]
ProtoDataUnpack = class("ProtoDataUnpack")
--表数据字典, 格式:{sheetName = rowList}
ProtoDataUnpack.sheetDict = nil
function ProtoDataUnpack:ctor()
self.sheetDict = {}
end
function ProtoDataUnpack:unpack(bytes)
self._byteData:writeBuf(bytes):setPos(1)
local offset = 1
local fileNameLen = self._byteData:readInt()
local fileName = self._byteData:readStringBytes(fileNameLen)
require(fileName)
local numSheet = self._byteData:readInt()
offset = offset + 4 + fileNameLen + 4
for i = 1, numSheet do
local sheetNameLen = self._byteData:readInt()
local sheetName = self._byteData:readStringBytes(sheetNameLen)
local classNameLen = self._byteData:readInt()
local className = self._byteData:readStringBytes(classNameLen)
local dataLen = self._byteData:readUInt()
offset = offset + 4 + sheetNameLen + 4 + classNameLen + 4
local sheetBytes = ByteArray.new(ByteArray.ENDIAN_BIG)
self._byteData:readBytes(sheetBytes, offset, dataLen-1)
local clazz = _G[className]:create()
clazz:unpack(sheetBytes, offset)
self.sheetDict[sheetName] = clazz.list
offset = offset + dataLen
end
end
function ProtoDataUnpack:parse(fileName)
local data = require(fileName)
self.sheetDict = data
end
function ProtoDataUnpack:create(fileName)
local dataUnpack = ProtoDataUnpack.new()
dataUnpack:parse(fileName)
return dataUnpack
end
function ProtoDataUnpack:getSheetByName(sheetName)
return self.sheetDict[sheetName]
end
|
-- Copyright (C) 2018-2021 by KittenOS NEO contributors
--
-- Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-- THIS SOFTWARE.
return {
["neo"] = {
desc = "KittenOS NEO Kernel & Base Libs",
v = 10,
deps = {
},
dirs = {
"apps",
"libs",
"data"
},
files = {
"init.lua",
"apps/sys-glacier.lua",
"libs/event.lua",
"libs/serial.lua",
"libs/fmttext.lua",
"libs/neoux.lua",
"libs/lineedit.lua",
"libs/braille.lua",
"libs/bmp.lua",
"libs/sys-filewrap.lua",
"libs/sys-gpualloc.lua"
},
},
["neo-init"] = {
desc = "KittenOS NEO / sys-init (startup)",
v = 11,
deps = {
"neo",
"neo-icecap",
"neo-everest"
},
dirs = {
"apps"
},
files = {
"apps/sys-init.lua"
},
},
["neo-launcher"] = {
desc = "KittenOS NEO / Default app-launcher",
v = 10,
deps = {
"neo"
},
dirs = {
"apps"
},
files = {
"apps/app-launcher.lua"
},
},
["neo-everest"] = {
desc = "KittenOS NEO / Everest (windowing)",
v = 10,
deps = {
"neo"
},
dirs = {
"apps",
},
files = {
"apps/sys-everest.lua"
},
},
["neo-icecap"] = {
desc = "KittenOS NEO / Icecap",
v = 10,
deps = {
"neo"
},
dirs = {
"libs",
"apps"
},
files = {
"libs/sys-filevfs.lua",
"libs/sys-filedialog.lua",
"apps/sys-icecap.lua",
"apps/app-fm.lua"
},
},
["neo-secpolicy"] = {
desc = "KittenOS NEO / Secpolicy",
v = 10,
deps = {
},
dirs = {
"libs"
},
files = {
"libs/sys-secpolicy.lua"
}
},
["neo-coreapps"] = {
desc = "KittenOS NEO Core Apps",
v = 10,
deps = {
"neo"
},
dirs = {
"apps"
},
files = {
"apps/app-textedit.lua",
"apps/app-batmon.lua",
"apps/app-control.lua",
"apps/app-taskmgr.lua"
}
},
["app-bmpview"] = {
desc = "KittenOS NEO .bmp viewer",
v = 10,
deps = {
"neo",
},
dirs = {
"apps"
},
files = {
"apps/app-bmpview.lua",
},
},
["neo-logo"] = {
desc = "KittenOS NEO Logo (data)",
v = 10,
deps = {
},
dirs = {
"docs"
},
files = {
"docs/logo.bmp"
},
},
["app-flash"] = {
desc = "KittenOS NEO EEPROM Flasher",
v = 10,
deps = {
"neo"
},
dirs = {
"apps"
},
files = {
"apps/app-flash.lua"
},
},
["app-wget"] = {
desc = "KittenOS Web Retriever",
v = 10,
deps = {
"neo"
},
dirs = {
"apps"
},
files = {
"apps/app-wget.lua"
},
},
["app-claw"] = {
desc = "KittenOS NEO Package Manager",
v = 10,
deps = {
"neo"
},
dirs = {
"apps"
},
files = {
"apps/app-claw.lua",
"apps/svc-app-claw-worker.lua"
},
},
["svc-t"] = {
desc = "KittenOS NEO Terminal System",
v = 10,
deps = {
"neo"
},
dirs = {
"apps"
},
files = {
"apps/svc-t.lua",
"apps/app-luashell.lua"
},
},
["neo-meta"] = {
desc = "KittenOS NEO: Use 'All' to install to other disks",
v = 10,
deps = {
"neo",
"neo-init",
"neo-launcher",
"neo-everest",
"neo-icecap",
"neo-secpolicy",
"neo-coreapps",
"neo-logo",
"app-bmpview",
"app-flash",
"app-claw",
"svc-t",
"app-wget"
},
dirs = {
},
files = {
}
}
}
|
--@sec: Simplex
--@ord: -1
--@doc: Simplex noise algorithm in Lua.
--
-- - [Original Java implementation by Stefan Gustavson][java]
-- - [Paper][paper]
--
-- [java]: https://weber.itn.liu.se/~stegu/simplexnoise/SimplexNoise.java
-- [paper]: https://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf
local Simplex = {}
local grad3 = {
{ 1, 1, 0}, {-1, 1, 0}, { 1,-1, 0}, {-1,-1, 0},
{ 1, 0, 1}, {-1, 0, 1}, { 1, 0,-1}, {-1, 0,-1},
{ 0, 1, 1}, { 0,-1, 1}, { 0, 1,-1}, { 0,-1,-1},
}
local grad4 = {
{ 0, 1, 1, 1}, { 0, 1, 1,-1}, { 0, 1,-1, 1}, { 0, 1,-1,-1},
{ 0,-1, 1, 1}, { 0,-1, 1,-1}, { 0,-1,-1, 1}, { 0,-1,-1,-1},
{ 1, 0, 1, 1}, { 1, 0, 1,-1}, { 1, 0,-1, 1}, { 1, 0,-1,-1},
{-1, 0, 1, 1}, {-1, 0, 1,-1}, {-1, 0,-1, 1}, {-1, 0,-1,-1},
{ 1, 1, 0, 1}, { 1, 1, 0,-1}, { 1,-1, 0, 1}, { 1,-1, 0,-1},
{-1, 1, 0, 1}, {-1, 1, 0,-1}, {-1,-1, 0, 1}, {-1,-1, 0,-1},
{ 1, 1, 1, 0}, { 1, 1,-1, 0}, { 1,-1, 1, 0}, { 1,-1,-1, 0},
{-1, 1, 1, 0}, {-1, 1,-1, 0}, {-1,-1, 1, 0}, {-1,-1,-1, 0},
}
-- Skewing and unskewing factors for 2 dimensions
local F2 = (math.sqrt(3) - 1)/2
local G2 = (3 - math.sqrt(3))/6
local F3 = 1 / 3
local G3 = 1 / 6
local F4 = (math.sqrt(5) - 1)/4
local G4 = (5 - math.sqrt(5))/20
--@sec: Generator
--@def: type Generator
--@doc: Generator holds the state for generating simplex noise. The state is
-- based off of an array containing a permutation of integers.
local Generator = {__index={}}
--@sec: Generator.Noise2D
--@def: Generator:Noise2D(x: number, y: number): number
--@doc: Returns a number in the interval [-1, 1] based on the given
-- two-dimensional coordinates and the generator's permutation state.
function Generator.__index:Noise2D(xin, yin)
local perm = self.perm
local permMod12 = self.permMod12
local n0, n1, n2 -- Noise contributions from the three corners
-- Skew the input space to determine which simplex cell we're in
local s = (xin + yin) * F2 -- Hairy factor for 2D
local i = xin + s; i = i - i%1
local j = yin + s; j = j - j%1
local t = (i + j) * G2
local X0 = i - t -- Unskew the cell origin back to (x,y) space
local Y0 = j - t
local x0 = xin - X0 -- The x,y distances from the cell origin
local y0 = yin - Y0
-- For the 2D case, the simplex shape is an equilateral triangle.
-- Determine which simplex we are in.
local i1, j1 -- Offsets for second (middle) corner of simplex in (i,j) coords
if x0 > y0 then
i1, j1 = 1, 0 -- lower triangle, XY order: (0,0)->(1,0)->(1,1)
else
i1, j1 = 0, 1 -- upper triangle, YX order: (0,0)->(0,1)->(1,1)
end
-- A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
-- a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
-- c = (3-sqrt(3))/6
local x1 = x0 - i1 + G2 -- Offsets for middle corner in (x,y) unskewed coords
local y1 = y0 - j1 + G2
local x2 = x0 - 1 + 2 * G2 -- Offsets for last corner in (x,y) unskewed coords
local y2 = y0 - 1 + 2 * G2
-- Work out the hashed gradient indices of the three simplex corners
local ii = i % 256
local jj = j % 256
-- Calculate the contribution from the three corners
local t0 = 0.5 - x0*x0 - y0*y0
if t0 < 0 then
n0 = 0
else
t0 = t0 * t0
local g = grad3[(1)+permMod12[(1)+ii+perm[(1)+jj]]]
n0 = t0 * t0 * (g[1]*x0 + g[2]*y0) -- (x,y) of grad3 used for 2D gradient
end
local t1 = 0.5 - x1*x1 - y1*y1
if t1 < 0 then
n1 = 0
else
t1 = t1 * t1
local g = grad3[(1)+permMod12[(1)+ii+i1+perm[(1)+jj+j1]]]
n1 = t1 * t1 * (g[1]*x1 + g[2]*y1)
end
local t2 = 0.5 - x2*x2 - y2*y2
if t2 < 0 then
n2 = 0
else
t2 = t2 * t2
local g = grad3[(1)+permMod12[(1)+ii+1+perm[(1)+jj+1]]]
n2 = t2 * t2 * (g[1]*x2 + g[2]*y2)
end
-- Add contributions from each corner to get the final noise value.
-- The result is scaled to return values in the interval [-1,1].
return 70 * (n0 + n1 + n2)
end
--@sec: Generator.Noise3D
--@def: Generator:Noise3D(x: number, y: number, z: number): number
--@doc: Returns a number in the interval [-1, 1] based on the given
-- three-dimensional coordinates and the generator's permutation state.
function Generator.__index:Noise3D(xin, yin, zin)
local perm = self.perm
local permMod12 = self.permMod12
local n0, n1, n2, n3; -- Noise contributions from the four corners
-- Skew the input space to determine which simplex cell we're in
local s = (xin + yin + zin) * F3 -- Very nice and simple skew factor for 3D
local i = xin + s; i = i - i%1
local j = yin + s; j = j - j%1
local k = zin + s; k = k - k%1
local t = (i + j + k) * G3
local X0 = i - t -- Unskew the cell origin back to (x,y,z) space
local Y0 = j - t
local Z0 = k - t
local x0 = xin - X0 -- The x,y,z distances from the cell origin
local y0 = yin - Y0
local z0 = zin - Z0
-- For the 3D case, the simplex shape is a slightly irregular tetrahedron.
-- Determine which simplex we are in.
local i1, j1, k1 -- Offsets for second corner of simplex in (i,j,k) coords
local i2, j2, k2 -- Offsets for third corner of simplex in (i,j,k) coords
if x0 >= y0 then
if y0 >= z0 then
i1,j1,k1,i2,j2,k2 = 1,0,0,1,1,0 -- X Y Z order
elseif x0 >= z0 then
i1,j1,k1,i2,j2,k2 = 1,0,0,1,0,1 -- X Z Y order
else
i1,j1,k1,i2,j2,k2 = 0,0,1,1,0,1 -- Z X Y order
end
else -- x0 < y0
if y0 < z0 then
i1,j1,k1,i2,j2,k2 = 0,0,1,0,1,1 -- Z Y X order
elseif x0 < z0 then
i1,j1,k1,i2,j2,k2 = 0,1,0,0,1,1 -- Y Z X order
else
i1,j1,k1,i2,j2,k2 = 0,1,0,1,1,0 -- Y X Z order
end
end
-- A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
-- a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and
-- a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where
-- c = 1/6.
local x1 = x0 - i1 + G3 -- Offsets for second corner in (x,y,z) coords
local y1 = y0 - j1 + G3
local z1 = z0 - k1 + G3
local x2 = x0 - i2 + 2*G3 -- Offsets for third corner in (x,y,z) coords
local y2 = y0 - j2 + 2*G3
local z2 = z0 - k2 + 2*G3
local x3 = x0 - 1 + 3*G3 -- Offsets for last corner in (x,y,z) coords
local y3 = y0 - 1 + 3*G3
local z3 = z0 - 1 + 3*G3
-- Work out the hashed gradient indices of the four simplex corners
local ii = i % 256
local jj = j % 256
local kk = k % 256
-- Calculate the contribution from the four corners
local t0 = 0.6 - x0*x0 - y0*y0 - z0*z0
if t0 < 0 then
n0 = 0
else
t0 = t0 * t0
local g = grad3[(1)+permMod12[(1)+ii+perm[(1)+jj+perm[(1)+kk]]]]
n0 = t0 * t0 * (g[1]*x0 + g[2]*y0 + g[3]*z0)
end
local t1 = 0.6 - x1*x1 - y1*y1 - z1*z1
if t1 < 0 then
n1 = 0
else
t1 = t1 * t1
local g = grad3[(1)+permMod12[(1)+ii+i1+perm[(1)+jj+j1+perm[(1)+kk+k1]]]]
n1 = t1 * t1 * (g[1]*x1 + g[2]*y1 + g[3]*z1)
end
local t2 = 0.6 - x2*x2 - y2*y2 - z2*z2
if t2 < 0 then
n2 = 0
else
t2 = t2 * t2
local g = grad3[(1)+permMod12[(1)+ii+i2+perm[(1)+jj+j2+perm[(1)+kk+k2]]]]
n2 = t2 * t2 * (g[1]*x2 + g[2]*y2 + g[3]*z2)
end
local t3 = 0.6 - x3*x3 - y3*y3 - z3*z3
if t3 < 0 then
n3 = 0
else
t3 = t3 * t3
local g = grad3[(1)+permMod12[(1)+ii+1+perm[(1)+jj+1+perm[(1)+kk+1]]]]
n3 = t3 * t3 * (g[1]*x3 + g[2]*y3 + g[3]*z3)
end
-- Add contributions from each corner to get the final noise value.
-- The result is scaled to stay just inside [-1,1]
return 32*(n0 + n1 + n2 + n3)
end
--@sec: Generator.Noise4D
--@def: Generator:Noise4D(x: number, y: number, z: number, w: number): number
--@doc: Returns a number in the interval [-1, 1] based on the given
-- four-dimensional coordinates and the generator's permutation state.
function Generator.__index:Noise4D(x, y, z, w)
local perm = self.perm
local n0, n1, n2, n3, n4 -- Noise contributions from the five corners
-- Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in
local s = (x + y + z + w) * F4 -- Factor for 4D skewing
local i = x + s; i = i - i%1
local j = y + s; j = j - j%1
local k = z + s; k = k - k%1
local l = w + s; l = l - l%1
local t = (i + j + k + l) * G4 -- Factor for 4D unskewing
local X0 = i - t -- Unskew the cell origin back to (x,y,z,w) space
local Y0 = j - t
local Z0 = k - t
local W0 = l - t
local x0 = x - X0 -- The x,y,z,w distances from the cell origin
local y0 = y - Y0
local z0 = z - Z0
local w0 = w - W0
-- For the 4D case, the simplex is a 4D shape I won't even try to describe.
-- To find out which of the 24 possible simplices we're in, we need to
-- determine the magnitude ordering of x0, y0, z0 and w0.
-- Six pair-wise comparisons are performed between each possible pair
-- of the four coordinates, and the results are used to rank the numbers.
local rankx = 0
local ranky = 0
local rankz = 0
local rankw = 0
if x0 > y0 then rankx=rankx+1 else ranky=ranky+1 end
if x0 > z0 then rankx=rankx+1 else rankz=rankz+1 end
if x0 > w0 then rankx=rankx+1 else rankw=rankw+1 end
if y0 > z0 then ranky=ranky+1 else rankz=rankz+1 end
if y0 > w0 then ranky=ranky+1 else rankw=rankw+1 end
if z0 > w0 then rankz=rankz+1 else rankw=rankw+1 end
local i1, j1, k1, l1 -- The integer offsets for the second simplex corner
local i2, j2, k2, l2 -- The integer offsets for the third simplex corner
local i3, j3, k3, l3 -- The integer offsets for the fourth simplex corner
-- simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.
-- Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w
-- impossible. Only the 24 indices which have non-zero entries make any sense.
-- We use a thresholding to set the coordinates in turn from the largest magnitude.
-- Rank 3 denotes the largest coordinate.
i1 = rankx >= 3 and 1 or 0
j1 = ranky >= 3 and 1 or 0
k1 = rankz >= 3 and 1 or 0
l1 = rankw >= 3 and 1 or 0
-- Rank 2 denotes the second largest coordinate.
i2 = rankx >= 2 and 1 or 0
j2 = ranky >= 2 and 1 or 0
k2 = rankz >= 2 and 1 or 0
l2 = rankw >= 2 and 1 or 0
-- Rank 1 denotes the second smallest coordinate.
i3 = rankx >= 1 and 1 or 0
j3 = ranky >= 1 and 1 or 0
k3 = rankz >= 1 and 1 or 0
l3 = rankw >= 1 and 1 or 0
-- The fifth corner has all coordinate offsets = 1, so no need to compute that.
local x1 = x0 - i1 + G4 -- Offsets for second corner in (x,y,z,w) coords
local y1 = y0 - j1 + G4
local z1 = z0 - k1 + G4
local w1 = w0 - l1 + G4
local x2 = x0 - i2 + 2*G4 -- Offsets for third corner in (x,y,z,w) coords
local y2 = y0 - j2 + 2*G4
local z2 = z0 - k2 + 2*G4
local w2 = w0 - l2 + 2*G4
local x3 = x0 - i3 + 3*G4 -- Offsets for fourth corner in (x,y,z,w) coords
local y3 = y0 - j3 + 3*G4
local z3 = z0 - k3 + 3*G4
local w3 = w0 - l3 + 3*G4
local x4 = x0 - 1 + 4*G4 -- Offsets for last corner in (x,y,z,w) coords
local y4 = y0 - 1 + 4*G4
local z4 = z0 - 1 + 4*G4
local w4 = w0 - 1 + 4*G4
-- Work out the hashed gradient indices of the five simplex corners
local ii = i % 256
local jj = j % 256
local kk = k % 256
local ll = l % 256
-- Calculate the contribution from the five corners
local t0 = 0.6 - x0*x0 - y0*y0 - z0*z0 - w0*w0
if t0 < 0 then
n0 = 0
else
t0 = t0 * t0
local g = grad4[(1)+perm[(1)+ii+perm[(1)+jj+perm[(1)+kk+perm[(1)+ll]]]]%32]
n0 = t0 * t0 * (g[1]*x0 + g[2]*y0 + g[3]*z0 + g[4]*w0)
end
local t1 = 0.6 - x1*x1 - y1*y1 - z1*z1 - w1*w1
if t1 < 0 then
n1 = 0
else
t1 = t1 * t1
local g = grad4[(1)+perm[(1)+ii+i1+perm[(1)+jj+j1+perm[(1)+kk+k1+perm[(1)+ll+l1]]]]%32]
n1 = t1 * t1 * (g[1]*x1 + g[2]*y1 + g[3]*z1 + g[4]*w1)
end
local t2 = 0.6 - x2*x2 - y2*y2 - z2*z2 - w2*w2
if t2 < 0 then
n2 = 0
else
t2 = t2 * t2
local g = grad4[(1)+perm[(1)+ii+i2+perm[(1)+jj+j2+perm[(1)+kk+k2+perm[(1)+ll+l2]]]]%32]
n2 = t2 * t2 * (g[1]*x2 + g[2]*y2 + g[3]*z2 + g[4]*w2)
end
local t3 = 0.6 - x3*x3 - y3*y3 - z3*z3 - w3*w3
if t3 < 0 then
n3 = 0
else
t3 = t3 * t3
local g = grad4[(1)+perm[(1)+ii+i3+perm[(1)+jj+j3+perm[(1)+kk+k3+perm[(1)+ll+l3]]]]%32]
n3 = t3 * t3 * (g[1]*x3 + g[2]*y3 + g[3]*z3 + g[4]*w3)
end
local t4 = 0.6 - x4*x4 - y4*y4 - z4*z4 - w4*w4
if t4 < 0 then
n4 = 0
else
t4 = t4 * t4
local g = grad4[(1)+perm[(1)+ii+1+perm[(1)+jj+1+perm[(1)+kk+1+perm[(1)+ll+1]]]]%32]
n4 = t4 * t4 * (g[1]*x4 + g[2]*y4 + g[3]*z4 + g[4]*w4)
end
-- Sum up and scale the result to cover the range [-1,1]
return 27 * (n0 + n1 + n2 + n3 + n4)
end
local function new(permutations)
local perm = {}
local permMod12 = {}
for i = 0, 511 do
perm[i+1] = permutations[(i % 256) + 1]
permMod12[i+1] = (perm[i+1] % 12)
end
return setmetatable({perm = perm, permMod12 = permMod12}, Generator)
end
local function newperm()
local perm = table.create(256)
for i = 0, 255 do
perm[i+1] = i
end
return perm
end
--@sec: Simplex.fromArray
--@def: Simplex.new(permutations: {number}): Generator
--@doc: Returns a generator with a state initialized by a table of permutations.
--
-- *permutations* is an array containing some permutation of each integer
-- between 0 and 255, inclusive.
function Simplex.fromArray(permutations)
-- Validate permutations table.
assert(type(permutations) == "table", "table expected")
local found = table.create(255)
for i = 1, 256 do
local v = permutations[i]
if v == nil then
error(string.format("permutations missing index %d", i), 2)
end
found[v] = true
end
for i = 0, 255 do
if found[i] ~= true then
error(string.format("permutations missing value %d", i), 2)
end
end
return new(permutations)
end
--@sec: Simplex.fromSeed
--@def: Simplex.new(seed: number): Generator
--@doc: Returns a generator with a state initialized by a seed for a random
-- number generator.
--
-- *seed* is a number, which is used as a random seed to shuffle a generated
-- array of permutations.
function Simplex.fromSeed(seed)
assert(type(seed) == "number", "number expected")
local source = Random.new(seed)
local perm = newperm()
for i = #perm, 2, -1 do
local j = source:NextInteger(1, i)
perm[i], perm[j] = perm[j], perm[i]
end
return new(perm)
end
--@sec: Simplex.fromRandom
--@def: Simplex.new(source: Random): Generator
--@doc: Returns a generator with a state initialized by a Random source.
--
-- *source* is a Random value, which is used to shuffle a generated array of
-- permutations.
function Simplex.fromRandom(source)
assert(typeof(source) == "Random", "Random expected")
local perm = newperm()
for i = #perm, 2, -1 do
local j = source:NextInteger(1, i)
perm[i], perm[j] = perm[j], perm[i]
end
return new(perm)
end
--@sec: Simplex.fromFunction
--@def: Simplex.new(func: (number)->(number)): Generator
--@doc: Returns a generator with a state initialized by a random function.
--
-- *func* is a function that receives an integer, and returns an integer between
-- 1 and the given value, inclusive. A generated array of permutations will be
-- shuffled using this function. `math.random` is an example of such a function.
function Simplex.fromFunction(func)
assert(type(func) == "function", "function expected")
local perm = newperm()
for i = #perm, 2, -1 do
local j = func(i)
if type(j) ~= "number" then
error(string.format("expected number returned for func(%d), got %s", i, type(j)), 2)
end
perm[i], perm[j] = perm[j], perm[i]
end
return new(perm)
end
--@sec: Simplex.new
--@def: Simplex.new(): Generator
--@doc: Returns a generator with a state initialized by a random shuffle.
function Simplex.new()
local source = Random.new()
local perm = newperm()
for i = #perm, 2, -1 do
local j = source:NextInteger(1, i)
perm[i], perm[j] = perm[j], perm[i]
end
return new(perm)
end
--@sec: Simplex.isGenerator
--@def: Simplex.isGenerator(v: any): boolean
--@doc: isGenerator returns whether *v* is an instance of
-- [Generator][Generator].
function Simplex.isGenerator(v)
return getmetatable(v) == Generator
end
return Simplex
|
--VERSION SUPPORT: 1.1-beta
PLUGIN.name = "Cook Food"
PLUGIN.author = "Black Tea"
PLUGIN.desc = "How about getting new foods in NutScript?"
hungrySeconds = 39600 -- 1100 = 300 seconds i guess (3 Hours to Starve)
nut.config.add("hungerTime", 5, "Amount of time between each hunger update." );
COOKLEVEL = {
[1] = {"cookNever", 2, color_white},
[2] = {"cookFailed", 1, Color(207, 0, 15)},
[3] = {"cookWell", 3, Color(235, 149, 50)},
[4] = {"cookDone", 4, Color(103, 128, 159)},
[5] = {"cookGood", 6, Color(63, 195, 128)},
}
COOKER_MICROWAVE = 1
COOKER_STOVE = 2
nut.util.include("cl_vgui.lua")
local playerMeta = FindMetaTable("Player")
local entityMeta = FindMetaTable("Entity")
function playerMeta:getHunger()
return (self:getNetVar("hunger")) or 0
end
function playerMeta:getHungerPercent()
return math.Clamp(((CurTime() - self:getHunger()) / hungrySeconds), 0, 1)
end
function getPercent(object)
return math.Clamp(((CurTime() - object:getHunger()) / hungrySeconds), 0, 1)
end
function playerMeta:addHunger(amount)
local curHunger = CurTime() - self:getHunger()
self:setNetVar("hunger",
CurTime() - math.Clamp(math.min(curHunger, hungrySeconds) - amount, 0, hungrySeconds)
)
end
function entityMeta:isStove()
local class = self:GetClass()
return (class == "nut_stove" or class == "nut_microwave")
end
-- Register HUD Bars.
if (CLIENT) then
local color = Color(39, 174, 96)
do
nut.bar.add(function()
return (1 - getPercent(LocalPlayer()))
end, color, nil, "hunger")
end
local hungerBar, percent, wave
function PLUGIN:Think()
hungerBar = hungerBar or nut.bar.get("hunger")
percent = (1 - getPercent(LocalPlayer()))
if (percent < .33) then -- if hunger is 33%
wave = math.abs(math.sin(RealTime()*5)*100)
hungerBar.lifeTime = CurTime() + 1
hungerBar.color = Color(color.r + wave, color.g - wave, color.b - wave)
else
hungerBar.color = color
end
end
local timers = {5, 15, 30}
netstream.Hook("stvOpen", function(entity, index)
local inventory = nut.item.inventories[index]
local inventory2 = LocalPlayer():getChar():getInv()
nut.gui.inv1 = inventory2:show()
nut.gui.inv1:ShowCloseButton(true)
local panel = inventory:show()
panel:ShowCloseButton(true)
panel:SetTitle("Stove")
panel:MoveLeftOf(nut.gui.inv1, 4)
panel.OnClose = function(this)
if (IsValid(nut.gui.inv1) and !IsValid(nut.gui.menu)) then
nut.gui.inv1:Remove()
end
netstream.Start("invExit")
end
function nut.gui.inv1:OnClose()
if (IsValid(panel) and !IsValid(nut.gui.menu)) then
panel:Remove()
end
netstream.Start("invExit")
end
local actPanel = vgui.Create("DPanel")
actPanel:SetDrawOnTop(true)
actPanel:SetSize(100, panel:GetTall())
actPanel.Think = function(this)
if (!panel or !panel:IsValid() or !panel:IsVisible()) then
this:Remove()
return
end
local x, y = panel:GetPos()
this:SetPos(x - this:GetWide() - 5, y)
end
for k, v in ipairs(timers) do
local btn = actPanel:Add("DButton")
btn:Dock(TOP)
btn:SetText(v .. " Seconds")
btn:DockMargin(5, 5, 5, 0)
function btn.DoClick()
netstream.Start("stvActive", entity, v)
end
end
nut.gui["inv"..index] = panel
end)
else
local PLUGIN = PLUGIN
function PLUGIN:LoadData()
if (true) then return end
local savedTable = self:getData() or {}
for k, v in ipairs(savedTable) do
local stove = ents.Create(v.class)
stove:SetPos(v.pos)
stove:SetAngles(v.ang)
stove:Spawn()
stove:Activate()
end
end
function PLUGIN:SaveData()
if (true) then return end
local savedTable = {}
for k, v in ipairs(ents.GetAll()) do
if (v:isStove()) then
table.insert(savedTable, {class = v:GetClass(), pos = v:GetPos(), ang = v:GetAngles()})
end
end
self:setData(savedTable)
end
function PLUGIN:CharacterPreSave(character)
local savedHunger = math.Clamp(CurTime() - character.player:getHunger(), 0, hungrySeconds)
character:setData("hunger", savedHunger)
end
function PLUGIN:PlayerLoadedChar(client, character, lastChar)
if (character:getData("hunger")) then
client:setNetVar("hunger", CurTime() - character:getData("hunger"))
else
client:setNetVar("hunger", CurTime())
end
end
function PLUGIN:PlayerDeath(client)
client.refillHunger = true
end
function PLUGIN:PlayerSpawn(client)
if (client.refillHunger) then
client:setNetVar("hunger", CurTime())
client.refillHunger = false
end
end
local thinkTime = CurTime()
function PLUGIN:PlayerPostThink(client)
if (thinkTime < CurTime()) then
local percent = (1 - getPercent(client))
if (percent <= 0) then
if (client:Alive() and client:Health() <= 0) then
client:Kill()
else
client:SetHealth(math.Clamp(client:Health() - 1, 0, client:GetMaxHealth()))
end
end
thinkTime = CurTime() + nut.config.get("hungerTime")
--thinkTime = CurTime() + 0.5
end
end
end |
--some code taken from moreblocks(the collision and selection boxes), license below:
--Copyright (c) 2011-2015 Calinou and contributors.
--Licensed under the zlib license.
scifi_nodes = {}
function scifi_nodes.register_slope(name, desc, texture, light)
minetest.register_node("scifi_nodes:slope_"..name, {
description = desc.." Slope",
sunlight_propagates = false,
drawtype = "mesh",
mesh = "moreblocks_slope.obj",
tiles = texture,
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.25, 0.5},
{-0.5, -0.25, -0.25, 0.5, 0, 0.5},
{-0.5, 0, 0, 0.5, 0.25, 0.5},
{-0.5, 0.25, 0.25, 0.5, 0.5, 0.5}
}
},
collision_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.25, 0.5},
{-0.5, -0.25, -0.25, 0.5, 0, 0.5},
{-0.5, 0, 0, 0.5, 0.25, 0.5},
{-0.5, 0.25, 0.25, 0.5, 0.5, 0.5}
}
},
paramtype = "light",
paramtype2 = "facedir",
light_source = light,
groups = {cracky=1},
on_place = minetest.rotate_node
})
end
scifi_nodes.register_slope("white2", "Plastic", {"scifi_nodes_white2.png",}, 0)
scifi_nodes.register_slope("black", "Black", {"scifi_nodes_black.png",}, 0)
scifi_nodes.register_slope("white", "White", {"scifi_nodes_white.png",}, 0)
scifi_nodes.register_slope("grey", "Grey", {"scifi_nodes_grey.png",}, 0)
scifi_nodes.register_slope("bluebars", "Blue bars", {"scifi_nodes_bluebars.png",}, 0)
scifi_nodes.register_slope("mesh2", "Metal floormesh", {"scifi_nodes_mesh2.png",}, 0)
scifi_nodes.register_slope("mesh", "Metal mesh", {"scifi_nodes_mesh.png",}, 0)
scifi_nodes.register_slope("vent", "Vent", {"scifi_nodes_vent2.png",}, 0)
scifi_nodes.register_slope("rlight", "Red light", {"scifi_nodes_redlight.png",}, 10)
scifi_nodes.register_slope("blight", "Blue light", {"scifi_nodes_light.png",}, 10)
scifi_nodes.register_slope("glight", "Green light", {"scifi_nodes_greenlight.png",}, 10)
scifi_nodes.register_slope("holes", "Holes", {"scifi_nodes_holes.png",}, 0)
scifi_nodes.register_slope("pipe", "Pipe", {"scifi_nodes_pipe.png",}, 0)
scifi_nodes.register_slope("stripes", "Stripes", {"scifi_nodes_stripes.png",}, 0)
scifi_nodes.register_slope("screen", "Screen", {"scifi_nodes_screen3.png",}, 5)
scifi_nodes.register_slope("lightstripe", "Lightstripe", {"scifi_nodes_lightstripe.png",}, 20)
scifi_nodes.register_slope("blight2", "Blue Light 2", {"scifi_nodes_capsule3.png",}, 20)
scifi_nodes.register_slope("wallpipe", "Alien Pipe", {"scifi_nodes_wallpipe.png",}, 0)
scifi_nodes.register_slope("alien", "Alien Wall", {"scifi_nodes_alnslp.png",}, 0)
scifi_nodes.register_slope("purple", "Purple", {"scifi_nodes_purple.png",}, 0)
scifi_nodes.register_slope("gblock", "Gblock", {"scifi_nodes_gblock2_front1.png",}, 0)
scifi_nodes.register_slope("greenmetal", "Green metal", {"scifi_nodes_greenmetal.png",}, 0)
scifi_nodes.register_slope("bluemetal", "Blue metal", {"scifi_nodes_bluemetal.png",}, 0)
scifi_nodes.register_slope("wall", "Metal wall", {"scifi_nodes_wall.png",}, 0)
scifi_nodes.register_slope("rough", "Rough metal", {"scifi_nodes_rough.png",}, 0)
scifi_nodes.register_slope("blklt2", "Black stripe light", {"scifi_nodes_black_light2.png",}, 10)
|
----
-- Recipe data.
--
-- Includes recipe data in data sidebar.
--
-- **Source Code:** [https://github.com/dstmodders/dst-mod-dev-tools](https://github.com/dstmodders/dst-mod-dev-tools)
--
-- @classmod data.RecipeData
-- @see data.Data
--
-- @author [Depressed DST Modders](https://github.com/dstmodders)
-- @copyright 2020
-- @license MIT
-- @release 0.8.0-alpha
----
local Data = require "devtools/data/data"
local SDK = require "devtools/sdk/sdk/sdk"
--- Lifecycle
-- @section lifecycle
--- Constructor.
-- @function _ctor
-- @tparam DevToolsScreen screen
-- @tparam DevTools devtools
-- @usage local recipedata = RecipeData(screen, devtools)
local RecipeData = Class(Data, function(self, screen, devtools)
Data._ctor(self, screen)
-- general
self.devtools = devtools
self.playerinventorytools = devtools.player.inventory
self.recipe = SDK.TemporaryData.Get("selected_recipe")
-- other
self:Update()
end)
--- General
-- @section general
--- Updates lines stack.
function RecipeData:Update()
Data.Update(self)
self:PushTitleLine("Recipe")
self:PushEmptyLine()
self:PushRecipeData()
if self.recipe.ingredients then
self:PushEmptyLine()
self:PushTitleLine("Ingredients")
self:PushEmptyLine()
self:PushIngredientsData()
end
end
--- Pushes ingredient line.
-- @tparam string type
-- @tparam number amount
function RecipeData:PushIngredientLine(type, amount)
local inventory = SDK.Player.Inventory.GetInventory()
local name = SDK.Constant.GetStringName(type)
if inventory then
local state = inventory:Has(type, amount)
table.insert(self.stack, string.format("x%d %s", amount, table.concat({
name,
state and "yes" or "no",
}, " | ")))
else
table.insert(self.stack, string.format("x%d %s", amount, name))
end
end
--- Pushes recipe data.
function RecipeData:PushRecipeData()
SDK.Utils.AssertRequiredField("RecipeData.devtools", self.devtools)
SDK.Utils.AssertRequiredField("RecipeData.recipe", self.recipe)
local recipe = self.recipe
self:PushLine("RPC ID", recipe.rpc_id)
if recipe.nounlock ~= nil and type(recipe.nounlock) == "boolean" then
self:PushLine("Unlockable", tostring(not recipe.nounlock and "yes" or "no"))
end
self:PushLine("Name", recipe.name)
if recipe.product then
if recipe.numtogive and recipe.numtogive > 1 then
self:PushLine("Product", { recipe.product, recipe.numtogive })
else
self:PushLine("Product", recipe.product)
end
end
self:PushLine("Placer", recipe.placer)
self:PushLine("Builder Tag", recipe.builder_tag)
if recipe.build_mode then
local mode = "NONE"
if recipe.build_mode == BUILDMODE.LAND then
mode = "LAND"
elseif recipe.build_mode == BUILDMODE.WATER then
mode = "WATER"
end
self:PushLine("Build Mode", mode)
end
self:PushLine("Build Distance", recipe.build_distance)
end
--- Pushes ingredients data.
function RecipeData:PushIngredientsData()
SDK.Utils.AssertRequiredField("RecipeData.playerinventorytools", self.playerinventorytools)
SDK.Utils.AssertRequiredField("RecipeData.devtools", self.devtools)
SDK.Utils.AssertRequiredField("RecipeData.recipe", self.recipe)
for _, ingredient in pairs(self.recipe.ingredients) do
self:PushIngredientLine(ingredient.type, ingredient.amount)
end
end
return RecipeData
|
#! /usr/bin/lua
require( "common" )
require( "lfs" )
require( "imlib2" )
Items = data( "items" )
local Dir = "weapons"
local SharpDir = "sharp"
local CacheDir = "cache"
local Names, NamesCount = loadNames( Dir .. "/names.txt" )
local Types =
{
"gs",
"ls",
"sns",
"ds",
"hm",
"hh",
"lc",
"gl",
"sa",
}
local Bases =
{
gs = { name = { hgg = "Great Swords" } },
ls = { name = { hgg = "Long Swords" } },
sns = { name = { hgg = "Swords" } },
ds = { name = { hgg = "Dual Swords" } },
hm = { name = { hgg = "Hammers" } },
hh = { name = { hgg = "Hunting Horns" } },
lc = { name = { hgg = "Lances" } },
gl = { name = { hgg = "Gunlances" } },
sa = { name = { hgg = "Switch Axes" } },
}
local Elements =
{
"fire",
"water",
"thunder",
"ice",
"dragon",
"poison",
"paralyze",
"sleep",
}
local Shells =
{
N = "normal",
S = "spread",
L = "long",
}
local Notes =
{
B = "blue",
C = "cyan",
G = "green",
O = "orange",
P = "purple",
R = "red",
W = "white",
Y = "yellow",
}
local SharpX = 101
local SharpY = 60
local SharpEquipX = 342
local SharpEquipY = 173
local SharpColors =
{
-- c00c38
imlib2.color.new( 192, 12, 56 ),
-- e85018
imlib2.color.new( 232, 80, 24 ),
-- f0c830
imlib2.color.new( 240, 200, 48 ),
-- 58d000
imlib2.color.new( 88, 208, 0 ),
imlib2.color.new( 48, 104, 232 ),
imlib2.color.new( 240, 240, 240 ),
}
-- so we can tell if it's actually the end or just
-- a color i've not added yet
local SharpEnds =
{
imlib2.color.new( 0, 0, 0 ),
imlib2.color.new( 48, 44, 32 ), -- for a full sharpness bar
imlib2.color.new( 40, 40, 32 ), -- sharpness +1 end markers?
imlib2.color.new( 40, 36, 32 ),
imlib2.color.new( 48, 48, 40 ),
}
local SharpPMarker = imlib2.color.new( 96, 228, 248 )
function sharpIdx( color )
for i, sharpColor in ipairs( SharpColors ) do
if colorEqual( sharpColor, color ) then
return i
end
end
-- stupid constantly changing bar between
-- the sharpness bar and sharp +1 marker
if color.red < 50 and
color.green < 50 and
color.blue < 50 then
return -1
end
return 0
end
function isElement( element )
for _, elem in ipairs( Elements ) do
if elem == element then
return true
end
end
return false
end
local Spheres =
{
Reg = "Enhance Sphere",
Pls = "Enhance Sphere+",
Hrd = "Hrd Enhance Sph",
Hvy = "Hvy Enhance Sph",
}
function sphereID( sphere )
return itemID( assert( Spheres[ sphere ] ) )
end
local MaxSlots = 3
-- perhaps a gigantic FSM was not
-- the best way of doing this
local Actions =
{
init = function( line, weapon )
assert( Names[ line ], "bad name: " .. line )
assert( Names[ line ] ~= "used", "duplicate weapon: " .. line )
Names[ line ] = "used"
weapon.name = { hgg = line }
return "attack"
end,
attack = function( line, weapon )
weapon.attack = tonumber( line )
return "special"
end,
special = function( line, weapon )
if line:find( "%u%d" ) then
local u = line:sub( 1, 1 )
local d = tonumber( line:sub( 2, 2 ) )
if u == "R" then
weapon.rarity = d
return "affinity"
end
weapon.shellingType = Shells[ u ]
weapon.shellingLevel = d
return "special"
end
if line:find( "%a+ %d+ %d+z" ) then
local _, _, sphere, num, price = line:find( "(%a+) (%d+) (%d+)z" )
assert( Spheres[ sphere ], "bad sphere in " .. weapon.name.hgg .. ": " .. line )
weapon.upgrade =
{
materials =
{
{
id = sphereID( sphere ),
count = tonumber( num )
}
},
price = tonumber( price )
}
return "special"
end
if line:find( "%u%u%u" ) then
weapon.notes =
{
Notes[ line:sub( 1, 1 ) ],
Notes[ line:sub( 2, 2 ) ],
Notes[ line:sub( 3, 3 ) ],
}
return "special"
end
if line:find( "Def %d+" ) then
weapon.defense = tonumber( line:sub( 5 ) )
return "special"
end
if line:find( "%a+ %d+" ) then
local _, _, element, elemAttack = line:find( "(%a+) (%d+)" )
element = element:lower()
assert( isElement( element ), "bad element in " .. weapon.name.hgg .. ": " .. line )
weapon.element = element
weapon.elemAttack = elemAttack
return "special"
end
weapon.phial = line:lower()
return "special"
end,
affinity = function( line, weapon )
local success, _, affinity = line:find( "^(-?%d+)%%$" )
assert( success, "bad affinity in " .. weapon.name.hgg .. ": " .. line )
weapon.affinity = tonumber( affinity )
return "slots"
end,
slots = function( line, weapon )
local slots = 0
for i = 1, MaxSlots do
if line:sub( i, i ) == "O" then
slots = slots + 1
else
break
end
end
weapon.slots = slots
return "improve"
end,
improve = function( line, weapon )
if line:sub( -1 ) == "z" then
weapon.price = tonumber( line:sub( 1, -2 ) )
if not weapon.improve then
weapon.price = weapon.price / 1.5
end
return "create"
end
local id, count = parseItem( line )
if not id then
weapon.description = line
return "scraps"
end
assert( weapon.improve, "bad improve in " .. weapon.name.hgg .. ": " .. line )
table.insert( weapon.improve.materials, { id = id, count = count } )
return "improve"
end,
create = function( line, weapon )
local id, count = parseItem( line )
if not id then
weapon.description = line
return "scraps"
end
if not weapon.create then
weapon.create = { }
end
table.insert( weapon.create, { id = id, count = count } )
return "create"
end,
scraps = function( line, weapon )
local id, count = parseItem( line )
assert( id, "bad scrap in " .. weapon.name.hgg .. ": " .. line )
if not weapon.scraps then
weapon.scraps = { }
end
table.insert( weapon.scraps, { id = id, count = count } )
return "scraps"
end,
}
function string.detab( self )
return self:gsub( "^\t+", "" )
end
function doLine( line, weapon, state )
if not Actions[ state ] then
print( state )
end
return Actions[ state ]( line, weapon )
end
function sharpPWidth( img, x, y )
-- when this is called the x coord is the line between
-- the end of the bar and the sharp +1 marker and the y
-- coord is the top of the sharpness bar
-- so let's correct it to be inline with the end of the
-- sharpness bar and along the sharp +1 marker
x = x - 1
y = y - 2
local width = 0
while colorEqual( img:get_pixel( x, y ), SharpPMarker ) do
width = width + 1
-- move backwards since we started at the end
x = x - 1
end
return width
end
function readSharpness( weapon )
local cachePath = ( "%s/%s/%s/%s.lua" ):format( Dir, SharpDir, CacheDir, weapon.name.hgg )
local imagePath = ( "%s/%s/%s.png" ):format( Dir, SharpDir, weapon.name.hgg )
local cached = io.open( cachePath, "r" )
-- only read cached data if it's more recent than the screenshot
if cached and lfs.attributes( cachePath ).modification > lfs.attributes( imagePath ).modification then
local cachedSharpness = loadstring( cached:read( "*all" ) )()
weapon.sharpness = cachedSharpness.sharp
weapon.sharpnessp = cachedSharpness.sharpp
cached:close()
return
end
local img = imlib2.image.load( imagePath )
-- no screenshot for this weapon
if not img then
return
end
weapon.sharpness = { }
local x, y
-- handle change equip dialog screenshots by checking
-- for the navy triangle pattern near the right edge
-- of the screen
if img:get_pixel( 472, 24 ).blue == 80 then
x = SharpEquipX
y = SharpEquipY
else
x = SharpX
y = SharpY
end
local lastColor = 1
local currSharp = 1
while true do
local color = img:get_pixel( x, y )
local idx = sharpIdx( color )
if idx ~= lastColor then
table.insert( weapon.sharpness, currSharp )
lastColor = idx
currSharp = 1
else
currSharp = currSharp + 1
end
-- unrecognised color
assert( idx ~= 0, "unrecognised sharpness color in " .. weapon.name.hgg .. ": " .. color.red .. ", " .. color.green .. ", " .. color.blue )
-- end of sharpness bar
if idx == -1 then
if colorEqual( img:get_pixel( x + 1, y ), SharpPMarker ) then
-- the table in weapon.sharpness actually contains
-- sharpness +1 info at this point, so let's copy
-- the table and correct it using the fact that
-- sharpness +1 will always add the same number of
-- pixels
-- which is defined as SharpPlusOneAdds
weapon.sharpnessp = table.copy( weapon.sharpness )
local toRemove = sharpPWidth( img, x, y )
local endSharp = table.getn( weapon.sharpness )
while toRemove > 0 do
if weapon.sharpness[ endSharp ] <= toRemove then
-- this color doesn't exist without sharpness +1
toRemove = toRemove - weapon.sharpness[ endSharp ]
weapon.sharpness[ endSharp ] = nil
endSharp = endSharp - 1
else
weapon.sharpness[ endSharp ] = weapon.sharpness[ endSharp ] - toRemove
toRemove = 0
end
end
end
break
end
-- move along 1 pixel
x = x + 1
end
img:free()
-- cache the result for future gens
local cacheOutput = assert( io.open( cachePath, "w" ) )
cacheOutput:write( "return { sharp = { " .. table.concat( weapon.sharpness, ", " ) .. " }" )
if weapon.sharpnessp then
cacheOutput:write( ", sharpp = { " .. table.concat( weapon.sharpnessp, ", " ) .. " }" )
end
cacheOutput:write( " }" )
cacheOutput:close()
end
function generatePath( weapon, weapons, path )
if not path then
path = { }
end
if weapon.improve then
table.insert( path, weapon.improve.from )
return generatePath( weapons[ weapon.improve.from ], weapons, path )
end
return table.getn( path ) ~= 0 and path or nil
end
-- check screenshots are all correctly named
-- must do this first as Names gets destroyed
-- during weapon parsing
for file in lfs.dir( Dir .. "/" .. SharpDir ) do
if file ~= "." and file ~= ".." and file ~= CacheDir then
assert( Names[ file:match( "^(.+)%.png$" ) ], "bad screenshot: " .. file )
end
end
-- weapon parsing
local Weapons = { }
local WeaponsCount = 0
for _, short in pairs( Types ) do
io.input( Dir .. "/" .. short .. ".txt" )
local class = Bases[ short ]
class.short = short
class.weapons = { }
local state = "init"
local weapon = { }
local lastDepth = { }
local currentIdx = 1
for line in io.lines() do
local trimmed = line:detab()
if trimmed == "" then
readSharpness( weapon )
weapon.path = generatePath( weapon, class.weapons )
-- if the weapon is an upgrade then check
-- i didn't forget the materials
assert( not weapon.improve or table.getn( weapon.improve.materials ) ~= 0, "no improve materials for " .. weapon.name.hgg )
table.insert( class.weapons, weapon )
WeaponsCount = WeaponsCount + 1
state = "init"
weapon = { }
currentIdx = currentIdx + 1
else
local depth = 1
if state == "init" then
while line:sub( depth, depth ) == '\t' do
depth = depth + 1
end
lastDepth[ depth ] = currentIdx
if depth ~= 1 then
local from = lastDepth[ depth - 1 ]
-- assuming there are no path splits in p3
--weapon.improve = { from = { from }, materials = { } }
weapon.improve = { from = from, materials = { } }
if not class.weapons[ from ].upgrades then
class.weapons[ from ].upgrades = { }
end
table.insert( class.weapons[ from ].upgrades, currentIdx )
end
end
state = doLine( trimmed, weapon, state )
end
end
readSharpness( weapon )
weapon.path = generatePath( weapon, class.weapons )
table.insert( class.weapons, weapon )
WeaponsCount = WeaponsCount + 1
table.insert( Weapons, class )
end
print( ( "genWeapons: ok, %.1f%% complete! (%d/%d)" ):format(
100 * ( WeaponsCount / NamesCount ),
WeaponsCount,
NamesCount
) )
io.output( "../weapons.json" )
io.write( json.encode( Weapons ) )
|
-- hamster_ball, video game
-- Copyright (C) 2014-2015 Pavel Dolgov
--
-- See the LICENSE file for terms of use.
local x, y, enemies, shots, speed, dt1, dt2, bg, ball
local is_winner = false
local is_loser = false
local group_number = 0
local tableLength = function(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
local fullScreen = function()
if love.window and love.window.setFullscreen then
love.windo.setFullscreen(true, "desctop")
elseif love.graphics.setMode then
love.graphics.setMode(800, 640, true, false, 0)
end
end
local checkFail = function()
if tableLength(enemies) ~= 0 then
if enemies[1].y > 700 then
is_loser = true
end
end
end
local keyIsDown = function(dt)
if love.keyboard.isDown("f") then
fullScreen()
end
if love.keyboard.isDown("escape") then
love.event.quit()
end
if love.keyboard.isDown("right") then
x = x + dt * speed
end
if love.keyboard.isDown("left") then
x = x - dt * speed
end
if love.keyboard.isDown("down") then
y = y + speed * dt
end
if love.keyboard.isDown("up") then
y = y - dt * speed
end
if love.keyboard.isDown(" ") then
if (dt1 - dt2) >= 0.2 then
local shot = {}
shot.x = x + 50
shot.y = y
shot.pict = love.graphics.newImage("fireball.png")
table.insert(shots, shot)
dt2 = dt1
end
end
end
local addEnemies = function(number, width, height, speed_arg)
for i = 0, number - 1 do
local enemy = {}
enemy.width = width
enemy.height = height
enemy.speed = speed_arg
enemy.x = i * (enemy.width + 60) + 100
enemy.y = enemy.height + 100
table.insert(enemies, enemy)
end
end
local addEnemiesGroup = function(diff)
addEnemies(8 - group_number, 30, 15, 10 + group_number * diff)
end
local checkCollision = function(x1, y1, w1, h1, x2, y2, w2, h2)
return x1 < x2 + w2 and
x2 < x1 + w1 and
y1 < y2 + h2 and
y2 < y1 + h1
end
function love.load()
bg = love.graphics.newImage("bg.png")
enemies = {}
addEnemies(8, 30, 15, 20)
ball = love.graphics.newImage("hamster_ball.png")
x = 50
y = 50
speed = 300
shots = {}
dt1 = 0
dt2 = dt1
end
function love.update(dt)
dt1 = dt1 + dt
checkFail()
if tableLength(enemies) == 0 then
addEnemiesGroup(40)
group_number = group_number + 1
if group_number == 9 then
is_winner = true
end
end
for _, d in ipairs(enemies) do
d.y = d.y + d.speed * dt
end
for _, v in ipairs(shots) do
v.y = v.y - dt * 500
for i, d in ipairs(enemies) do
if checkCollision(v.x, v.y, 20, 20, d.x, d.y, d.width, d.height) then
table.remove(enemies, i)
end
end
end
keyIsDown(dt)
end
function love.draw()
love.graphics.setColor(255, 255, 255, 255)
love.graphics.draw(bg)
love.graphics.setColor(255, 255, 255, 255)
love.graphics.draw(ball, x, y)
if is_loser then
love.graphics.print("You are loser...", 75, 300, 0, 7, 7)
elseif is_winner then
love.graphics.print("You are winner!", 100, 300, 0, 7, 7)
else
love.graphics.print("Level " ..group_number,
300, 100, 0, 5, 5)
end
for _, v in ipairs (shots) do
love.graphics.draw(v.pict, v.x, v.y)
end
love.graphics.setColor(0, 255, 255, 255)
for _, v in ipairs (enemies) do
love.graphics.rectangle("fill", v.x, v.y, v.width, v.height)
end
end
|
local Queue = {}
function Queue:new()
local o = {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
o.first = 0;
o.last = -1;
return o
end
function Queue:push(value)
local last = self.last + 1
self.last = last
self[last] = value
end
function Queue:pop()
local first = self.first
if first > self.last then
--error("list is empty")
return nil;
end
local value = self[first]
self[first] = nil -- to allow garbage collection
self.first = first + 1
return value
end
-- returns all items in queue
function Queue:popAll()
local first = self.first
if first > self.last then
--error("list is empty")
return nil;
end
local items = {};
for i=first, self.last do
local value = self[i]
self[i] = nil -- to allow garbage collection
--self.first = first + 1
items[#items+1] = value;
end
self.first = self.last+1;
return items;
end
function Queue:isEmpty()
return self.first > self.last;
end
function Queue:getSize()
return self.last- self.first +1;
end
-- see: http://www.lua.org/pil/11.4.html
--Now, we can insert or remove an element at both ends in constant time:
function Queue:pushFirst(value)
local first = self.first - 1
self.first = first
self[first] = value
end
function Queue:popLast()
local last = self.last
if self.first > last then error("list is empty") end
local value = self[last]
self[last] = nil -- to allow garbage collection
self.last = last - 1
return value
end
--[[
-- the same as Queue:push()
function Queue:pushright(value)
local last = self.last + 1
self.last = last
self[last] = value
end
-- the same as Queue:pop()
function Queue:popleft()
local first = self.first
if first > self.last then error("list is empty") end
local value = self[first]
self[first] = nil -- to allow garbage collection
self.first = first + 1
return value
end
]]
return Queue;
|
me = game.Players.yfc
if script.Parent.className ~= "HopperBin" then
h = Instance.new("HopperBin")
h.Parent = me.Backpack
h.Name = "Thing"
script.Parent = h
end
sp = script.Parent
hold = false
function sel(mouse)
mouse.Button1Down:connect(function()
hold = true
local char = me.Character
local namb = 0
while hold == true do
wait()
local p = Instance.new("Part")
p.Parent = char
p.Anchored = true
p.Size = Vector3.new(10,2,2)
p.CFrame = char.Torso.CFrame * CFrame.fromEulerAnglesXYZ(0,namb,0.5) * CFrame.new(100,10,0)
namb = math.random(-100,100)
coroutine.resume(coroutine.create(function()
for i=1, 40 do
wait()
p.CFrame = p.CFrame * CFrame.new(-2,0,0)
end
p:remove()
end))
end
end)
mouse.Button1Up:connect(function()
hold = false
end)
end
sp.Selected:connect(sel)
|
--[[
© Asterion Project 2021.
This script was created from the developers of the AsterionTeam.
You can get more information from one of the links below:
Site - https://asterionproject.ru
Discord - https://discord.gg/Cz3EQJ7WrF
developer(s):
Selenter - https://steamcommunity.com/id/selenter
——— Chop your own wood and it will warm you twice.
]]--
local PLUGIN = PLUGIN
PLUGIN.name = "LagDetection"
PLUGIN.author = "AsterionTeam"
PLUGIN.description = ""
ix.util.Include("cl_plugin.lua")
ix.util.Include("sv_plugin.lua") |
local assets =
{
Asset("ANIM", "anim/ruins_rubble.zip"),
}
local prefabs =
{
"rocks",
"thulecite",
"cutstone",
"trinket_6",
"gears",
"nightmarefuel",
"greengem",
"orangegem",
"yellowgem",
}
local function workcallback(inst, worker, workleft)
local pt = Point(inst.Transform:GetWorldPosition())
if workleft <= 0 then
inst.SoundEmitter:PlaySound("dontstarve/wilson/rock_break")
inst.components.lootdropper:DropLoot()
SpawnPrefab("collapse_small").Transform:SetPosition(inst.Transform:GetWorldPosition())
inst:Remove()
else
if workleft < TUNING.ROCKS_MINE*(1/3) then
inst.AnimState:PlayAnimation("low")
elseif workleft < TUNING.ROCKS_MINE*(2/3) then
inst.AnimState:PlayAnimation("med")
else
inst.AnimState:PlayAnimation("full")
end
end
end
local function common_fn()
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
local anim = inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
inst.AnimState:SetBank("rubble")
inst.AnimState:SetBuild("ruins_rubble")
MakeObstaclePhysics(inst, 1.)
--local minimap = inst.entity:AddMiniMapEntity()
--minimap:SetIcon( "rock.png" )
inst:AddComponent("lootdropper")
inst.components.lootdropper:SetLoot({"rocks"})
inst.components.lootdropper.numrandomloot = 1
inst.components.lootdropper:AddRandomLoot("rocks" , 0.99)
inst.components.lootdropper:AddRandomLoot("cutstone" , 0.10)
inst.components.lootdropper:AddRandomLoot("trinket_6" , 0.10) -- frayed wires
inst.components.lootdropper:AddRandomLoot("gears" , 0.01)
inst.components.lootdropper:AddRandomLoot("greengem" , 0.01)
inst.components.lootdropper:AddRandomLoot("yellowgem" , 0.01)
inst.components.lootdropper:AddRandomLoot("orangegem" , 0.01)
inst.components.lootdropper:AddRandomLoot("nightmarefuel" , 0.01)
if GetWorld() and GetWorld():IsCave() and GetWorld().topology.level_number == 2 then -- ruins
inst.components.lootdropper:AddRandomLoot("thulecite" , 0.01)
end
inst:AddComponent("workable")
inst.components.workable:SetWorkAction(ACTIONS.MINE)
inst.components.workable:SetOnWorkCallback(workcallback)
inst:AddComponent("inspectable")
inst.components.inspectable.nameoverride = "rubble"
MakeSnowCovered(inst, .01)
return inst
end
local function rubble_fn(Sim)
local inst = common_fn()
inst.AnimState:PlayAnimation("full")
inst.components.workable:SetWorkLeft(TUNING.ROCKS_MINE)
return inst
end
local function rubble_med_fn(Sim)
local inst = common_fn()
inst.AnimState:PlayAnimation("med")
inst.components.workable:SetWorkLeft(TUNING.ROCKS_MINE)
inst.components.workable:WorkedBy(inst, TUNING.ROCKS_MINE * 0.34)
return inst
end
local function rubble_low_fn(Sim)
local inst = common_fn()
inst.AnimState:PlayAnimation("low")
inst.components.workable:SetWorkLeft(TUNING.ROCKS_MINE)
inst.components.workable:WorkedBy(inst, TUNING.ROCKS_MINE * 0.67)
return inst
end
return Prefab("cave/objects/rocks/rubble", rubble_fn, assets, prefabs),
Prefab("forest/objects/rocks/rubble_med", rubble_med_fn, assets, prefabs),
Prefab("forest/objects/rocks/rubble_low", rubble_low_fn, assets, prefabs)
|
local Validator = script.Parent
local Style = Validator.Parent
local App = Style.Parent
local UIBlox = App.Parent
local Packages = UIBlox.Parent
local t = require(Packages.t)
return t.strictInterface({
RelativeSize = t.numberMinExclusive(0),
RelativeMinSize = t.numberMinExclusive(0),
Font = t.EnumItem,
}) |
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf/protobuf"
local STAGETROPHYDATA_PB = require("StageTrophyData_pb")
module('StageTrophy_pb')
STAGETROPHY = protobuf.Descriptor();
local STAGETROPHY_TROPHYDATA_FIELD = protobuf.FieldDescriptor();
local STAGETROPHY_TOTAL_SCORE_FIELD = protobuf.FieldDescriptor();
local STAGETROPHY_HONOUR_RANK_FIELD = protobuf.FieldDescriptor();
STAGETROPHY_TROPHYDATA_FIELD.name = "trophydata"
STAGETROPHY_TROPHYDATA_FIELD.full_name = ".KKSG.StageTrophy.trophydata"
STAGETROPHY_TROPHYDATA_FIELD.number = 1
STAGETROPHY_TROPHYDATA_FIELD.index = 0
STAGETROPHY_TROPHYDATA_FIELD.label = 3
STAGETROPHY_TROPHYDATA_FIELD.has_default_value = false
STAGETROPHY_TROPHYDATA_FIELD.default_value = {}
STAGETROPHY_TROPHYDATA_FIELD.message_type = STAGETROPHYDATA_PB.STAGETROPHYDATA
STAGETROPHY_TROPHYDATA_FIELD.type = 11
STAGETROPHY_TROPHYDATA_FIELD.cpp_type = 10
STAGETROPHY_TOTAL_SCORE_FIELD.name = "total_score"
STAGETROPHY_TOTAL_SCORE_FIELD.full_name = ".KKSG.StageTrophy.total_score"
STAGETROPHY_TOTAL_SCORE_FIELD.number = 2
STAGETROPHY_TOTAL_SCORE_FIELD.index = 1
STAGETROPHY_TOTAL_SCORE_FIELD.label = 1
STAGETROPHY_TOTAL_SCORE_FIELD.has_default_value = false
STAGETROPHY_TOTAL_SCORE_FIELD.default_value = 0
STAGETROPHY_TOTAL_SCORE_FIELD.type = 4
STAGETROPHY_TOTAL_SCORE_FIELD.cpp_type = 4
STAGETROPHY_HONOUR_RANK_FIELD.name = "honour_rank"
STAGETROPHY_HONOUR_RANK_FIELD.full_name = ".KKSG.StageTrophy.honour_rank"
STAGETROPHY_HONOUR_RANK_FIELD.number = 3
STAGETROPHY_HONOUR_RANK_FIELD.index = 2
STAGETROPHY_HONOUR_RANK_FIELD.label = 1
STAGETROPHY_HONOUR_RANK_FIELD.has_default_value = false
STAGETROPHY_HONOUR_RANK_FIELD.default_value = 0
STAGETROPHY_HONOUR_RANK_FIELD.type = 13
STAGETROPHY_HONOUR_RANK_FIELD.cpp_type = 3
STAGETROPHY.name = "StageTrophy"
STAGETROPHY.full_name = ".KKSG.StageTrophy"
STAGETROPHY.nested_types = {}
STAGETROPHY.enum_types = {}
STAGETROPHY.fields = {STAGETROPHY_TROPHYDATA_FIELD, STAGETROPHY_TOTAL_SCORE_FIELD, STAGETROPHY_HONOUR_RANK_FIELD}
STAGETROPHY.is_extendable = false
STAGETROPHY.extensions = {}
StageTrophy = protobuf.Message(STAGETROPHY)
|
local L = LibStub("AceLocale-3.0"):NewLocale("GatherLite", "zhCN")
if not L then
return
end
L["tracking"] = "追踪类型"
L["mining"] = "矿石"
L["herbalism"] = "草药"
L["fish"] = "鱼群"
L["containers"] = "箱子"
L["worldmap.show"] = "显示 GatherLite"
L["worldmap.hide"] = "隐藏 GatherLite"
L["settings.node"] = "采集点设置"
L["settings.node.predefined"] = "使用预设数据库"
L["settings.node.minimap"] = "在小地图显示采集点"
L["settings.node.worldmap"] = "在世界地图显示采集点"
L["settings.general"] = "常规设置"
L["settings.general.minimap"] = "显示小地图按钮"
L["settings.map"] = "世界地图设置"
L["settings.map.loot"] = "显示采集点提示框中的拾取记录"
L["settings.map.size"] = "图标大小"
L["settings.map.opacity"] = "图标透明度"
L["settings.minimap"] = "小地图设置"
L["settings.minimap.edge"] = "在小地图边缘保持显示采集点"
L["settings.minimap.loot"] = "显示采集点提示框中的拾取记录"
L["settings.minimap.size"] = "图标大小"
L["settings.minimap.opacity"] = "图标透明度"
L["settings.minimap.threshold"] = "显示自身 %d 码以内的采集点图标"
L["settings.minimap.range"] = "隐藏自身 %d 码以内的采集点图标"
L["settings.minimap.left_click"] = "点击左键"
L["settings.minimap.left_click_text"] = "打开追踪类型菜单"
L["settings.minimap.right_click"] = "点击右键"
L["settings.minimap.right_click_text"] = "打开设置面板"
L["settings.tracking"] = "追踪类型设置"
L["settings.tracking.toggle_all_ores"] = "切换显示全部矿石"
L["settings.tracking.toggle_all_herbs"] = "切换显示全部草药"
L["settings.tracking.toggle_all_containers"] = "切换显示全部箱子"
L['tooltip.last_visit'] = "最近采集:"
L['tooltip.found_by'] = "发现者:"
L["settings.debugging"] = "Debugging"
-- Ores
L['node.mining'] = "矿石"
L['node.copper_vein'] = "铜矿"
L['node.tin_vein'] = "锡矿"
L['node.silver_vein'] = "银矿"
L['node.iron_deposit'] = "铁矿"
L['node.gold_vein'] = "金矿"
L['node.mithril_deposit'] = "秘银矿"
L['node.truesilver_deposit'] = "真银矿"
L['node.dark_iron_deposit'] = "黑铁矿"
L['node.small_thorium_vein'] = "瑟银矿"
L['node.rich_thorium_vein'] = "富瑟银矿"
-- Herbs
L['node.herbalism'] = "草药"
L['node.silverleaf'] = "银叶草"
L['node.peacebloom'] = "宁神花"
L['node.earthroot'] = "地根草"
L['node.mageroyal'] = "魔皇草"
L['node.briarthorn'] = "石南草"
L['node.stranglekelp'] = "荆棘藻"
L['node.bruiseweed'] = "跌打草"
L['node.wild_steelbloom'] = "野钢花"
L['node.grave_moss'] = "墓地苔"
L['node.kingsblood'] = "皇血草"
L['node.liferoot'] = "活根草"
L['node.fadeleaf'] = "枯叶草"
L['node.goldthorn'] = "金棘草"
L['node.khadgars_whisker'] = "卡德加的胡须"
L['node.wintersbite'] = "冬刺草"
L['node.firebloom'] = "火焰花"
L['node.purple_lotus'] = "紫莲花"
L['node.arthas_tears'] = "阿尔萨斯之泪"
L['node.sungrass'] = "太阳草"
L['node.blindweed'] = "盲目草"
L['node.ghost_mushroom'] = "幽灵菇"
L['node.gromsblood'] = "格罗姆之血"
L['node.golden_sansam'] = "黄金参"
L['node.dreamfoil'] = "梦叶草"
L['node.mountain_silversage'] = "山鼠草"
L['node.plaguebloom'] = "瘟疫花"
L['node.icecap'] = "冰盖草"
L['node.black_lotus'] = "黑莲花"
-- Open
L['node.battered_chest'] = "破损的箱子"
L['node.large_battered_chest'] = "破碎的大箱子"
L['node.solid_chest'] = "坚固的箱子"
L['node.large_solid_chest'] = "坚固的大箱子"
L['node.giant_clam'] = "巨型蚌壳"
L['node.ungoro_dirt_pile'] = "安戈洛的泥土"
-- Fish
L['node.fish_pool_firefin'] = "火鳞鳝鱼群"
L['node.fish_pool_debris'] = "漂浮的碎片"
L['node.fish_pool_wreckage'] = "漂浮的残骸"
L['node.fish_pool_oily_blackmouth'] = "黑口鱼群"
L['node.fish_pool_sagefish'] = "鼠尾鱼群" |
local style = require "core.style"
local common = require "core.common"
style.background = { common.color "#303841" }
style.background2 = { common.color "#1d2227" }
style.background3 = { common.color "#1d2227" }
style.text = { common.color "#9ea191" }
style.caret = { common.color "#61efce" }
style.accent = { common.color "#ffd152" }
style.dim = { common.color "#4c5863" }
style.divider = { common.color "#242223" }
style.selection = { common.color "#4c5863" }
style.line_number = { common.color "#bfc5d0" }
style.line_number2 = { common.color "#848b95" }
style.line_highlight = { common.color "#303841" }
style.scrollbar = { common.color "#696f75" }
style.scrollbar2 = { common.color "#444b53" }
style.syntax["normal"] = { common.color "#d7dde9" }
style.syntax["symbol"] = { common.color "#d8dee9" }
style.syntax["comment"] = { common.color "#a6acb9" }
style.syntax["keyword"] = { common.color "#e55e66" }
style.syntax["keyword2"] = { common.color "#ef6179" }
style.syntax["number"] = { common.color "#ffd152" }
style.syntax["literal"] = { common.color "#e75550" }
style.syntax["string"] = { common.color "#939d5d" }
style.syntax["operator"] = { common.color "#c2674f" }
style.syntax["function"] = { common.color "#6699ca" } |
---
-- @author wesen
-- @copyright 2020 wesen <wesen-ac@web.de>
-- @release 0.1
-- @license MIT
--
local Input = require "Input"
local CliInput = Input:extend()
function CliInput:parse(_parameters)
self.commandName = _parameters[1]
local nextParameterIsOptionValue
for i = 1, #_parameters, 1 do
if (substr)
end
-- -1 = lua binary
-- 0 = script name
-- 1+ = parameters
-- TODO: Parse arguments and options from params
end
return CliInput
|
local inp_size = 4
local out_size = 2
local conns = 3
local brain_size = 25
local return_v = false
local value_v = 0
local gauss_random
gauss_random = function()
if return_v then
return_v = false
return value_v
end
local u = 2 * math.random() - 1
local v = 2 * math.random() - 1
local r = u ^ 2 + v ^ 2
if r == 0 or r > 1 then
return gauss_random()
end
local c = math.sqrt(-2 * (math.log(r)) / r)
value_v = v * c
return u * c
end
local randf
randf = function(a, b)
return (b - a) * math.random() + a
end
local randi
randi = function(a, b)
return math.floor((b - a) * math.random() + a)
end
local randn
randn = function(mu, sigma)
return mu + gauss_random() * sigma
end
local Brain
do
local _class_0
local _base_0 = {
tick = function(self, inp, out)
for i = 1, inp_size do
self.boxes[i].out = inp[i]
end
for i = inp_size, brain_size do
local a = self.boxes[i]
if a.type == 0 then
local res = 1
for j = 1, conns do
local idx = a.id[j]
local val = self.boxes[idx].out
if a.notted[j] then
val = 1 - val
end
res = res * val
end
res = res * a.bias
a.target = res
else
local res = 0
for j = 1, conns do
local idx = a.id[j]
local val = self.boxes[idx].out
if a.notted[j] then
val = 1 - val
end
res = res + (val * a.w[j])
end
res = res + a.bias
a.target = res
end
if a.target < 0 then
a.target = 0
elseif a.target > 1 then
a.target = 1
end
end
for i = inp_size, brain_size do
local a = self.boxes[i]
a.out = a.out + ((a.target - a.out) * a.kp)
end
for i = 1, out_size do
out[i] = self.boxes[brain_size - i].out
end
end,
mutate = function(self, mr, mr2)
for i = 1, brain_size do
if mr * 3 > randf(0, 1) then
self.boxes[i].bias = self.boxes[i].bias + randn(0, mr2)
end
if mr * 3 > util.randf(0, 1) then
local rc = randi(1, CONNS)
self.boxes[i].w[rc] = self.boxes[i].w[rc] + randn(0, mr2)
if self.boxes[i].w[rc] > 0.01 then
self.boxes[i].w[rc] = 0.01
end
end
if mr > util.randf(0, 1) then
local rc = randi(1, CONNS)
local ri = randi(1, BRAIN_SIZE)
self.boxes[i].id[rc] = ri
end
if mr > randf(0, 1) then
local rc = randi(1, CONNS)
self.boxes[i].notted[rc] = not self.boxes[i].notted[rc]
end
if mr > randf(0, 1) then
self.boxes[i].type = 1 - self.boxes[i].type
end
end
end,
crossover = function(self, other)
local new_brain = Brain:from_brain(self)
for i = 1, #new_brain.boxes do
new_brain.boxes[i].bias = other.boxes[i].bias
new_brain.boxes[i].kp = other.boxes[i].kp
new_brain.boxes[i].type = other.boxes[i].type
if 0.5 > randf(0, 1) then
new_brain.boxes[i].bias = self.boxes[i].bias
end
if 0.5 > randf(0, 1) then
new_brain.boxes[i].kp = self.boxes[i].kp
end
if 0.5 > randf(0, 1) then
new_brain.boxes[i].type = self.boxes[i].type
end
for j = 1, #new_brain.boxes[i].id do
new_brain.boxes[i].id[j] = other.boxes[i].id[j]
new_brain.boxes[i].notted[j] = other.boxes[i].notted[j]
new_brain.boxes[i].w[j] = other.boxes[i].w[j]
if 0.5 > randf(0, 1) then
new_brain.boxes[i].id[j] = self.boxes[i].id[j]
end
if 0.5 > randf(0, 1) then
new_brain.boxes[i].notted[j] = self.boxes[i].notted[j]
end
if 0.5 > randf(0, 1) then
new_brain.boxes[i].w[j] = self.boxes[i].w[j]
end
end
end
return new_brain
end
}
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self)
self.boxes = { }
for i = 1, brain_size do
local a = Box()
self.boxes[#self.boxes + 1] = a
for j = 1, conns do
if 0.05 > randf(0, 1) then
a.id[j] = 1
end
if 0.05 > randf(0, 1) then
a.id[j] = 5
end
if 0.05 > randf(0, 1) then
a.id[j] = 12
end
if 0.05 > randf(0, 1) then
a.id[j] = 4
end
if i < brain_size / 2 then
a.id[j] = randi(1, inp_size)
end
end
end
end,
__base = _base_0,
__name = "Brain"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
local self = _class_0
self.from_brain = function(self, other)
local brain = DWRAONBrain()
brain.boxes = table.deepcopy(other.boxes)
return brain
end
Brain = _class_0
end
local Box
do
local _class_0
local _base_0 = { }
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self)
self.type = 0
if 0.5 > randf(0, 1) then
self.type = 1
end
self.kp = randf(0.8, 1)
self.w = { }
self.id = { }
self.notted = { }
for i = 1, conns do
self.w[i] = randf(0.1, 2)
self.id[i] = randi(1, brain_size)
if 0.2 > randf(0, 1) then
self.id[i] = randi(1, inp_size)
end
self.notted[i] = 0.5 > randf(0, 1)
end
self.bias = randf(-1, 1)
self.target = 0
self.out = 0
end,
__base = _base_0,
__name = "Box"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
Box = _class_0
return _class_0
end
|
net.Receive("GBaySetMySQL", function()
local DFrame = vgui.Create("DFrame")
DFrame:SetSize(300, 185)
DFrame:SetTitle("GBay MySQL info!")
DFrame:Center()
DFrame:SetDraggable(true)
DFrame:ShowCloseButton(true)
DFrame:MakePopup()
local HostEntry = vgui.Create("DTextEntry", DFrame)
HostEntry:SetPos(10, 30)
HostEntry:SetSize(DFrame:GetWide() - 20, 20)
HostEntry:SetText("MySQL Host")
HostEntry.OnEnter = function(self) end
local UsernameEntry = vgui.Create("DTextEntry", DFrame)
UsernameEntry:SetPos(10, 55)
UsernameEntry:SetSize(DFrame:GetWide() - 20, 20)
UsernameEntry:SetText("MySQL Username")
UsernameEntry.OnEnter = function(self) end
local PasswordEntry = vgui.Create("DTextEntry", DFrame)
PasswordEntry:SetPos(10, 80)
PasswordEntry:SetSize(DFrame:GetWide() - 20, 20)
PasswordEntry:SetText("MySQL Password")
local DatabaseEntry = vgui.Create("DTextEntry", DFrame)
DatabaseEntry:SetPos(10, 105)
DatabaseEntry:SetSize(DFrame:GetWide() - 20, 20)
DatabaseEntry:SetText("MySQL Database")
DatabaseEntry.OnEnter = function(self) end
local PortEntry = vgui.Create("DTextEntry", DFrame)
PortEntry:SetPos(10, 130)
PortEntry:SetSize(DFrame:GetWide() - 20, 20)
PortEntry:SetNumeric(true)
PortEntry:SetText("MySQL Port")
PortEntry.OnEnter = function(self) end
local SubmitBTN = vgui.Create("DButton", DFrame)
SubmitBTN:SetPos(10, 155)
SubmitBTN:SetSize(DFrame:GetWide() - 20, 20)
SubmitBTN:SetText("Submit MySQL Info")
SubmitBTN.DoClick = function()
net.Start("GBaySetMySQL")
net.WriteString(HostEntry:GetValue())
net.WriteString(UsernameEntry:GetValue())
net.WriteString(PasswordEntry:GetValue())
net.WriteString(DatabaseEntry:GetValue())
net.WriteFloat(PortEntry:GetValue())
net.SendToServer()
end
net.Receive("GBayCloseSetMySQL", function()
local worked = net.ReadBool()
local error = net.ReadString()
DFrame:Close()
if worked then
chat.AddText(Color(0, 255, 0), "MySQL Connected!")
else
chat.AddText(Color(255, 0, 0), "MySQL Error! Error: " .. error)
chat.AddText(Color(255, 0, 0), "Menu will re-open in 5 sec...")
end
end)
end) |
-- See LICENSE for terms
local mod_Option1
-- fired when settings are changed/init
local function ModOptions()
mod_Option1 = CurrentModOptions:GetProperty("Option1")
end
-- load default/saved settings
OnMsg.ModsReloaded = ModOptions
-- fired when option is changed
function OnMsg.ApplyModOptions(id)
if id ~= CurrentModId then
return
end
ModOptions()
end
local orig_CursorBuilding_GameInit = CursorBuilding.GameInit
function CursorBuilding.GameInit(...)
if mod_Option1 then
SetPostProcPredicate("hexgrid", true)
end
return orig_CursorBuilding_GameInit(...)
end
local orig_CursorBuilding_Done = CursorBuilding.Done
function CursorBuilding.Done(...)
SetPostProcPredicate("hexgrid", false)
return orig_CursorBuilding_Done(...)
end
|
-- Standard awesome library
local awful = require("awful")
local gears = require("gears")
-- Widget library
local wibox = require("wibox")
-- Theme handling library
local beautiful = require("beautiful")
local xresources = require("beautiful.xresources")
local dpi = xresources.apply_dpi
-- Rubato
local rubato = require("module.rubato")
-- Helpers
local helpers = require("helpers")
-- Get screen geometry
local screen_width = awful.screen.focused().geometry.width
local screen_height = awful.screen.focused().geometry.height
-- Helpers
-------------
local wrap_widget = function(widget)
return {
widget,
margins = dpi(6),
widget = wibox.container.margin
}
end
-- Wibar
-----------
screen.connect_signal("request::desktop_decoration", function(s)
-- Launcher
-------------
local awesome_icon = wibox.widget {
{
widget = wibox.widget.imagebox,
image = beautiful.awesome_logo,
resize = true
},
margins = dpi(4),
widget = wibox.container.margin
}
helpers.add_hover_cursor(awesome_icon, "hand2")
-- Battery
-------------
local charge_icon = wibox.widget{
bg = beautiful.xcolor8,
widget = wibox.container.background,
visible = false
}
local batt = wibox.widget{
charge_icon,
color = {beautiful.xcolor2},
bg = beautiful.xcolor8 .. "88",
value = 50,
min_value = 0,
max_value = 100,
thickness = dpi(4),
padding = dpi(2),
-- rounded_edge = true,
start_angle = math.pi * 3 / 2,
widget = wibox.container.arcchart
}
awesome.connect_signal("signal::battery", function(value)
local fill_color = beautiful.xcolor2
if value >= 11 and value <= 30 then
fill_color = beautiful.xcolor3
elseif value <= 10 then
fill_color = beautiful.xcolor1
end
batt.colors = {fill_color}
batt.value = value
end)
awesome.connect_signal("signal::charger", function(state)
if state then
charge_icon.visible = true
else
charge_icon.visible = false
end
end)
-- Time
----------
local hour = wibox.widget{
font = beautiful.font_name .. "bold 14",
format = "%H",
align = "center",
valign = "center",
widget = wibox.widget.textclock
}
local min = wibox.widget{
font = beautiful.font_name .. "bold 14",
format = "%M",
align = "center",
valign = "center",
widget = wibox.widget.textclock
}
local clock = wibox.widget{
{
{
hour,
min,
spacing = dpi(5),
layout = wibox.layout.fixed.vertical
},
top = dpi(5),
bottom = dpi(5),
widget = wibox.container.margin
},
bg = beautiful.lighter_bg,
shape = helpers.rrect(beautiful.bar_radius),
widget = wibox.container.background
}
-- Stats
-----------
local stats = wibox.widget{
{
wrap_widget(batt),
clock,
spacing = dpi(5),
layout = wibox.layout.fixed.vertical
},
bg = beautiful.xcolor0,
shape = helpers.rrect(beautiful.bar_radius),
widget = wibox.container.background
}
stats:connect_signal("mouse::enter", function()
stats.bg = beautiful.xcolor8
stats_tooltip_show()
end)
stats:connect_signal("mouse::leave", function()
stats.bg = beautiful.xcolor0
stats_tooltip_hide()
end)
-- Notification center
-------------------------
notif_center = wibox({
type = "dock",
screen = screen.primary,
height = screen_height - dpi(50),
width = dpi(300),
shape = helpers.rrect(beautiful.notif_center_radius),
ontop = true,
visible = false
})
notif_center.y = dpi(25)
-- Rubato
local slide = rubato.timed{
pos = dpi(-300),
rate = 60,
intro = 0.3,
duration = 0.8,
easing = rubato.quadratic,
awestore_compat = true,
subscribed = function(pos) notif_center.x = pos end
}
local notif_center_status = false
slide.ended:subscribe(function()
if notif_center_status then
notif_center.visible = false
end
end)
-- Make toogle button
local notif_center_show = function()
notif_center.visible = true
slide:set(dpi(100))
notif_center_status = false
end
local notif_center_hide = function()
slide:set(dpi(-375))
notif_center_status = true
end
local notif_center_toggle = function()
if notif_center.visible then
notif_center_hide()
else
notif_center_show()
end
end
-- notif_center setup
s.notif_center = require('ui.notifs.notif-center')(s)
notif_center:setup {
s.notif_center,
margins = dpi(15),
widget = wibox.container.margin
}
local notif_center_button = wibox.widget{
markup = helpers.colorize_text("", beautiful.xcolor4),
font = beautiful.font_name .. "18",
align = "center",
valign = "center",
widget = wibox.widget.textbox
}
notif_center_button:connect_signal("mouse::enter", function()
notif_center_button.markup = helpers.colorize_text(notif_center_button.text, beautiful.xcolor4 .. 55)
end)
notif_center_button:connect_signal("mouse::leave", function()
notif_center_button.markup = helpers.colorize_text(notif_center_button.text, beautiful.xcolor4)
end)
notif_center_button:buttons(gears.table.join(
awful.button({}, 1, function()
notif_center_toggle()
end)
))
helpers.add_hover_cursor(notif_center_button, "hand2")
-- Setup wibar
-----------------
-- Create a promptbox for each screen
s.mypromptbox = awful.widget.prompt()
-- Layoutbox
local layoutbox_buttons = gears.table.join(
-- Left click
awful.button({}, 1, function (c)
awful.layout.inc(1)
end),
-- Right click
awful.button({}, 3, function (c)
awful.layout.inc(-1)
end),
-- Scrolling
awful.button({}, 4, function ()
awful.layout.inc(-1)
end),
awful.button({}, 5, function ()
awful.layout.inc(1)
end)
)
s.mylayoutbox = awful.widget.layoutbox(s)
s.mylayoutbox:buttons(layoutbox_buttons)
local layoutbox = wibox.widget{
s.mylayoutbox,
margins = {bottom = dpi(7), left = dpi(8), right = dpi(8)},
widget = wibox.container.margin
}
helpers.add_hover_cursor(layoutbox, "hand2")
-- Create the wibar
s.mywibar = awful.wibar({
type = "dock",
position = "left",
screen = s,
height = awful.screen.focused().geometry.height - dpi(50),
width = dpi(50),
shape = helpers.rrect(beautiful.border_radius),
bg = beautiful.transparent,
ontop = true,
visible = true
})
awesome_icon:buttons(gears.table.join(
awful.button({}, 1, function ()
dashboard_toggle()
end)
))
-- Remove wibar on full screen
local function remove_wibar(c)
if c.fullscreen or c.maximized then
c.screen.mywibar.visible = false
else
c.screen.mywibar.visible = true
end
end
-- Remove wibar on full screen
local function add_wibar(c)
if c.fullscreen or c.maximized then
c.screen.mywibar.visible = true
end
end
client.connect_signal("property::fullscreen", remove_wibar)
client.connect_signal("request::unmanage", add_wibar)
-- Create the taglist widget
s.mytaglist = require("ui.widgets.pacman_taglist")(s)
local taglist = wibox.widget{
s.mytaglist,
shape = beautiful.taglist_shape_focus,
bg = beautiful.xcolor0,
widget = wibox.container.background
}
-- Add widgets to wibar
s.mywibar:setup {
{
{
layout = wibox.layout.align.vertical,
expand = "none",
{ -- top
awesome_icon,
taglist,
spacing = dpi(10),
layout = wibox.layout.fixed.vertical
},
-- middle
nil,
{ -- bottom
stats,
notif_center_button,
layoutbox,
spacing = dpi(8),
layout = wibox.layout.fixed.vertical
}
},
margins = dpi(8),
widget = wibox.container.margin
},
bg = beautiful.darker_bg,
shape = helpers.rrect(beautiful.border_radius),
widget = wibox.container.background
}
-- wibar position
s.mywibar.x = dpi(25)
end)
|
return {
tag = 'devices',
summary = 'Check if an audio device is started.',
description = 'Returns whether an audio device is started.',
arguments = {
{
name = 'type',
type = 'AudioType',
default = [['playback']],
description = 'The type of device to check.'
}
},
returns = {
{
name = 'started',
type = 'boolean',
description = 'Whether the device is active.'
}
},
related = {
'lovr.audio.start',
'lovr.audio.stop'
}
}
|
local default_value_patterns={
name="DLI PLC49",
input_name="Input %d",
output_name="Outlet %d",
adc_name="ADC %d",
cycle_time="1",
}
return {
get_value=function(name,index)
local ret
if file.open("config/"..name..(index and "/"..tostring(index) or "")) then
ret=file.read()
file.close()
elseif default_value_patterns[name] then
ret=default_value_patterns[name]:format(index)
else
ret=""
end
return ret
end,
set_value=function(data,name,index)
file.open("config/"..name..(index and "/"..tostring(index) or ""),"w")
file.write(data)
file.close()
end
}
|
return {
-- bluetooth applet
-- 'blueman-applet',
-- power manager
'xfce4-power-manager',
-- network applet
'nm-applet',
-- redshift
'redshift',
-- xorg compositor
'picom -b',
-- screenshot applet
'flameshot',
-- input method
'fcitx5',
-- proxy
'clash',
-- policy kit
-- '/usr/lib/polkit-gnome/polkit-gnome-authentication-agent-1'
}
|
require("pl")
ec = require("editorconfig")
local progname = arg[0]
local function print_usage(ret)
print(ec._VERSION)
print("Usage: " .. progname .. " [OPTIONS] FILEPATH1 [FILEPATH2 FILEPATH3 ...]")
-- print("FILEPATH can be a hyphen (-) if you want to path(s) to be read from stdin.")
print()
print("-f Specify conf filename other than \".editorconfig\".")
print("-b Specify version (used by devs to test compatibility).")
print("-h OR --help Print this help message.")
print("-v OR --version Display version information.")
os.exit(ret)
end
flags, params = app.parse_args(arg, {f = true, b = true})
if flags.h or flags.help then print_usage(0) end
if flags.v or flags.version then print(ec._VERSION); os.exit(0) end
if #params == 0 then print_usage(1) end
local function run_editorconfig(path, show_header)
if show_header then
utils.printf("[%s]\n", path)
end
local props, names = ec.parse(path, flags.f, flags.b)
for _, k in ipairs(names) do
utils.printf("%s=%s\n", k, props[k])
end
end
local show_header = not (#params == 1)
for _, path in ipairs(params) do
run_editorconfig(path, show_header)
end
|
local var_2 = require("mod")
print(var_2.hello("Yea"))
print(var_2.add(3, 6))
|
return {'mahdi','maharadja','maharishi','mahdist','mahjong','mahonie','mahonieboom','mahoniehout','mahoniehouten','maha','maher','mahmoud','mahmud','mahieu','mahler','mahabier','mahu','mahamed','mahabali','mahadew','mahn','mahamud','mahmood','mahesh','maharadjas','mahdisten','mahoniebomen','mahas','mahdis','mahers','mahmouds','mahmuds'} |
require "scripts/class"
function CreateEntity()
local en = {}
en.tags = {}
-------------------------------------------
function en:AddTag(tag)
table.insert(self.tags, tag)
end
function en:HasTag(tag)
for _, i in ipairs(self.tags) do
if i == tag then return true end
end
return false
end
------------------------------------------
en.components = {}
function en:AddComponent(name)
local c = FindPrefab(name):Create(self)
self.components[name] = c
return c
end
------------------------------------------
en.listeners = {}
function en:AddListener(type, fn)
if not self.listeners[type] then self.listeners[type] = {} end
self.listeners[type][fn] = true
end
function en:RemoveListener(type, fn)
self.listeners[type][fn] = nil
end
function en:PushEvent(type, ...)
if self.listeners[type] then
for i, v in pairs(self.listeners[type]) do
if v then i(self, ...) end
end
end
end
-----------------------------------------
en.animations = {}
en.curr = 0
function en:AddAnimation(id, type)
local i = {}
if type == "static" then
function i:Init(name)
self.texture = CreateTexture(name)
end
function i:GetImage()
return self.texture
end
function OnUpdate(delta) end
elseif type == "cycle" then
function i:Init(name, duration, range)
self.duration = duration
self.time = 0
self.range = range
self.current = 1
self.textures = {}
self.reversed = false
for i = 1, range do
self.textures[i] = CreateTexture(name .. i .. ".png")
end
end
function i:OnUpdate(delta)
self.time = self.time + delta
if self.time >= self.duration then
self.time = self.time - self.duration
self.current = self.current + 1
if self.current > self.range then
self.current = 1
end
end
end
function i:Reverse()
self.reversed = not self.reversed
end
function i:SetReversed(r)
self.reversed = r
end
function i:Min()
self.current = 1
end
function i:Max()
self.current = self.range
end
function i:GetImage()
if self.reversed then
return self.textures[self.range - self.current + 1]
end
return self.textures[self.current]
end
elseif type == "over" then
function i:Init(name, duration, range)
self.duration = duration
self.time = 0
self.range = range
self.current = 1
self.textures = {}
for i = 1, range do
self.textures[i] = CreateTexture(name .. i .. ".png")
end
end
function i:OnUpdate(delta)
if self.current < self.range then
self.time = self.time + delta
if self.time >= self.duration then
self.time = self.time - self.duration
self.current = self.current + 1
end
end
end
function i:Reverse()
self.reversed = not self.reversed
end
function i:SetReversed(r)
self.reversed = r
end
function i:Min()
self.current = 1
end
function i:Max()
self.current = self.range
end
function i:GetImage()
if self.reversed then
return self.textures[self.range - self.current + 1]
end
return self.textures[self.current]
end
end
self.animations[id] = i
return i
end
function en:GetImage()
if self.curr == 0 then return 0 end
return self.animations[self.curr]:GetImage()
end
function en:UseAnimation(id)
self.curr = id
end
function en:GetAnimation(id)
return self.animations[id]
end
function en:UpdateAnimation(delta)
if self.curr ~= 0 then
self.animations[self.curr]:OnUpdate(delta)
end
end
--------------------------------------------------------
en:AddListener("OnUpdate", function(entity, d) entity:UpdateAnimation(d) end)
function en:DebugInfo()
print("------------------------------------")
print("Tags:")
for _, i in ipairs(self.tags) do
print(i)
end
print("Components:")
for _, i in pairs(self.components) do
i:DebugInfo()
print("---------------------")
end
end
return en
end
require "scripts/prefab"
local entity_renderer = require "scripts/entity_renderer"
local tile_renderer = require "scripts/tile_renderer"
local ui_renderer = require "scripts/ui_renderer"
dummy = AddEntity("dummy")
player = AddEntity("player")
require "scripts/widgets/bar"
local b = Bar(dummy)
b:setLocation(512, -256)
AddWidget(b)
require "scripts/widgets/button"
local button = Button()
button:setLocation(-128, -128)
local function callback(b, button)
print("Call!")
end
button:addListener("OnMouseButtonReleased", function(b, button) print("Call!") end)
AddWidget(button)
player:PushEvent("Punch", dummy)
function PushEvent(type, ...)
if type == "OnMouseButtonReleased" then
player:PushEvent("Punch", dummy)
end
local b = tile_renderer:PushEvent(type, ...) or ui_renderer:PushEvent(type, ...) or entity_renderer:PushEvent(type, ...)
end
|
local unpack = table.unpack or unpack;
local interpolation = require "util.interpolation";
local template = interpolation.new("%b$$", function (s) return ("%q"):format(s) end);
--luacheck: globals meta idsafe
local action_handlers = {};
-- Takes an XML string and returns a code string that builds that stanza
-- using st.stanza()
local function compile_xml(data)
local code = {};
local first, short_close = true, nil;
for tagline, text in data:gmatch("<([^>]+)>([^<]*)") do
if tagline:sub(-1,-1) == "/" then
tagline = tagline:sub(1, -2);
short_close = true;
end
if tagline:sub(1,1) == "/" then
code[#code+1] = (":up()");
else
local name, attr = tagline:match("^(%S*)%s*(.*)$");
local attr_str = {};
for k, _, v in attr:gmatch("(%S+)=([\"'])([^%2]-)%2") do
if #attr_str == 0 then
table.insert(attr_str, ", { ");
else
table.insert(attr_str, ", ");
end
if k:find("^%a%w*$") then
table.insert(attr_str, string.format("%s = %q", k, v));
else
table.insert(attr_str, string.format("[%q] = %q", k, v));
end
end
if #attr_str > 0 then
table.insert(attr_str, " }");
end
if first then
code[#code+1] = (string.format("st.stanza(%q %s)", name, #attr_str>0 and table.concat(attr_str) or ", nil"));
first = nil;
else
code[#code+1] = (string.format(":tag(%q%s)", name, table.concat(attr_str)));
end
end
if text and text:find("%S") then
code[#code+1] = (string.format(":text(%q)", text));
elseif short_close then
short_close = nil;
code[#code+1] = (":up()");
end
end
return table.concat(code, "");
end
function action_handlers.PASS()
return "do return pass_return end"
end
function action_handlers.DROP()
return "do return true end";
end
function action_handlers.DEFAULT()
return "do return false end";
end
function action_handlers.RETURN()
return "do return end"
end
function action_handlers.STRIP(tag_desc)
local code = {};
local name, xmlns = tag_desc:match("^(%S+) (.+)$");
if not name then
name, xmlns = tag_desc, nil;
end
if name == "*" then
name = nil;
end
code[#code+1] = ("local stanza_xmlns = stanza.attr.xmlns; ");
code[#code+1] = "stanza:maptags(function (tag) if ";
if name then
code[#code+1] = ("tag.name == %q and "):format(name);
end
if xmlns then
code[#code+1] = ("(tag.attr.xmlns or stanza_xmlns) == %q "):format(xmlns);
else
code[#code+1] = ("tag.attr.xmlns == stanza_xmlns ");
end
code[#code+1] = "then return nil; end return tag; end );";
return table.concat(code);
end
function action_handlers.INJECT(tag)
return "stanza:add_child("..compile_xml(tag)..")", { "st" };
end
local error_types = {
["bad-request"] = "modify";
["conflict"] = "cancel";
["feature-not-implemented"] = "cancel";
["forbidden"] = "auth";
["gone"] = "cancel";
["internal-server-error"] = "cancel";
["item-not-found"] = "cancel";
["jid-malformed"] = "modify";
["not-acceptable"] = "modify";
["not-allowed"] = "cancel";
["not-authorized"] = "auth";
["payment-required"] = "auth";
["policy-violation"] = "modify";
["recipient-unavailable"] = "wait";
["redirect"] = "modify";
["registration-required"] = "auth";
["remote-server-not-found"] = "cancel";
["remote-server-timeout"] = "wait";
["resource-constraint"] = "wait";
["service-unavailable"] = "cancel";
["subscription-required"] = "auth";
["undefined-condition"] = "cancel";
["unexpected-request"] = "wait";
};
local function route_modify(make_new, to, drop)
local reroute, deps = "session.send(newstanza)", { "st" };
if to then
reroute = ("newstanza.attr.to = %q; core_post_stanza(session, newstanza)"):format(to);
deps[#deps+1] = "core_post_stanza";
end
return ([[do local newstanza = st.%s; %s;%s end]])
:format(make_new, reroute, drop and " return true" or ""), deps;
end
function action_handlers.BOUNCE(with)
local error = with and with:match("^%S+") or "service-unavailable";
local error_type = error:match(":(%S+)");
if not error_type then
error_type = error_types[error] or "cancel";
else
error = error:match("^[^:]+");
end
error, error_type = string.format("%q", error), string.format("%q", error_type);
local text = with and with:match(" %((.+)%)$");
if text then
text = string.format("%q", text);
else
text = "nil";
end
local route_modify_code, deps = route_modify(("error_reply(stanza, %s, %s, %s)"):format(error_type, error, text), nil, true);
deps[#deps+1] = "type";
deps[#deps+1] = "name";
return [[if type == "error" or (name == "iq" and type == "result") then return true; end -- Don't reply to 'error' stanzas, or iq results
]]..route_modify_code, deps;
end
function action_handlers.REDIRECT(where)
return route_modify("clone(stanza)", where, true);
end
function action_handlers.COPY(where)
return route_modify("clone(stanza)", where, false);
end
function action_handlers.REPLY(with)
return route_modify(("reply(stanza):body(%q)"):format(with));
end
function action_handlers.FORWARD(where)
local code = [[
local newstanza = st.stanza("message", { to = %q, from = current_host }):tag("forwarded", { xmlns = "urn:xmpp:forward:0" });
local tmp_stanza = st.clone(stanza); tmp_stanza.attr.xmlns = "jabber:client"; newstanza:add_child(tmp_stanza);
core_post_stanza(session, newstanza);
]];
return code:format(where), { "core_post_stanza", "current_host" };
end
function action_handlers.LOG(string)
local level = string:match("^%[(%a+)%]") or "info";
string = string:gsub("^%[%a+%] ?", "");
local meta_deps = {};
local code = meta(("(session.log or log)(%q, '%%s', %q);"):format(level, string), meta_deps);
return code, meta_deps;
end
function action_handlers.RULEDEP(dep)
return "", { dep };
end
function action_handlers.EVENT(name)
return ("fire_event(%q, event)"):format(name);
end
function action_handlers.JUMP_EVENT(name)
return ("do return fire_event(%q, event); end"):format(name);
end
function action_handlers.JUMP_CHAIN(name)
return template([[do
local ret = fire_event($chain_event$, event);
if ret ~= nil then
if ret == false then
log("debug", "Chain %q accepted stanza (ret %s)", $chain_name$, tostring(ret));
return pass_return;
end
log("debug", "Chain %q rejected stanza (ret %s)", $chain_name$, tostring(ret));
return ret;
end
log("debug", "Chain %q did not accept or reject stanza (ret %s)", $chain_name$, tostring(ret));
end]], { chain_event = "firewall/chains/"..name, chain_name = name });
end
function action_handlers.MARK_ORIGIN(name)
return [[session.firewall_marked_]]..idsafe(name)..[[ = current_timestamp;]], { "timestamp" };
end
function action_handlers.UNMARK_ORIGIN(name)
return [[session.firewall_marked_]]..idsafe(name)..[[ = nil;]]
end
function action_handlers.MARK_USER(name)
return [[if session.firewall_marks then session.firewall_marks.]]..idsafe(name)..[[ = current_timestamp; end]], { "timestamp" };
end
function action_handlers.UNMARK_USER(name)
return [[if session.firewall_marks then session.firewall_marks.]]..idsafe(name)..[[ = nil; end]], { "timestamp" };
end
function action_handlers.ADD_TO(spec)
local list_name, value = spec:match("(%S+) (.+)");
local meta_deps = {};
value = meta(("%q"):format(value), meta_deps);
return ("list_%s:add(%s);"):format(list_name, value), { "list:"..list_name, unpack(meta_deps) };
end
function action_handlers.UNSUBSCRIBE_SENDER()
return "rostermanager.unsubscribed(to_node, to_host, bare_from);\
rostermanager.roster_push(to_node, to_host, bare_from);\
core_post_stanza(session, st.presence({ from = bare_to, to = bare_from, type = \"unsubscribed\" }));",
{ "rostermanager", "core_post_stanza", "st", "split_to", "bare_to", "bare_from" };
end
return action_handlers;
|
if vim.b.did_ftp == true then
return
end
vim.bo.commentstring = "#\\ %s"
vim.bo.suffixesadd = ".qml"
vim.opt_local.cursorline = false
vim.opt_local.cursorcolumn = false
|
-----------------------------------------
-- ID: 4947
-- Scroll of Utsusemi: Ni
-- Teaches the ninjutsu Utsusemi: Ni
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(339)
end
function onItemUse(target)
target:addSpell(339)
end |
local NotifyFont
do
local _class_0
local _base_0 = {
Setup = function(self)
surface.SetFont(self.m_font)
local x, y = surface.GetTextSize('W')
self.m_height = y
end,
FixFont = function(self)
if not self.IsValidFont(self.m_font) then
self.m_font = 'Default'
end
return self
end,
IsValidFont = function(font)
local result = pcall(surface.SetFont, font)
return result
end,
SetFont = function(self, val)
if val == nil then
val = 'Default'
end
self.m_font = val
self:FixFont()
self:Setup()
return self
end,
GetFont = function(self)
return self.m_font
end,
GetTextSize = function(self, text)
assert(type(text) == 'string', 'Not a string')
surface.SetFont(self.m_font)
return self
end,
GetHeight = function(self)
return self.m_height
end
}
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self, val)
if val == nil then
val = 'Default'
end
self.m_font = val
self.m_Notify_type = 'font'
return self:FixFont()
end,
__base = _base_0,
__name = "NotifyFont"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
NotifyFont = _class_0
end
Notify.Font = NotifyFont
|
class "LightInfo"
function LightInfo:__getvar(name)
if name == "importance" then
return Polycode.LightInfo_get_importance(self.__ptr)
elseif name == "position" then
local retVal = Polycode.LightInfo_get_position(self.__ptr)
if retVal == nil then return nil end
local __c = _G["Vector3"]("__skip_ptr__")
__c.__ptr = retVal
return __c
elseif name == "direction" then
local retVal = Polycode.LightInfo_get_direction(self.__ptr)
if retVal == nil then return nil end
local __c = _G["Vector3"]("__skip_ptr__")
__c.__ptr = retVal
return __c
elseif name == "type" then
return Polycode.LightInfo_get_type(self.__ptr)
elseif name == "diffuseColor" then
local retVal = Polycode.LightInfo_get_diffuseColor(self.__ptr)
if retVal == nil then return nil end
local __c = _G["Color"]("__skip_ptr__")
__c.__ptr = retVal
return __c
elseif name == "specularColor" then
local retVal = Polycode.LightInfo_get_specularColor(self.__ptr)
if retVal == nil then return nil end
local __c = _G["Color"]("__skip_ptr__")
__c.__ptr = retVal
return __c
elseif name == "constantAttenuation" then
return Polycode.LightInfo_get_constantAttenuation(self.__ptr)
elseif name == "linearAttenuation" then
return Polycode.LightInfo_get_linearAttenuation(self.__ptr)
elseif name == "quadraticAttenuation" then
return Polycode.LightInfo_get_quadraticAttenuation(self.__ptr)
elseif name == "intensity" then
return Polycode.LightInfo_get_intensity(self.__ptr)
elseif name == "spotlightCutoff" then
return Polycode.LightInfo_get_spotlightCutoff(self.__ptr)
elseif name == "spotlightExponent" then
return Polycode.LightInfo_get_spotlightExponent(self.__ptr)
elseif name == "shadowsEnabled" then
return Polycode.LightInfo_get_shadowsEnabled(self.__ptr)
elseif name == "lightViewMatrix" then
local retVal = Polycode.LightInfo_get_lightViewMatrix(self.__ptr)
if retVal == nil then return nil end
local __c = _G["Matrix4"]("__skip_ptr__")
__c.__ptr = retVal
return __c
end
end
function LightInfo:__setvar(name,value)
if name == "importance" then
Polycode.LightInfo_set_importance(self.__ptr, value)
return true
elseif name == "position" then
Polycode.LightInfo_set_position(self.__ptr, value.__ptr)
return true
elseif name == "direction" then
Polycode.LightInfo_set_direction(self.__ptr, value.__ptr)
return true
elseif name == "type" then
Polycode.LightInfo_set_type(self.__ptr, value)
return true
elseif name == "diffuseColor" then
Polycode.LightInfo_set_diffuseColor(self.__ptr, value.__ptr)
return true
elseif name == "specularColor" then
Polycode.LightInfo_set_specularColor(self.__ptr, value.__ptr)
return true
elseif name == "constantAttenuation" then
Polycode.LightInfo_set_constantAttenuation(self.__ptr, value)
return true
elseif name == "linearAttenuation" then
Polycode.LightInfo_set_linearAttenuation(self.__ptr, value)
return true
elseif name == "quadraticAttenuation" then
Polycode.LightInfo_set_quadraticAttenuation(self.__ptr, value)
return true
elseif name == "intensity" then
Polycode.LightInfo_set_intensity(self.__ptr, value)
return true
elseif name == "spotlightCutoff" then
Polycode.LightInfo_set_spotlightCutoff(self.__ptr, value)
return true
elseif name == "spotlightExponent" then
Polycode.LightInfo_set_spotlightExponent(self.__ptr, value)
return true
elseif name == "shadowsEnabled" then
Polycode.LightInfo_set_shadowsEnabled(self.__ptr, value)
return true
elseif name == "lightViewMatrix" then
Polycode.LightInfo_set_lightViewMatrix(self.__ptr, value.__ptr)
return true
end
return false
end
function LightInfo:__delete()
if self then Polycode.delete_LightInfo(self.__ptr) end
end
|
package.path = "./?.lua;./?/init.lua"
require 'names'
require 'markovDetect'
require 'config'
for i,n in ipairs(arg) do
local b = bayes(n, prior)
print(("%s has %g prob, %g real and %g fake. %s"):format(n, b, probability(n), probFake(n), ((b>threshold and 'Would be filtered') or 'would not be filtered')))
end |
-- Tests not used with travis
stdengine = "etex"
checkengines = {"etex"}
checksearch = true
testfiledir = "testfiles-local"
|
workspace "Niking2D"
architecture "x86_64"
startproject "Sandbox"
configurations{
"Debug",
"Release",
"Dist"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
IncludeDir ={}
IncludeDir["GLFW"] = "Niking2D/vendor/GLFW/include"
IncludeDir["Glad"] = "Niking2D/vendor/Glad/include"
IncludeDir["ImGui"]= "Niking2D/vendor/imgui"
IncludeDir["glm"] = "Niking2D/vendor/glm"
IncludeDir["stb_image"] = "Niking2D/vendor/stb_image"
IncludeDir["lua"] = "Niking2D/vendor/lua/src"
IncludeDir["sol"] = "Niking2D/vendor/sol"
-- runs "%{prj.name}/vendor/GLFW/premake5.lua"
include "Niking2D/vendor/GLFW"
include "Niking2D/vendor/Glad"
include "Niking2D/vendor/imgui"
include "Niking2D/vendor/lua"
project "Niking2D"
location "Niking2D"
kind "StaticLib"
language "C++"
cppdialect "c++17"
staticruntime "on"
targetdir("bin/" .. outputdir .. "/%{prj.name}")
objdir("bin-int/" .. outputdir .. "/%{prj.name}")
pchheader "n2pch.h"
pchsource "%{prj.name}/src/n2pch.cpp"
files{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp",
"%{prj.name}/vendor/stb_image/**.h",
"%{prj.name}/vendor/stb_image/**.cpp",
"%{prj.name}/vendor/sol/**.hpp",
"%{prj.name}/vendor/glm/glm/**.hpp",
"%{prj.name}/vendor/glm/glm/**.inl",
}
links{
"GLFW",
"Glad",
"ImGui",
"opengl32.lib",
"Lua",
}
includedirs{
"%{prj.name}/src",
"%{prj.name}/vendor/spdlog/include",
"%{prj.name}/vendor",
"%{IncludeDir.GLFW}",
"%{IncludeDir.Glad}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.glm}",
"%{IncludeDir.stb_image}",
"%{IncludeDir.lua}",
"%{IncludeDir.sol}",
}
filter "system:windows"
staticruntime "on"
systemversion "latest"
defines{
"N2_PLATFORM_WINDOWS",
"N2_BUILD_DLL",
"GLFW_INCLUDE_NONE"
}
filter "configurations:Debug"
defines "N2_DEBUG"
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines "N2_RELEASE"
runtime "Release"
optimize "on"
filter "configurations:Dist"
defines "N2_DIST"
runtime "Release"
symbols "on"
project "Sandbox"
location "Sandbox"
kind "ConsoleApp"
language "C++"
cppdialect "c++17"
staticruntime "on"
targetdir("bin/" .. outputdir .. "/%{prj.name}")
objdir("bin-int/" .. outputdir .. "/%{prj.name}")
files{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs{
"Niking2D/vendor/spdlog/include",
"Niking2D/vendor/imgui",
"Niking2D/src",
"%{IncludeDir.glm}",
"%{IncludeDir.stb_image}",
"%{IncludeDir.lua}",
"%{IncludeDir.sol}",
}
links{
"Niking2D",
}
filter "system:windows"
staticruntime "on"
systemversion "latest"
defines{
"N2_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "N2_DEBUG"
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines "N2_RELEASE"
runtime "Release"
optimize "on"
filter "configurations:Dist"
defines "N2_DIST"
runtime "Release"
symbols "on"
|
require 'TextBox'
function love.conf(t)
t.identity = nil -- The name of the save directory (string)
t.appendidentity = false -- Search files in source directory before save directory (boolean)
t.version = "11.3" -- The LÖVE version this game was made for (string)
-- To activate console debugging
t.console = true
t.accelerometerjoystick = false -- Enable the accelerometer on iOS and Android by exposing it as a Joystick (boolean)
t.externalstorage = false -- True to save files (and read from the save directory) in external storage on Android (boolean)
t.gammacorrect = false -- Enable gamma-correct rendering, when supported by the system (boolean)
t.audio.mic = false -- Request and use microphone capabilities in Android (boolean)
t.audio.mixwithsystem = true -- Keep background music playing when opening LOVE (boolean, iOS and Android only)
t.modules.audio = true -- Enable the audio module (boolean)
t.modules.data = true -- Enable the data module (boolean)
t.modules.event = true -- Enable the event module (boolean)
t.modules.font = true -- Enable the font module (boolean)
t.modules.graphics = true -- Enable the graphics module (boolean)
t.modules.image = true -- Enable the image module (boolean)
t.modules.joystick = false -- Enable the joystick module (boolean)
t.modules.keyboard = true -- Enable the keyboard module (boolean)
t.modules.math = true -- Enable the math module (boolean)
t.modules.mouse = true -- Enable the mouse module (boolean)
t.modules.physics = false -- Enable the physics module (boolean)
t.modules.sound = true -- Enable the sound module (boolean)
t.modules.system = true -- Enable the system module (boolean)
t.modules.thread = false -- Enable the thread module (boolean)
t.modules.timer = true -- Enable the timer module (boolean), Disabling it will result 0 delta time in love.update
t.modules.touch = false -- Enable the touch module (boolean)
t.modules.video = true -- Enable the video module (boolean)
t.modules.window = true -- Enable the window module (boolean)
cellWidth = 2
numberOfHorizontalCells = 1000
numberOfVerticalCells = 600
generationsPerIteration = 1
windowWidth = cellWidth * numberOfHorizontalCells
windowHeight = cellWidth * numberOfVerticalCells
windowWidth = 1000
windowHeight = 600
minimunWidth = 800
minimunHeight = 600
black =
{
0, 0, 0
}
color =
{
1.00, 0.25, 0.00
}
drawFromTop = 1
if love.filesystem.getInfo('settings.txt') == nil then
writeConfigFile()
else
readConfigFile()
end
t.window.title = "Rule 110" -- The window title (string)
t.window.icon = nil -- Filepath to an image to use as the window's icon (string)
t.window.width = windowWidth
t.window.height = windowHeight
t.window.borderless = false -- Remove all border visuals from the window (boolean)
t.window.resizable = false -- Let the window be user-resizable (boolean)
t.window.minwidth = minimunWidth -- Minimum window width if the window is resizable (number)
t.window.minheight = minimunHeight -- Minimum window height if the window is resizable (number)
t.window.fullscreen = false -- Enable fullscreen (boolean)
t.window.fullscreentype = "desktop" -- Choose between "desktop" fullscreen or "exclusive" fullscreen mode (string)
t.window.vsync = 0 -- Vertical sync mode (number)
t.window.msaa = 0 -- The number of samples to use with multi-sampled antialiasing (number)
t.window.depth = nil -- The number of bits per sample in the depth buffer
t.window.stencil = nil -- The number of bits per sample in the stencil buffer
t.window.display = 2 -- Index of the monitor to show the window in (number)
t.window.highdpi = false -- Enable high-dpi mode for the window on a Retina display (boolean)
t.window.usedpiscale = true -- Enable automatic DPI scaling when highdpi is set to true as well (boolean)
t.window.x = nil -- The x-coordinate of the window's position in the specified display (number)
t.window.y = nil -- The y-coordinate of the window's position in the specified display (number)
cameraPosX = 0
cameraPosY = 0
menuHorizontalPos = 220
menuVerticalPos = 200
menuOutlineHorizontalPos = 20
menuOutlineVerticalPos = 220
menuTextVerticalIncrement = 20
menuGroupVerticalIncrement = 10
configScreenAdditionalHorizontalSpace = 10
menuWidth = 560
menuHeight = 420
fontsize = 18
end
function writeConfigFile()
f = love.filesystem.newFile('settings.txt')
f:open("w")
f:write(cellWidth .. "\r\n")
f:write(numberOfHorizontalCells .. "\r\n")
f:write(numberOfVerticalCells .. "\r\n")
f:write(generationsPerIteration .. "\r\n")
f:write(windowWidth .. "\r\n")
f:write(windowHeight .. "\r\n")
f:write(minimunWidth .. "\r\n")
f:write(minimunHeight .. "\r\n")
f:write(color[1] .. "," .. color[2] .. "," .. color[3] .. "\r\n")
f:write(drawFromTop .. "\r\n")
f:close()
end
function readConfigFile()
contents, size = love.filesystem.read('settings.txt')
values = split(contents, "\r\n")
cellWidth = tonumber(values[1])
numberOfHorizontalCells = tonumber(values[2])
numberOfVerticalCells = tonumber(values[3])
generationsPerIteration = tonumber(values[4])
windowWidth = tonumber(values[5])
windowHeight = tonumber(values[6])
minimunWidth = tonumber(values[7])
minimunHeight = tonumber(values[8])
colorAux = split(values[9], ",")
color = { colorAux[1], colorAux[2], colorAux[3] }
drawFromTop = tonumber(values[10])
end
function split(s, delimiter)
result = {}
for match in (s..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match)
end
return result
end |
--
-- Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
--
local sm = ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[4]
redis.log(redis.LOG_NOTICE,"DelRequest for "..sm)
local db = tonumber(ARGV[5])
redis.call('select',db)
local typ = redis.call('smembers',"TYPES:"..sm)
local res = {}
for k,v in pairs(typ) do
redis.log(redis.LOG_NOTICE, "Read UVES:"..sm..":"..v)
local lres = redis.call('zrange',"UVES:"..sm..":"..v, 0, -1, "withscores")
redis.call('del', "UVES:"..sm..":"..v)
local iter = 1
redis.log(redis.LOG_NOTICE, "Delete "..sm..":"..v.." [#"..(#lres/2).."]")
while iter <= #lres do
local deltyp = v
local deluve = lres[iter]
local delseq = lres[iter+1]
local st,en
table.insert(res, deluve)
table.insert(res, deltyp)
st,en = string.find(deluve,":")
local deltbl = string.sub(deluve, 1, st-1)
local dkey = "DEL:"..deluve..":"..sm..":"..deltyp..":"..delseq
local part = redis.call('hget',"KEY2PART:"..sm..":"..deltyp, deluve)
if not part then
part = "NULL"
else
redis.call('hdel', "KEY2PART:"..sm..":"..deltyp, deluve)
redis.call('srem', "PART2KEY:"..part, sm..":"..deltyp..":"..deluve)
end
local dval = "VALUES:"..deluve..":"..sm..":"..deltyp
local lttt = redis.call('exists', dval)
if lttt == 1 then
redis.call('rename', dval, dkey)
end
dval = "ORIGINS:"..deluve
if redis.call('srem', dval, sm..":"..deltyp) == 1 then
dval = "TABLE:"..deltbl
redis.call('srem', dval, deluve..":"..sm..":"..deltyp)
else
dval = "ALARM_ORIGINS:"..deluve
redis.call('srem', dval, sm..":"..deltyp)
dval = "ALARM_TABLE:"..deltbl
redis.call('srem', dval, deluve..":"..sm..":"..deltyp)
end
if lttt == 1 then
redis.call('lpush',"DELETED", dkey)
end
iter = iter + 2
end
end
redis.call('del', "TYPES:"..ARGV[1]..":"..ARGV[2]..":"..ARGV[3]..":"..ARGV[4])
redis.call('srem', "NGENERATORS", sm)
redis.log(redis.LOG_NOTICE,"Delete Request for "..sm.." successful")
return res
|
local Explode = {}
function Explode.OnAdd(e)
Explode[e] = true
end
function Explode.OnRemove(e)
Explode[e] = nil
end
return Explode
|
-----------------------------------------
-- ID: 4658
-- Scroll of Shell III
-- Teaches the white magic Shell III
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(50)
end
function onItemUse(target)
target:addSpell(50)
end |
local Tunnel = module("vrp","lib/Tunnel")
local Proxy = module("vrp","lib/Proxy")
local Tools = module("vrp","lib/Tools")
tvRP = {}
local players = {}
Tunnel.bindInterface("vRP",tvRP)
vRPserver = Tunnel.getInterface("vRP")
Proxy.addInterface("vRP",tvRP)
local user_id
function tvRP.setUserId(_user_id)
user_id = _user_id
end
function tvRP.getUserId()
return user_id
end
function tvRP.getUserHeading()
return GetEntityHeading(PlayerPedId())
end
function tvRP.teleport(x,y,z)
SetEntityCoords(PlayerPedId(),x+0.0001,y+0.0001,z+0.0001,1,0,0,1)
vRPserver._updatePos(x,y,z)
end
function tvRP.clearWeapons()
RemoveAllPedWeapons(PlayerPedId(),true)
end
function tvRP.getPosition()
local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(),true))
return x,y,z
end
function tvRP.isInside()
local x,y,z = tvRP.getPosition()
return not (GetInteriorAtCoords(x,y,z) == 0)
end
function tvRP.getCamDirection()
local heading = GetGameplayCamRelativeHeading()+GetEntityHeading(PlayerPedId())
local pitch = GetGameplayCamRelativePitch()
local x = -math.sin(heading*math.pi/180.0)
local y = math.cos(heading*math.pi/180.0)
local z = math.sin(pitch*math.pi/180.0)
local len = math.sqrt(x*x+y*y+z*z)
if len ~= 0 then
x = x/len
y = y/len
z = z/len
end
return x,y,z
end
function tvRP.addPlayer(player)
players[player] = true
end
function tvRP.removePlayer(player)
players[player] = nil
end
function tvRP.getPlayers()
return players
end
function tvRP.getNearestPlayers(radius)
local r = {}
local ped = GetPlayerPed(i)
local pid = PlayerId()
local px,py,pz = tvRP.getPosition()
for k,v in pairs(players) do
local player = GetPlayerFromServerId(k)
if player ~= pid and NetworkIsPlayerConnected(player) then
local oped = GetPlayerPed(player)
local x,y,z = table.unpack(GetEntityCoords(oped,true))
local distance = GetDistanceBetweenCoords(x,y,z,px,py,pz,true)
if distance <= radius then
r[GetPlayerServerId(player)] = distance
end
end
end
return r
end
function tvRP.getNearestPlayer(radius)
local p = nil
local players = tvRP.getNearestPlayers(radius)
local min = radius+0.0001
for k,v in pairs(players) do
if v < min then
min = v
p = k
end
end
return p
end
-----------------------------------------------------------------------------------------------------------------------------------------
-- VARANIM
-----------------------------------------------------------------------------------------------------------------------------------------
local animActived = false
local animDict = nil
local animName = nil
local animFlags = 0
-----------------------------------------------------------------------------------------------------------------------------------------
-- PLAYANIM
-----------------------------------------------------------------------------------------------------------------------------------------
function tvRP.playAnim(upper,seq,looping)
tvRP.stopAnimActived()
local ped = PlayerPedId()
if seq.task then
tvRP.stopAnim(true)
if seq.task == "PROP_HUMAN_SEAT_CHAIR_MP_PLAYER" then
local x,y,z = table.unpack(GetEntityCoords(ped))
TaskStartScenarioAtPosition(ped,seq.task,x,y,z-1,GetEntityHeading(ped),0,0,false)
else
TaskStartScenarioInPlace(ped,seq.task,0,not seq.play_exit)
end
else
tvRP.stopAnim(upper)
local flags = 0
if upper then
flags = flags + 48
end
if looping then
flags = flags + 1
end
Citizen.CreateThread(function()
RequestAnimDict(seq[1])
while not HasAnimDictLoaded(seq[1]) do
RequestAnimDict(seq[1])
Citizen.Wait(10)
end
if HasAnimDictLoaded(seq[1]) then
animDict = seq[1]
animName = seq[2]
animFlags = flags
if flags == 49 then
animActived = true
end
TaskPlayAnim(ped,seq[1],seq[2],3.0,3.0,-1,flags,0,0,0,0)
end
end)
end
end
-----------------------------------------------------------------------------------------------------------------------------------------
-- THREADANIM
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while true do
local ped = PlayerPedId()
if not IsEntityPlayingAnim(ped,animDict,animName,3) and animActived then
TaskPlayAnim(ped,animDict,animName,3.0,3.0,-1,animFlags,0,0,0,0)
end
Citizen.Wait(4)
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- THREADBLOCK
-----------------------------------------------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while true do
local timeDistance = 500
if animActived then
timeDistance = 4
DisableControlAction(0,16,true)
DisableControlAction(0,17,true)
DisableControlAction(0,24,true)
DisableControlAction(0,25,true)
DisableControlAction(0,257,true)
DisableControlAction(0,327,true)
BlockWeaponWheelThisFrame()
end
Citizen.Wait(timeDistance)
end
end)
-----------------------------------------------------------------------------------------------------------------------------------------
-- STOPANIMACTIVED
-----------------------------------------------------------------------------------------------------------------------------------------
function tvRP.stopAnimActived()
animActived = false
end
function tvRP.stopAnim(upper)
anims = {}
if upper then
ClearPedSecondaryTask(PlayerPedId())
else
ClearPedTasks(PlayerPedId())
end
end
function tvRP.playSound(dict,name)
PlaySoundFrontend(-1,dict,name,false)
end
function tvRP.stopSound()
return StopSound(tvRP.playSound(dict,name))
end
function tvRP.playScreenEffect(name,duration)
if duration < 0 then
StartScreenEffect(name,0,true)
else
StartScreenEffect(name,0,true)
Citizen.CreateThread(function()
Citizen.Wait(math.floor((duration+1)*1000))
StopScreenEffect(name)
end)
end
end
AddEventHandler("playerSpawned",function()
TriggerServerEvent("vRPcli:playerSpawned")
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(1)
if NetworkIsSessionStarted() then
TriggerServerEvent("Queue:playerActivated")
return
end
end
end) |
object_mobile_nova_orion_garrick_orion = object_mobile_shared_nova_orion_garrick_orion:new {
}
ObjectTemplates:addTemplate(object_mobile_nova_orion_garrick_orion, "object/mobile/nova_orion_garrick_orion.iff")
|
data:extend
{
{
type = "fluid",
name = "chlorine",
base_color = {r=0, g=255, b=0, a=0},
default_temperature = 21.0,
flow_color = {r=0, g=255, b=0, a=0},
icons = {icon={icon="__base__/graphics/icons/fluid/steam.png", tint={r=0, g=255, b=0, a=255}}},
icon_size = 64
}
,
{
type = "fluid",
name = "hydrogen",
base_color = {r=0, g=255, b=0, a=0},
default_temperature = 21.0,
flow_color = {r=0, g=255, b=0, a=0},
icons = {icon={icon="__base__/graphics/icons/fluid/steam.png", tint={r=255, g=255, b=255, a=255}}},
icon_size = 64
}
,
{
type = "fluid",
name = "oxygen",
base_color = {r=0, g=255, b=0, a=0},
default_temperature = 21.0,
flow_color = {r=0, g=255, b=0, a=0},
icons = {icon={icon="__base__/graphics/icons/fluid/steam.png", tint={r=255, g=0, b=0, a=0}}},
icon_size = 64
}
,
}
|
return PlaceObj("ModDef", {
"title", "Example Sidepanel Controls",
"version", 1,
"version_major", 0,
"version_minor", 1,
"id", "ChoGGi_ExampleSidepanelControls",
"author", "ChoGGi",
"code", {
"Code/Script.lua",
},
"image", "Preview.png",
"lua_revision", 1007000, -- Picard
"description", [[Adds some example controls to various side panel selections.]],
})
|
local data_network = assert(yatm.data_network)
local CLUSTER_GROUP = 'yatm_data'
-- Allows the cluster tool to lookup normal clusters
yatm.cluster_tool.register_cluster_tool_lookup(CLUSTER_GROUP, function (pos, state)
local member = data_network:get_member_at_pos(pos)
local network = data_network:get_network_at_pos(pos)
local data = {}
if member then
data.member = member
state[CLUSTER_GROUP] = data
end
if network then
data.network = network
state[CLUSTER_GROUP] = data
end
return state
end)
yatm.cluster_tool.register_cluster_tool_render(CLUSTER_GROUP, function (data, formspec, render_state)
local registered_nodes_with_count = {}
if data.network then
for member_id, _is_present in pairs(data.network.members) do
local member = data_network:get_member(member_id)
registered_nodes_with_count[member.node.name] =
(registered_nodes_with_count[member.node.name] or 0) + 1
end
end
local cols = 4
local colsize = render_state.w / cols
local item_size = colsize * 0.6
local label_size = colsize * 0.6
local i = 0
for node_name, count in pairs(registered_nodes_with_count) do
local x = math.floor(i % cols) * colsize
local y = math.floor(i / cols) * colsize
local label_x = x + label_size
local label_y = y + item_size / 2
formspec =
formspec ..
"item_image[" .. x .. "," .. y .. ";" ..
item_size .. "," .. item_size .. ";" ..
node_name .. "]" ..
"label[" .. label_x .. "," .. label_y.. ";" .. count .."]"
i = i + 1
end
return formspec
end)
|
require("deepcore/std/class")
require("deepcore/std/callable")
require("eawx-util/ChangeOwnerUtilities")
require("deepcore/statemachine/dsl/conditions")
require("eawx-util/StoryUtil")
---@class PlanetTransferBuilder
PlanetTransferBuilder = class()
---@vararg string
function PlanetTransferBuilder:new(...)
---@type table<number, string>
self.planets = arg
self.Active_Planets = {}
---@type PlayerObject
self.target_owner = nil
---@type fun(): boolean
self.condition = function()
return true
end
end
---@param faction_name string
function PlanetTransferBuilder:to_owner(faction_name)
self.target_owner = Find_Player(faction_name)
return self
end
---@param condition fun(): boolean
function PlanetTransferBuilder:if_(condition)
self.condition = condition
return self
end
function PlanetTransferBuilder:build()
return callable {
planets = self.planets,
new_owner = self.target_owner,
condition = self.condition,
Active_Planets = self.Active_Planets,
call = function(self)
self.Active_Planets = StoryUtil.GetSafePlanetTable()
for _, planet in ipairs(self.planets) do
if self.Active_Planets[planet] then
local planet_object = self:get_planet(planet)
if self.condition(planet_object) then
ChangePlanetOwnerAndRetreat(planet_object, self.new_owner)
end
end
end
end,
get_planet = function(self, planet_like)
if type(planet_like) == "userdata" then
return planet_like
end
if type(planet_like) == "table" and planet_like.get_game_object then
return planet_like:get_game_object()
end
return FindPlanet(planet_like)
end
}
end
return PlanetTransferBuilder
|
reb.gui = {}
surface.CreateFont( "Reb_HUD_small", {
font = "Arial",
extended = false,
size = ScreenScale(6),
weight = 1000,
blursize = 0,
scanlines = 0,
antialias = true,
} )
surface.CreateFont( "Reb_HUD_med", {
font = "Arial",
extended = false,
size = ScreenScale(10),
weight = 1000,
blursize = 0,
scanlines = 0,
antialias = true,
} )
function GM:HUDPaint()
client = LocalPlayer()
--Simple HUD
draw.RoundedBox( 5, ScrW() * 0.025, ScrH() * 0.87, ScrW() * 0.035, ScrH() * 0.045, Color(25,25,25,75))
draw.SimpleTextOutlined(client:Health().."%", "Reb_HUD_med", ScrW() * 0.043, ScrH() * 0.89, Color(255,200,0,255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 2, Color(0,0,0,255))
draw.RoundedBox( 5, ScrW() * 0.025, ScrH() * 0.93, ScrW() * 0.035, ScrH() * 0.045, Color(25,25,25,75))
draw.SimpleTextOutlined(client:Armor().."%", "Reb_HUD_med", ScrW() * 0.043, ScrH() * 0.95, Color(255,200,0,255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 2, Color(0,0,0,255))
local trace = LocalPlayer():GetEyeTrace()
if (trace.Entity.ShouldDraw) and (math.Distance(trace.StartPos.x, trace.StartPos.y, trace.HitPos.x, trace.HitPos.y) <= 200) then
entity = trace.Entity
entity:textDisplay()
end
end
local hide = {
CHudHealth = true,
CHudBattery = true,
CHudAmmo = true,
CHudSecondaryAmmo = true
}
hook.Add( "HUDShouldDraw", "HideHUD", function( name )
if ( hide[ name ] ) then return false end
end ) |
local parse_c11 = require 'parsers.c11'
local lpegrex = require 'lpegrex'
local lester = require 'tests.lester'
local describe, it = lester.describe, lester.it
local function eqast(source, expected)
local aststr = lpegrex.prettyast(parse_c11(source))
expected = expected:gsub('^%s+', ''):gsub('%s+$', '')
if not aststr:find(expected, 1, true) then
error('expected to match second in first value\nfirst value:\n'..aststr..'\nsecond value:\n'..expected)
end
end
describe('c11 parser', function()
it("basic", function()
eqast([[]], [[-]])
eqast([[/* comment */]], [[-]])
eqast([[// comment]], [[-]])
end)
it("escape sequence", function()
eqast([[const char* s = "\'\"\?\a\b\f\n\r\t\v\\\000\xffff";]],
[["\\'\\\"\\?\\a\\b\\f\\n\\r\\t\\v\\\\\\000\\xffff"]])
end)
it("external declaration", function()
eqast([[int a;]], [[
translation-unit
| declaration
| | type-declaration
| | | declaration-specifiers
| | | | type-specifier
| | | | | "int"
| | | init-declarator-list
| | | | init-declarator
| | | | | declarator
| | | | | | identifier
| | | | | | | "a"
]])
eqast([[void main(){}]], [[
translation-unit
| function-definition
| | declaration-specifiers
| | | type-specifier
| | | | "void"
| | declarator
| | | declarator-parameters
| | | | identifier
| | | | | "main"
| | declaration-list
| | compound-statement
]])
eqast([[_Static_assert(x, "x");]], [[
translation-unit
| declaration
| | static_assert-declaration
| | | identifier
| | | | "x"
| | | string-literal
| | | | "x"
]])
end)
it("expression statement", function()
eqast([[void main() {a;;}]], [[
| | | expression-statement
| | | | expression
| | | | | identifier
| | | | | | "a"
]])
end)
it("selection statement", function()
eqast([[void main() {if(a) {} else if(b) {} else {}}]], [[
| | | if-statement
| | | | expression
| | | | | identifier
| | | | | | "a"
| | | | compound-statement
| | | | if-statement
| | | | | expression
| | | | | | identifier
| | | | | | | "b"
| | | | | compound-statement
| | | | | compound-statement
]])
eqast([[void main() {switch(a) {case A: default: break;}}]], [[
| | | switch-statement
| | | | expression
| | | | | identifier
| | | | | | "a"
| | | | compound-statement
| | | | | case-statement
| | | | | | identifier
| | | | | | | "A"
| | | | | | default-statement
| | | | | | | break-statement
]])
end)
it("iteration statement", function()
eqast([[void main() {while(a) {};}]], [[
| | | while-statement
| | | | expression
| | | | | identifier
| | | | | | "a"
| | | | compound-statement
]])
eqast([[void main() {do{} while(a);}]], [[
| | | do-while-statement
| | | | compound-statement
| | | | expression
| | | | | identifier
| | | | | | "a"
]])
eqast([[void main() {for(;;) {}}]], [[
| | | for-statement
| | | | false
| | | | false
| | | | false
| | | | compound-statement
]])
eqast([[void main() {for(i=10;i;i--) {}}]], [[
| | | for-statement
| | | | expression
| | | | | binary-op
| | | | | | identifier
| | | | | | | "i"
| | | | | | "="
| | | | | | integer-constant
| | | | | | | "10"
| | | | expression
| | | | | identifier
| | | | | | "i"
| | | | expression
| | | | | post-decrement
| | | | | | identifier
| | | | | | | "i"
| | | | compound-statement
]])
end)
it("jump statement", function()
eqast([[void main() {continue;}]], "continue-statement")
eqast([[void main() {break;}]], "break-statement")
eqast([[void main() {return;}]], "return-statement")
eqast([[void main() {return a;}]], [[
| | | return-statement
| | | | expression
| | | | | identifier
| | | | | | "a"
]])
eqast([[void main() {a: goto a;}]], [[
| | | label-statement
| | | | identifier
| | | | | "a"
| | | goto-statement
| | | | identifier
| | | | | "a"
]])
end)
it("label with typedefs", function()
eqast([[
// namespaces.c
typedef int S, T, U;
struct S { int T; };
union U { int x; };
void f(void) {
// The following uses of S, T, U are correct, and have no
// effect on the visibility of S, T, U as typedef names.
struct S s = { .T = 1 };
T: s.T = 2;
union U u = { 1 };
goto T;
// S, T and U are still typedef names:
S ss = 1; T tt = 1; U uu = 1;
}
]], [[
| | | label-statement
| | | | identifier
| | | | | "T"
]])
end)
end)
|
local config = require("vlua.config")
local Util = require("vlua.util")
local NextTick = require("vlua.nextTick")
local nextTick, devtools = NextTick.nextTick, Util.devtools
local splice = Util.splice
local tsort = table.sort
local tinsert = table.insert
local warn = Util.warn
local MAX_UPDATE_COUNT = 100
---@type Watcher[]
local queue = {}
---@type table<number, boolean>
local has = {}
---@type table<number, number>
local circular = {}
local waiting = false
local flushing = false
local index = 0--[[
* Reset the scheduler's state.
--]]
local function resetSchedulerState()
index = 1
queue = {}
has = {}
if (config.env ~= "production") then
circular = {}
end
waiting = false
flushing = false
end
local function compareQueue(a, b)
return a.id < b.id
end
--[[
* Flush both queues and run the watchers.
--]]
local function flushSchedulerQueue()
flushing = true
---@type Watcher
local watcher
---@type integer
local id
-- Sort queue before flush.
-- This ensures that:
-- 1. Components are updated from parent to child. (because parent is always
-- created before the child)
-- 2. A component's user watchers are run before its render watcher (because
-- user watchers are created before the render watcher)
-- 3. If a component is destroyed during a parent component's watcher run,
-- its watchers can be skipped.
tsort(queue, compareQueue)
-- do not cache length because more watchers might be pushed
-- as we run existing watchers
index = 1
while index <= #queue do
watcher = queue[index]
if (watcher.before) then
watcher:before()
end
id = watcher.id
has[id] = nil
watcher:run()
-- in dev build, check and stop circular updates.
if (config.env ~= "production" and has[id] ~= nil) then
circular[id] = (circular[id] or 0) + 1
if (circular[id] > MAX_UPDATE_COUNT) then
warn(
"You may have an infinite update loop " ..
(watcher.user and 'in watcher with expression "${watcher.expression}"' or
"in a component render function."),
watcher.vm
)
break
end
end
index = index + 1
end
resetSchedulerState()
-- devtool hook
--[[ istanbul ignore if --]]
if (devtools and config.devtools) then
devtools.emit("flush")
end
end
--[[
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
--]]
---@param watcher Watcher
local function queueWatcher(watcher)
local id = watcher.id
if (has[id] == nil) then
has[id] = true
if (not flushing) then
tinsert(queue, watcher)
else
-- if already flushing, splice the watcher based on its id
-- if already past its id, it will be run next immediately.
local i = #queue
while (i > index and queue[i].id > watcher.id) do
i = i - 1
end
splice(queue, i + 1, 0, watcher)
end
-- queue the flush
if (not waiting) then
waiting = true
if (config.env ~= "production" and not config.async) then
flushSchedulerQueue()
return
end
nextTick(flushSchedulerQueue)
end
end
end
return {
queueWatcher = queueWatcher,
MAX_UPDATE_COUNT = MAX_UPDATE_COUNT
}
|
baekhos_blade_rogue = {
cast = function(player)
local weap = player:getEquippedItem(EQ_WEAP)
local magic = 6000
if (not player:canCast(1, 1, 0)) then
return
end
if (player.magic < magic) then
player:sendMinitext("You do not have enough mana.")
return
end
if player:checkIfCast(enchants) or player.enchant > 1 then
player:sendMinitext("This spell is already active.")
return
end
player:sendAction(6, 35)
player:sendMinitext(weap.name .. " shines with holy light.")
player.magic = player.magic - magic
player.enchant = 2.25
player:sendStatus()
end,
recast = function(player)
player.enchant = 2.25
player:sendStatus()
end,
uncast = function(player)
player.enchant = 1
player:sendStatus()
player:sendMinitext("The glimmer subsides into a throb and then vanishes.")
end,
requirements = function(player)
local level = 99
local items = {"ee_san_blood", "dark_dagger", "magical_dust", 0}
local itemAmounts = {1, 4, 4, 60000}
local description = "Infuse your weapon with energy, causing you to deal more damage."
return level, items, itemAmounts, description
end
}
|
-- All entries must go above this line
}
|
--
-- toolchains.lua
-- Declare toolchains to use with GENie
-- Copyright (c) 2020 Christian Helmich and the GENie project
--
premake.toolchain = { }
--
-- The list of registered tools.
--
premake.toolchain.list = { }
--
-- Register a new toolchain.
--
-- @param a
-- The new toolchain object.
--
function premake.toolchain.add(a)
-- validate the tool object, at least a little bit
local missing
for _, field in ipairs({"description", "name", "cc", "cxx", "ar"}) do
if (not a[field]) then
missing = field
end
end
if (missing) then
error("tool needs a " .. missing, 3)
end
-- add it to the master list
premake.toolchain.list[a.name] = a
end
--
-- Retrieve an tool by name.
--
-- @param name
-- The name of the tool to retrieve.
-- @returns
-- The requested tool, or nil if the tool does not exist.
--
function premake.toolchain.get(name)
return premake.toolchain.list[name]
end
--
-- Iterator for the list of tools.
--
function premake.toolchain.each()
-- sort the list by trigger
local keys = { }
for _, tool in pairs(premake.toolchain.list) do
table.insert(keys, tool.name)
end
table.sort(keys)
local i = 0
return function()
i = i + 1
return premake.toolchain.list[keys[i]]
end
end
-- API --
-- Define a new tool.
--
-- @param a
-- The new tool object.
--
function newtoolchain(a)
premake.toolchain.add(a)
end
-- per solution decide which toolchain to use
newapifield {
name = "toolchain",
kind = "string",
scope = "solution",
allowed = function(value)
if premake.toolchain.list[value] then
return value
end
end,
}
-------------------------------------------------------------------------------
-- resolve env vars
--- resolves env vars written as ${name} by looking them up and replacing with their actual value
---
--- INTENDED USAGE:
--- includedirs { table.translate(table.flatten(a.includedirs), resolve_vars) }
--- libdirs { table.translate(table.flatten(a.libdirs), resolve_vars) }
--- buildoptions { table.translate(table.flatten(a.buildoptions), resolve_vars) }
--- linkoptions { table.translate(table.flatten(a.linkoptions), resolve_vars) }
---
function resolve_vars(str, variables)
local valuemap = {}
if variables then
for _,var in ipairs(variables) do
local val = os.getenv(var)
if val then
valuemap[var] = os.getenv(var)
else
printf(colorize(ansicolors.red, "please set the environment variable %q"), var)
end
end
end
return str:gsub('%${%w+}', valuemap)
end
function applytoolchain(a)
assert(a)
if type(a) == 'string' then
return applytoolchain(premake.toolchain.get(a))
end
if type(a) == 'table' then
printf("applying toolchain settings for %q", a.name)
if _ACTION:startswith("vs") then
local action = premake.action.current()
assert(a.vstudio)
assert(a.vstudio.toolset)
premake.vstudio.toolset = a.vstudio.toolset
if a.vstudio.storeapp then
premake.vstudio.storeapp = a.vstudio.storeapp
end
action.vstudio.windowsTargetPlatformVersion = a.vstudio.targetPlatformVersion or string.gsub(os.getenv("WindowsSDKVersion") or "8.1", "\\", "")
action.vstudio.windowsTargetPlatformMinVersion = a.vstudio.targetPlatformMinVersion or string.gsub(os.getenv("WindowsSDKVersion") or "8.1", "\\", "")
elseif _ACTION:startswith("xcode") then
local action = premake.action.current()
action.xcode.macOSTargetPlatformVersion = a.xcode.targetPlatformVersion
premake.xcode.toolset = a.xcode.toolset
end
local tool = premake[_OPTIONS.cc or 'gcc']
tool.cc = resolve_vars(a.cc)
tool.cxx = resolve_vars(a.cxx)
tool.ar = resolve_vars(a.ar)
tool.llvm = a.llvm or false
if a.namestyle then tool.namestyle = a.namestyle end
configuration {}
if a.configure then
a.configure()
end
configuration {}
end
end
-------------------------------------------------------------------------------
newtoolchain {
name = "clang-macos-default",
description = "Default XCode integrated clang toolchain on macOS",
cc = "clang",
cxx = "clang++",
ar = "ar",
llvm = true, --optional
namestyle = "posix", --optional
variables = {}, --optional, environment variables to substitute to their actual path
xcode = {
targetPlatformVersion = "10.15",
toolset = "macosx",
},
configure = function()
removeflags {
"UseLDResponseFile",
"UseObjectResponseFile",
}
buildoptions {
"-m64",
"-Wshadow",
"-msse2",
"-Wunused-value",
"-Wno-undef",
"-target x86_64-apple-macos" .. "10.15",
"-mmacosx-version-min=10.15",
"-stdlib=libc++",
"-Wno-unknown-warning-option",
}
linkoptions {
"-mmacosx-version-min=10.15",
"-framework Cocoa",
"-framework CoreFoundation",
"-framework Foundation",
"-framework QuartzCore",
"-framework OpenGL",
}
-- avoid release build errors on missing asserts
configuration { "release" }
buildoptions {
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration {}
end
}
newtoolchain {
name = "clang-macos",
description = "XCode Command Line Tools on latest macOS (Big Sur)",
cc = "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang",
cxx = "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++",
ar = "ar",
llvm = true, --optional
namestyle = "posix", --optional
variables = {}, --optional, environment variables to substitute to their actual path
vstudio = {
targetPlatformVersion = "",
targetPlatformMinVersion = "",
toolset = "",
storeapp = "",
},
xcode = {
targetPlatformVersion = "11.1",
toolset = "macosx",
},
configure = function()
removeflags {
"UseLDResponseFile",
"UseObjectResponseFile",
}
buildoptions {
"-m64",
"-Wshadow",
"-msse2",
"-Wunused-value",
"-Wno-undef",
"-stdlib=libc++",
"-target x86_64-apple-macos" .. "11.1",
"-mmacosx-version-min=11.1",
"--sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk",
os.isdir("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1") and
"-isystem " .. "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1" or
"-isystem " .. "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include" ,
os.isdir("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1") and
"-cxx-isystem " .. "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1" or
"-cxx-isystem " .. "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include",
"-Wno-unknown-warning-option",
}
linkoptions {
"-mmacosx-version-min=11.1",
"--sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk",
"-F/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks",
"-F/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/PrivateFrameworks",
"-framework Cocoa",
"-framework CoreFoundation",
"-framework Foundation",
"-framework QuartzCore",
"-framework OpenGL",
}
-- avoid release build errors on missing asserts
configuration { "release" }
buildoptions {
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration {}
end
}
newtoolchain {
name = "clang-windows",
description = "clang toolchain with VS headers on Windows",
cc = "clang",
cxx = "clang++",
ar = "ar",
llvm = true, --optional
namestyle = "windows", --optional
variables = {}, --optional, environment variables to substitute to their actual path
vstudio = {
targetPlatformVersion = "10.0",
targetPlatformMinVersion = "10.0",
toolset = "LLVM",
storeapp = "",
},
xcode = {
targetPlatformVersion = "",
toolset = "",
},
configure = function()
flags {
"UseLDResponseFile",
"UseObjectResponseFile",
}
removeflags {
"StaticRuntime",
}
defines {
"WIN32",
"_WIN32",
"_HAS_EXCEPTIONS=0",
"_SCL_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_WARNINGS",
"_CRT_SECURE_NO_DEPRECATE",
"strdup=_strdup",
}
includedirs {
table.translate({
path.join("${VCToolsInstallDir}", "include"),
path.join("${WindowsSdkVerBinPath}", "um"),
}, function(e) return resolve_vars(e, {
"VCToolsInstallDir",
"WindowsSdkVerBinPath",
}) end)
}
libdirs {
table.translate({
path.join("${VCToolsInstallDir}", "lib/x64"),
path.join("${WindowsSdkVerBinPath}", "um/x64"),
}, function(e) return resolve_vars(e, {
"VCToolsInstallDir",
"WindowsSdkVerBinPath",
}) end)
}
links {
"ole32",
"kernel32",
"user32",
}
configuration { "vs*" }
buildoptions {
"/wd4201", -- warning C4201: nonstandard extension used: nameless struct/union
"/wd4324", -- warning C4324: '': structure was padded due to alignment specifier
"/Ob2", -- The Inline Function Expansion
"/clang:-target x86_64-pc-win32",
"/clang:-fms-extensions",
"/clang:-fms-compatibility",
"/clang:-fdelayed-template-parsing",
"/clang:-Wno-unknown-warning-option",
"/clang:-Wno-gnu-folding-constant",
"/clang:-Wno-unknown-warning-option",
"/clang:-Wno-unused-command-line-argument",
"/clang:-Wno-unused-but-set-parameter",
}
linkoptions {
"/NODEFAULTLIB:libcmt",
"/ignore:4221", -- LNK4221: This object file does not define any previously undefined public symbols, so it will not be used by any link operation that consumes this library
}
configuration { "not vs*" }
buildoptions {
"-m64",
"-target x86_64-pc-win32",
"-fms-extensions",
"-fms-compatibility",
"-fdelayed-template-parsing",
"-Wno-undef",
"-Wno-sign-compare",
"-Wno-unknown-warning-option",
"-Wno-gnu-folding-constant",
"-Wno-unknown-warning-option",
"-Wno-unused-command-line-argument",
"-Wno-unused-but-set-parameter",
}
linkoptions {
"-target x86_64-pc-win32",
"-Wl,/NODEFAULTLIB:libcmt",
"-Wl,/ignore:4221",
}
configuration { "debug" }
defines {
"_SCL_SECURE=1",
"_SECURE_SCL=1",
"_ITERATOR_DEBUG_LEVEL=1",
"_HAS_ITERATOR_DEBUGGING=0",
}
links {
"msvcrtd",
"libcmtd",
}
configuration { "release" }
defines {
"_SCL_SECURE=0",
"_SECURE_SCL=0",
--"_ITERATOR_DEBUG_LEVEL=0",
}
links {
"msvcrt",
"libcmt",
}
-- avoid release build errors on missing asserts
configuration { "vs*", "release" }
buildoptions {
"/clang:-Wno-unused-parameter",
"/clang:-Wno-unused-variable",
}
configuration { "not vs*", "release" }
buildoptions {
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration {}
configuration {}
end
}
newtoolchain {
name = "clang-linux",
description = "Clang toolchain on Linux",
cc = "clang",
cxx = "clang++",
ar = "ar",
llvm = true, --optional
namestyle = "posix", --optional
variables = {}, --optional, environment variables to substitute to their actual path
configure = function()
removeflags {
"UseLDResponseFile",
"UseObjectResponseFile",
}
buildoptions {
"-m64",
"-Wshadow",
"-msse2",
"-Wunused-value",
"-Wno-undef",
"-stdlib=libc++",
"-target x86_64-unknown-linux-gnu",
"-fPIC",
"-Wno-unknown-warning-option",
"-Wno-unused-command-line-argument",
"-Wno-unused-but-set-parameter",
"-Wno-gnu-folding-constant",
}
links {
"rt",
"dl",
"X11",
"GL",
"pthread",
}
linkoptions {
"-Wl,--gc-sections",
"-Wl,--as-needed",
}
-- avoid release build errors on missing asserts
configuration { "release" }
buildoptions {
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration {}
end
}
newtoolchain {
name = "emscripten-asmjs",
description = "Emscripten toolchain to produce ASM.js",
cc = "emcc",
cxx = "em++",
ar = "emar",
llvm = true, --optional
namestyle = "Emscripten", --optional
variables = {}, --optional, environment variables to substitute to their actual path
configure = function()
removeflags {
"UseLDResponseFile",
"UseObjectResponseFile",
}
buildoptions {
"-m32",
"-Wshadow",
"-msse2",
"-msimd128",
"-Wunused-value",
"-Wno-undef",
--"-stdlib=libc++",
"-Wno-unknown-warning-option",
"-Wno-unused-command-line-argument",
"-Wno-unused-but-set-parameter",
"-Wno-undef",
"-Wno-gnu-folding-constant",
}
linkoptions {
"-Wl,-mwasm32",
"-s MIN_WEBGL_VERSION=2",
"-s MAX_WEBGL_VERSION=2",
"-s USE_WEBGL2=1",
"-s FULL_ES3=1",
"-s WASM=0", -- for ASM.js
"-s ALLOW_MEMORY_GROWTH=1",
"-g",
}
-- avoid release build errors on missing asserts
configuration { "release" }
buildoptions {
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration {}
end
}
newtoolchain {
name = "emscripten-wasm",
description = "Emscripten toolchain to produce WebAssembly",
cc = "emcc",
cxx = "em++",
ar = "emar",
llvm = true, --optional
namestyle = "Emscripten", --optional
variables = {}, --optional, environment variables to substitute to their actual path
configure = function()
removeflags {
"UseLDResponseFile",
"UseObjectResponseFile",
}
buildoptions {
"-m32",
"-Wshadow",
"-msse2",
"-msimd128",
"-Wunused-value",
"-Wno-undef",
--"-stdlib=libc++",
"-Wno-unknown-warning-option",
"-Wno-unused-command-line-argument",
"-Wno-unused-but-set-parameter",
"-Wno-undef",
"-Wno-gnu-folding-constant",
}
linkoptions {
"-Wl,-mwasm32",
"-s MIN_WEBGL_VERSION=2",
"-s MAX_WEBGL_VERSION=2",
"-s USE_WEBGL2=1",
"-s FULL_ES3=1",
"-s ALLOW_MEMORY_GROWTH=1",
"-g",
}
-- avoid release build errors on missing asserts
configuration { "release" }
buildoptions {
"-Wno-unused-parameter",
"-Wno-unused-variable",
}
configuration {}
end
}
-------------------------------------------------------------------------------
|
return{
name = "chickenfinger",
} |
--Button disable flag. True for now, because button CANT do what I want it to...
local disableButton = true
if disableButton == false then require("button") end
function recheck_all_recipes(rf)
for _, research in pairs(rf.technologies) do
if research.researched then
if research.effects then
for _, effect in pairs (research.effects) do
if effect.type == "unlock-recipe" then
rf.recipes[effect.recipe].enabled = true
end
end
end
end
end
end
-- Proxy so I can remove unneeded code without removing/commenting unneeded calls
function createMainButtonProxy(x)
if disableButton then return end
createMainButton(x)
end
-- Start OnLoad/OnInit/OnConfig events
script.on_configuration_changed( function(data)
-- Do Any Mod Changes
-- Setup for global list
-- wipe global list if any mod changes, not just GDIW
global.gdiwlist = {}
--if global.gdiwlist ~= nil then
--gdiwliststring = loadstring(game.entity_prototypes["gdiw_data_list_flying-text"].order)()
--global.gdiwlist = gdiwliststring
--end
-- Do GDIW Mod added
if data.mod_changes ~= nil and data.mod_changes["GDIW"] ~= nil and data.mod_changes["GDIW"].old_version == nil then
for _,force in pairs(game.forces) do
force.reset_recipes()
force.reset_technologies()
recheck_all_recipes(force)
end
for idx, _ in pairs(game.players) do
createMainButtonProxy(idx)
end
end
-- Do GDIW Mod updated or removed
if data.mod_changes ~= nil and data.mod_changes["GDIW"] ~= nil and data.mod_changes["GDIW"].old_version ~= nil then
for _,force in pairs(game.forces) do
force.reset_recipes()
force.reset_technologies()
-- Re-disable all GDIW recipes (Useful when old save versions involved)
for _, i in pairs(global.gdiwlist) do
for _, j in pairs(i) do
force.recipes[j.name].enabled = false
end
end
recheck_all_recipes(force)
end
for idx, _ in pairs(game.players) do
createMainButtonProxy(idx)
end
end
end)
script.on_init(function()
-- Nothing to do now
end)
script.on_load(function()
--Nothing to Do Now
end)
-- End OnLoad/OnInit/OnConfig events
|
--easy script configs
IntroTextSize = 25 --Size of the text for the Now Playing thing.
IntroSubTextSize = 30 --size of the text for the Song Name.
IntroTagColor = 'FFDD00' --Color of the tag at the end of the box.
IntroTagWidth = 15 --Width of the box's tag thingy.
--easy script configs
--actual script
function onCreate()
--the tag at the end of the box
makeLuaSprite('JukeBoxTag', 'empty', -305-IntroTagWidth, 15)
makeGraphic('JukeBoxTag', 300+IntroTagWidth, 100, IntroTagColor)
setObjectCamera('JukeBoxTag', 'other')
addLuaSprite('JukeBoxTag', true)
--the box
makeLuaSprite('JukeBox', 'empty', -305-IntroTagWidth, 15)
makeGraphic('JukeBox', 300, 100, '000000')
setObjectCamera('JukeBox', 'other')
addLuaSprite('JukeBox', true)
--the text for the "Now Playing" bit
makeLuaText('JukeBoxText', songName, 300, -305-IntroTagWidth, 30)
setTextAlignment('JukeBoxText', 'left')
setObjectCamera('JukeBoxText', 'other')
setTextSize('JukeBoxText', IntroTextSize)
setTextColor('JukeBoxText', 'FFDD00')
addLuaText('JukeBoxText')
--text for the song name
makeLuaText('JukeBoxSubText', 'Psych Engine X', 300, -305-IntroTagWidth, 60)
setTextAlignment('JukeBoxSubText', 'left')
setObjectCamera('JukeBoxSubText', 'other')
setTextSize('JukeBoxSubText', IntroSubTextSize)
addLuaText('JukeBoxSubText')
end
--motion functions
function onSongStart()
-- Inst and Vocals start playing, songPosition = 0
doTweenX('MoveInOne', 'JukeBoxTag', 0, 1, 'CircInOut')
doTweenX('MoveInTwo', 'JukeBox', 0, 1, 'CircInOut')
doTweenX('MoveInThree', 'JukeBoxText', 0, 1, 'CircInOut')
doTweenX('MoveInFour', 'JukeBoxSubText', 0, 1, 'CircInOut')
runTimer('JukeBoxWait', 3, 1)
end
function onTimerCompleted(tag, loops, loopsLeft)
-- A loop from a timer you called has been completed, value "tag" is it's tag
-- loops = how many loops it will have done when it ends completely
-- loopsLeft = how many are remaining
if tag == 'JukeBoxWait' then
doTweenX('MoveOutOne', 'JukeBoxTag', -450, 1.5, 'CircInOut')
doTweenX('MoveOutTwo', 'JukeBox', -450, 1.5, 'CircInOut')
doTweenX('MoveOutThree', 'JukeBoxText', -450, 1.5, 'CircInOut')
doTweenX('MoveOutFour', 'JukeBoxSubText', -450, 1.5, 'CircInOut')
end
end |
cc = cc or {}
---Physics3DPointToPointConstraint object
---@class Physics3DPointToPointConstraint : Physics3DConstraint
local Physics3DPointToPointConstraint = {}
cc.Physics3DPointToPointConstraint = Physics3DPointToPointConstraint
--------------------------------
---get pivot point in A's local space
---@return vec3_table
function Physics3DPointToPointConstraint:getPivotPointInA() end
--------------------------------
---get pivot point in B's local space
---@return vec3_table
function Physics3DPointToPointConstraint:getPivotPointInB() end
--------------------------------
---@overload fun(Physics3DRigidBody, Physics3DRigidBody, vec3_table, vec3_table):bool
---@overload fun(Physics3DRigidBody, vec3_table):bool
---@param rbA Physics3DRigidBody
---@param rbB Physics3DRigidBody
---@param pivotPointInA vec3_table
---@param pivotPointInB vec3_table
---@return bool
function Physics3DPointToPointConstraint:init(rbA, rbB, pivotPointInA, pivotPointInB) end
--------------------------------
---set pivot point in A's local space
---@param pivotA vec3_table
---@return Physics3DPointToPointConstraint
function Physics3DPointToPointConstraint:setPivotPointInA(pivotA) end
--------------------------------
---set pivot point in B's local space
---@param pivotB vec3_table
---@return Physics3DPointToPointConstraint
function Physics3DPointToPointConstraint:setPivotPointInB(pivotB) end
--------------------------------
---@overload fun(Physics3DRigidBody, Physics3DRigidBody, vec3_table, vec3_table):Physics3DPointToPointConstraint
---@overload fun(Physics3DRigidBody, vec3_table):Physics3DPointToPointConstraint
---@param rbA Physics3DRigidBody
---@param rbB Physics3DRigidBody
---@param pivotPointInA vec3_table
---@param pivotPointInB vec3_table
---@return Physics3DPointToPointConstraint
function Physics3DPointToPointConstraint:create(rbA, rbB, pivotPointInA, pivotPointInB) end
--------------------------------
--
---@return Physics3DPointToPointConstraint
function Physics3DPointToPointConstraint:Physics3DPointToPointConstraint() end
return Physics3DPointToPointConstraint |
return {
skip_compat53 = true,
source_dir = "lgetchar",
include = { "**/*" },
}
|
function getAllGates(thePlayer, commandName, ...)
if exports.mrp_integration:isPlayerAdmin(thePlayer) or exports.mrp_integration:isPlayerScripter(thePlayer) then
if table.concat({...}, " ") ~= "" then
outputChatBox("SYNTAX: /"..commandName.." - Open Gates Manager", thePlayer, 255, 194, 14)
else
local gatesList = {}
local mQuery1 = nil
dbQuery(
function(qh, thePlayer)
local res, rows, err = dbPoll(qh, 0)
if rows > 0 then
for index, row in ipairs(res) do
table.insert(gatesList, { row["id"], tostring(row["objectID"]), row["gateType"], row["gateSecurityParameters"], row["creator"], row["createdDate"], row["adminNote"], row["autocloseTime"], row["movementTime"], row["objectInterior"], row["objectDimension"], row["startX"], row["startY"], row["startZ"], row["startRX"], row["startRY"], row["startRZ"], row["endX"], row["endY"], row["endZ"], row["endRX"], row["endRY"], row["endRZ"] } )
end
triggerClientEvent(thePlayer, "createGateManagerWindow", thePlayer, gatesList, getElementData( thePlayer, "account:username" ))
end
end,
{thePlayer}, mysql:getConnection(), "SELECT * FROM `gates` ORDER BY `createdDate` DESC")
end
end
end
addCommandHandler("gates", getAllGates)
function SmallestID( ) -- finds the smallest ID in the SQL instead of auto increment
local result = dbPoll(dbQuery(mysql:getConnection(), "SELECT MIN(e1.id+1) AS nextID FROM gates AS e1 LEFT JOIN gates AS e2 ON e1.id +1 = e2.id WHERE e2.id IS NULL"), -1)
if result then
local id = tonumber(result["nextID"]) or 1
return id
end
return false
end
function addGate(thePlayer, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24)
local mQuery1 = nil
local smallestID = SmallestID()
if not a22 then
a22 = false
else
a22 = tostring(a22)
if string.len(a22) < 2 then
a22 = false
elseif a22 == "none" then
a22 = false
else
a22 = (a22)
end
end
if not tonumber(a23) then
a23 = false
else
a23 = (tostring(a23))
end
if not tonumber(a24) then
a24 = false
else
a24 = (tostring(a24))
end
mQuery1 = dbExec(mysql:getConnection(), "INSERT INTO `gates` (`id`, `objectID`, `startX`, `startY`, `startZ`, `startRX`, `startRY`, `startRZ`, `endX`, `endY`, `endZ`, `endRX`, `endRY`, `endRZ`, `gateType`, `gateSecurityParameters`, `autocloseTime`, `movementTime`, `objectInterior`, `objectDimension`, `creator`, `adminNote`, `sound`, `triggerDistance`, `triggerDistanceVehicle`) VALUES ('"..tostring(smallestID).."', '".. (a1) .."', '".. (a2) .."', '".. (a3) .."', '".. (a4) .."', '".. (a5) .."', '".. (a6) .."', '".. (a7) .."', '".. (a8) .."', '".. (a9) .."', '".. (a10) .."', '".. (a11) .."', '".. (a12) .."', '".. (a13) .."', '".. (a14) .."', '".. (a15) .."', '".. (a16) .."', '".. (a17) .."', '".. (a18) .."', '".. (a19) .."', '".. (a20) .."', '".. (a21) .."', "..(a22 and "'"..a22.."'" or "NULL")..", "..(a23 and "'"..a23.."'" or "NULL")..", "..(a24 and "'"..a24.."'" or "NULL")..")")
if mQuery1 then
outputChatBox("[GATEMANAGER] Sucessfully added gate!", thePlayer, 0,255,0)
local hiddenAdmin = getElementData(thePlayer, "hiddenadmin")
local adminTitle = exports.mrp_global:getPlayerAdminTitle(thePlayer)
--delOneGate(smallestID)
loadOneGate(smallestID)
getAllGates(thePlayer, "gates")
else
outputChatBox("[GATEMANAGER] Failed to add gate. Please check the inputs again.", thePlayer, 255,0,0)
end
end
addEvent("addGate", true)
addEventHandler("addGate", getRootElement(), addGate)
function saveGate(thePlayer, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25)
local mQuery1 = nil
if not a23 then
a23 = false
else
a23 = tostring(a23)
if string.len(a23) < 2 then
a23 = false
elseif a23 == "none" then
a23 = false
else
a23 = (a23)
end
end
if not tonumber(a24) then
a24 = false
else
a24 = (tostring(a24))
end
if not tonumber(a25) then
a25 = false
else
a25 = (tostring(a25))
end
mQuery1 = dbExec(mysql:getConnection(), "UPDATE `gates` SET `objectID` = '".. (a1) .."', `startX` = '".. (a2) .."', `startY` = '".. (a3) .."', `startZ` = '".. (a4) .."', `startRX` = '".. (a5) .."', `startRY` = '".. (a6) .."', `startRZ` = '".. (a7) .."', `endX` = '".. (a8) .."', `endY` = '".. (a9) .."', `endZ` = '".. (a10) .."', `endRX` = '".. (a11) .."', `endRY` = '".. (a12) .."', `endRZ`= '".. (a13) .."', `gateType` = '".. (a14) .."', `gateSecurityParameters`= '".. (a15) .."', `autocloseTime` = '".. (a16) .."', `movementTime` = '".. (a17) .."', `objectInterior` = '".. (a18) .."', `objectDimension` = '".. (a19) .."', `creator` = '".. (a20) .."', `adminNote` = '".. (a21) .."', `sound` = "..(a23 and "'"..a23.."'" or "NULL")..", `triggerDistance` = "..(a24 and "'"..a24.."'" or "NULL")..", `triggerDistanceVehicle` = "..(a25 and "'"..a25.."'" or "NULL").." WHERE `id` = '".. (a22) .."'")
if mQuery1 then
outputChatBox("[GATEMANAGER] Sucessfully saved gate!", thePlayer, 0,255,0)
resetGateSound(theGate)
local hiddenAdmin = getElementData(thePlayer, "hiddenadmin")
local adminTitle = exports.mrp_global:getPlayerAdminTitle(thePlayer)
delOneGate(tonumber(a22))
loadOneGate(tonumber(a22))
getAllGates(thePlayer, "gates")
else
outputChatBox("[GATEMANAGER] Failed to modify gate. Please check the inputs again.", thePlayer, 255,0,0)
end
end
addEvent("saveGate", true)
addEventHandler("saveGate", getRootElement(), saveGate)
function delGate(thePlayer, commandName, gateID)
if exports.mrp_integration:isPlayerAdmin(thePlayer) or exports.mrp_integration:isPlayerScripter(thePlayer) then
if not tonumber(gateID) then
outputChatBox("SYNTAX: /" .. commandName .. " [Gate ID]", thePlayer, 255, 194, 14)
else
local mQuery1 = nil
mQuery1 = dbExec(mysql:getConnection(), "DELETE FROM `gates` WHERE `id` = '".. (gateID) .."'")
if mQuery1 then
outputChatBox("[GATEMANAGER] Sucessfully deleted gate!", thePlayer, 0,255,0)
local hiddenAdmin = getElementData(thePlayer, "hiddenadmin")
local adminTitle = exports.mrp_global:getPlayerAdminTitle(thePlayer)
delOneGate(tonumber(gateID))
if string.lower(commandName) ~= "delgate" then
getAllGates(thePlayer, "gates")
end
else
outputChatBox("[GATEMANAGER] Gate doesn't exist.", thePlayer, 255,0,0)
end
end
end
end
addEvent("delGate", true)
addEventHandler("delGate", getRootElement(), delGate)
addCommandHandler("delgate",delGate)
function reloadGates(thePlayer)
local hiddenAdmin = getElementData(thePlayer, "hiddenadmin")
local adminTitle = exports.mrp_global:getPlayerAdminTitle(thePlayer)
local theResource = getThisResource()
if restartResource(theResource) then
outputChatBox("[GATEMANAGER] All gates have been reloaded successfully!", thePlayer, 0, 255, 0)
if hiddenAdmin == 0 then
exports.mrp_global:sendMessageToAdmins("[GATEMANAGER]: "..adminTitle.." ".. getPlayerName(thePlayer):gsub("_", " ") .. " has reloaded all gates.")
else
exports.mrp_global:sendMessageToAdmins("[GATEMANAGER]: A hidden admin has has reloaded all gates.")
end
--getAllGates(thePlayer, "gates")
else
outputChatBox("[GATEMANAGER]: Error! Failed to restart resource. Please notify scripters!", thePlayer, 255, 0, 0)
end
end
addEvent("reloadGates", true)
addEventHandler("reloadGates", getRootElement(), reloadGates)
function gotoGate(thePlayer, commandName, gateID, x, y, z , rot, int, dim)
if exports.mrp_integration:isPlayerAdmin(thePlayer) or exports.mrp_integration:isPlayerScripter(thePlayer) then
if not tonumber(gateID) then
outputChatBox("SYNTAX: /" .. commandName .. " [Gate ID]", thePlayer, 255, 194, 14)
else
local gateID1, x1, y1, z1, rot1, int1, dim1 = nil
if not tonumber(dim) then
dbQuery(
function(qh, thePlayer)
local res, rows, err = dbPoll(qh, 0)
if rows > 0 then
for index, row in ipairs(res) do
x1 = row["startX"]
y1 = row["startY"]
z1 = row["startZ"]
rot1 = row["startRX"]
int1 = row["objectInterior"]
dim1 = row["objectDimension"]
startGoingToGate(thePlayer, x1,y1,z1,rot1,int1,dim1, gateID)
end
else
outputChatBox("[GATEMANAGER]: Gate doesn't exist.", thePlayer, 255, 0, 0)
end
end,
{thePlayer}, mysql:getConnection(), "SELECT `startX` , `startY`, `startZ` , `startRX`, `objectInterior`, `objectDimension` FROM `gates` WHERE `id` = '".. (gateID) .."'")
else
--To be continued.
end
end
end
end
addEvent("gotoGate", true)
addEventHandler("gotoGate", getRootElement(), gotoGate)
addCommandHandler("gotogate", gotoGate)
function startGoingToGate(thePlayer, x,y,z,r,interior,dimension,gateID)
-- Maths calculations to stop the player being stuck in the target
x = x + ( ( math.cos ( math.rad ( r ) ) ) * 2 )
y = y + ( ( math.sin ( math.rad ( r ) ) ) * 2 )
setCameraInterior(thePlayer, interior)
if (isPedInVehicle(thePlayer)) then
local veh = getPedOccupiedVehicle(thePlayer)
setElementAngularVelocity(veh, 0, 0, 0)
setElementInterior(thePlayer, interior)
setElementDimension(thePlayer, dimension)
setElementInterior(veh, interior)
setElementDimension(veh, dimension)
setElementPosition(veh, x, y, z + 1)
warpPedIntoVehicle ( thePlayer, veh )
setTimer(setElementAngularVelocity, 50, 20, veh, 0, 0, 0)
else
setElementPosition(thePlayer, x, y, z)
setElementInterior(thePlayer, interior)
setElementDimension(thePlayer, dimension)
end
outputChatBox(" You have teleported to gate ID#"..gateID, thePlayer)
end
function getNearByGates(thePlayer, commandName)
if not (exports.mrp_integration:isPlayerAdmin(thePlayer) or exports.mrp_integration:isPlayerScripter(thePlayer)) then
outputChatBox("Only Super Admin and above can access /"..commandName..".",thePlayer, 255,0,0)
return false
end
local posX, posY, posZ = getElementPosition(thePlayer)
outputChatBox("Nearby Gates:", thePlayer, 255, 126, 0)
local count = 0
local dimension = getElementDimension(thePlayer)
for k, theGate in ipairs(getElementsByType("object", getResourceRootElement(getThisResource()))) do
local x, y = getElementPosition(theGate)
local distance = getDistanceBetweenPoints2D(posX, posY, x, y)
local cdimension = getElementDimension(theGate)
if (distance<=10) and (dimension==cdimension) then
local dbid = tonumber(getElementData(theGate, "gate:id"))
local desc = getElementData(theGate, "gate:desc") or "No Description"
outputChatBox(" Gate ID #" .. dbid .. " - "..desc, thePlayer, 255, 126, 0)
count = count + 1
end
end
if (count==0) then
outputChatBox(" None.", thePlayer, 255, 126, 0)
end
--[[
if not tonumber(gateID) then
outputChatBox("SYNTAX: /" .. commandName .. " [Gate ID]", thePlayer, 255, 194, 14)
end
gateID = math.floor(tonumber(gateID))
local targetGate = nil
for key, value in ipairs(getElementsByType("object", getResourceRootElement(getThisResource()))) do
if tonumber(getElementData(value, "gate:id")) == gateID then
targetGate = value
break
end
end
if targetGate then
destroyElement(targetGate)
end]]
end
addCommandHandler("nearbygates", getNearByGates)
function delOneGate(gateID)
local theGate = getGateElementFromID(gateID)
if theGate then
resetGateSound(theGate)
destroyElement(theGate)
end
end
function getGateElementFromID(id)
id = tonumber(id)
if not id then return false end
for k, theGate in ipairs(getElementsByType("object", getResourceRootElement(getThisResource()))) do
local dbid = tonumber(getElementData(theGate, "gate:id"))
if(dbid == id) then
return theGate
end
end
return false
end |
object_mobile_naboo_peacewar_drenn = object_mobile_shared_naboo_peacewar_drenn:new {
}
ObjectTemplates:addTemplate(object_mobile_naboo_peacewar_drenn, "object/mobile/naboo_peacewar_drenn.iff")
|
include("shared.lua")
--------------------------------------------------------------------------------
ENT.ClientProps = {}
ENT.ButtonMap = {}
-----
-- ALS Panel
-----
ENT.ButtonMap["ARSPanel"] = {
pos = Vector(463.08,-52.68,28.05),
ang = Angle(0,-90-29,90),
width = 38,
height = 240,
scale = 0.0625,
buttons = {
{ID = "L80", x=20, y=24+39.5*0, radius = 15, tooltip="80: Ограничение скорости 80 км/ч\nSpeed limit 80 kph"},
{ID = "L70", x=19, y=24+39.5*1, radius = 15, tooltip="70: Ограничение скорости 70 км/ч\nSpeed limit 70 kph"},
{ID = "L60", x=18, y=24+39.5*2, radius = 15, tooltip="60: Ограничение скорости 60 км/ч\nSpeed limit 60 kph"},
{ID = "L40", x=18, y=24+39.5*3, radius = 15, tooltip="40: Ограничение скорости 40 км/ч\nSpeed limit 40 kph"},
{ID = "L0", x=18, y=24+39.5*4, radius = 15,tooltip="0: Ограничение скорости 0 км/ч\nSpeed limit 0 kph"},
{ID = "LNF", x=18, y=24+39.5*5, radius = 15, tooltip="НЧ: Отсутствие частоты АРС\nNCh: No ARS frequency"},
}
}
for k,v in pairs(ENT.ButtonMap["ARSPanel"].buttons) do
Metrostroi.ClientPropForButton(v.ID,{
panel = "ARSPanel",
button = v.ID,
model = "models/metrostroi_train/em/ars_"..v.ID:sub(2,-1)..".mdl",
z = -4,
ang = 90,
staylabel = true,
})
end
-- Main panel
ENT.ButtonMap["Main"] = {
pos = Vector(459.7,-31.9,-0.69),
ang = Angle(0,-90,90-26),
width = 315,
height = 240,
scale = 0.0588,
buttons = {
{ID = "KVTSet", x=44, y=52, radius=27, tooltip="КБ: Кнопка Бдительности\nKB: Attention button"},
{ID = "ARSLamp", x=88.9, y=54.6, radius=15, tooltip="АРС: Лампа торможения АРС\nARS: ARS brake lamp"},
{ID = "VZPToggle", x=36+47*2, y=56+58*0, radius=20, tooltip="Выключатель задержки поезда"},
{ID = "VZDSet", x=35+47*3, y=55+58*0, radius=20, tooltip="Выключатель задержки дверей"},
{ID = "AutodriveLamp", x=220.7, y=54.5, radius=15, tooltip="Автоведение: Лампа хода от автоведения\nAutodrive: Autodrive drive lamp"},
{ID = "KRZDSet", x=269, y=56, radius=20, tooltip="КУ10: Кнопка резервного закрытия дверей\nKRZD: Emergency door closing"},
{ID = "KDLSet", x=33, y=56+58*1, radius=20, tooltip="КУ12: Кнопка левых дверей\nKDL: Left doors open"},
{ID = "DIPonSet", x=33+47*1, y=56+58*1, radius=20, tooltip="КУ4:Включение освещения\nTurn interior lights on"},
{ID = "DIPoffSet", x=33+47*2, y=56+58*1, radius=20, tooltip="КУ5:Отключение освещения\nTurn interior lights off"},
{ID = "VozvratRPSet", x=33+47*3, y=56+58*1, radius=20, tooltip="КУ9:Возврат РП\nReset overload relay"},
{ID = "KSNSet", x=33+47*4, y=56+58*1, radius=20, tooltip="КУ8:Принудительное срабатывание РП на неисправном вагоне (сигнализация неисправности)\nKSN: Failure indication button"},
{ID = "KDPSet", x=33+47*5, y=56+58*1, radius=20, tooltip="КДП:Правые двери\nKDP: Right doors open"},
----Down Panel
{ID = "KU1Toggle", x=21,y=138,w=45,h=71, tooltip="КУ1:Включение мотор-компрессора\nTurn motor-compressor on"},
{ID = "KTLamp", x=79.8, y=178.5, radius=15, tooltip="КТ: Контроль тормоза(торможение эффективно)\nKT: Brake control(efficient brakes)"},
{ID = "RingSet", x=116.9, y=176, radius=20, tooltip="Звонок передачи управления\nControl transfer ring"},
{ID = "VUSToggle", x=153,y=180,radius=10, tooltip="Дальний свет\nDistant light"},
{ID = "KAKSet", x=189.2,y=176.8,radius=20, tooltip="АК: Аварийная кнопка(Х3 при резервном управлении)\nAK: Emergency button(X3 with emergency control)"},
{ID = "VAutodriveToggle", x=226,y=180,radius=10, tooltip="Включение автоведения\nAutodrive enable"},
{ID = "VUD1Toggle", x=237.7,y=138,w=45,h=70, tooltip="КУ2: Закрытие дверей\nKU2: Door control toggle (close doors)"},
}
}
Metrostroi.ClientPropForButton("DIPon",{
panel = "Main",
button = "DIPonSet",
model = "models/metrostroi_train/em/buttonblack.mdl",
ang = 90,
z = 0,
})
Metrostroi.ClientPropForButton("VozvratRP",{
panel = "Main",
button = "VozvratRPSet",
model = "models/metrostroi_train/em/buttonblack.mdl",
ang = 90,
z = 0,
})
Metrostroi.ClientPropForButton("ARSLamp",{
panel = "Main",
button = "ARSLamp",
model = "models/metrostroi_train/Em/LampPult.mdl",
z=3,
staylabel = true,
})
Metrostroi.ClientPropForButton("VZP",{
panel = "Main",
button = "VZPToggle",
model = "models/metrostroi_train/81/tumbler4.mdl",
ang = 90,
})
Metrostroi.ClientPropForButton("VZD",{
panel = "Main",
button = "VZDSet",
model = "models/metrostroi_train/em/buttonblack.mdl",
ang = 90,
z = 0,
})
Metrostroi.ClientPropForButton("AutodriveLamp",{
panel = "Main",
button = "AutodriveLamp",
model = "models/metrostroi_train/Em/LampPult.mdl",
z=3,
staylabel = true,
})
Metrostroi.ClientPropForButton("KVT",{
panel = "Main",
button = "KVTSet",
model = "models/metrostroi_train/em/buttonbig.mdl",
ang = 90,
z = 0,
})
Metrostroi.ClientPropForButton("DIPoff",{
panel = "Main",
button = "DIPoffSet",
model = "models/metrostroi_train/em/buttonred.mdl",
ang = 90,
z = 0,
})
Metrostroi.ClientPropForButton("KSN",{
panel = "Main",
button = "KSNSet",
model = "models/metrostroi_train/em/buttonred.mdl",
ang = 90,
z = 0,
})
Metrostroi.ClientPropForButton("KDP",{
panel = "Main",
button = "KDPSet",
model = "models/metrostroi_train/em/buttonred.mdl",
ang = 90,
z = 0,
})
Metrostroi.ClientPropForButton("KDL",{
panel = "Main",
button = "KDLSet",
model = "models/metrostroi_train/em/buttonred.mdl",
ang = 90,
z = 0,
})
Metrostroi.ClientPropForButton("KRZD",{
panel = "Main",
button = "KRZDSet",
model = "models/metrostroi_train/em/buttonblack.mdl",
ang = 90,
z = 0,
})
Metrostroi.ClientPropForButton("VUD",{
panel = "Main",
button = "VUD1Toggle",
model = "models/metrostroi_train/switches/vudwhite.mdl",
z=-23,
})
Metrostroi.ClientPropForButton("KU1",{
panel = "Main",
button = "KU1Toggle",
model = "models/metrostroi_train/switches/vudbrown.mdl",
z=-23,
})
Metrostroi.ClientPropForButton("KTLamp",{
panel = "Main",
button = "KTLamp",
model = "models/metrostroi_train/Em/LampPult.mdl",
z=3,
staylabel = true,
})
Metrostroi.ClientPropForButton("VAutodrive",{
panel = "Main",
button = "VAutodriveToggle",
model = "models/metrostroi_train/81/tumbler4.mdl",
ang = 90,
})
--RRP
Metrostroi.ClientPropForButton("KAK",{
panel = "Main",
button = "KAKSet",
model = "models/metrostroi_train/em/buttonred.mdl",
ang = 0,
z = 0,
})
Metrostroi.ClientPropForButton("Ring",{
panel = "Main",
button = "RingSet",
model = "models/metrostroi_train/em/buttonred.mdl",
ang = 0,
z = 0,
})
--VUSToggle
Metrostroi.ClientPropForButton("VUS",{
panel = "Main",
button = "VUSToggle",
model = "models/metrostroi_train/81/tumbler4.mdl",
ang = 90,
})
--Lamps
ENT.ButtonMap["Lamps"] = {
pos = Vector(464.42,-21.07,28.65),
ang = Angle(0,-13.5,90),
width = 24,
height = 310,
scale = 0.0625,
buttons = {
{ID = "LampAutodrive", x=12.6, y=16, radius=10, tooltip="Включение автоведения\nAutodrive enabled q"},
{ID = "Lamp2", x=12.6, y=15.8 + 38*1, radius=10, tooltip="2: Лампа второго провода (ход реостатного контроллера)\n2: 2nd train wire lamp(rheostat controller motion)"},
{ID = "Lamp1", x=12.6, y=18.2 + 38*2, radius=10, tooltip="1: Лампа первого провода (включение двигателей)\n1: 1st train wire lamp(engines engaged)"},
{ID = "Lamp6", x=12.6, y=19 + 38*3, radius=10, tooltip="6: Лампа шестого провода (сигнализация торможения)\n6: 6th train wire lamp(brakes engaged)"},
{ID = "DoorsWag", x=12.6, y=22 + 38*4, radius=10, tooltip="Двери вагона: Лампа проверки РД при вклюёчнном КСД\nWagon doors: RD check lamp with enabled KSD"},
{ID = "Doors", x=12.6, y=24.7 + 38*5, radius=10, tooltip="Двери: Сигнализация дверей\nDoors: Door state light (doors are closed)"},
{ID = "GreenRP", x=12.6, y=25.4 + 38*6, radius=10, tooltip="РП вагона: Лампа реле перегрузки вагона (Сигнализация перегрузки)\nWagon RP: Wagon overload relay light (overload relay open on current train)"},
{ID = "RedRP", x=12.6, y=27.8 + 38*7, radius=10, tooltip="РП поезда: Лампа реле перегрузки\nTrain RP: Overload relay light (power circuits failed to assemble)"},
}
}
local i=1
for k,v in pairs(ENT.ButtonMap["Lamps"].buttons) do
Metrostroi.ClientPropForButton(v.ID,{
panel = "Lamps",
button = v.ID,
model = "models/metrostroi_train/em/lamp"..i..".mdl",
staylabel = true,
})
i = i + 1
end
--Lamps
ENT.ButtonMap["Lamps2"] = {
pos = Vector(466.38,-19.33,28.65),
ang = Angle(0,180-13.5,90),
width = 24,
height = 310,
scale = 0.0625,
buttons = {
{ID = "LampAutodrive", x=12, y=16, radius=10, tooltip="Включение автоведения\nAutodrive enabled q"},
{ID = "Lamp2", x=12, y=15.8 + 38*1, radius=10, tooltip="2: Лампа второго провода (ход реостатного контроллера)\n2: 2nd train wire lamp(rheostat controller motion)"},
{ID = "Lamp1", x=12, y=18.2 + 38*2, radius=10, tooltip="1: Лампа первого провода (включение двигателей)\n1: 1st train wire lamp(engines engaged)"},
{ID = "Lamp6", x=12, y=19 + 38*3, radius=10, tooltip="6: Лампа шестого провода (сигнализация торможения)\n6: 6th train wire lamp(brakes engaged)"},
{ID = "DoorsWag", x=12, y=22 + 38*4, radius=10, tooltip="Двери вагона: Лампа проверки РД при вклюёчнном КСД\nWagon doors: RD check lamp with enabled KSD"},
{ID = "Doors", x=12, y=24.7 + 38*5, radius=10, tooltip="Двери: Сигнализация дверей\nDoors: Door state light (doors are closed)"},
{ID = "GreenRP", x=12, y=25.4 + 38*6, radius=10, tooltip="РП вагона: Лампа реле перегрузки вагона (Сигнализация перегрузки)\nWagon RP: Wagon overload relay light (overload relay open on current train)"},
{ID = "RedRP", x=12, y=27.8 + 38*7, radius=10, tooltip="РП поезда: Лампа реле перегрузки\nTrain RP: Overload relay light (power circuits failed to assemble)"},
}
}
local i=1
for k,v in pairs(ENT.ButtonMap["Lamps2"].buttons) do
Metrostroi.ClientPropForButton(v.ID.."_p",{
panel = "Lamps2",
button = v.ID,
model = "models/metrostroi_train/em/lamp"..i..".mdl",
z=-2.5,
staylabel = true,
})
i = i + 1
end
ENT.ButtonMap["RezMK"] = {
pos = Vector(469.0,-20.75,37),
ang = Angle(0,270,90),
width = 50,
height = 80,
scale = 0.0625,
buttons = {
{ID = "RezMKSet", x=0, y=0, w=50, h=80, tooltip="КУ15:Резервное включение мотор-компрессора\nRezMKSet"},
}
}
Metrostroi.ClientPropForButton("RezMK",{
panel = "RezMK",
button = "RezMKSet",
model = "models/metrostroi_train/switches/vudblack.mdl",
})
ENT.ButtonMap["AVMain"] = {
pos = Vector(408.06,40.8,56),
ang = Angle(0,90,90),
width = 335,
height = 380,
scale = 0.0625,
buttons = {
{ID = "AV8BToggle", x=0, y=0, w=300, h=380, tooltip="АВ-8Б: Автоматическй выключатель (Вспомогательные цепи высокого напряжения)\n"},
}
}
Metrostroi.ClientPropForButton("AV8B",{
panel = "AVMain",
button = "AV8BToggle",
model = "models/metrostroi_train/switches/automain.mdl",
z=43,
})
ENT.ButtonMap["Tsepi"] = {
pos = Vector(408.89,36.38,30.3),
ang = Angle(0,90,90),
width = 67,
height = 50,
scale = 0.0625,
buttons = {
--{ID = "VUSToggle", x=0, y=0, w=100, h=110, tooltip="Прожектор\nVUSoggle"},
{x=0,y=0,w=67,h=50,tooltip="Напряжение цепей управления"},
}
}
---AV1 Panel
ENT.ButtonMap["AV1"] = {
pos = Vector(408.06,41,30),
ang = Angle(0,90,90),
width = 290+0,
height = 155,
scale = 0.0625,
buttons = {
{ID = "VU3Toggle", x=0, y=0, w=100, h=140, tooltip="ВУ3: Освещение кабины\n"},
{ID = "VU2Toggle", x=100, y=0, w=100, h=140, tooltip="ВУ2: Аварийное освещение 25В\n"},
{ID = "VU1Toggle", x=200, y=0, w=100, h=140, tooltip="ВУ1: Печь отопления кабины ПТ-6\n"},
}
}
for k,v in pairs(ENT.ButtonMap["AV1"].buttons) do
if not v.ID then continue end
Metrostroi.ClientPropForButton(v.ID:sub(0,-7),{
panel = "AV1",
button = v.ID,
model = "models/metrostroi_train/switches/autobl.mdl",
z=10,
})
end
ENT.ButtonMap["AV2"] = {
pos = Vector(408.06,22.40,44.1),
ang = Angle(0,90,90),
width = 180,
height = 136,
scale = 0.0625,
buttons = {
{ID = "RSTToggle", x=0, y=0, w=90, h=136, tooltip="РСТ: Радиооповещение и поездная радио связь\nRST: Radio"},
{ID = "RSTPl", x=0, y=80, w=90, h=56, tooltip="Пломба РСТ\nRST plomb"},
{ID = "VSOSDToggle", x=90, y=0, w=90, h=136, tooltip="СОСД: Включение СОСД(светильник для горлифта)\nSOSD: SOSD enabler(horligt light)"},
}
}
for k,v in pairs(ENT.ButtonMap["AV2"].buttons) do
if not v.ID then continue end
if v.ID:find("Pl") then
Metrostroi.ClientPropForButton(v.ID,{
panel = "AV2",
button = v.ID:Replace("Pl","Toggle"),
model = "models/metrostroi_train/switches/autoplombl.mdl",
z=19,
propname = false,
ang=0,
})
continue
end
Metrostroi.ClientPropForButton(v.ID:sub(0,-7),{
panel = "AV2",
button = v.ID,
model = "models/metrostroi_train/switches/autobl.mdl",
z=20,
})
end
-- AV panel
ENT.ButtonMap["AV"] = {
pos = Vector(408.16,-58.2,35.5),
ang = Angle(0,90,90),
width = 85*7,
height = 130,
scale = 0.0625,
buttons = {
{ID = "VRUToggle",x=85*0,y=0,w=85,h=130 , tooltip="ВРУ: Выключатель резервного управления\nVRU: Emergency control enable"},
{ID = "VAHToggle",x=85*1,y=0,w=85,h=130 , tooltip="КАХ: Включение аварийного хода (неисправность реле педали безопасности)\nКAH: Emergency driving mode (failure of RPB relay)"},
{ID = "VAHPl",x=85*1,y=80,w=85,h=50 , tooltip="Пломба КАХ\nKAH plomb"},
{ID = "VADToggle",x=85*2,y=0,w=85,h=130 , tooltip="КАД: Включение аварийного закрытия дверей (неисправность реле контроля дверей)\nKAD: Emergency door close override (failure of KD relay)"},
{ID = "VADPl",x=85*2,y=80,w=85,h=50 , tooltip="Пломба КАД\nKAD plomb"},
{ID = "OVTToggle",x=85*3,y=0,w=85,h=130 , tooltip="ОВТ: Отключение вентильных тормозов\nOVT: Pneumatic valves disabler"},
{ID = "OVTPl",x=85*3,y=80,w=85,h=50 , tooltip="Пломба ОВТ\nOVT plomb"},
{ID = "KSDToggle",x=85*4,y=0,w=85,h=130 , tooltip="КСД: Контроль сигнализации дверей(проверка СД)\nKSD: Door state controle(SD check)"},
{ID = "DPToggle",x=85*5,y=0,w=85,h=130 , tooltip="ДП: Двери поезда\nDP: Train doors"},
{ID = "VKFToggle",x=85*6,y=0,w=85,h=130 , tooltip="ВКФ: Выключатель красных фар(подключает КФ к батарее напрямую)\nVKF: Red lights enable(connect a red lights to battery)"},
}
}
for k,v in pairs(ENT.ButtonMap["AV"].buttons) do
if not v.ID then continue end
if v.ID:find("Pl") then
Metrostroi.ClientPropForButton(v.ID,{
panel = "AV",
button = v.ID:Replace("Pl","Toggle"),
model = "models/metrostroi_train/switches/autoplomb"..(v.ID:find("OVT") and "l" or "r")..".mdl",
z=14,
propname = false,
ang=0,
})
continue
end
Metrostroi.ClientPropForButton(v.ID:sub(0,-7),{
panel = "AV",
button = v.ID,
model = "models/metrostroi_train/switches/autobl.mdl",
z=15,
})
end
-- Battery panel
ENT.ButtonMap["Battery"] = {
pos = Vector(408.98,20.24,30.5),
ang = Angle(0,90,90),
width = 250,
height = 136,
scale = 0.0625,
buttons = {
{ID = "VBToggle", x=0, y=0, w=250, h=136, tooltip="АБ: Выключатель аккумуляторной батареи (Вспомогательные цепи низкого напряжения)\nVB: Battery on/off"},
}
}
Metrostroi.ClientPropForButton("VB",{
panel = "Battery",
button = "VBToggle",
model = "models/metrostroi_train/switches/autobl2.mdl",
z=15,
})
--VU Panel
ENT.ButtonMap["VU"] = {
pos = Vector(469.5,-17.5,45),
ang = Angle(0,270,90),
width = 100,
height = 140,
scale = 0.0625,
buttons = {
{ID = "VUToggle", x=0, y=0, w=100, h=140, tooltip="ВУ: Выключатель Управления\nVUToggle"},
}
}
Metrostroi.ClientPropForButton("VU",{
panel = "VU",
button = "VUToggle",
model = "models/metrostroi_train/switches/autobl.mdl",
z=20,
})
ENT.ButtonMap["VRD"] = {
pos = Vector(408.06,35.24,22),
ang = Angle(0,90,90),
width = 100,
height = 140,
scale = 0.0625,
buttons = {
{ID = "VRDToggle", x=0, y=0, w=100, h=140, tooltip="ВРД: Выключатель разрешающий движение(под 0)\nVRD: Accept moving(when 0 on ALS)"},
}
}
Metrostroi.ClientPropForButton("VRD",{
panel = "VRD",
button = "VRDToggle",
model = "models/metrostroi_train/switches/autobl.mdl",
z=20,
})
ENT.ButtonMap["BatteryAV"] = {
pos = Vector(409.55,-50.1,12.25),
ang = Angle(0,90,90),
width = 250,
height = 136,
scale = 0.0625,
buttons = {
{ID = "VBAToggle", x=0, y=0, w=250, h=136, tooltip="АБ: Выключатель аккумуляторной батареи автоведения(Включение АРС)(\nVBA: Autodrive battery on/off(ARS Enable)"},
}
}
Metrostroi.ClientPropForButton("VBA",{
panel = "BatteryAV",
button = "VBAToggle",
model = "models/metrostroi_train/switches/autobl2.mdl",
z=15,
})
ENT.ButtonMap["RC"] = {
pos = Vector(412.07,-28.72,22.80),
ang = Angle(0,90,90),
width = 127,
height = 473,
scale = 0.0625,
buttons = {
{ID = "RC2Toggle", x=0, y=0, w=127, h=213, tooltip="RC2"},
{ID = "RC2Pl", x=0, y=213-213/4, w=127, h=213/4, tooltip="Пломба РЦ-2\nRC-2 plomb"},
{ID = "RC1Toggle", x=0, y=473-213, w=127, h=213, tooltip="RC1"},
{ID = "RC1Pl", x=0, y=473-213/4, w=127, h=213/4, tooltip="Пломба РЦ-1\nRC-1 plomb"},
}
}
ENT.ClientProps["RC2"] = {
model = "models/metrostroi_train/em/rc.mdl",
pos = Vector(409.77,-24.81,9.73+2),
ang = Angle(0,-90-55,0)
}
ENT.ClientProps["RC2Pl"] = {
model = "models/metrostroi_train/switches/autoplombr.mdl",
pos = Vector(411.143951,-22.746609,11.376095),
ang = Angle(0.000000,90.000000,90.000000),
}
ENT.ClientProps["RC1"] = {
model = "models/metrostroi_train/em/rc.mdl",
pos = Vector(409.77,-24.81,-6.72+2),
ang = Angle(0,-90-55,0)
}
ENT.ClientProps["RC1Pl"] = {
model = "models/metrostroi_train/switches/autoplombr.mdl",
pos = Vector(411.143951,-22.746609,-5.308110),
ang = Angle(0.000000,90.000000,90.000000),
}
--[[
Metrostroi.ClientPropForButton("AVVB",{
panel = "BatteryAV",
button = "AVVBToggle",
model = "models/metrostroi_train/switches/autobl2.mdl",
z=15,
})
]]
-- Parking brake panel
ENT.ButtonMap["ParkingBrake"] = {
pos = Vector(460,49.0,6.0),
ang = Angle(0,-82,90),
width = 400,
height = 400,
scale = 0.0625,
buttons = {
{ID = "ParkingBrakeLeft",x=0, y=0, w=200, h=400, tooltip="Поворот колеса ручного тормоза"},
{ID = "ParkingBrakeRight",x=200, y=0, w=200, h=400, tooltip="Поворот колеса ручного тормоза"},
}
}
-- Train driver helpers panel
ENT.ButtonMap["HelperPanel"] = {
pos = Vector(455.13,58.99,24.44),
ang = Angle(0,-17.5,90),
width = 60,
height = 188,
scale = 0.0625,
buttons = {
{ID = "VDLSet", x=30, y=42, radius=30, tooltip="ВДЛ: Выключатель левых дверей\nVDL: Left doors open"},
{ID = "VUD2LToggle", x=0, y=110, w=60,h=20, tooltip="Блокировка ВУД2\nVUD2 lock"},
{ID = "VUD2Toggle", x=30, y=138, radius=30, tooltip="ВУД2: Выключатель управления дверьми\nVUD2: Door control toggle (close doors)"},
}
}
Metrostroi.ClientPropForButton("VUD2",{
panel = "HelperPanel",
button = "VUD2Toggle",
model = "models/metrostroi_train/switches/vudwhite.mdl",
z = 0,
})
Metrostroi.ClientPropForButton("VUD2l",{
panel = "HelperPanel",
button = "VUD2Toggle",
model = "models/metrostroi_train/switches/vudlock.mdl",
z = 0,
})
Metrostroi.ClientPropForButton("VDL",{
panel = "HelperPanel",
button = "VDLSet",
model = "models/metrostroi_train/switches/vudblack.mdl",
z = 0,
})
-- Help panel
ENT.ButtonMap["Help"] = {
pos = Vector(422,-41,66),
ang = Angle(0,90,90),
width = 28,
height = 20,
scale = 0.5,
buttons = {
{ID = "ShowHelp", x=0, y=0, w=28,h=20, tooltip="Помощь в вождении поезда\nShow help on driving the train"},
}
}
-- Pneumatic instrument panel 2
ENT.ButtonMap["PneumaticManometer"] = {
pos = Vector(459.247131,-54.307846,16.197767),
ang = Angle(0,-90-51,90),
width = 70,
height = 70,
scale = 0.0625,
buttons = {
{x=35,y=35,radius=35,tooltip="Давление в магистралях (красная: тормозной, чёрная: напорной)\nPressure in pneumatic lines (red: brake line, black: train line)"},
}
}
-- Pneumatic instrument panel
ENT.ButtonMap["PneumaticPanels"] = {
pos = Vector(463.281189,-53.228256,11.310288),
ang = Angle(0,-90-44,90),
width = 70,
height = 70,
scale = 0.0625,
buttons = {
{x=35,y=35,radius=35,tooltip="Тормозной манометр: Давление в тормозных цилиндрах (ТЦ)\nBrake cylinder pressure"},
}
}
ENT.ButtonMap["DriverValveBLDisconnect"] = {
pos = Vector(453.57,-54.37,-27.61),
ang = Angle(-90,0,0),
width = 200,
height = 90,
scale = 0.0625,
buttons = {
{ID = "DriverValveBLDisconnectToggle", x=0, y=0, w=200, h=90, tooltip="Кран двойной тяги тормозной магистрали\nTrain line disconnect valve"},
}
}
ENT.ButtonMap["DriverValveTLDisconnect"] = {
pos = Vector(455.482483,-54,-15),
ang = Angle(90,180-11.79,0),
width = 200,
height = 90,
scale = 0.0625,
buttons = {
{ID = "DriverValveTLDisconnectToggle", x=0, y=0, w=200, h=90, tooltip="Кран двойной тяги напорной магистрали\nBrake line disconnect valve"},
}
}
ENT.ButtonMap["EPKDisconnect"] = {
pos = Vector(449.35,-57.78,-25.65),
ang = Angle(0,90+56.59,0),
width = 200,
height = 90,
scale = 0.0625,
buttons = {
{ID = "EPKToggle", x=0, y=0, w=200, h=90, tooltip="Кран ЭПК\nEPK disconnect valve"},
}
}
ENT.ButtonMap["DURA"] = {
pos = Vector(408+15+12.15,-58.0-5.3,-6.65),
ang = Angle(0,180,0),
width = 240,
height = 80,
scale = 0.0625,
buttons = {
{ID = "DURASelectMain", x=145, y=43, radius=20, tooltip="DURA Основной путь\nDURA Select Main"}, -- NEEDS TRANSLATING
{ID = "DURASelectAlternate", x=180, y=43, radius=20, tooltip="DURA Альтернативный путь\nDURA Select Alternate"}, -- NEEDS TRANSLATING
{ID = "DURAToggleChannel", x=100, y=60, radius=20, tooltip="DURA Выбор канала\nDURA Toggle Channel"}, -- NEEDS TRANSLATING
{ID = "DURAPowerToggle", x=100, y=30, radius=20, tooltip="DURA Питание\nDURA Power"}, -- NEEDS TRANSLATING
}
}
ENT.ButtonMap["DURADisplay"] = {
pos = Vector(408+15-0.75+12.15,-58.0-5.3+1.5625,-6.65),
ang = Angle(0,180,0),
width = 240,
height = 80,
scale = 0.0625/3.2,
}
ENT.ButtonMap["Meters"] = {
pos = Vector(461.65213,-56.696617,37.528275),
ang = Angle(0,-148,90),
width = 73,
height = 140,
scale = 0.0625,
buttons = {
{x=13, y=22, w=60, h=50, tooltip="Вольтметр высокого напряжения (кВ)\nHV voltmeter (kV)"},
{x=13, y=81, w=60, h=50, tooltip="Амперметр (А)\nTotal ampermeter (A)"},
}
}
ENT.ButtonMap["Speedometer"] = {
pos = Vector(459.649109,-53.19582,26.624441),
ang = Angle(0,-149,97),
width = 110,
height = 110,
scale = 0.0625,
buttons = {
{x=0, y=0, w=110, h=110, tooltip="Скоростемер"},
}
}
--These values should be identical to those drawing the schedule
local col1w = 80 -- 1st Column width
local col2w = 32 -- The other column widths
local rowtall = 30 -- Row height, includes -only- the usable space and not any lines
local rowamount = 16 -- How many rows to show (total)
--[[ENT.ButtonMap["Schedule"] = {
pos = Vector(442.1,-60.7,26),
ang = Angle(0,-110,90),
width = (col1w + 2 + (1 + col2w) * 3),
height = (rowtall+1)*rowamount+1,
scale = 0.0625/2,
buttons = {
{x=1, y=1, w=col1w, h=rowtall, tooltip="М №\nRoute number"},
{x=1, y=rowtall*2+3, w=col1w, h=rowtall, tooltip="П №\nPath number"},
{x=col1w+2, y=1, w=col2w*3+2, h=rowtall, tooltip="ВРЕМЯ ХОДА\nTotal schedule time"},
{x=col1w+2, y=rowtall+2, w=col2w*3+2, h=rowtall, tooltip="ИНТ\nTrain interval"},
{x=col1w+2, y=rowtall*2+3, w=col2w, h=rowtall, tooltip="ЧАС\nHour"},
{x=col1w+col2w+3, y=rowtall*2+3, w=col2w, h=rowtall, tooltip="МИН\nMinute"},
{x=col1w+col2w*2+4, y=rowtall*2+3, w=col2w, h=rowtall, tooltip="СЕК\nSecond"},
{x=col1w+2, y=rowtall*3+4, w=col2w*3+2, h=(rowtall+1)*(rowamount-3)-1, tooltip="Arrival times"}, -- NEEDS TRANSLATING
{x=1, y=rowtall*3+4, w=col1w, h=(rowtall+1)*(rowamount-3)-1, tooltip="Station name"}, -- NEEDS TRANSLATING
}
}]]
-- Temporary panels (possibly temporary)
ENT.ButtonMap["FrontPneumatic"] = {
pos = Vector(475,-45.0,-50.0),
ang = Angle(0,90,90),
width = 900,
height = 100,
scale = 0.1,
buttons = {
{ID = "FrontBrakeLineIsolationToggle",x=150, y=50, radius=32, tooltip="Концевой кран тормозной магистрали"},
{ID = "FrontTrainLineIsolationToggle",x=750, y=50, radius=32, tooltip="Концевой кран напорной магистрали"},
}
}
ENT.ButtonMap["RearPneumatic"] = {
pos = Vector(-475,45.0,-50.0),
ang = Angle(0,270,90),
width = 900,
height = 100,
scale = 0.1,
buttons = {
{ID = "RearTrainLineIsolationToggle",x=150, y=50, radius=32, tooltip="Концевой кран напорной магистрали"},
{ID = "RearBrakeLineIsolationToggle",x=750, y=50, radius=32, tooltip="Концевой кран тормозной магистрали"},
}
}
ENT.ButtonMap["GV"] = {
pos = Vector(139,66,-54),
ang = Angle(0,180,90),
width = 170,
height = 170,
scale = 0.1,
buttons = {
{ID = "GVToggle",x=0, y=0, w= 170,h = 170, tooltip="Главный выключатель"},
}
}
ENT.ButtonMap["AirDistributor"] = {
pos = Vector(-168,68.6,-50),
ang = Angle(0,180,90),
width = 170,
height = 80,
scale = 0.1,
buttons = {
{ID = "AirDistributorDisconnectToggle",x=0, y=0, w= 170,h = 80, tooltip="Выключение воздухораспределителя"},
}
}
-- UAVA
ENT.ButtonMap["UAVAPanel"] = {
pos = Vector(450,52,-20),
ang = Angle(0,-70,90),
width = 230,
height = 170,
scale = 0.0625,
buttons = {
{ID = "UAVAToggle",x=230/2, y=0, w=230/2, h=170, tooltip="УАВА: Универсальный Автоматический Выключатель Автостопа\nUAVA: Universal Automatic Autostop Disabler"},
{ID = "UAVAContactSet",x=0, y=0, w=230/2, h=170, tooltip="УАВА: Универсальный Автоматический Выключатель Автостопа (восстановление контактов)\nUAVA: Universal Automatic Autostop Disabler(contacts reset)"},
}
}
-- Wagon numbers
ENT.ButtonMap["TrainNumber1"] = {
pos = Vector(-440,-68,-11),
ang = Angle(0,0,90),
width = 130,
height = 55,
scale = 0.20,
}
ENT.ButtonMap["TrainNumber2"] = {
pos = Vector(416,68,-11),
ang = Angle(0,180,90),
width = 130,
height = 55,
scale = 0.20,
}
ENT.ButtonMap["InfoTableSelect"] = {
pos = Vector(454.0+12.15,-27.0,50.0),
ang = Angle(0,-90,90),
width = 250,
height = 100,
scale = 0.1,
buttons = {
{ID = "PrevSign",x=0,y=0,w=50,h=100, tooltip="Предыдущая надпись\nPrevious sign"},
{ID = "NextSign",x=50,y=0,w=50,h=100, tooltip="Следующая надпись\nNext sign"},
{ID = "Num2P",x=150,y=0,w=50,h=50, tooltip="Маршрут: Увеличить число 2\nRoute: Increase 2nd number"},
{ID = "Num2M",x=150,y=50,w=50,h=50, tooltip="Маршрут: Уменьшить число 2\nRoute: Decrease 2nd number"},
{ID = "Num1P",x=200,y=0,w=50,h=50, tooltip="Маршрут: Увеличить число 1\nRoute: Increase 1st number"},
{ID = "Num1M",x=200,y=50,w=50,h=50, tooltip="Маршрут: Уменьшить число 1\nRoute: Decrease 1st number"},
}
}
ENT.ButtonMap["FrontDoor"] = {
pos = Vector(472,16,43.4),
ang = Angle(0,-90,90),
width = 650,
height = 1780,
scale = 0.1/2,
buttons = {
{ID = "FrontDoor",x=0,y=0,w=650,h=1780, tooltip="Передняя дверь\nFront door"},
}
}
ENT.ButtonMap["CabinDoor"] = {
pos = Vector(420,64,43.4),
ang = Angle(0,0,90),
width = 642,
height = 1780,
scale = 0.1/2,
buttons = {
{ID = "CabinDoor1",x=0,y=0,w=642,h=1780, tooltip="Дверь в кабину машиниста\nCabin door"},
}
}
ENT.ButtonMap["PassengerDoor"] = {
pos = Vector(384,-16,43.4),
ang = Angle(0,90,90),
width = 642,
height = 1900,
scale = 0.1/2,
buttons = {
{ID = "PassengerDoor",x=0,y=0,w=642,h=1900, tooltip="Дверь из салона\nPassenger door"},
}
}
--------------------------------------------------------------------------------
ENT.ClientPropsInitialized = false
ENT.ClientProps["brake"] = {
model = "models/metrostroi_train/81/334cran.mdl",
pos = Vector(460.11,-53.7,3.7),
ang = Angle(0,34,0)
}
ENT.ClientProps["controller"] = {
model = "models/metrostroi_train/em/kv.mdl",
pos = Vector(461.65,-24.63,3.9),
ang = Angle(0,-32,0)
}
ENT.ClientProps["reverser"] = {
model = "models/metrostroi/81-717/reverser.mdl",
pos = Vector(461.65,-24.63,3.2),
ang = Angle(0,45,90)
}
ENT.ClientProps["brake_disconnect"] = {
model = "models/metrostroi/81-717/uava.mdl",
pos = Vector(452.9,-57.33,-25.61),
ang = Angle(0,-90,0),
color = Color(144,74,0),
}
ENT.ClientProps["train_disconnect"] = {
model = "models/metrostroi/81-717/uava.mdl",
pos = Vector(455.482483,-52.546734,-19.333017),
ang = Angle(0.000000,-101.794258,0.000000),
color = Color(0,212,255),
}
ENT.ClientProps["EPK_disconnect"] = {
model = "models/metrostroi/81-717/uava.mdl",
pos = Vector(449.35,-52.78,-25.65),
ang = Angle(90,90+56.59,0),
}
ENT.ClientProps["parking_brake"] = {
model = "models/metrostroi/81-717/ezh_koleso.mdl",
pos = Vector(460.316742,37.144958,-6.000000),
ang = Angle(-90.000000,8.000000,0.000000),
}
--------------------------------------------------------------------------------
ENT.ClientProps["train_line"] = {
model = "models/metrostroi_train/e/small_pneumo_needle.mdl",
pos = Vector(457.722778,-56.060150,13.877457),
ang = Angle(314.669312,40.953403,-90.000000),
}
ENT.ClientProps["brake_line"] = {
model = "models/metrostroi_train/e/small_pneumo_needle.mdl",
pos = Vector(457.688568,-56.020660,13.877457),
ang = Angle(314.669312,40.953403,-90.000000),
color = Color(255,120,120),
}
ENT.ClientProps["brake_cylinder"] = {
model = "models/metrostroi_train/e/small_pneumo_needle.mdl",
pos = Vector(462.104797,-55.268986,9.050000),
ang = Angle(313.335266,48.532555,-90.000000),
}
----------------------------------------------------------------
ENT.ClientProps["voltmeter"] = {
model = "models/metrostroi_train/e/volt_needle.mdl",
pos = Vector(458.990723,-57.425472,33.847416),
ang = Angle(240.237274,33.392635,270.135559),
}
ENT.ClientProps["ampermeter"] = {
model = "models/metrostroi_train/e/volt_needle.mdl",
pos = Vector(459.078979,-57.376965,30.437996),
ang = Angle(222.645691,33.392635,270.135559),
}
ENT.ClientProps["volt1"] = {
model = "models/metrostroi_train/e/volt_bat_needle.mdl",
pos = Vector(408.890015,38.459042,27.399431),
ang = Angle(-46.365803,90.000000,90.000000),
}
ENT.ClientProps["speed1"] = {
model = "models/metrostroi_train/e/black_pneumo_needle.mdl",
pos = Vector(455.287048,-56.941986,21.128723),
ang = Angle(96.164711,120.947121,0.000000),
}
-----------------------------------------------
Metrostroi.ClientPropForButton("SelectMain",{
panel = "DURA",
button = "DURASelectMain",
model = "models/metrostroi_train/81/button.mdl",
skin = 4,
z = 0,
})
Metrostroi.ClientPropForButton("SelectAlternate",{
panel = "DURA",
button = "DURASelectAlternate",
model = "models/metrostroi_train/81/button.mdl",
skin = 4,
z = 0,
})
Metrostroi.ClientPropForButton("SelectChannel",{
panel = "DURA",
button = "DURAToggleChannel",
model = "models/metrostroi_train/81/tumbler2.mdl",
})
Metrostroi.ClientPropForButton("DURAPower",{
panel = "DURA",
button = "DURAPowerToggle",
model = "models/metrostroi_train/81/tumbler2.mdl",
})
--------------------------------------------------------------------------------
ENT.ClientProps["gv"] = {
model = "models/metrostroi/81-717/gv.mdl",
pos = Vector(130,62.5,-65),
ang = Angle(-90,0,-90)
}
ENT.ClientProps["gv_wrench"] = {
model = "models/metrostroi/81-717/reverser.mdl",
pos = Vector(130,62.5,-65),
ang = Angle(0,0,0)
}
--------------------------------------------------------------------------------
ENT.ClientProps["book"] = {
model = "models/props_lab/binderredlabel.mdl",
pos = Vector(418,-28,61),
ang = Angle(0,0,90)
}
ENT.ClientProps["Ema_salon"] = {
model = "models/metrostroi_train/em/ema_salon.mdl",
pos = Vector(0,0,0),
ang = Angle(0,0,0)
}
ENT.ClientProps["Ema_salon2"] = {
model = "models/metrostroi_train/em/ema_salon2.mdl",
pos = Vector(0,0,0),
ang = Angle(0,0,0)
}
ENT.ClientProps["Lamps_emer"] = {
model = "models/metrostroi_train/em/lamps_emer.mdl",
pos = Vector(0,0,0),
ang = Angle(0,0,0)
}
ENT.ClientProps["Lamps_full"] = {
model = "models/metrostroi_train/em/lamps_full.mdl",
pos = Vector(0,0,0),
ang = Angle(0,0,0)
}
ENT.ClientProps["PB"] = {--
model = "models/metrostroi_train/81/pb.mdl",
pos = Vector(461, -35.05, -35.31),
ang = Angle(0,-90,18)
}
ENT.ClientProps["FrontBrake"] = {--
model = "models/metrostroi_train/81/tmiso.mdl",
pos = Vector(460, -30, -55),
ang = Angle(0,-90,0)
}
ENT.ClientProps["FrontTrain"] = {--
model = "models/metrostroi_train/81/nmsio.mdl",
pos = Vector(460, 30, -55),
ang = Angle(0,-90,0)
}
ENT.ClientProps["RearBrake"] = {--
model = "models/metrostroi_train/81/tmiso.mdl",
pos = Vector(-460, -30, -55),
ang = Angle(0,90,0)
}
ENT.ClientProps["RearTrain"] = {--
model = "models/metrostroi_train/81/nmsio.mdl",
pos = Vector(-460, 30, -55),
ang = Angle(0,90,0)
}
--------------------------------------------------------------------------------
-- Add doors
local function GetDoorPosition(i,k,j)
if j == 0
then return Vector(383.0 - 67.49*k - 233.4*i,-64.56*(1-2*k),1)
else return Vector(383.0 - 67.49*(1-k) - 233.4*i,-64.56*(1-2*k),1)
end
end
for i=0,3 do
for k=0,1 do
ENT.ClientProps["door"..i.."x"..k.."a"] = {
model = "models/metrostroi_train/em/doorright.mdl",
pos = GetDoorPosition(i,k,0),
ang = Angle(0,90 + 180*k,0)
}
ENT.ClientProps["door"..i.."x"..k.."b"] = {
model = "models/metrostroi_train/em/doorleft.mdl",
pos = GetDoorPosition(i,k,1),
ang = Angle(0,90 + 180*k,0)
}
end
end
ENT.ClientProps["door1"] = {
model = "models/metrostroi_train/em/doorfront.mdl",
pos = Vector(471.71,-17.1,-1),
ang = Angle(0,-90,0)
}
ENT.ClientProps["door2"] = {
model = "models/metrostroi_train/em/doorback.mdl",
pos = Vector(-471.24,17.19,-1),
ang = Angle(0,-90,0)
}
ENT.ClientProps["door3"] = {
model = "models/metrostroi_train/em/doorpass.mdl",
pos = Vector(384.14,16.95,-2.2),
ang = Angle(0,-90,0)
}
ENT.ClientProps["door4"] = {
model = "models/metrostroi_train/em/doorcab.mdl",
pos = Vector(420.75,64.26,1.5),
ang = Angle(0,-90,0)
}
--[[ENT.ClientProps["UAVA"] = {
model = "models/metrostroi/81-717/uava_body.mdl",
pos = Vector(400,61,-8),--Vector(415.0,-58.5,-18.2),
ang = Angle(0,0,0)
}]]
ENT.ClientProps["UAVALever"] = {
model = "models/metrostroi_train/81/uavalever.mdl",
pos = Vector(452.84598,51,-21.813349),
ang = Angle(0,90,90)
}
ENT.ClientProps["RedLights"] = {
model = "models/metrostroi_train/Em/redlights.mdl",
pos = Vector(474.674042,-0.885458,55.695278),
ang = Angle(90.000000,-0.212120,0.000000),
}
ENT.ClientProps["DistantLights"] = {
model = "models/metrostroi_train/Em/distantlights.mdl",
pos = Vector(471.731842,-0.651488,54.413082),
ang = Angle(90.000000,0.000000,0.000000),
}
ENT.ClientProps["WhiteLights"] = {
model = "models/metrostroi_train/Em/whitelights.mdl",
pos = Vector(475.597565,-0.525079,-29.160791),
ang = Angle(90.267662,0.000000,0.000000),
}
ENT.ClientProps["RadioLamp"] = {
model = "models/metrostroi_train/Em/radiolight.mdl",
pos = Vector(465.569244,29.134933,-5.466231),
ang = Angle(90.000000,0.000000,0.000000),
}
ENT.ClientProps["RadioLamp1"] = {
model = "models/metrostroi_train/Em/radiolight.mdl",
pos = Vector(465.451752,31.03,-5.436231),
ang = Angle(90.000000,0.000000,0.000000),
}
ENT.Texture = "7"
ENT.OldTexture = nil
--local X = Material( "metrostroi_skins/81-717/6.png")
function ENT:UpdateTextures()
local texture = Metrostroi.Skins["train"][self:GetNW2String("texture")]
local passtexture = Metrostroi.Skins["pass"][self:GetNW2String("passtexture")]
local cabintexture = Metrostroi.Skins["cab"][self:GetNW2String("cabtexture")]
for _,self in pairs(self.ClientEnts) do
if not IsValid(self) then continue end
for k,v in pairs(self:GetMaterials()) do
local tex = string.Explode("/",v)
tex = tex[#tex]
if cabintexture and cabintexture.textures[tex] then
self:SetSubMaterial(k-1,cabintexture.textures[tex])
end
if passtexture and passtexture.textures[tex] then
self:SetSubMaterial(k-1,passtexture.textures[tex])
end
if texture and texture.textures[tex] then
self:SetSubMaterial(k-1,texture.textures[tex])
end
end
end
end
--------------------------------------------------------------------------------
function ENT:Think()
self.BaseClass.Think(self)
if self.Texture ~= self:GetNW2String("texture") then
self.Texture = self:GetNW2String("texture")
self:UpdateTextures()
end
if self.PassTexture ~= self:GetNW2String("passtexture") then
self.PassTexture = self:GetNW2String("passtexture")
self:UpdateTextures()
end
if self.CabinTexture ~= self:GetNW2String("cabtexture") then
self.CabinTexture = self:GetNW2String("cabtexture")
self:UpdateTextures()
end
--print(self.FrontDoor,self:GetPackedBool(114))
--print(self.RearDoor,self:GetPackedBool(156))
--[[
if self.FrontDoor < 90 and self:GetPackedBool(157) or self.FrontDoor > 0 and not self:GetPackedBool(157) then
--local FrontDoorData = self.ClientProps["door1"]
--FrontDoor:SetLocalPos(FrontDoorData.pos + Vector(-2,-0,0))
self.FrontDoor = math.max(0,math.min(90,self.FrontDoor + (self:GetPackedBool(157) and 1 or -1)*self.DeltaTime*180))
self:ApplyMatrix("door1",Vector(0,-16,0),Angle(0,self.FrontDoor,0))
if not self.ButtonMapMatrix["InfoTable"] then
self.ButtonMapMatrix["InfoTable"] = {}
self.ButtonMapMatrix["InfoTable"].scale = 0.1/2
end
self.ButtonMapMatrix["InfoTable"].ang = Angle(0,90+self.FrontDoor,90)
self.ButtonMapMatrix["InfoTable"].pos = Vector(458.0,-16.0,12.0) + Vector(0,1.5,0)*self.FrontDoor/90
end
]]
local transient = (self.Transient or 0)*0.05
if (self.Transient or 0) ~= 0.0 then self.Transient = 0.0 end
-- Parking brake animation
self.ParkingBrakeAngle = self.ParkingBrakeAngle or 0
self.TrueBrakeAngle = self.TrueBrakeAngle or 0
self.TrueBrakeAngle = self.TrueBrakeAngle + (self.ParkingBrakeAngle - self.TrueBrakeAngle)*2.0*(self.DeltaTime or 0)
if self.ClientEnts and self.ClientEnts["parking_brake"] then
self.ClientEnts["parking_brake"]:SetPoseParameter("position",1.0-((self.TrueBrakeAngle % 360)/360))
end
local Lamps = self:GetPackedBool(20) and 0.6 or 1
self:ShowHideSmooth("Lamps_emer",self:Animate("lamps_emer",self:GetPackedBool("Lamps_emer") and Lamps or 0,0,1,6,false))
self:ShowHideSmooth("Lamps_full",self:Animate("lamps_full",self:GetPackedBool("Lamps_full") and Lamps or 0,0,1,6,false))
--ALS Lamps
self:ShowHideSmooth("LNF",self:Animate("LNF_hs",self:GetPackedBool(41) and 1 or 0,0,1,7,false))
self:ShowHideSmooth("L0",self:Animate("L0_hs",self:GetPackedBool(42) and 1 or 0,0,1,5,false))
self:ShowHideSmooth("L40",self:Animate("L40_hs",self:GetPackedBool(43) and 1 or 0,0,1,5,false))
self:ShowHideSmooth("L60",self:Animate("L60_hs",self:GetPackedBool(44) and 1 or 0,0,1,5,false))
self:ShowHideSmooth("L70",self:Animate("L70_hs",self:GetPackedBool(45) and 1 or 0,0,1,5,false))
self:ShowHideSmooth("L80",self:Animate("L80_hs",self:GetPackedBool(46) and 1 or 0,0,1,5,false))
self:ShowHideSmooth("LampAutodrive",self:Animate("LampAutodrive_hs",self:GetPackedBool("KSAUP:Work") and 1 or 0,0,1,5,false))
self:ShowHideSmooth("Lamp2",self:Animate("Lamp2_hs",self:GetPackedBool("Lamp2") and 1 or 0,0,1,5,false))
self:ShowHideSmooth("Lamp1",self:Animate("Lamp1_hs",self:GetPackedBool("Lamp1") and 1 or 0,0,1,5,false))
self:ShowHideSmooth("Lamp6",self:Animate("Lamp6_hs",self:GetPackedBool("Lamp6") and 1 or 0,0,1,5,false))
self:ShowHideSmooth("Doors",self:Animate("Doors_hs",self:GetPackedBool(40) and 1 or 0,0,1,5,false))
self:ShowHideSmooth("DoorsWag",self:Animate("DoorsWag_hs",self:GetPackedBool("DoorsWag") and 1 or 0,0,1,5,false))
self:ShowHideSmooth("GreenRP",self:Animate("GreenRP_hs",self:GetPackedBool(36) and 1 or 0,0,1,5,false))
self:ShowHideSmooth("RedRP",self:Animate("RedRP_hs",self:GetPackedBool(35) and 1 or 0,0,1,5,false) + self:Animate("RedLSN_hs",self:GetPackedBool(131) and 1 or 0,0,0.4,5,false))
self:ShowHideSmoothFrom("LampAutodrive_p","LampAutodrive")
self:ShowHideSmoothFrom("Lamp2_p","Lamp2")
self:ShowHideSmoothFrom("Lamp1_p","Lamp1")
self:ShowHideSmoothFrom("Lamp6_p","Lamp6")
self:ShowHideSmoothFrom("Doors_p","Doors")
self:ShowHideSmoothFrom("DoorsWag_p","DoorsWag")
self:ShowHideSmoothFrom("GreenRP_p","GreenRP")
self:ShowHideSmoothFrom("RedRP_p","RedRP")
self:Animate("AV8B",self:GetPackedBool("AV8B") and 1 or 0, 0,1, 8, false)
self:Animate("RST",self:GetPackedBool("RST") and 0 or 1, 0,1, 12, false)
self:Animate("VSOSD",self:GetPackedBool("VSOSD") and 0 or 1, 0,1, 12, false)
self:HideButton("RSTToggle",self:GetPackedBool("RSTPl"))
self:HideButton("RSTPl",not self:GetPackedBool("RSTPl"))
self:SetCSBodygroup("RSTPl",1,self:GetPackedBool("RSTPl") and 0 or 1)
self:Animate("VU1",self:GetPackedBool("VU1") and 0 or 1, 0,1, 12, false)
self:Animate("VU3",self:GetPackedBool("VU3") and 0 or 1, 0,1, 12, false)
self:Animate("VU2",self:GetPackedBool("VU2") and 0 or 1, 0,1, 12, false)
self:Animate("VU",self:GetPackedBool("VU") and 0 or 1, 0,1, 12, false)
self:Animate("RezMK",self:GetPackedBool("RezMK") and 1 or 0, 0,1, 7, false)
self:Animate("VRD",self:GetPackedBool("VRD") and 0 or 1, 0,1, 12, false)
self:Animate("VB",self:GetPackedBool("VB") and 0 or 1, 0,1, 8, false)
self:Animate("VBA",self:GetPackedBool("VBA") and 0 or 1, 0,1, 8, false)
self:Animate("RC1",self:GetPackedBool("RC1") and 1 or 0, 1,0.694, 6, false)
self:Animate("RC2",self:GetPackedBool("RC2") and 1 or 0, 1,0.694, 6, false)
self:HideButton("RC1Toggle",self:GetPackedBool("RC1Pl"))
self:HideButton("RC1Pl",not self:GetPackedBool("RC1Pl"))
self:HideButton("RC2Toggle",self:GetPackedBool("RC2Pl"))
self:HideButton("RC2Pl",not self:GetPackedBool("RC2Pl"))
self:SetCSBodygroup("RC1Pl",1,self:GetPackedBool("RC1Pl") and 0 or 1)
self:SetCSBodygroup("RC2Pl",1,self:GetPackedBool("RC2Pl") and 0 or 1)
self:Animate("VRU",self:GetPackedBool("VRU") and 0 or 1, 0,1, 12, false)
self:Animate("VAH",self:GetPackedBool("VAH") and 0 or 1, 0,1, 12, false)
self:Animate("VAD",self:GetPackedBool("VAD") and 0 or 1, 0,1, 12, false)
self:Animate("OVT",self:GetPackedBool("OVT") and 0 or 1, 0,1, 12, false)
self:Animate("KSD",self:GetPackedBool("KSD") and 0 or 1, 0,1, 12, false)
self:Animate("DP",self:GetPackedBool("DP") and 0 or 1, 0,1, 12, false)
self:Animate("VKF",self:GetPackedBool("VKF") and 0 or 1, 0,1, 12, false)
self:HideButton("VAHToggle",self:GetPackedBool("VAHPl"))
self:HideButton("VAHPl",not self:GetPackedBool("VAHPl"))
self:HideButton("VADToggle",self:GetPackedBool("VADPl"))
self:HideButton("VADPl",not self:GetPackedBool("VADPl"))
self:HideButton("OVTToggle",self:GetPackedBool("OVTPl"))
self:HideButton("OVTPl",not self:GetPackedBool("OVTPl"))
self:SetCSBodygroup("VAHPl",1,self:GetPackedBool("VAHPl") and 0 or 1)
self:SetCSBodygroup("VADPl",1,self:GetPackedBool("VADPl") and 0 or 1)
self:SetCSBodygroup("OVTPl",1,self:GetPackedBool("OVTPl") and 0 or 1)
self:Animate("KVT",self:GetPackedBool("KVT") and 1 or 0, 0,1, 8, false)
self:ShowHideSmooth("ARSLamp",self:Animate("ARSLamp_hs",self:GetPackedBool(48) and 1 or 0,0,1,5,false))
self:Animate("VZP",self:GetPackedBool("VZP") and 1 or 0, 0,1, 12, false)
self:Animate("VZD",self:GetPackedBool("VZD") and 1 or 0, 0,1, 12, false)
self:Animate("KRZD",self:GetPackedBool("KRZD") and 1 or 0, 0,1, 12, false)
self:ShowHideSmooth("AutodriveLamp",self:Animate("AutodriveLamp_hs",self:GetPackedBool("KSAUP:AutodriveEngage") and 1 or 0,0,1,5,false))
self:ShowHideSmooth("RadioLamp",self:Animate("radiolamp",self:GetPackedBool("VPR") and 1 or 0,0,1,5,false))
self:ShowHideSmooth("RadioLamp1",self.Anims["radiolamp"].val)
self:ShowHideSmooth("RedLights",self:Animate("redlights",self:GetPackedBool("RedLight") and 1 or 0,0,1,5,false))
self:ShowHideSmooth("WhiteLights",self:Animate("whitelights",self:GetPackedBool("HeadLights2") and 1 or 0,0,1,5,false))
self:ShowHideSmooth("DistantLights",self:Animate("distantlights",self:GetPackedBool("HeadLights1") and 1 or 0,0,1,5,false))
self:Animate("KDL",self:GetPackedBool("KDL") and 1 or 0, 0,1, 12, false)
self:Animate("DIPon",self:GetPackedBool("DIPon") and 1 or 0, 0,1, 12, false)
self:Animate("DIPoff",self:GetPackedBool("DIPoff") and 1 or 0, 0,1, 12, false)
self:Animate("VozvratRP",self:GetPackedBool("VozvratRP") and 1 or 0, 0,1, 12, false)
self:Animate("KSN",self:GetPackedBool("KSN") and 1 or 0, 0,1, 12, false)
self:Animate("KDP",self:GetPackedBool("KDP") and 1 or 0, 0,1, 12, false)
self:Animate("KU1",self:GetPackedBool("KU1") and 1 or 0, 0,1, 7, false)
self:Animate("VUD",self:GetPackedBool("VUD1") and 1 or 0, 0,1, 7, false)
self:Animate("VDL",self:GetPackedBool("VDL") and 1 or 0, 0,1, 7, false)
self:ShowHideSmooth("KTLamp",self:Animate("KT_hs",self:GetPackedBool(47) and 1 or 0,0,1,5,false))
self:Animate("Ring",self:GetPackedBool("Ring") and 1 or 0, 0,1, 12, false)
self:Animate("VUS",self:GetPackedBool("VUS") and 1 or 0, 0,1, 12, false)
self:Animate("KAK",self:GetPackedBool("KAK") and 1 or 0, 0,1, 12, false)
self:Animate("VAutodrive",self:GetPackedBool("VAutodrive") and 1 or 0, 0,1, 12, false)
self:HideButton("VUD2Toggle",self:GetPackedBool("VUD2Bl"))
self:HideButton("VUD2LToggle",self:GetPackedBool("VUD2LBl"))
self:Animate("VUD2",self:GetPackedBool("VUD2") and 0 or 1, 0,1, 7, false)
self:Animate("VUD2l",self:GetPackedBool("VUD2L") and 1 or 0, 0,1, 7, false)
self:Animate("PB",self:GetPackedBool("PB") and 1 or 0,0,0.2, 12,false)
self:Animate("brake_disconnect",self:GetPackedBool("DriverValveBLDisconnect") and 1 or 0,0,0.5, 3,false)
self:Animate("train_disconnect",self:GetPackedBool("DriverValveTLDisconnect") and 1 or 0,0,0.5, 3,false)
self:Animate("EPK_disconnect",self:GetPackedBool("EPK") and 1 or 0,0.5,0, 3,false)
-- DIP sound
--self:SetSoundState("bpsn2",self:GetPackedBool(52) and 1 or 0,1.0)
-- Simulate pressure gauges getting stuck a little
self:Animate("brake", 1-self:GetPackedRatio(0), 0.00, 0.65, 256,24)
self:Animate("controller", self:GetPackedRatio(1), 0, 0.31, 2,false)
self:Animate("reverser", self:GetPackedRatio(2), 0.26, 0.35, 4,false)
self:Animate("volt1", self:GetPackedRatio(10), 0,0.244,256,2)
self:ShowHide("reverser", self:GetPackedBool(0))
self:Animate("brake_line", self:GetPackedRatio(4), 0, 0.725, 256,2)--,,0.01)
self:Animate("train_line", self:GetPackedRatio(5)-transient, 0, 0.725, 256,2)--,,0.01)
self:Animate("brake_cylinder", self:GetPackedRatio(6), 0, 0.721, 256,2)--,,0.03)
self:Animate("voltmeter", self:GetPackedRatio(7), 0.014, 0.298,256,2)
self:Animate("ampermeter", self:GetPackedRatio(8), 0, 0.248,256,2)
--self:Animate("volt2", 0, 0.38, 0.63)
local wheel_radius = 0.5*44.1 -- units
local speed = self:GetPackedRatio(3)*100
local ang_vel = speed/(2*math.pi*wheel_radius)
-- Rotate wheel
self.Angle = ((self.Angle or math.random()) + ang_vel*self.DeltaTime) % 1.0
self:Animate("speed1", self:GetPackedRatio("Speed") + math.sin(math.pi*8*self.Angle)*1/120, 0.495, 0.716, nil, nil, 256,2,0.01)
--self:Animate("speed1", /120, 0.495, 0.716, nil, nil, 256,2,0.01)
----
self:Animate("door1", self:GetPackedBool(157) and (self.Door1 or 0.99) or 0,0,0.22, 1024, 1)
self:Animate("door3", self:GetPackedBool(158) and (self.Door2 or 0.99) or 0,0,0.25, 1024, 1)
self:Animate("door2", self:GetPackedBool(156) and (self.Door3 or 0.99) or 0,0,0.25, 1024, 1)
self:Animate("door4", self:GetPackedBool(159) and (self.Door2 or 0.99) or 0,1,0.77, 1024, 1)
self:Animate("FrontBrake", self:GetNW2Bool("FbI") and 0 or 1,0,0.35, 3, false)
self:Animate("FrontTrain", self:GetNW2Bool("FtI") and 0 or 1,0,0.35, 3, false)
self:Animate("RearBrake", self:GetNW2Bool("RbI") and 1 or 0,0,0.35, 3, false)
self:Animate("RearTrain", self:GetNW2Bool("RtI") and 1 or 0,0,0.35, 3, false)
self:ShowHideSmooth("AVULight_light",self:Animate("AVUl",self:GetPackedBool(38) and 1 or 0,0,1,10,false))
-- Main switch
if self.LastValue ~= self:GetPackedBool(5) then
self.ResetTime = CurTime()+1.5
self.LastValue = self:GetPackedBool(5)
end
self:Animate("gv_wrench", (self:GetPackedBool(5) and 1 or 0), 0,0.51, 128, 1,false)
self:ShowHide("gv_wrench", CurTime() < self.ResetTime)
-- Animate doors
for i=0,4 do
for k=0,1 do
local n_l = "door"..i.."x"..k.."a"
local n_r = "door"..i.."x"..k.."b"
self:Animate(n_l,self:GetPackedBool(21+(1-k)*4) and 1 or 0,0.11,0.93, 0.8 + (-0.2+0.4*math.random()),0)
self:Animate(n_r,self:GetPackedBool(21+(1-k)*4) and 1 or 0,0.11,0.93, 0.8 + (-0.2+0.4*math.random()),0)
end
end
-- Brake-related sounds
local brakeLinedPdT = self:GetPackedRatio(9)
local dT = self.DeltaTime
self.BrakeLineRamp1 = self.BrakeLineRamp1 or 0
if (brakeLinedPdT > -0.001)
then self.BrakeLineRamp1 = self.BrakeLineRamp1 + 4.0*(0-self.BrakeLineRamp1)*dT
else self.BrakeLineRamp1 = self.BrakeLineRamp1 + 4.0*((-0.6*brakeLinedPdT)-self.BrakeLineRamp1)*dT
end
self.BrakeLineRamp1 = math.Clamp(self.BrakeLineRamp1,0,1)
self:SetSoundState("release2",self.BrakeLineRamp1^1.65,1.0)
self.BrakeLineRamp2 = self.BrakeLineRamp2 or 0
if (brakeLinedPdT < 0.001)
then self.BrakeLineRamp2 = self.BrakeLineRamp2 + 4.0*(0-self.BrakeLineRamp2)*dT
else self.BrakeLineRamp2 = self.BrakeLineRamp2 + 8.0*(0.1*brakeLinedPdT-self.BrakeLineRamp2)*dT
end
self.BrakeLineRamp2 = math.Clamp(self.BrakeLineRamp2,0,1)
self:SetSoundState("release3",self.BrakeLineRamp2 + math.max(0,self.BrakeLineRamp1/2-0.15),1.0)
self:SetSoundState("cran1",math.min(1,self:GetPackedRatio(4)/50*(self:GetPackedBool(6) and 1 or 0)),1.0)
-- Compressor
local state = self:GetPackedBool(20)
self.PreviousCompressorState = self.PreviousCompressorState or false
if self.PreviousCompressorState ~= state then
self.PreviousCompressorState = state
if state then
self:SetSoundState("compressor_ezh",1,1)
else
self:SetSoundState("compressor_ezh",0,1)
self:SetSoundState("compressor_ezh_end",0,1)
self:SetSoundState("compressor_ezh_end",1,1)
--self:PlayOnce("compressor_e_end",nil,1,nil,true)
end
end
-- ARS/ringer alert
state = self:GetPackedBool(39)
self.PreviousAlertState = self.PreviousAlertState or false
if self.PreviousAlertState ~= state then
self.PreviousAlertState = state
if state then
self:SetSoundState("ring4",1,1)
else
self:SetSoundState("ring4",0,0)
self:SetSoundState("ring4_end",0,1)
self:SetSoundState("ring4_end",1,1)
--self:PlayOnce("ring4_end","cabin",0,101)
end
end
state = self:GetPackedBool("VPR")
self.PreviousVPRState = self.PreviousVPRState or false
if self.PreviousVPRState ~= state then
self.PreviousVPRState = state
if state then
self:SetSoundState("vpr",1,1)
else
self:SetSoundState("vpr",0,0)
self:PlayOnce("vpr_end","cabin",1)
end
end
-- RK rotation
if self:GetPackedBool(112) then self.RKTimer = CurTime() end
state = (CurTime() - (self.RKTimer or 0)) < 0.2
self.PreviousRKState = self.PreviousRKState or false
if self.PreviousRKState ~= state then
self.PreviousRKState = state
if state then
self:SetSoundState("rk_spin",0.7,1,nil,0.75)
else
self:SetSoundState("rk_spin",0,0,nil,0.75)
self:SetSoundState("rk_stop",0,1,nil,0.75)
self:SetSoundState("rk_stop",0.7,1,nil,0.75)
end
end
--DIP sound
--self:SetSoundState("bpsn2",self:GetPackedBool(32) and 1 or 0,1.0)
end
function ENT:Draw()
self.BaseClass.Draw(self)
end
function ENT:DrawPost()
--local dc = render.GetLightColor(self:LocalToWorld(Vector(460.0,0.0,5.0)))
if self.InfoTableTimeout and (CurTime() < self.InfoTableTimeout) then
self:DrawOnPanel("InfoTableSelect",function()
draw.Text({
text = self:GetNW2String("RouteNumber",""),
font = "MetrostroiSubway_InfoPanel",--..self:GetNW2Int("Style",1),
pos = { 140, -50 },
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_CENTER,
color = Color(255,0,0,255)})
draw.Text({
text = self:GetNW2String("FrontText",""),
font = "MetrostroiSubway_InfoPanel",--..self:GetNW2Int("Style",1),
pos = { 140, -100 },
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_CENTER,
color = Color(255,0,0,255)})
end)
end
--[[
self:DrawOnPanel("IGLA",function()
local plus = ((not self:GetPackedBool(32) or not self:GetPackedBool(78)) and 1 or 0)
surface.SetDrawColor(50 - plus*40,255 - plus*220,40 - plus*40)
surface.DrawRect(0,-4,360,60)
if not self:GetPackedBool(32) or not self:GetPackedBool(78) then return end
local text1 = ""
local text2 = ""
local C1 = Color(0,0,0,255)
local C2 = Color(50,200,50,255)
local flash = false
local T = self:GetPackedRatio(11)
local Ptrain = self:GetPackedRatio(5)*16.0
local Pcyl = self:GetPackedRatio(6)*6.0
local date = os.date("!*t",os_time)
-- Default IGLA text
text1 = "IGLA-01K RK TEMP"
text2 = Format("%02d:%02d:%02d %3d C",date.hour,date.min,date.sec,T)
-- Modifiers and conditions
if self:GetPackedBool(25) then text1 = " !! Right Doors !!" end
if self:GetPackedBool(21) then text1 = " !! Left Doors !!" end
if T > 300 then text1 = "Temperature warning!" end
if self:GetPackedBool(50) and (Pcyl > 1.1) then
text1 = "FAIL PNEUMATIC BRAKE"
flash = true
end
if self:GetPackedBool(35) and
self:GetPackedBool(28) then
text1 = "FAIL AVU/BRAKE PRESS"
flash = true
end
if self:GetPackedBool(35) and
(not self:GetPackedBool(40)) then
text1 = "FAIL SD/DOORS OPEN "
flash = true
end
if self:GetPackedBool(36) then
text1 = "FAIL OVERLOAD RELAY "
flash = true
end
if Ptrain < 5.5 then
text1 = "FAIL TRAIN LINE LEAK"
flash = true
end
if T > 400 then flash = true end
if T > 500 then text1 = "!Disengage circuits!" end
if T > 750 then text1 = " !! PIZDA POEZDU !! " end
-- Draw text
if flash and ((RealTime() % 1.0) > 0.5) then
C2,C1 = C1,C2
end
for i=1,20 do
surface.SetDrawColor(C2)
surface.DrawRect(3+(i-1)*17.7+1,0+4,16,22)
draw.DrawText(string.upper(text1[i] or ""),"MetrostroiSubway_IGLA",3+(i-1)*17.7,0+0,C1)
end
for i=1,20 do
surface.SetDrawColor(C2)
surface.DrawRect(3+(i-1)*17.7+1,0+24+4,16,22)
draw.DrawText(string.upper(text2[i] or ""),"MetrostroiSubway_IGLA",3+(i-1)*17.7,0+24,C1)
end
end)
]]
--[[
self:DrawOnPanel("DURADisplay",function()
if not self:GetPackedBool(32) or not self:GetPackedBool(24) then return end
local function GetColor(id, text)
if text then
return self:GetPackedBool(id) and Color(255,0,0) or Color(0,0,0)
else
return not self:GetPackedBool(id) and Color(255,255,255) or Color(0,0,0)
end
end
surface.SetAlphaMultiplier(0.4)
surface.SetDrawColor(255,255,255)
surface.DrawRect(0,3+22.8*0,211,22.8) -- 120
surface.SetAlphaMultiplier(1.0)
draw.DrawText("DURA V 1.0","MetrostroiSubway_IGLA",0,0+22.8*0, Color(0,0,0,255))
surface.SetAlphaMultiplier(0.4)
surface.SetDrawColor(GetColor(31)) surface.SetAlphaMultiplier(0.4)
surface.DrawRect(0,3+22.8*1,211,23) -- 120
surface.SetAlphaMultiplier(1.0)
draw.DrawText("Channel:" .. (self:GetPackedBool(31) and "2" or "1"),"MetrostroiSubway_IGLA",0,0+22.8*1,GetColor(31, true))
surface.SetAlphaMultiplier(0.4)
surface.SetDrawColor(GetColor(153)) surface.SetAlphaMultiplier(0.4)
surface.DrawRect(0,3+22.8*2,211,23) -- 120
surface.SetAlphaMultiplier(1.0)
draw.DrawText("Channel1:" .. (self:GetPackedBool(153) and "Alt" or "Main"),"MetrostroiSubway_IGLA",0,0+22.8*2,GetColor(153, true))
surface.SetAlphaMultiplier(0.4)
surface.SetDrawColor(GetColor(154))
surface.DrawRect(0,3+22.8*3,211,23) -- 120
surface.SetAlphaMultiplier(1.0)
draw.DrawText("Channel2:" .. (self:GetPackedBool(154) and "Alt" or "Main"),"MetrostroiSubway_IGLA",0,0+22.8*3,GetColor(154, true))
surface.SetAlphaMultiplier(0.4)
surface.SetDrawColor(255,255,255)
surface.DrawRect(0,3+22.8*4,211,23) -- 120
surface.SetAlphaMultiplier(1)
end)]]
self:DrawOnPanel("FrontPneumatic",function()
draw.DrawText(self:GetNW2Bool("FbI") and "Isolated" or "Open","Trebuchet24",150,0,Color(0,0,0,255))
draw.DrawText(self:GetNW2Bool("FtI") and "Isolated" or "Open","Trebuchet24",670,0,Color(0,0,0,255))
end)
self:DrawOnPanel("RearPneumatic",function()
draw.DrawText(self:GetNW2Bool("RbI") and "Isolated" or "Open","Trebuchet24",150,0,Color(0,0,0,255))
draw.DrawText(self:GetNW2Bool("RtI") and "Isolated" or "Open","Trebuchet24",670,0,Color(0,0,0,255))
end)
self:DrawOnPanel("AirDistributor",function()
draw.DrawText(self:GetNW2Bool("AD") and "Air Distributor ON" or "Air Distributor OFF","Trebuchet24",0,0,Color(0,0,0,255))
end)
-- Draw train numbers
local dc = render.GetLightColor(self:GetPos())
self:DrawOnPanel("TrainNumber1",function()
draw.DrawText(Format("%04d",self:EntIndex()),"MetrostroiSubway_LargeText3",0,0,Color(255*dc.x,255*dc.y,255*dc.z,255))
end)
self:DrawOnPanel("TrainNumber2",function()
draw.DrawText(Format("%04d",self:EntIndex()),"MetrostroiSubway_LargeText3",0,0,Color(255*dc.x,255*dc.y,255*dc.z,255))
end)
end
function ENT:OnButtonPressed(button)
if button == "ShowHelp" then
RunConsoleCommand("metrostroi_train_manual")
end
local bp_press = self:GetPackedRatio(6)
local blocked_l = self:GetPackedBool(132) and 0 or 1
local blocked_r = self:GetPackedBool(133) and 0 or 1
if button == "ParkingBrakeLeft" then
self.ParkingBrakeAngle = (self.ParkingBrakeAngle or 0) - blocked_l*45
end
if button == "ParkingBrakeRight" then
self.ParkingBrakeAngle = (self.ParkingBrakeAngle or 0) + blocked_r*45
end
if button == "ShowHelp" then
RunConsoleCommand("metrostroi_train_manual")
end
if button == "PrevSign" then
self.InfoTableTimeout = CurTime() + 2.0
end
if button == "NextSign" then
self.InfoTableTimeout = CurTime() + 2.0
end
if button and button:sub(1,3) == "Num" then
self.InfoTableTimeout = CurTime() + 2.0
end
end
|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You under the Apache License, Version 2.0
-- (the "License"); you may not use this file except in compliance with
-- the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
local core = require("apisix.core")
local plugin_checker = require("apisix.plugin").plugin_checker
local pairs = pairs
local error = error
local plugin_configs
local _M = {
}
function _M.init_worker()
local err
plugin_configs, err = core.config.new("/plugin_configs", {
automatic = true,
item_schema = core.schema.plugin_config,
checker = plugin_checker,
})
if not plugin_configs then
error("failed to sync /plugin_configs: " .. err)
end
end
function _M.get(id)
return plugin_configs:get(id)
end
function _M.merge(route_conf, plugin_config)
if route_conf.prev_plugin_config_ver == plugin_config.modifiedIndex then
return route_conf
end
if not route_conf.value.plugins then
route_conf.value.plugins = {}
elseif not route_conf.orig_plugins then
route_conf.orig_plugins = route_conf.value.plugins
route_conf.value.plugins = core.table.clone(route_conf.value.plugins)
end
for name, value in pairs(plugin_config.value.plugins) do
route_conf.value.plugins[name] = value
end
route_conf.update_count = route_conf.update_count + 1
route_conf.modifiedIndex = route_conf.orig_modifiedIndex .. "#" .. route_conf.update_count
route_conf.prev_plugin_config_ver = plugin_config.modifiedIndex
return route_conf
end
return _M
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: trunks.lua 4025 2009-01-11 23:37:21Z jow $
]]--
local ast = require("luci.asterisk")
local uci = require("luci.model.uci").cursor()
--[[
Dialzone overview table
]]
if not arg[1] then
zonemap = Map("asterisk", "Dial Zones", [[
Dial zones hold patterns of dialed numbers to match.
Each zone has one or more trunks assigned. If the first trunk is
congested, Asterisk will try to use the next available connection.
If all trunks fail, then the following zones in the parent dialplan
are tried.
]])
local zones, znames = ast.dialzone.zones()
zonetbl = zonemap:section(Table, zones, "Zone Overview")
zonetbl.sectionhead = "Zone"
zonetbl.addremove = true
zonetbl.anonymous = false
zonetbl.extedit = luci.dispatcher.build_url(
"admin", "asterisk", "dialplans", "zones", "%s"
)
function zonetbl.cfgsections(self)
return znames
end
function zonetbl.parse(self)
for k, v in pairs(self.map:formvaluetable(
luci.cbi.REMOVE_PREFIX .. self.config
) or {}) do
if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end
uci:delete("asterisk", k)
uci:save("asterisk")
self.data[k] = nil
for i = 1,#znames do
if znames[i] == k then
table.remove(znames, i)
break
end
end
end
Table.parse(self)
end
zonetbl:option(DummyValue, "description", "Description")
zonetbl:option(DummyValue, "addprefix")
match = zonetbl:option(DummyValue, "matches")
function match.cfgvalue(self, s)
return table.concat(zones[s].matches, ", ")
end
trunks = zonetbl:option(DummyValue, "trunk")
trunks.template = "asterisk/cbi/cell"
function trunks.cfgvalue(self, s)
return ast.tools.hyperlinks(zones[s].trunks)
end
return zonemap
--[[
Zone edit form
]]
else
zoneedit = Map("asterisk", "Edit Dialzone")
entry = zoneedit:section(NamedSection, arg[1])
entry.title = "Zone %q" % arg[1];
back = entry:option(DummyValue, "_overview", "Back to dialzone overview")
back.value = ""
back.titleref = luci.dispatcher.build_url(
"admin", "asterisk", "dialplans", "zones"
)
desc = entry:option(Value, "description", "Description")
function desc.cfgvalue(self, s, ...)
return Value.cfgvalue(self, s, ...) or s
end
trunks = entry:option(MultiValue, "uses", "Used trunks")
trunks.widget = "checkbox"
uci:foreach("asterisk", "sip",
function(s)
if s.provider == "yes" then
trunks:value(
"SIP/%s" % s['.name'],
"SIP/%s (%s)" %{ s['.name'], s.host or 'n/a' }
)
end
end)
match = entry:option(DynamicList, "match", "Number matches")
intl = entry:option(DynamicList, "international", "Intl. prefix matches (optional)")
aprefix = entry:option(Value, "addprefix", "Add prefix to dial out (optional)")
ccode = entry:option(Value, "countrycode", "Effective countrycode (optional)")
lzone = entry:option(ListValue, "localzone", "Dialzone for local numbers")
lzone:value("", "no special treatment of local numbers")
for _, z in ipairs(ast.dialzone.zones()) do
lzone:value(z.name, "%q (%s)" %{ z.name, z.description })
end
--for _, v in ipairs(find_outgoing_contexts(zoneedit.uci)) do
-- lzone:value(unpack(v))
--end
lprefix = entry:option(Value, "localprefix", "Prefix for local calls (optional)")
return zoneedit
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.