1
0
mirror of https://github.com/ComfyFactory/ComfyFactorio.git synced 2025-02-03 13:12:11 +02:00

Merge pull request #21 from Gerkiz/changes

Changes
This commit is contained in:
MewMew 2019-03-11 17:57:46 +01:00 committed by GitHub
commit 5232b7e779
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 309 additions and 77 deletions

View File

@ -3,8 +3,8 @@
-- This module sets the rewards based on the killscore(score module)
local Event = require 'utils.event'
local Token = require 'utils.global_token'
local Task = require 'utils.Task'
local Token = require 'utils.token'
local Task = require 'utils.task'
local floor = math.floor
local sqrt = math.sqrt
local insert = table.insert
@ -246,4 +246,4 @@ end
Event.add(defines.events.on_entity_died, kill_rewards)
Event.add(defines.events.on_player_joined_game, check_data)
Event.add(defines.events.on_gui_click, rewards_gui)
Event.add(defines.events.on_gui_click, rewards_gui)

243
utils/core.lua Normal file
View File

@ -0,0 +1,243 @@
-- Dependencies
local Game = require 'utils.game'
local Color = require 'utils.color_presets'
-- localized functions
local random = math.random
local sqrt = math.sqrt
local floor = math.floor
local format = string.format
local match = string.match
local insert = table.insert
local concat = table.concat
-- local constants
local prefix = '## - '
local minutes_to_ticks = 60 * 60
local hours_to_ticks = 60 * 60 * 60
local ticks_to_minutes = 1 / minutes_to_ticks
local ticks_to_hours = 1 / hours_to_ticks
-- local vars
local Module = {}
--- Measures distance between pos1 and pos2
function Module.distance(pos1, pos2)
local dx = pos2.x - pos1.x
local dy = pos2.y - pos1.y
return sqrt(dx * dx + dy * dy)
end
--- Takes msg and prints it to all players except provided player
-- @param msg <string|table> table if locale is used
-- @param player <LuaPlayer> the player not to send the message to
-- @param color <table> the color to use for the message, defaults to white
function Module.print_except(msg, player, color)
if not color then
color = Color.white
end
for _, p in pairs(game.connected_players) do
if p ~= player then
p.print(msg, color)
end
end
end
--- Prints a message to all online admins
-- @param msg <string|table> table if locale is used
-- @param source <LuaPlayer|string|nil> string must be the name of a player, nil for server_commands.
function Module.print_admins(msg, source)
local source_name
local chat_color
if source then
if type(source) == 'string' then
source_name = source
chat_color = game.players[source].chat_color
else
source_name = source.name
chat_color = source.chat_color
end
else
source_name = 'server_commands'
chat_color = Color.yellow
end
local formatted_msg = {'utils_core.print_admins',prefix, source_name, msg}
log(formatted_msg)
for _, p in pairs(game.connected_players) do
if p.admin then
p.print(formatted_msg, chat_color)
end
end
end
--- Returns a valid string with the name of the actor of a command.
function Module.get_actor()
if game.player then
return game.player.name
end
return '<server_commands>'
end
function Module.cast_bool(var)
if var then
return true
else
return false
end
end
function Module.find_entities_by_last_user(player, surface, filters)
if type(player) == 'string' or not player then
error("bad argument #1 to '" .. debug.getinfo(1, 'n').name .. "' (number or LuaPlayer expected, got " .. type(player) .. ')', 1)
return
end
if type(surface) ~= 'table' and type(surface) ~= 'number' then
error("bad argument #2 to '" .. debug.getinfo(1, 'n').name .. "' (number or LuaSurface expected, got " .. type(surface) .. ')', 1)
return
end
local entities = {}
local filter = filters or {}
if type(surface) == 'number' then
surface = game.surfaces[surface]
end
if type(player) == 'number' then
player = Game.get_player_by_index(player)
end
filter.force = player.force.name
for _, e in pairs(surface.find_entities_filtered(filter)) do
if e.last_user == player then
insert(entities, e)
end
end
return entities
end
function Module.ternary(c, t, f)
if c then
return t
else
return f
end
end
--- Takes a time in ticks and returns a string with the time in format "x hour(s) x minute(s)"
function Module.format_time(ticks)
local result = {}
local hours = floor(ticks * ticks_to_hours)
if hours > 0 then
ticks = ticks - hours * hours_to_ticks
insert(result, hours)
if hours == 1 then
insert(result, 'hour')
else
insert(result, 'hours')
end
end
local minutes = floor(ticks * ticks_to_minutes)
insert(result, minutes)
if minutes == 1 then
insert(result, 'minute')
else
insert(result, 'minutes')
end
return concat(result, ' ')
end
--- Prints a message letting the player know they cannot run a command
-- @param name string name of the command
function Module.cant_run(name)
Game.player_print("Can't run command (" .. name .. ') - insufficient permission.')
end
--- Logs the use of a command and its user
-- @param actor string with the actor's name (usually acquired by calling get_actor)
-- @param command the command's name as table element
-- @param parameters the command's parameters as a table (optional)
function Module.log_command(actor, command, parameters)
local action = concat {'[Admin-Command] ', actor, ' used: ', command}
if parameters then
action = concat {action, ' ', parameters}
end
log(action)
end
function Module.comma_value(n) -- credit http://richard.warburton.it
local left, num, right = match(n, '^([^%d]*%d)(%d*)(.-)$')
return left .. (num:reverse():gsub('(%d%d%d)', '%1,'):reverse()) .. right
end
--- Asserts the argument is one of type arg_types
-- @param arg the variable to check
-- @param arg_types the type as a table of sings
-- @return boolean
function Module.verify_mult_types(arg, arg_types)
for _, arg_type in pairs(arg_types) do
if type(arg) == arg_type then
return true
end
end
return false
end
--- Returns a random RGB color as a table
function Module.random_RGB()
return {r = random(0, 255), g = random(0, 255), b = random(0, 255)}
end
--- Sets a table element to value while also returning value.
-- @param tbl table to change the element of
-- @param key string
-- @param value nil|boolean|number|string|table to set the element to
-- @return value
function Module.set_and_return(tbl, key, value)
tbl[key] = value
return value
end
--- Takes msg and prints it to all players. Also prints to the log and discord
-- @param msg <string> The message to print
-- @param warning_prefix <string> The name of the module/warning
function Module.action_warning(warning_prefix, msg)
game.print(prefix .. msg, Color.yellow)
msg = format('%s %s', warning_prefix, msg)
log(msg)
server_commands_commands.to_discord_bold(msg)
end
--- Takes msg and prints it to all players except provided player. Also prints to the log and discord
-- @param msg <string> The message to print
-- @param warning_prefix <string> The name of the module/warning
-- @param player <LuaPlayer> the player not to send the message to
function Module.silent_action_warning(warning_prefix, msg, player)
Module.print_except(prefix .. msg, player, Color.yellow)
msg = format('%s %s', warning_prefix, msg)
log(msg)
server_commands.to_discord_bold(msg)
end
-- add utility functions that exist in base factorio/util
require 'util'
--- Moves a position according to the parameters given
-- Notice: only accepts cardinal directions as direction
-- @param position <table> table containing a map position
-- @param direction <defines.direction> north, east, south, west
-- @param distance <number>
-- @return <table> modified position
Module.move_position = util.moveposition
--- Takes a direction and gives you the opposite
-- @param direction <defines.direction> north, east, south, west, northeast, northwest, southeast, southwest
-- @return <number> representing the direction
Module.opposite_direction = util.oppositedirection
--- Takes the string of a module and returns whether is it available or not
-- @param name <string> the name of the module (ex. 'utils.core')
-- @return <boolean>
Module.is_module_available = util.ismoduleavailable
return Module

View File

@ -1,7 +1,8 @@
local Event = require 'utils.event'
local Global = require 'utils.global'
local Task = require 'utils.Task'
local Token = require 'utils.global_token'
local Game = require 'utils.game'
local Token = require 'utils.token'
local player_corpses = {}
@ -14,7 +15,7 @@ Global.register(
local function player_died(event)
local player_index = event.player_index
local player = game.players[player_index]
local player = Game.get_player_by_index(player_index)
if not player or not player.valid then
return
@ -88,7 +89,9 @@ local corpse_util_mined_entity =
local function mined_entity(event)
local entity = event.entity
if entity and entity.valid and entity.name == 'character-corpse' then
if not entity or not entity.valid or entity.name ~= 'character-corpse' then
return
end
-- The corpse may be mined but not removed (if player doesn't have inventory space)
-- so we wait one tick to see if the corpse is gone.
Task.set_timeout_in_ticks(
@ -100,7 +103,6 @@ local function mined_entity(event)
tick = entity.character_corpse_tick_of_death
}
)
end
end
Event.add(defines.events.on_player_died, player_died)

View File

@ -1,45 +0,0 @@
local Token = {}
local tokens = {}
local counter = 0
function Token.register(var)
counter = counter + 1
tokens[counter] = var
return counter
end
function Token.get(token_id)
return tokens[token_id]
end
global.tokens = {}
function Token.register_global(var)
local c = #global.tokens + 1
global.tokens[c] = var
return c
end
function Token.get_global(token_id)
return global.tokens[token_id]
end
function Token.set_global(token_id, var)
global.tokens[token_id] = var
end
local uid_counter = 0
function Token.uid()
uid_counter = uid_counter + 1
return uid_counter
end
return Token

View File

@ -71,4 +71,4 @@ function PriorityQueue.peek(queue)
return queue[1]
end
return PriorityQueue
return PriorityQueue

View File

@ -1,7 +1,7 @@
local Queue = {}
function Queue.new()
local queue = {_head = 0, _tail = 0}
local queue = {_head = 0, _tail = 0}
return queue
end
@ -25,9 +25,10 @@ function Queue.pop(queue)
local element = queue[index]
queue[index] = nil
queue._tail = index - 1
if element then
queue._tail = index - 1
end
return element
end
return Queue
return Queue

View File

@ -1,13 +1,13 @@
-- Threading simulation module
-- Task.sleep()
-- @author Valansch
-- github: https://github.com/Valansch/RedMew
-- @author Valansch and Grilledham
-- github: https://github.com/Refactorio/RedMew
-- ======================================================= --
local Queue = require 'utils.Queue'
local PriorityQueue = require 'utils.PriorityQueue'
local Queue = require 'utils.queue'
local PriorityQueue = require 'utils.priority_queue'
local Event = require 'utils.event'
local Token = require 'utils.global_token'
local Token = require 'utils.token'
local Task = {}
@ -21,6 +21,18 @@ local function comp(a, b)
return a.time < b.time
end
global.tpt = global.task_queue_speed
local function get_task_per_tick()
if game.tick % 300 == 0 then
local size = global.total_task_weight
global.tpt = math.floor(math.log10(size + 1)) * global.task_queue_speed
if global.tpt < 1 then
global.tpt = 1
end
end
return global.tpt
end
local function on_tick()
local queue = global.task_queue
for i = 1, get_task_per_tick() do
@ -29,7 +41,11 @@ local function on_tick()
-- result is error if not success else result is a boolean for if the task should stay in the queue.
local success, result = pcall(Token.get(task.func_token), task.params)
if not success then
log(result)
if _DEBUG then
error(result)
else
log(result)
end
Queue.pop(queue)
global.total_task_weight = global.total_task_weight - task.weight
elseif not result then
@ -42,37 +58,52 @@ local function on_tick()
local callbacks = global.callbacks
local callback = PriorityQueue.peek(callbacks)
while callback ~= nil and game.tick >= callback.time do
local success, error = pcall(Token.get(callback.func_token), callback.params)
local success, result = pcall(Token.get(callback.func_token), callback.params)
if not success then
log(error)
if _DEBUG then
error(result)
else
log(result)
end
end
PriorityQueue.pop(callbacks, comp)
callback = PriorityQueue.peek(callbacks)
end
end
global.tpt = global.task_queue_speed
function get_task_per_tick()
if game.tick % 300 == 0 then
local size = global.total_task_weight
global.tpt = math.floor(math.log10(size + 1)) * global.task_queue_speed
if global.tpt < 1 then
global.tpt = 1
end
end
return global.tpt
end
--- Allows you to set a timer (in ticks) after which the tokened function will be run with params given as an argument
-- Cannot be called before init
-- @param ticks <number>
-- @param func_token <number> a token for a function store via the token system
-- @param params <any> the argument to send to the tokened function
function Task.set_timeout_in_ticks(ticks, func_token, params)
if not game then
error('cannot call when game is not available', 2)
end
local time = game.tick + ticks
local callback = {time = time, func_token = func_token, params = params}
PriorityQueue.push(global.callbacks, callback, comp)
end
--- Allows you to set a timer (in seconds) after which the tokened function will be run with params given as an argument
-- Cannot be called before init
-- @param sec <number>
-- @param func_token <number> a token for a function store via the token system
-- @param params <any> the argument to send to the tokened function
function Task.set_timeout(sec, func_token, params)
if not game then
error('cannot call when game is not available', 2)
end
Task.set_timeout_in_ticks(60 * sec, func_token, params)
end
--- Queueing allows you to split up heavy tasks which don't need to be completed in the same tick.
-- Queued tasks are generally run 1 per tick. If the queue backs up, more tasks will be processed per tick.
-- @param func_token <number> a token for a function stored via the token system
-- If this function returns `true` it will run again the next tick, delaying other queued tasks (see weight)
-- @param params <any> the argument to send to the tokened function
-- @param weight <number> (defaults to 1) weight is the number of ticks a task is expected to take.
-- Ex. if the task is expected to repeat multiple times (ie. the function returns true and loops several ticks)
function Task.queue_task(func_token, params, weight)
weight = weight or 1
global.total_task_weight = global.total_task_weight + weight