Name | Type | is_array | initial_value |
do; local _, codeLoc = pcall(error, "", 2) --get line number where DebugUtils begins.
--[[
--------------------------
-- | Debug Utils 2.1a | --
--------------------------
--> https://www.hiveworkshop.com/threads/lua-debug-utils-incl-ingame-console.353720/
- by Eikonium, with special thanks to:
- @Bribe, for pretty table print, showing that xpcall's message handler executes before the stack unwinds and useful suggestions like name caching and stack trace improvements.
- @Jampion, for useful suggestions like print caching and applying Debug.try to all code entry points
- @Luashine, for useful feedback and building "WC3 Debug Console Paste Helper" (https://github.com/Luashine/wc3-debug-console-paste-helper#readme)
- @HerlySQR, for showing a way to get a stack trace in Wc3 (https://www.hiveworkshop.com/threads/lua-getstacktrace.340841/)
- @Macadamia, for showing a way to print warnings upon accessing undeclared globals, where this all started with (https://www.hiveworkshop.com/threads/lua-very-simply-trick-to-help-lua-users-track-syntax-errors.326266/)
-----------------------------------------------------------------------------------------------------------------------------
| Provides debugging utility for Wc3-maps using Lua. |
| |
| Including: |
| 1. Automatic ingame error messages upon running erroneous code from triggers or timers. |
| 2. Ingame Console that allows you to execute code via Wc3 ingame chat. |
| 3. Automatic warnings upon reading undeclared globals (which also triggers after misspelling globals) |
| 4. Debug-Library functions for manual error handling. |
| 5. Caching of loading screen print messages until game start (which simplifies error handling during loading screen) |
| 6. Overwritten tostring/print-functions to show the actual string-name of an object instead of the memory position. |
| 7. Conversion of war3map.lua-error messages to local file error messages. |
| 8. Other useful debug utility (table.print and Debug.wc3Type) |
-----------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Installation: |
| |
| 1. Copy the code (DebugUtils.lua, StringWidth.lua and IngameConsole.lua) into your map. Use script files (Ctrl+U) in your trigger editor, not text-based triggers! |
| 2. Order the files: DebugUtils above StringWidth above IngameConsole. Make sure they are above ALL other scripts (crucial for local line number feature). |
| 3. Adjust the settings in the settings-section further below to receive the debug environment that fits your needs. |
| |
| Deinstallation: |
| |
| - Debug Utils is meant to provide debugging utility and as such, shall be removed or invalidated from the map closely before release. |
| - Optimally delete the whole Debug library. If that isn't suitable (because you have used library functions at too many places), you can instead replace Debug Utils |
| by the following line of code that will invalidate all Debug functionality (without breaking your code): |
| Debug = setmetatable({try = function(...) return select(2,pcall(...)) end}, {__index = function(t,k) return DoNothing end}); try = Debug.try |
| - If that is also not suitable for you (because your systems rely on the Debug functionality to some degree), at least set ALLOW_INGAME_CODE_EXECUTION to false. |
| - Be sure to test your map thoroughly after removing Debug Utils. |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
* Documentation and API-Functions:
*
* - All automatic functionality provided by Debug Utils can be deactivated using the settings directly below the documentation.
*
* -------------------------
* | Ingame Code Execution |
* -------------------------
* - Debug Utils provides the ability to run code via chat command from within Wc3, if you have conducted step 3 from the installation section.
* - You can either open the ingame console by typing "-console" into the chat, or directly execute code by typing "-exec <code>".
* - See IngameConsole script for further documentation.
*
* ------------------
* | Error Handling |
* ------------------
* - Debug Utils automatically applies error handling (i.e. Debug.try) to code executed by your triggers and timers (error handling means that error messages are printed on screen, if anything doesn't run properly).
* - You can still use the below library functions for manual debugging.
*
* Debug.try(funcToExecute, ...) -> ...
* - Help function for debugging another function (funcToExecute) that prints error messages on screen, if funcToExecute fails to execute.
* - DebugUtils will automatically apply this to all code run by your triggers and timers, so you rarely need to apply this manually (maybe on code run in the Lua root).
* - Calls funcToExecute with the specified parameters (...) in protected mode (which means that following code will continue to run even if funcToExecute fails to execute).
* - If the call is successful, returns the specified function's original return values (so p1 = Debug.try(Player, 0) will work fine).
* - If the call is unsuccessful, prints an error message on screen (including stack trace and parameters you have potentially logged before the error occured)
* - By default, the error message consists of a line-reference to war3map.lua (which you can look into by forcing a syntax error in WE or by exporting it from your map via File -> Export Script).
* You can get more helpful references to local script files instead, see section about "Local script references".
* - Example: Assume you have a code line like "func(param1,param2)", which doesn't work and you want to know why.
* Option 1: Change it to "Debug.try(func, param1, param2)", i.e. separate the function from the parameters.
* Option 2: Change it to "Debug.try(function() return func(param1, param2) end)", i.e. pack it into an anonymous function (optionally skip the return statement).
* Debug.log(...)
* - Logs the specified parameters to the Debug-log. The Debug-log will be printed upon the next error being catched by Debug.try, Debug.assert or Debug.throwError.
* - The Debug-log will only hold one set of parameters per code-location. That means, if you call Debug.log() inside any function, only the params saved within the latest call of that function will be kept.
* Debug.throwError(...)
* - Prints an error message including document, line number, stack trace, previously logged parameters and all specified parameters on screen. Parameters can have any type.
* - In contrast to Lua's native error function, this can be called outside of protected mode and doesn't halt code execution.
* Debug.assert(condition:boolean, errorMsg:string, ...) -> ...
* - Prints the specified error message including document, line number, stack trace and previously logged parameters on screen, IF the specified condition fails (i.e. resolves to false/nil).
* - Returns ..., IF the specified condition holds.
* - This works exactly like Lua's native assert, except that it also works outside of protected mode and does not halt code execution.
* Debug.traceback() -> string
* - Returns the stack trace at the position where this is called. You need to manually print it.
* Debug.getLine([depth: integer]) -> integer?
* - Returns the line in war3map.lua, where this function is executed.
* - You can specify a depth d >= 1 to instead return the line, where the d-th function in the stack trace was called. I.e. depth = 2 will return the line of execution of the function that calls Debug.getLine.
* - Due to Wc3's limited stack trace ability, this might sometimes return nil for depth >= 3, so better apply nil-checks on the result.
* Debug.getLocalErrorMsg(errorMsg:string) -> string
* - Takes an error message containing a file and a linenumber and converts war3map.lua-lines to local document lines as defined by uses of Debug.beginFile() and Debug.endFile().
* - Error Msg must be formatted like "<document>:<linenumber><Rest>".
*
* -----------------------------------
* | Warnings for undeclared globals |
* -----------------------------------
* - DebugUtils will print warnings on screen, if you read an undeclared global variable.
* - This is technically the case, when you misspelled on a function name, like calling CraeteUnit instead of CreateUnit.
* - Keep in mind though that the same warning will pop up after reading a global that was intentionally nilled. If you don't like this, turn of this feature in the settings.
*
* -----------------
* | Print Caching |
* -----------------
* - DebugUtils caches print()-calls occuring during loading screen and delays them to after game start.
* - This also applies to loading screen error messages, so you can wrap erroneous parts of your Lua root in Debug.try-blocks and see the message after game start.
*
* -------------------------
* | Local File Stacktrace |
* -------------------------
* - By default, error messages and stack traces printed by the error handling functionality of Debug Utils contain references to war3map.lua (a big file just appending all your local scripts).
* - The Debug-library provides the two functions below to index your local scripts, activating local file names and line numbers (matching those in your IDE) instead of the war3map.lua ones.
* - This allows you to inspect errors within your IDE (VSCode) instead of the World Editor.
*
* Debug.beginFile(fileName: string [, depth: integer])
* - Tells the Debug library that the specified file begins exactly here (i.e. in the line, where this is called).
* - Using this improves stack traces of error messages. "war3map.lua"-references between <here> and the next Debug.endFile() will be converted to file-specific references.
* - All war3map.lua-lines located between the call of Debug.beginFile(fileName) and the next call of Debug.beginFile OR Debug.endFile are treated to be part of "fileName".
* - !!! To be called in the Lua root in Line 1 of every document you wish to track. Line 1 means exactly line 1, before any comment! This way, the line shown in the trace will exactly match your IDE.
* - Depth can be ignored, except if you want to use a custom wrapper around Debug.beginFile(), in which case you need to set the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.beginFile().
* Debug.endFile([depth: integer])
* - Ends the current file that was previously begun by using Debug.beginFile(). War3map.lua-lines after this will not be converted until the next instance of Debug.beginFile().
* - The next call of Debug.beginFile() will also end the previous one, so using Debug.endFile() is optional. Mainly recommended to use, if you prefer to have war3map.lua-references in a certain part of your script (such as within GUI triggers).
* - Depth can be ignored, except if you want to use a custom wrapper around Debug.endFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.endFile().
*
* ----------------
* | Name Caching |
* ----------------
* - DebugUtils overwrites the tostring-function so that it prints the name of a non-primitive object (if available) instead of its memory position. The same applies to print().
* - For instance, print(CreateUnit) will show "function: CreateUnit" on screen instead of "function: 0063A698".
* - The table holding all those names is referred to as "Name Cache".
* - All names of objects in global scope will automatically be added to the Name Cache both within Lua root and again at game start (to get names for overwritten natives and your own objects).
* - New names entering global scope will also automatically be added, even after game start. The same applies to subtables of _G up to a depth of Debug.settings.NAME_CACHE_DEPTH.
* - Objects within subtables will be named after their parent tables and keys. For instance, the name of the function within T = {{bla = function() end}} is "T[1].bla".
* - The automatic adding doesn't work for objects saved into existing variables/keys after game start (because it's based on __newindex metamethod which simply doesn't trigger)
* - You can manually add names to the name cache by using the following API-functions:
*
* Debug.registerName(whichObject:any, name:string)
* - Adds the specified object under the specified name to the name cache, letting tostring and print output "<type>: <name>" going foward.
* - The object must be non-primitive, i.e. this won't work on strings, numbers and booleans.
* - This will overwrite existing names for the specified object with the specified name.
* Debug.registerNamesFrom(parentTable:table [, parentTableName:string] [, depth])
* - Adds names for all values from within the specified parentTable to the name cache.
* - Names for entries will be like "<parentTableName>.<key>" or "<parentTableName>[<key>]" (depending on the key type), using the existing name of the parentTable from the name cache.
* - You can optionally specify a parentTableName to use that for the entry naming instead of the existing name. Doing so will also register that name for the parentTable, if it doesn't already has one.
* - Specifying the empty string as parentTableName will suppress it in the naming and just register all values as "<key>". Note that only string keys will be considered this way.
* - In contrast to Debug.registerName(), this function will NOT overwrite existing names, but just add names for new objects.
* Debug.oldTostring(object:any) -> string
* - The old tostring-function in case you still need outputs like "function: 0063A698".
*
* -----------------
* | Other Utility |
* -----------------
*
* Debug.wc3Type(object:any) -> string
* - Returns the Warcraft3-type of the input object. E.g. Debug.wc3Type(Player(0)) will return "player".
* - Returns type(object), if used on Lua-objects.
* table.tostring(whichTable [, depth:integer] [, pretty_yn:boolean])
* - Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth (unlimited, if not specified).
* - E.g. for T = {"a", 5, {7}}, table.tostring(T) would output '{(1, "a"), (2, 5), (3, {(1, 7)})}' (if using concise style, i.e. pretty_yn being nil or false).
* - Not specifying a depth can potentially lead to a stack overflow for self-referential tables (e.g X = {}; X[1] = X). Choose a sensible depth to prevent this (in doubt start with 1 and test upwards).
* - Supports pretty style by setting pretty_yn to true. Pretty style is linebreak-separated, uses indentations and has other visual improvements. Use it on small tables only, because Wc3 can't show that many linebreaks at once.
* - All of the following is valid syntax: table.tostring(T), table.tostring(T, depth), table.tostring(T, pretty_yn) or table.tostring(T, depth, pretty_yn).
* - table.tostring is not multiplayer-synced.
* table.print(whichTable [, depth:integer] [, pretty_yn:boolean])
* - Prints table.tostring(...).
*
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------]]
-- disable sumneko extension warnings for imported resource
---@diagnostic disable
----------------
--| Settings |--
----------------
Debug = {
--BEGIN OF SETTINGS--
settings = {
SHOW_TRACE_ON_ERROR = true ---Set to true to show a stack trace on every error in addition to the regular message (msg sources: automatic error handling, Debug.try, Debug.throwError, ...)
, INCLUDE_DEBUGUTILS_INTO_TRACE = true ---Set to true to include lines from Debug Utils into the stack trace. Those show the source of error handling, which you might consider redundant.
, USE_TRY_ON_TRIGGERADDACTION = true ---Set to true for automatic error handling on TriggerAddAction (applies Debug.try on every trigger action).
, USE_TRY_ON_CONDITION = true ---Set to true for automatic error handling on boolexpressions created via Condition() or Filter() (essentially applies Debug.try on every trigger condition).
, USE_TRY_ON_TIMERSTART = true ---Set to true for automatic error handling on TimerStart (applies Debug.try on every timer callback).
, USE_TRY_ON_ENUMFUNCS = true ---Set to true for automatic error handling on ForGroup, ForForce, EnumItemsInRect and EnumDestructablesInRect (applies Debug.try on every enum callback)
, USE_TRY_ON_COROUTINES = true ---Set to true for improved stack traces on errors within coroutines (applies Debug.try on coroutine.create and coroutine.wrap). This lets stack traces point to the erroneous function executed within the coroutine (instead of the function creating the coroutine).
, ALLOW_INGAME_CODE_EXECUTION = true ---Set to true to enable IngameConsole and -exec command.
, WARNING_FOR_UNDECLARED_GLOBALS = false ---Set to true to print warnings upon accessing undeclared globals (i.e. globals with nil-value). This is technically the case after having misspelled on a function name (like CraeteUnit instead of CreateUnit).
, SHOW_TRACE_FOR_UNDECLARED_GLOBALS = false ---Set to true to include a stack trace into undeclared global warnings. Only takes effect, if WARNING_FOR_UNDECLARED_GLOBALS is also true.
, USE_PRINT_CACHE = true ---Set to true to let print()-calls during loading screen be cached until the game starts.
, PRINT_DURATION = nil ---Adjust the duration in seconds that values printed by print() last on screen. Set to nil to use default duration (which depends on string length).
, USE_NAME_CACHE = true ---Set to true to let tostring/print output the string-name of an object instead of its memory location (except for booleans/numbers/strings). E.g. print(CreateUnit) will output "function: CreateUnit" instead of "function: 0063A698".
, AUTO_REGISTER_NEW_NAMES = true ---Automatically adds new names from global scope (and subtables of _G up to NAME_CACHE_DEPTH) to the name cache by adding metatables with the __newindex metamethod to ALL tables accessible from global scope.
, NAME_CACHE_DEPTH = 4 ---Set to 0 to only affect globals. Experimental feature: Set to an integer > 0 to also cache names for subtables of _G (up to the specified depth). Warning: This will alter the __newindex metamethod of subtables of _G (but not break existing functionality).
}
--END OF SETTINGS--
--START OF CODE--
, data = {
nameCache = {} ---@type table<any,string> contains the string names of any object in global scope (random for objects that have multiple names)
, nameCacheMirror = {} ---@type table<string,any> contains the (name,object)-pairs of all objects in the name cache. Used to prevent name duplicates that might otherwise occur upon reassigning globals.
, nameDepths = {} ---@type table<any,integer> contains the depth of the name used by by any object in the name cache (i.e. the depth within the parentTable).
, autoIndexedTables = {} ---@type table<table,boolean> contains (t,true), if DebugUtils already set a __newindex metamethod for name caching in t. Prevents double application.
, paramLog = {} ---@type table<string,string> saves logged information per code location. to be filled by Debug.log(), to be printed by Debug.try()
, sourceMap = {{firstLine= 1,file='DebugUtils'}} ---@type table<integer,{firstLine:integer,file:string,lastLine?:integer}> saves lines and file names of all documents registered via Debug.beginFile().
, printCache = {n=0} ---@type string[] contains the strings that were attempted to print during loading screen.
}
}
--localization
local settings, paramLog, nameCache, nameDepths, autoIndexedTables, nameCacheMirror, sourceMap, printCache = Debug.settings, Debug.data.paramLog, Debug.data.nameCache, Debug.data.nameDepths, Debug.data.autoIndexedTables, Debug.data.nameCacheMirror, Debug.data.sourceMap, Debug.data.printCache
--Write DebugUtils first line number to sourceMap:
---@diagnostic disable-next-line
Debug.data.sourceMap[1].firstLine = tonumber(codeLoc:match(":\x25d+"):sub(2,-1))
-------------------------------------------------
--| File Indexing for local Error Msg Support |--
-------------------------------------------------
-- Functions for war3map.lua -> local file conversion for error messages.
---Returns the line number in war3map.lua, where this is called (for depth = 0).
---Choose a depth d > 0 to instead return the line, where the d-th function in the stack leading to this call is executed.
---@param depth? integer default: 0.
---@return number?
function Debug.getLine(depth)
depth = depth or 0
local _, location = pcall(error, "", depth + 3) ---@diagnostic disable-next-line
local line = location:match(":\x25d+") --extracts ":1000" from "war3map.lua:1000:..."
return tonumber(line and line:sub(2,-1)) --check if line is nil before applying string.sub to prevent errors (nil can result from string.match above, although it should never do so in our case)
end
---Tells the Debug library that the specified file begins exactly here (i.e. in the line, where this is called).
---
---Using this improves stack traces of error messages. Stack trace will have "war3map.lua"-references between this and the next Debug.endFile() converted to file-specific references.
---
---To be called in the Lua root in Line 1 of every file you wish to track! Line 1 means exactly line 1, before any comment! This way, the line shown in the trace will exactly match your IDE.
---
---If you want to use a custom wrapper around Debug.beginFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.beginFile().
---@param fileName string
---@param depth? integer default: 0. Set to 1, if you call this from a wrapper (and use the wrapper in line 1 of every document).
---@param lastLine? integer Ignore this. For compatibility with Total Initialization.
function Debug.beginFile(fileName, depth, lastLine)
depth, fileName = depth or 0, fileName or '' --filename is not actually optional, we just default to '' to prevent crashes.
local line = Debug.getLine(depth + 1)
if line then --for safety reasons. we don't want to add a non-existing line to the sourceMap
table.insert(sourceMap, {firstLine = line, file = fileName, lastLine = lastLine}) --automatically sorted list, because calls of Debug.beginFile happen logically in the order of the map script.
end
end
---Tells the Debug library that the file previously started with Debug.beginFile() ends here.
---This is in theory optional to use, as the next call of Debug.beginFile will also end the previous. Still good practice to always use this in the last line of every file.
---If you want to use a custom wrapper around Debug.endFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.endFile().
---@param depth? integer
function Debug.endFile(depth)
depth = depth or 0
local line = Debug.getLine(depth + 1)
sourceMap[#sourceMap].lastLine = line
end
---Takes an error message containing a file and a linenumber and converts both to local file and line as saved to Debug.sourceMap.
---@param errorMsg string must be formatted like "<document>:<linenumber><RestOfMsg>".
---@return string convertedMsg a string of the form "<localDocument>:<localLinenumber><RestOfMsg>"
function Debug.getLocalErrorMsg(errorMsg)
local startPos, endPos = errorMsg:find(":\x25d*") --start and end position of line number. The part before that is the document, part after the error msg.
if startPos and endPos then --can be nil, if input string was not of the desired form "<document>:<linenumber><RestOfMsg>".
local document, line, rest = errorMsg:sub(1, startPos), tonumber(errorMsg:sub(startPos+1, endPos)), errorMsg:sub(endPos+1, -1) --get error line in war3map.lua
if document == 'war3map.lua:' and line then --only convert war3map.lua-references to local position. Other files such as Blizzard.j.lua are not converted (obiously).
for i = #sourceMap, 1, -1 do --find local file containing the war3map.lua error line.
if line >= sourceMap[i].firstLine then --war3map.lua line is part of sourceMap[i].file
if not sourceMap[i].lastLine or line <= sourceMap[i].lastLine then --if lastLine is given, we must also check for it
return sourceMap[i].file .. ":" .. (line - sourceMap[i].firstLine + 1) .. rest
else --if line is larger than firstLine and lastLine of sourceMap[i], it is not part of a tracked file -> return global war3map.lua position.
break --prevent return within next step of the loop ("line >= sourceMap[i].firstLine" would be true again, but wrong file)
end
end
end
end
end
return errorMsg
end
local convertToLocalErrorMsg = Debug.getLocalErrorMsg
----------------------
--| Error Handling |--
----------------------
local concat
---Applies tostring() on all input params and concatenates them 4-space-separated.
---@param firstParam any
---@param ... any
---@return string
concat = function(firstParam, ...)
if select('#', ...) == 0 then
return tostring(firstParam)
end
return tostring(firstParam) .. ' ' .. concat(...)
end
---Returns the stack trace between the specified startDepth and endDepth.
---The trace lists file names and line numbers. File name is only listed, if it has changed from the previous traced line.
---The previous file can also be specified as an input parameter to suppress the first file name in case it's identical.
---@param startDepth integer
---@param endDepth integer
---@return string trace
local function getStackTrace(startDepth, endDepth)
local trace, separator = "", ""
local _, currentFile, lastFile, tracePiece, lastTracePiece
for loopDepth = startDepth, endDepth do --get trace on different depth level
_, tracePiece = pcall(error, "", loopDepth) ---@type boolean, string
tracePiece = convertToLocalErrorMsg(tracePiece)
if #tracePiece > 0 and lastTracePiece ~= tracePiece then --some trace pieces can be empty, but there can still be valid ones beyond that
currentFile = tracePiece:match("^.-:")
--Hide DebugUtils in the stack trace (except main reference), if settings.INCLUDE_DEBUGUTILS_INTO_TRACE is set to true.
if settings.INCLUDE_DEBUGUTILS_INTO_TRACE or (loopDepth == startDepth) or currentFile ~= "DebugUtils:" then
trace = trace .. separator .. ((currentFile == lastFile) and tracePiece:match(":\x25d+"):sub(2,-1) or tracePiece:match("^.-:\x25d+"))
lastFile, lastTracePiece, separator = currentFile, tracePiece, " <- "
end
end
end
return trace
end
---Message Handler to be used by the try-function below.
---Adds stack trace plus formatting to the message and prints it.
---@param errorMsg string
---@param startDepth? integer default: 4 for use in xpcall
local function errorHandler(errorMsg, startDepth)
startDepth = startDepth or 4 --xpcall doesn't specify this param, so it must default to 4 for this case
errorMsg = convertToLocalErrorMsg(errorMsg)
--Print original error message and stack trace.
print("|cffff5555ERROR at " .. errorMsg .. "|r")
if settings.SHOW_TRACE_ON_ERROR then
print("|cffff5555Traceback (most recent call first):|r")
print("|cffff5555" .. getStackTrace(startDepth,200) .. "|r")
end
--Also print entries from param log, if there are any.
for location, loggedParams in pairs(paramLog) do
print("|cff888888Logged at " .. convertToLocalErrorMsg(location) .. loggedParams .. "|r")
paramLog[location] = nil
end
end
---Tries to execute the specified function with the specified parameters in protected mode and prints an error message (including stack trace), if unsuccessful.
---
---Example use: Assume you have a code line like "CreateUnit(0,1,2)", which doesn't work and you want to know why.
---* Option 1: Change it to "Debug.try(CreateUnit, 0, 1, 2)", i.e. separate the function from the parameters.
---* Option 2: Change it to "Debug.try(function() return CreateUnit(0,1,2) end)", i.e. pack it into an anonymous function. You can skip the "return", if you don't need the return values.
---When no error occured, the try-function will return all values returned by the input function.
---When an error occurs, try will print the resulting error and stack trace.
---@param funcToExecute function the function to call in protected mode
---@param ... any params for the input-function
---@return ... any
function Debug.try(funcToExecute, ...)
return select(2, xpcall(funcToExecute, errorHandler,...))
end
---@diagnostic disable-next-line lowercase-global
try = Debug.try
---Prints "ERROR:" and the specified error objects on the Screen. Also prints the stack trace leading to the error. You can specify as many arguments as you wish.
---
---In contrast to Lua's native error function, this can be called outside of protected mode and doesn't halt code execution.
---@param ... any objects/errormessages to be printed (doesn't have to be strings)
function Debug.throwError(...)
errorHandler(getStackTrace(4,4) .. ": " .. concat(...), 5)
end
---Prints the specified error message, if the specified condition fails (i.e. if it resolves to false or nil).
---
---Returns all specified arguments after the errorMsg, if the condition holds.
---
---In contrast to Lua's native assert function, this can be called outside of protected mode and doesn't halt code execution (even in case of condition failure).
---@param condition any actually a boolean, but you can use any object as a boolean.
---@param errorMsg string the message to be printed, if the condition fails
---@param ... any will be returned, if the condition holds
function Debug.assert(condition, errorMsg, ...)
if condition then
return ...
else
errorHandler(getStackTrace(4,4) .. ": " .. errorMsg, 5)
end
end
---Returns the stack trace at the code position where this function is called.
---The returned string includes war3map.lua/blizzard.j.lua code positions of all functions from the stack trace in the order of execution (most recent call last). It does NOT include function names.
---@return string
function Debug.traceback()
return getStackTrace(3,200)
end
---Saves the specified parameters to the debug log at the location where this function is called. The Debug-log will be printed for all affected locations upon the try-function catching an error.
---The log is unique per code location: Parameters logged at code line x will overwrite the previous ones logged at x. Parameters logged at different locations will all persist and be printed.
---@param ... any save any information, for instance the parameters of the function call that you are logging.
function Debug.log(...)
local _, location = pcall(error, "", 3) ---@diagnostic disable-next-line: need-check-nil
paramLog[location or ''] = concat(...)
end
------------------------------------
--| Name Caching (API-functions) |--
------------------------------------
--Help-table. The registerName-functions below shall not work on call-by-value-types, i.e. booleans, strings and numbers (renaming a value of any primitive type doesn't make sense).
local skipType = {boolean = true, string = true, number = true, ['nil'] = true}
--Set weak keys to nameCache and nameDepths and weak values for nameCacheMirror to prevent garbage collection issues
setmetatable(nameCache, {__mode = 'k'})
setmetatable(nameDepths, getmetatable(nameCache))
setmetatable(nameCacheMirror, {__mode = 'v'})
---Removes the name from the name cache, if already used for any object (freeing it for the new object). This makes sure that a name is always unique.
---This doesn't solve the
---@param name string
local function removeNameIfNecessary(name)
if nameCacheMirror[name] then
nameCache[nameCacheMirror[name]] = nil
nameCacheMirror[name] = nil
end
end
---Registers a name for the specified object, which will be the future output for tostring(whichObject).
---You can overwrite existing names for whichObject by using this.
---@param whichObject any
---@param name string
function Debug.registerName(whichObject, name)
if not skipType[type(whichObject)] then
removeNameIfNecessary(name)
nameCache[whichObject] = name
nameCacheMirror[name] = whichObject
nameDepths[name] = 0
end
end
---Registers a new name to the nameCache as either just <key> (if parentTableName is the empty string), <table>.<key> (if parentTableName is given and string key doesn't contain whitespace) or <name>[<key>] notation (for other keys in existing tables).
---Only string keys without whitespace support <key>- and <table>.<key>-notation. All other keys require a parentTableName.
---@param parentTableName string | '""' empty string suppresses <table>-affix.
---@param key any
---@param object any only call-be-ref types allowed
---@param parentTableDepth? integer
local function addNameToCache(parentTableName, key, object, parentTableDepth)
parentTableDepth = parentTableDepth or -1
--Don't overwrite existing names for the same object, don't add names for primitive types.
if nameCache[object] or skipType[type(object)] then
return
end
local name
--apply dot-syntax for string keys without whitespace
if type(key) == 'string' and not string.find(key, "\x25s") then
if parentTableName == "" then
name = key
nameDepths[object] = 0
else
name = parentTableName .. "." .. key
nameDepths[object] = parentTableDepth + 1
end
--apply bracket-syntax for all other keys. This requires a parentTableName.
elseif parentTableName ~= "" then
name = type(key) == 'string' and ('"' .. key .. '"') or key
name = parentTableName .. "[" .. tostring(name) .. "]"
nameDepths[object] = parentTableDepth + 1
end
--Stop in cases without valid name (like parentTableName = "" and key = [1])
if name then
removeNameIfNecessary(name)
nameCache[object] = name
nameCacheMirror[name] = object
end
end
---Registers all call-by-reference objects in the given parentTable to the nameCache.
---Automatically filters out primitive objects and already registed Objects.
---@param parentTable table
---@param parentTableName? string
local function registerAllObjectsInTable(parentTable, parentTableName)
parentTableName = parentTableName or nameCache[parentTable] or ""
--Register all call-by-ref-objects in parentTable
for key, object in pairs(parentTable) do
addNameToCache(parentTableName, key, object, nameDepths[parentTable])
end
end
---Adds names for all values of the specified parentTable to the name cache. Names will be "<parentTableName>.<key>" or "<parentTableName>[<key>]", depending on the key type.
---
---Example: Given a table T = {f = function() end, [1] = {}}, tostring(T.f) and tostring(T[1]) will output "function: T.f" and "table: T[1]" respectively after running Debug.registerNamesFrom(T).
---The name of T itself must either be specified as an input parameter OR have previously been registered. It can also be suppressed by inputting the empty string (so objects will just display by their own names).
---The names of objects in global scope are automatically registered during loading screen.
---@param parentTable table base table of which all entries shall be registered (in the Form parentTableName.objectName).
---@param parentTableName? string|'""' Nil: takes <parentTableName> as previously registered. Empty String: Skips <parentTableName> completely. String <s>: Objects will show up as "<s>.<objectName>".
---@param depth? integer objects within sub-tables up to the specified depth will also be added. Default: 1 (only elements of whichTable). Must be >= 1.
---@overload fun(parentTable:table, depth:integer)
function Debug.registerNamesFrom(parentTable, parentTableName, depth)
--Support overloaded definition fun(parentTable:table, depth:integer)
if type(parentTableName) == 'number' then
depth = parentTableName
parentTableName = nil
end
--Apply default values
depth = depth or 1
parentTableName = parentTableName or nameCache[parentTable] or ""
--add name of T in case it hasn't already
if not nameCache[parentTable] and parentTableName ~= "" then
Debug.registerName(parentTable, parentTableName)
end
--Register all call-by-ref-objects in parentTable. To be preferred over simple recursive approach to ensure that top level names are preferred.
registerAllObjectsInTable(parentTable, parentTableName)
--if depth > 1 was specified, also register Names from subtables.
if depth > 1 then
for _, object in pairs(parentTable) do
if type(object) == 'table' then
Debug.registerNamesFrom(object, nil, depth - 1)
end
end
end
end
-------------------------------------------
--| Name Caching (Loading Screen setup) |--
-------------------------------------------
---Registers all existing object names from global scope and Lua incorporated libraries to be used by tostring() overwrite below.
local function registerNamesFromGlobalScope()
--Add all names from global scope to the name cache.
Debug.registerNamesFrom(_G, "")
--Add all names of Warcraft-enabled Lua libraries as well:
--Could instead add a depth to the function call above, but we want to ensure that these libraries are added even if the user has chosen depth 0.
for _, lib in ipairs({coroutine, math, os, string, table, utf8, Debug}) do
Debug.registerNamesFrom(lib)
end
--Add further names that are not accessible from global scope:
--Player(i)
for i = 0, GetBJMaxPlayerSlots() - 1 do
Debug.registerName(Player(i), "Player(" .. i .. ")")
end
end
--Set empty metatable to _G. __index is added when game starts (for "attempt to read undeclared global"-errors), __newindex is added right below (for building the name cache).
setmetatable(_G, getmetatable(_G) or {}) --getmetatable(_G) should always return nil provided that DebugUtils is the topmost script file in the trigger editor, but we still include this for safety-
-- Save old tostring into Debug Library before overwriting it.
Debug.oldTostring = tostring
if settings.USE_NAME_CACHE then
local oldTostring = tostring
tostring = function(obj) --new tostring(CreateUnit) prints "function: CreateUnit"
--tostring of non-primitive object is NOT guaranteed to be like "<type>:<hex>", because it might have been changed by some __tostring-metamethod.
if settings.USE_NAME_CACHE then --return names from name cache only if setting is enabled. This allows turning it off during runtime (via Ingame Console) to revert to old tostring.
return nameCache[obj] and ((oldTostring(obj):match("^.-: ") or (oldTostring(obj) .. ": ")) .. nameCache[obj]) or oldTostring(obj)
end
return Debug.oldTostring(obj)
end
--Add names to Debug.data.objectNames within Lua root. Called below the other Debug-stuff to get the overwritten versions instead of the original ones.
registerNamesFromGlobalScope()
--Prepare __newindex-metamethod to automatically add new names to the name cache
if settings.AUTO_REGISTER_NEW_NAMES then
local nameRegisterNewIndex
---__newindex to be used for _G (and subtables up to a certain depth) to automatically register new names to the nameCache.
---Tables in global scope will use their own name. Subtables of them will use <parentName>.<childName> syntax.
---Global names don't support container[key]-notation (because "_G[...]" is probably not desired), so we only register string type keys instead of using prettyTostring.
---@param t table
---@param k any
---@param v any
---@param skipRawset? boolean set this to true when combined with another __newindex. Suppresses rawset(t,k,v) (because the other __newindex is responsible for that).
nameRegisterNewIndex = function(t,k,v, skipRawset)
local parentDepth = nameDepths[t] or 0
--Make sure the parent table has an existing name before using it as part of the child name
if t == _G or nameCache[t] then
local existingName = nameCache[v]
if not existingName then
addNameToCache((t == _G and "") or nameCache[t], k, v, parentDepth)
end
--If v is a table and the parent table has a valid name, inherit __newindex to v's existing metatable (or create a new one), if that wasn't already done.
if type(v) == 'table' and nameDepths[v] < settings.NAME_CACHE_DEPTH then
if not existingName then
--If v didn't have a name before, also add names for elements contained in v by construction (like v = {x = function() end} ).
Debug.registerNamesFrom(v, settings.NAME_CACHE_DEPTH - nameDepths[v])
end
--Apply __newindex to new tables.
if not autoIndexedTables[v] then
autoIndexedTables[v] = true
local mt = getmetatable(v)
if not mt then
mt = {}
setmetatable(v, mt) --only use setmetatable when we are sure there wasn't any before to prevent issues with "__metatable"-metamethod.
end
---@diagnostic disable-next-line: assign-type-mismatch
local existingNewIndex = mt.__newindex
local isTable_yn = (type(existingNewIndex) == 'table')
--If mt has an existing __newindex, add the name-register effect to it (effectively create a new __newindex using the old)
if existingNewIndex then
mt.__newindex = function(t,k,v)
nameRegisterNewIndex(t,k,v, true) --setting t[k] = v might not be desired in case of existing newindex. Skip it and let existingNewIndex make the decision.
if isTable_yn then
existingNewIndex[k] = v
else
return existingNewIndex(t,k,v)
end
end
else
--If mt doesn't have an existing __newindex, add one that adds the object to the name cache.
mt.__newindex = nameRegisterNewIndex
end
end
end
end
--Set t[k] = v.
if not skipRawset then
rawset(t,k,v)
end
end
--Apply metamethod to _G.
local existingNewIndex = getmetatable(_G).__newindex --should always be nil provided that DebugUtils is the topmost script in your trigger editor. Still included for safety.
local isTable_yn = (type(existingNewIndex) == 'table')
if existingNewIndex then
getmetatable(_G).__newindex = function(t,k,v)
nameRegisterNewIndex(t,k,v, true)
if isTable_yn then
existingNewIndex[k] = v
else
existingNewIndex(t,k,v)
end
end
else
getmetatable(_G).__newindex = nameRegisterNewIndex
end
end
end
------------------------------------------------------
--| Native Overwrite for Automatic Error Handling |--
------------------------------------------------------
--A table to store the try-wrapper for each function. This avoids endless re-creation of wrapper functions within the hooks below.
--Weak keys ensure that garbage collection continues as normal.
local tryWrappers = setmetatable({}, {__mode = 'k'}) ---@type table<function,function>
local try = Debug.try
---Takes a function and returns a wrapper executing the same function within Debug.try.
---Wrappers are permanently stored (until the original function is garbage collected) to ensure that they don't have to be created twice for the same function.
---@param func? function
---@return function
local function getTryWrapper(func)
if func then
tryWrappers[func] = tryWrappers[func] or function(...) return try(func, ...) end
end
return tryWrappers[func] --returns nil for func = nil (important for TimerStart overwrite below)
end
--Overwrite TriggerAddAction, TimerStart, Condition, Filter and Enum natives to let them automatically apply Debug.try.
--Also overwrites coroutine.create and coroutine.wrap to let stack traces point to the function executed within instead of the function creating the coroutine.
if settings.USE_TRY_ON_TRIGGERADDACTION then
local originalTriggerAddAction = TriggerAddAction
TriggerAddAction = function(whichTrigger, actionFunc)
return originalTriggerAddAction(whichTrigger, getTryWrapper(actionFunc))
end
end
if settings.USE_TRY_ON_TIMERSTART then
local originalTimerStart = TimerStart
TimerStart = function(whichTimer, timeout, periodic, handlerFunc)
originalTimerStart(whichTimer, timeout, periodic, getTryWrapper(handlerFunc))
end
end
if settings.USE_TRY_ON_CONDITION then
local originalCondition = Condition
Condition = function(func)
return originalCondition(getTryWrapper(func))
end
Filter = Condition
end
if settings.USE_TRY_ON_ENUMFUNCS then
local originalForGroup = ForGroup
ForGroup = function(whichGroup, callback)
originalForGroup(whichGroup, getTryWrapper(callback))
end
local originalForForce = ForForce
ForForce = function(whichForce, callback)
originalForForce(whichForce, getTryWrapper(callback))
end
local originalEnumItemsInRect = EnumItemsInRect
EnumItemsInRect = function(r, filter, actionfunc)
originalEnumItemsInRect(r, filter, getTryWrapper(actionfunc))
end
local originalEnumDestructablesInRect = EnumDestructablesInRect
EnumDestructablesInRect = function(r, filter, actionFunc)
originalEnumDestructablesInRect(r, filter, getTryWrapper(actionFunc))
end
end
if settings.USE_TRY_ON_COROUTINES then
local originalCoroutineCreate = coroutine.create
---@diagnostic disable-next-line: duplicate-set-field
coroutine.create = function(f)
return originalCoroutineCreate(getTryWrapper(f))
end
local originalCoroutineWrap = coroutine.wrap
---@diagnostic disable-next-line: duplicate-set-field
coroutine.wrap = function(f)
return originalCoroutineWrap(getTryWrapper(f))
end
end
------------------------------------------
--| Cache prints during Loading Screen |--
------------------------------------------
-- Apply the duration as specified in the settings.
if settings.PRINT_DURATION then
local display, getLocalPlayer, dur = DisplayTimedTextToPlayer, GetLocalPlayer, settings.PRINT_DURATION
print = function(...) ---@diagnostic disable-next-line: param-type-mismatch
display(getLocalPlayer(), 0, 0, dur, concat(...))
end
end
-- Delay loading screen prints to after game start.
if settings.USE_PRINT_CACHE then
local oldPrint = print
--loading screen print will write the values into the printCache
print = function(...)
if bj_gameStarted then
oldPrint(...)
else --during loading screen only: concatenate input arguments 4-space-separated, implicitely apply tostring on each, cache to table
---@diagnostic disable-next-line
printCache.n = printCache.n + 1
printCache[printCache.n] = concat(...)
end
end
end
-------------------------
--| Modify Game Start |--
-------------------------
local originalMarkGameStarted = MarkGameStarted
--Hook certain actions into the start of the game.
MarkGameStarted = function()
originalMarkGameStarted()
if settings.WARNING_FOR_UNDECLARED_GLOBALS then
local existingIndex = getmetatable(_G).__index
local isTable_yn = (type(existingIndex) == 'table')
getmetatable(_G).__index = function(t, k) --we made sure that _G has a metatable further above.
if string.sub(tostring(k),1,3) ~= 'bj_' then --prevents intentionally nilled bj-variables from triggering the check within Blizzard.j-functions, like bj_cineFadeFinishTimer.
print("Trying to read undeclared global at " .. getStackTrace(4,4) .. ": " .. tostring(k)
.. (settings.SHOW_TRACE_FOR_UNDECLARED_GLOBALS and "\nTraceback (most recent call first):\n" .. getStackTrace(4,200) or ""))
end
if existingIndex then
if isTable_yn then
return existingIndex[k]
end
return existingIndex(t,k)
end
return rawget(t,k)
end
end
--Add names to Debug.data.objectNames again to ensure that overwritten natives also make it to the name cache.
--Overwritten natives have a new value, but the old key, so __newindex didn't trigger. But we can be sure that objectNames[v] doesn't yet exist, so adding again is safe.
if settings.USE_NAME_CACHE then
for _,v in pairs(_G) do
nameCache[v] = nil
end
registerNamesFromGlobalScope()
end
--Print messages that have been cached during loading screen.
if settings.USE_PRINT_CACHE then
--Note that we don't restore the old print. The overwritten variant only applies caching behaviour to loading screen prints anyway and "unhooking" always adds other risks.
for _, str in ipairs(printCache) do
print(str)
end ---@diagnostic disable-next-line: cast-local-type
XXX = printCache
printCache = nil --frees reference for the garbage collector
end
--Create triggers listening to "-console" and "-exec" chat input.
if settings.ALLOW_INGAME_CODE_EXECUTION and IngameConsole then
IngameConsole.createTriggers()
end
end
---------------------
--| Other Utility |--
---------------------
do
---Returns the type of a warcraft object as string, e.g. "unit" upon inputting a unit.
---@param input any
---@return string
function Debug.wc3Type(input)
local typeString = type(input)
if typeString == 'userdata' then
typeString = tostring(input) --tostring returns the warcraft type plus a colon and some hashstuff.
return typeString:sub(1, (typeString:find(":", nil, true) or 0) -1) --string.find returns nil, if the argument is not found, which would break string.sub. So we need to replace by 0.
else
return typeString
end
end
Wc3Type = Debug.wc3Type --for backwards compatibility
local conciseTostring, prettyTostring
---Translates a table into a comma-separated list of its (key,value)-pairs. Also translates subtables up to the specified depth.
---E.g. {"a", 5, {7}} will display as '{(1, "a"), (2, 5), (3, {(1, 7)})}'.
---@param object any
---@param depth? integer default: unlimited. Unlimited depth will throw a stack overflow error on self-referential tables.
---@return string
conciseTostring = function (object, depth)
depth = depth or -1
if type(object) == 'string' then
return '"' .. object .. '"'
elseif depth ~= 0 and type(object) == 'table' then
local elementArray = {}
local keyAsString
for k,v in pairs(object) do
keyAsString = type(k) == 'string' and ('"' .. tostring(k) .. '"') or tostring(k)
table.insert(elementArray, '(' .. keyAsString .. ', ' .. conciseTostring(v, depth -1) .. ')')
end
return '{' .. table.concat(elementArray, ', ') .. '}'
end
return tostring(object)
end
---Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth.
---Major differences to concise print are:
--- * Format: Linebreak-formatted instead of one-liner, uses "[key] = value" instead of "(key,value)"
--- * Will also unpack tables used as keys
--- * Also includes the table's memory position as returned by tostring(table).
--- * Tables referenced multiple times will only be unpacked upon first encounter and abbreviated on subsequent encounters
--- * As a consequence, pretty version can be executed with unlimited depth on self-referential tables.
---@param object any
---@param depth? integer default: unlimited.
---@param constTable table
---@param indent string
---@return string
prettyTostring = function(object, depth, constTable, indent)
depth = depth or -1
local objType = type(object)
if objType == "string" then
return '"'..object..'"' --wrap the string in quotes.
elseif objType == 'table' and depth ~= 0 then
if not constTable[object] then
constTable[object] = tostring(object):gsub(":","")
if next(object)==nil then
return constTable[object]..": {}"
else
local mappedKV = {}
for k,v in pairs(object) do
table.insert(mappedKV, '\n ' .. indent ..'[' .. prettyTostring(k, depth - 1, constTable, indent .. " ") .. '] = ' .. prettyTostring(v, depth - 1, constTable, indent .. " "))
end
return constTable[object]..': {'.. table.concat(mappedKV, ',') .. '\n'..indent..'}'
end
end
end
return constTable[object] or tostring(object)
end
---Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth.
---Supports concise style and pretty style.
---Concise will display {"a", 5, {7}} as '{(1, "a"), (2, 5), (3, {(1, 7)})}'.
---Pretty is linebreak-separated, so consider table size before converting. Pretty also abbreviates tables referenced multiple times.
---Can be called like table.tostring(T), table.tostring(T, depth), table.tostring(T, pretty_yn) or table.tostring(T, depth, pretty_yn).
---table.tostring is not multiplayer-synced.
---@param whichTable table
---@param depth? integer default: unlimited
---@param pretty_yn? boolean default: false (concise)
---@return string
---@overload fun(whichTable:table, pretty_yn?:boolean):string
function table.tostring(whichTable, depth, pretty_yn)
--reassign input params, if function was called as table.tostring(whichTable, pretty_yn)
if type(depth) == 'boolean' then
pretty_yn = depth
depth = -1
end
return pretty_yn and prettyTostring(whichTable, depth, {}, "") or conciseTostring(whichTable, depth)
end
---Prints a list of (key,value)-pairs contained in the specified table and its subtables up to the specified depth.
---Supports concise style and pretty style. Pretty is linebreak-separated, so consider table size before printing.
---Can be called like table.print(T), table.print(T, depth), table.print(T, pretty_yn) or table.print(T, depth, pretty_yn).
---@param whichTable table
---@param depth? integer default: unlimited
---@param pretty_yn? boolean default: false (concise)
---@overload fun(whichTable:table, pretty_yn?:boolean)
function table.print(whichTable, depth, pretty_yn)
print(table.tostring(whichTable, depth, pretty_yn))
end
end
end
Debug.endFile()
if Debug and Debug.beginFile then Debug.beginFile("IngameConsole") end
--[[
--------------------------
----| Ingame Console |----
--------------------------
/**********************************************
* Allows you to use the following ingame commands:
* "-exec <code>" to execute any code ingame.
* "-console" to start an ingame console interpreting any further chat input as code and showing both return values of function calls and error messages. Furthermore, the print function will print
* directly to the console after it got started. You can still look up all print messages in the F12-log.
***********************
* -------------------
* |Using the console|
* -------------------
* Any (well, most) chat input by any player after starting the console is interpreted as code and directly executed. You can enter terms (like 4+5 or just any variable name), function calls (like print("bla"))
* and set-statements (like y = 5). If the code has any return values, all of them are printed to the console. Erroneous code will print an error message.
* Chat input starting with a hyphen is being ignored by the console, i.e. neither executed as code nor printed to the console. This allows you to still use other chat commands like "-exec" without prompting errors.
***********************
* ------------------
* |Multiline-Inputs|
* ------------------
* You can prevent a chat input from being immediately executed by preceeding it with the '>' character. All lines entered this way are halted, until any line not starting with '>' is being entered.
* The first input without '>' will execute all halted lines (and itself) in one chunk.
* Example of a chat input (the console will add an additional '>' to every line):
* >function a(x)
* >return x
* end
***********************
* Note that multiline inputs don't accept pure term evaluations, e.g. the following input is not supported and will prompt an error, while the same lines would have worked as two single-line inputs:
* >x = 5
* x
***********************
* -------------------
* |Reserved Keywords|
* -------------------
* The following keywords have a reserved functionality, i.e. are direct commands for the console and will not be interpreted as code:
* - 'help' - will show a list of all reserved keywords along very short explanations.
* - 'exit' - will shut down the console
* - 'share' - will share the players console with every other player, allowing others to read and write into it. Will force-close other players consoles, if they have one active.
* - 'clear' - will clear all text from the console, except the word 'clear'
* - 'lasttrace' - will show the stack trace of the latest error that occured within IngameConsole
* - 'show' - will show the console, after it was accidently hidden (you can accidently hide it by showing another multiboard, while the console functionality is still up and running).
* - 'printtochat' - will let the print function return to normal behaviour (i.e. print to the chat instead of the console).
* - 'printtoconsole'- will let the print function print to the console (which is default behaviour).
* - 'autosize on' - will enable automatic console resize depending on the longest string in the display. This is turned on by default.
* - 'autosize off' - will disable automatic console resize and instead linebreak long strings into multiple lines.
* - 'textlang eng' - lets the console use english Wc3 text language font size to compute linebreaks (look in your Blizzard launcher settings to find out)
* - 'textlang ger' - lets the console use german Wc3 text language font size to compute linebreaks (look in your Blizzard launcher settings to find out)
***********************
* --------------
* |Paste Helper|
* --------------
* @Luashine has created a tool that simplifies pasting multiple lines of code from outside Wc3 into the IngameConsole.
* This is particularly useful, when you want to execute a large chunk of testcode containing several linebreaks.
* Goto: https://github.com/Luashine/wc3-debug-console-paste-helper#readme
*
*************************************************/
--]]
----------------
--| Settings |--
----------------
---@class IngameConsole
IngameConsole = {
--Settings
numRows = 20 ---@type integer Number of Rows of the console (multiboard), excluding the title row. So putting 20 here will show 21 rows, first being the title row.
, autosize = true ---@type boolean Defines, whether the width of the main Column automatically adjusts with the longest string in the display.
, currentWidth = 0.5 ---@type number Current and starting Screen Share of the console main column.
, mainColMinWidth = 0.3 ---@type number Minimum Screen share of the console main column.
, mainColMaxWidth = 0.8 ---@type number Maximum Scren share of the console main column.
, tsColumnWidth = 0.06 ---@type number Screen Share of the Timestamp Column
, linebreakBuffer = 0.008 ---@type number Screen Share that is added to longest string in display to calculate the screen share for the console main column. Compensates for the small inaccuracy of the String Width function.
, maxLinebreaks = 8 ---@type integer Defines the maximum amount of linebreaks, before the remaining output string will be cut and not further displayed.
, printToConsole = true ---@type boolean defines, if the print function should print to the console or to the chat
, sharedConsole = false ---@type boolean defines, if the console is displayed to each player at the same time (accepting all players input) or if all players much start their own console.
, showTraceOnError = false ---@type boolean defines, if the console shows a trace upon printing errors. Usually not too useful within console, because you have just initiated the erroneous call.
, textLanguage = 'eng' ---@type string text language of your Wc3 installation, which influences font size (look in the settings of your Blizzard launcher). Currently only supports 'eng' and 'ger'.
, colors = {
timestamp = "bbbbbb" ---@type string Timestamp Color
, singleLineInput = "ffffaa" ---@type string Color to be applied to single line console inputs
, multiLineInput = "ffcc55" ---@type string Color to be applied to multi line console inputs
, returnValue = "00ffff" ---@type string Color applied to return values
, error = "ff5555" ---@type string Color to be applied to errors resulting of function calls
, keywordInput = "ff00ff" ---@type string Color to be applied to reserved keyword inputs (console reserved keywords)
, info = "bbbbbb" ---@type string Color to be applied to info messages from the console itself (for instance after creation or after printrestore)
}
--Privates
, numCols = 2 ---@type integer Number of Columns of the console (multiboard). Adjusting this requires further changes on code base.
, player = nil ---@type player player for whom the console is being created
, currentLine = 0 ---@type integer Current Output Line of the console.
, inputload = '' ---@type string Input Holder for multi-line-inputs
, output = {} ---@type string[] Array of all output strings
, outputTimestamps = {} ---@type string[] Array of all output string timestamps
, outputWidths = {} ---@type number[] remembers all string widths to allow for multiboard resize
, trigger = nil ---@type trigger trigger processing all inputs during console lifetime
, multiboard = nil ---@type multiboard
, timer = nil ---@type timer gets started upon console creation to measure timestamps
, errorHandler = nil ---@type fun(errorMsg:string):string error handler to be used within xpcall. We create one per console to make it compatible with console-specific settings.
, lastTrace = '' ---@type string trace of last error occured within console. To be printed via reserved keyword "lasttrace"
--Statics
, keywords = {} ---@type table<string,function> saves functions to be executed for all reserved keywords
, playerConsoles = {} ---@type table<player,IngameConsole> Consoles currently being active. up to one per player.
, originalPrint = print ---@type function original print function to restore, after the console gets closed.
}
IngameConsole.__index = IngameConsole
IngameConsole.__name = 'IngameConsole'
------------------------
--| Console Creation |--
------------------------
---Creates and opens up a new console.
---@param consolePlayer player player for whom the console is being created
---@return IngameConsole
function IngameConsole.create(consolePlayer)
local new = {} ---@type IngameConsole
setmetatable(new, IngameConsole)
---setup Object data
new.player = consolePlayer
new.output = {}
new.outputTimestamps = {}
new.outputWidths = {}
--Timer
new.timer = CreateTimer()
TimerStart(new.timer, 3600., true, nil) --just to get TimeElapsed for printing Timestamps.
--Trigger to be created after short delay, because otherwise it would fire on "-console" input immediately and lead to stack overflow.
new:setupTrigger()
--Multiboard
new:setupMultiboard()
--Create own error handler per console to be compatible with console-specific settings
new:setupErrorHandler()
--Share, if settings say so
if IngameConsole.sharedConsole then
new:makeShared() --we don't have to exit other players consoles, because we look for the setting directly in the class and there just logically can't be other active consoles.
end
--Welcome Message
new:out('info', 0, false, "Console started. Any further chat input will be executed as code, except when beginning with \x22-\x22.")
return new
end
---Creates the multiboard used for console display.
function IngameConsole:setupMultiboard()
self.multiboard = CreateMultiboard()
MultiboardSetRowCount(self.multiboard, self.numRows + 1) --title row adds 1
MultiboardSetColumnCount(self.multiboard, self.numCols)
MultiboardSetTitleText(self.multiboard, "Console")
local mbitem
for col = 1, self.numCols do
for row = 1, self.numRows + 1 do --Title row adds 1
mbitem = MultiboardGetItem(self.multiboard, row -1, col -1)
MultiboardSetItemStyle(mbitem, true, false)
MultiboardSetItemValueColor(mbitem, 255, 255, 255, 255) -- Colors get applied via text color code
MultiboardSetItemWidth(mbitem, (col == 1 and self.tsColumnWidth) or self.currentWidth )
MultiboardReleaseItem(mbitem)
end
end
mbitem = MultiboardGetItem(self.multiboard, 0, 0)
MultiboardSetItemValue(mbitem, "|cffffcc00Timestamp|r")
MultiboardReleaseItem(mbitem)
mbitem = MultiboardGetItem(self.multiboard, 0, 1)
MultiboardSetItemValue(mbitem, "|cffffcc00Line|r")
MultiboardReleaseItem(mbitem)
self:showToOwners()
end
---Creates the trigger that responds to chat events.
function IngameConsole:setupTrigger()
self.trigger = CreateTrigger()
TriggerRegisterPlayerChatEvent(self.trigger, self.player, "", false) --triggers on any input of self.player
TriggerAddCondition(self.trigger, Condition(function() return string.sub(GetEventPlayerChatString(),1,1) ~= '-' end)) --console will not react to entered stuff starting with '-'. This still allows to use other chat orders like "-exec".
TriggerAddAction(self.trigger, function() self:processInput(GetEventPlayerChatString()) end)
end
---Creates an Error Handler to be used by xpcall below.
---Adds stack trace plus formatting to the message.
function IngameConsole:setupErrorHandler()
self.errorHandler = function(errorMsg)
errorMsg = Debug.getLocalErrorMsg(errorMsg)
local _, tracePiece, lastFile = nil, "", errorMsg:match("^.-:") or "<unknown>" -- errors on objects created within Ingame Console don't have a file and linenumber. Consider "x = {}; x[nil] = 5".
local fullMsg = errorMsg .. "\nTraceback (most recent call first):\n" .. (errorMsg:match("^.-:\x25d+") or "<unknown>")
--Get Stack Trace. Starting at depth 5 ensures that "error", "messageHandler", "xpcall" and the input error message are not included.
for loopDepth = 5, 50 do --get trace on depth levels up to 50
---@diagnostic disable-next-line: cast-local-type, assign-type-mismatch
_, tracePiece = pcall(error, "", loopDepth) ---@type boolean, string
tracePiece = Debug.getLocalErrorMsg(tracePiece)
if #tracePiece > 0 then --some trace pieces can be empty, but there can still be valid ones beyond that
fullMsg = fullMsg .. " <- " .. ((tracePiece:match("^.-:") == lastFile) and tracePiece:match(":\x25d+"):sub(2,-1) or tracePiece:match("^.-:\x25d+"))
lastFile = tracePiece:match("^.-:")
end
end
self.lastTrace = fullMsg
return "ERROR: " .. (self.showTraceOnError and fullMsg or errorMsg)
end
end
---Shares this console with all players.
function IngameConsole:makeShared()
local player
for i = 0, GetBJMaxPlayers() -1 do
player = Player(i)
if (GetPlayerSlotState(player) == PLAYER_SLOT_STATE_PLAYING) and (IngameConsole.playerConsoles[player] ~= self) then --second condition ensures that the player chat event is not added twice for the same player.
IngameConsole.playerConsoles[player] = self
TriggerRegisterPlayerChatEvent(self.trigger, player, "", false) --triggers on any input
end
end
self.sharedConsole = true
end
---------------------
--| In |--
---------------------
---Processes a chat string. Each input will be printed. Incomplete multiline-inputs will be halted until completion. Completed inputs will be converted to a function and executed. If they have an output, it will be printed.
---@param inputString string
function IngameConsole:processInput(inputString)
--if the input is a reserved keyword, conduct respective actions and skip remaining actions.
if IngameConsole.keywords[inputString] then --if the input string is a reserved keyword
self:out('keywordInput', 1, false, inputString)
IngameConsole.keywords[inputString](self) --then call the method with the same name. IngameConsole.keywords["exit"](self) is just self.keywords:exit().
return
end
--if the input is a multi-line-input, queue it into the string buffer (inputLoad), but don't yet execute anything
if string.sub(inputString, 1, 1) == '>' then --multiLineInput
inputString = string.sub(inputString, 2, -1)
self:out('multiLineInput',2, false, inputString)
self.inputload = self.inputload .. inputString .. '\n'
else --if the input is either singleLineInput OR the last line of multiLineInput, execute the whole thing.
self:out(self.inputload == '' and 'singleLineInput' or 'multiLineInput', 1, false, inputString)
self.inputload = self.inputload .. inputString
local loadedFunc, errorMsg = load("return " .. self.inputload) --adds return statements, if possible (works for term statements)
if loadedFunc == nil then
loadedFunc, errorMsg = load(self.inputload)
end
self.inputload = '' --empty inputload before execution of pcall. pcall can break (rare case, can for example be provoked with metatable.__tostring = {}), which would corrupt future console inputs.
--manually catch case, where the input did not define a proper Lua statement (i.e. loadfunc is nil)
local results = loadedFunc and table.pack(xpcall(loadedFunc, self.errorHandler)) or {false, "Input is not a valid Lua-statement: " .. errorMsg}
--output error message (unsuccessful case) or return values (successful case)
if not results[1] then --results[1] is the error status that pcall always returns. False stands for: error occured.
self:out('error', 0, true, results[2]) -- second result of pcall is the error message in case an error occured
elseif results.n > 1 then --Check, if there was at least one valid output argument. We check results.n instead of results[2], because we also get nil as a proper return value this way.
self:out('returnValue', 0, true, table.unpack(results, 2, results.n))
end
end
end
----------------------
--| Out |--
----------------------
-- split color codes, split linebreaks, print lines separately, print load-errors, update string width, update text, error handling with stack trace.
---Duplicates Color coding around linebreaks to make each line printable separately.
---Operates incorrectly on lookalike color codes invalidated by preceeding escaped vertical bar (like "||cffffcc00bla|r").
---Also operates incorrectly on multiple color codes, where the first is missing the end sequence (like "|cffffcc00Hello |cff0000ffWorld|r")
---@param inputString string
---@return string, integer
function IngameConsole.spreadColorCodes(inputString)
local replacementTable = {} --remembers all substrings to be replaced and their replacements.
for foundInstance, color in inputString:gmatch("((|c\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x).-|r)") do
replacementTable[foundInstance] = foundInstance:gsub("(\r?\n)", "|r\x251" .. color)
end
return inputString:gsub("((|c\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x).-|r)", replacementTable)
end
---Concatenates all inputs to one string, spreads color codes around line breaks and prints each line to the console separately.
---@param colorTheme? '"timestamp"'| '"singleLineInput"' | '"multiLineInput"' | '"result"' | '"keywordInput"' | '"info"' | '"error"' | '"returnValue"' Decides about the color to be applied. Currently accepted: 'timestamp', 'singleLineInput', 'multiLineInput', 'result', nil. (nil equals no colorTheme, i.e. white color)
---@param numIndentations integer Number of '>' chars that shall preceed the output
---@param hideTimestamp boolean Set to false to hide the timestamp column and instead show a "->" symbol.
---@param ... any the things to be printed in the console.
function IngameConsole:out(colorTheme, numIndentations, hideTimestamp, ...)
local inputs = table.pack(...)
for i = 1, inputs.n do
inputs[i] = tostring(inputs[i]) --apply tostring on every input param in preparation for table.concat
end
--Concatenate all inputs (4-space-separated)
local printOutput = table.concat(inputs, ' ', 1, inputs.n)
printOutput = printOutput:find("(\r?\n)") and IngameConsole.spreadColorCodes(printOutput) or printOutput
local substrStart, substrEnd = 1, 1
local numLinebreaks, completePrint = 0, true
repeat
substrEnd = (printOutput:find("(\r?\n)", substrStart) or 0) - 1
numLinebreaks, completePrint = self:lineOut(colorTheme, numIndentations, hideTimestamp, numLinebreaks, printOutput:sub(substrStart, substrEnd))
hideTimestamp = true
substrStart = substrEnd + 2
until substrEnd == -1 or numLinebreaks > self.maxLinebreaks
if substrEnd ~= -1 or not completePrint then
self:lineOut('info', 0, false, 0, "Previous value not entirely printed after exceeding maximum number of linebreaks. Consider adjusting 'IngameConsole.maxLinebreaks'.")
end
self:updateMultiboard()
end
---Prints the given string to the console with the specified colorTheme and the specified number of indentations.
---Only supports one-liners (no \n) due to how multiboards work. Will add linebreaks though, if the one-liner doesn't fit into the given multiboard space.
---@param colorTheme? '"timestamp"'| '"singleLineInput"' | '"multiLineInput"' | '"result"' | '"keywordInput"' | '"info"' | '"error"' | '"returnValue"' Decides about the color to be applied. Currently accepted: 'timestamp', 'singleLineInput', 'multiLineInput', 'result', nil. (nil equals no colorTheme, i.e. white color)
---@param numIndentations integer Number of greater '>' chars that shall preceed the output
---@param hideTimestamp boolean Set to false to hide the timestamp column and instead show a "->" symbol.
---@param numLinebreaks integer
---@param printOutput string the line to be printed in the console.
---@return integer numLinebreaks, boolean hasPrintedEverything returns true, if everything could be printed. Returns false otherwise (can happen for very long strings).
function IngameConsole:lineOut(colorTheme, numIndentations, hideTimestamp, numLinebreaks, printOutput)
--add preceeding greater chars
printOutput = ('>'):rep(numIndentations) .. printOutput
--Print a space instead of the empty string. This allows the console to identify, if the string has already been fully printed (see while-loop below).
if printOutput == '' then
printOutput = ' '
end
--Compute Linebreaks.
local linebreakWidth = ((self.autosize and self.mainColMaxWidth) or self.currentWidth )
local partialOutput = nil
local maxPrintableCharPosition
local printWidth
while string.len(printOutput) > 0 and numLinebreaks <= self.maxLinebreaks do --break, if the input string has reached length 0 OR when the maximum number of linebreaks would be surpassed.
--compute max printable substring (in one multiboard line)
maxPrintableCharPosition, printWidth = IngameConsole.getLinebreakData(printOutput, linebreakWidth - self.linebreakBuffer, self.textLanguage)
--adds timestamp to the first line of any output
if numLinebreaks == 0 then
partialOutput = printOutput:sub(1, numIndentations) .. ((IngameConsole.colors[colorTheme] and "|cff" .. IngameConsole.colors[colorTheme] .. printOutput:sub(numIndentations + 1, maxPrintableCharPosition) .. "|r") or printOutput:sub(numIndentations + 1, maxPrintableCharPosition)) --Colorize the output string, if a color theme was specified. IngameConsole.colors[colorTheme] can be nil.
table.insert(self.outputTimestamps, "|cff" .. IngameConsole.colors['timestamp'] .. ((hideTimestamp and ' ->') or IngameConsole.formatTimerElapsed(TimerGetElapsed(self.timer))) .. "|r")
else
partialOutput = (IngameConsole.colors[colorTheme] and "|cff" .. IngameConsole.colors[colorTheme] .. printOutput:sub(1, maxPrintableCharPosition) .. "|r") or printOutput:sub(1, maxPrintableCharPosition) --Colorize the output string, if a color theme was specified. IngameConsole.colors[colorTheme] can be nil.
table.insert(self.outputTimestamps, ' ..') --need a dummy entry in the timestamp list to make it line-progress with the normal output.
end
numLinebreaks = numLinebreaks + 1
--writes output string and width to the console tables.
table.insert(self.output, partialOutput)
table.insert(self.outputWidths, printWidth + self.linebreakBuffer) --remember the Width of this printed string to adjust the multiboard size in case. 0.5 percent is added to avoid the case, where the multiboard width is too small by a tiny bit, thus not showing some string without spaces.
--compute remaining string to print
printOutput = string.sub(printOutput, maxPrintableCharPosition + 1, -1) --remaining string until the end. Returns empty string, if there is nothing left
end
self.currentLine = #self.output
return numLinebreaks, string.len(printOutput) == 0 --printOutput is the empty string, if and only if everything has been printed
end
---Lets the multiboard show the recently printed lines.
function IngameConsole:updateMultiboard()
local startIndex = math.max(self.currentLine - self.numRows, 0) --to be added to loop counter to get to the index of output table to print
local outputIndex = 0
local maxWidth = 0.
local mbitem
for i = 1, self.numRows do --doesn't include title row (index 0)
outputIndex = i + startIndex
mbitem = MultiboardGetItem(self.multiboard, i, 0)
MultiboardSetItemValue(mbitem, self.outputTimestamps[outputIndex] or '')
MultiboardReleaseItem(mbitem)
mbitem = MultiboardGetItem(self.multiboard, i, 1)
MultiboardSetItemValue(mbitem, self.output[outputIndex] or '')
MultiboardReleaseItem(mbitem)
maxWidth = math.max(maxWidth, self.outputWidths[outputIndex] or 0.) --looping through non-defined widths, so need to coalesce with 0
end
--Adjust Multiboard Width, if necessary.
maxWidth = math.min(math.max(maxWidth, self.mainColMinWidth), self.mainColMaxWidth)
if self.autosize and self.currentWidth ~= maxWidth then
self.currentWidth = maxWidth
for i = 1, self.numRows +1 do
mbitem = MultiboardGetItem(self.multiboard, i-1, 1)
MultiboardSetItemWidth(mbitem, maxWidth)
MultiboardReleaseItem(mbitem)
end
self:showToOwners() --reshow multiboard to update item widths on the frontend
end
end
---Shows the multiboard to all owners (one or all players)
function IngameConsole:showToOwners()
if self.sharedConsole or GetLocalPlayer() == self.player then
MultiboardDisplay(self.multiboard, true)
MultiboardMinimize(self.multiboard, false)
end
end
---Formats the elapsed time as "mm: ss. hh" (h being a hundreds of a sec)
function IngameConsole.formatTimerElapsed(elapsedInSeconds)
return string.format("\x2502d: \x2502.f. \x2502.f", elapsedInSeconds // 60, math.fmod(elapsedInSeconds, 60.) // 1, math.fmod(elapsedInSeconds, 1) * 100)
end
---Computes the max printable substring for a given string and a given linebreakWidth (regarding a single line of console).
---Returns both the substrings last char position and its total width in the multiboard.
---@param stringToPrint string the string supposed to be printed in the multiboard console.
---@param linebreakWidth number the maximum allowed width in one line of the console, before a string must linebreak
---@param textLanguage string 'ger' or 'eng'
---@return integer maxPrintableCharPosition, number printWidth
function IngameConsole.getLinebreakData(stringToPrint, linebreakWidth, textLanguage)
local loopWidth = 0.
local bytecodes = table.pack(string.byte(stringToPrint, 1, -1))
for i = 1, bytecodes.n do
loopWidth = loopWidth + string.charMultiboardWidth(bytecodes[i], textLanguage)
if loopWidth > linebreakWidth then
return i-1, loopWidth - string.charMultiboardWidth(bytecodes[i], textLanguage)
end
end
return bytecodes.n, loopWidth
end
-------------------------
--| Reserved Keywords |--
-------------------------
---Exits the Console
---@param self IngameConsole
function IngameConsole.keywords.exit(self)
DestroyMultiboard(self.multiboard)
DestroyTrigger(self.trigger)
DestroyTimer(self.timer)
IngameConsole.playerConsoles[self.player] = nil
if next(IngameConsole.playerConsoles) == nil then --set print function back to original, when no one has an active console left.
print = IngameConsole.originalPrint
end
end
---Lets the console print to chat
---@param self IngameConsole
function IngameConsole.keywords.printtochat(self)
self.printToConsole = false
self:out('info', 0, false, "The print function will print to the normal chat.")
end
---Lets the console print to itself (default)
---@param self IngameConsole
function IngameConsole.keywords.printtoconsole(self)
self.printToConsole = true
self:out('info', 0, false, "The print function will print to the console.")
end
---Shows the console in case it was hidden by another multiboard before
---@param self IngameConsole
function IngameConsole.keywords.show(self)
self:showToOwners() --might be necessary to do, if another multiboard has shown up and thereby hidden the console.
self:out('info', 0, false, "Console is showing.")
end
---Prints all available reserved keywords plus explanations.
---@param self IngameConsole
function IngameConsole.keywords.help(self)
self:out('info', 0, false, "The Console currently reserves the following keywords:")
self:out('info', 0, false, "'help' shows the text you are currently reading.")
self:out('info', 0, false, "'exit' closes the console.")
self:out('info', 0, false, "'lasttrace' shows the stack trace of the latest error that occured within IngameConsole.")
self:out('info', 0, false, "'share' allows other players to read and write into your console, but also force-closes their own consoles.")
self:out('info', 0, false, "'clear' clears all text from the console.")
self:out('info', 0, false, "'show' shows the console. Sensible to use, when displaced by another multiboard.")
self:out('info', 0, false, "'printtochat' lets Wc3 print text to normal chat again.")
self:out('info', 0, false, "'printtoconsole' lets Wc3 print text to the console (default).")
self:out('info', 0, false, "'autosize on' enables automatic console resize depending on the longest line in the display.")
self:out('info', 0, false, "'autosize off' retains the current console size.")
self:out('info', 0, false, "'textlang eng' will use english text installation font size to compute linebreaks (default).")
self:out('info', 0, false, "'textlang ger' will use german text installation font size to compute linebreaks.")
self:out('info', 0, false, "Preceeding a line with '>' prevents immediate execution, until a line not starting with '>' has been entered.")
end
---Clears the display of the console.
---@param self IngameConsole
function IngameConsole.keywords.clear(self)
self.output = {}
self.outputTimestamps = {}
self.outputWidths = {}
self.currentLine = 0
self:out('keywordInput', 1, false, 'clear') --we print 'clear' again. The keyword was already printed by self:processInput, but cleared immediately after.
end
---Shares the console with other players in the same game.
---@param self IngameConsole
function IngameConsole.keywords.share(self)
for _, console in pairs(IngameConsole.playerConsoles) do
if console ~= self then
IngameConsole.keywords['exit'](console) --share was triggered during console runtime, so there potentially are active consoles of others players that need to exit.
end
end
self:makeShared()
self:showToOwners() --showing it to the other players.
self:out('info', 0,false, "The console of player " .. GetConvertedPlayerId(self.player) .. " is now shared with all players.")
end
---Enables auto-sizing of console (will grow and shrink together with text size)
---@param self IngameConsole
IngameConsole.keywords["autosize on"] = function(self)
self.autosize = true
self:out('info', 0,false, "The console will now change size depending on its content.")
end
---Disables auto-sizing of console
---@param self IngameConsole
IngameConsole.keywords["autosize off"] = function(self)
self.autosize = false
self:out('info', 0,false, "The console will retain the width that it currently has.")
end
---Lets linebreaks be computed by german font size
---@param self IngameConsole
IngameConsole.keywords["textlang ger"] = function(self)
self.textLanguage = 'ger'
self:out('info', 0,false, "Linebreaks will now compute with respect to german text installation font size.")
end
---Lets linebreaks be computed by english font size
---@param self IngameConsole
IngameConsole.keywords["textlang eng"] = function(self)
self.textLanguage = 'eng'
self:out('info', 0,false, "Linebreaks will now compute with respect to english text installation font size.")
end
---Prints the stack trace of the latest error that occured within IngameConsole.
---@param self IngameConsole
IngameConsole.keywords["lasttrace"] = function(self)
self:out('error', 0,false, self.lastTrace)
end
--------------------
--| Main Trigger |--
--------------------
do
--Actions to be executed upon typing -exec
local function execCommand_Actions()
local input = string.sub(GetEventPlayerChatString(),7,-1)
print("Executing input: |cffffff44" .. input .. "|r")
--try preceeding the input by a return statement (preparation for printing below)
local loadedFunc, errorMsg = load("return ".. input)
if not loadedFunc then --if that doesn't produce valid code, try without return statement
loadedFunc, errorMsg = load(input)
end
--execute loaded function in case the string defined a valid function. Otherwise print error.
if errorMsg then
print("|cffff5555Invalid Lua-statement: " .. Debug.getLocalErrorMsg(errorMsg) .. "|r")
else
---@diagnostic disable-next-line: param-type-mismatch
local results = table.pack(Debug.try(loadedFunc))
if results[1] ~= nil or results.n > 1 then
for i = 1, results.n do
results[i] = tostring(results[i])
end
--concatenate all function return values to one colorized string
print("|cff00ffff" .. table.concat(results, ' ', 1, results.n) .. "|r")
end
end
end
local function execCommand_Condition()
return string.sub(GetEventPlayerChatString(), 1, 6) == "-exec "
end
local function startIngameConsole()
--if the triggering player already has a console, show that console and stop executing further actions
if IngameConsole.playerConsoles[GetTriggerPlayer()] then
IngameConsole.playerConsoles[GetTriggerPlayer()]:showToOwners()
return
end
--create Ingame Console object
IngameConsole.playerConsoles[GetTriggerPlayer()] = IngameConsole.create(GetTriggerPlayer())
--overwrite print function
print = function(...)
IngameConsole.originalPrint(...) --the new print function will also print "normally", but clear the text immediately after. This is to add the message to the F12-log.
if IngameConsole.playerConsoles[GetLocalPlayer()] and IngameConsole.playerConsoles[GetLocalPlayer()].printToConsole then
ClearTextMessages() --clear text messages for all players having an active console
end
for player, console in pairs(IngameConsole.playerConsoles) do
if console.printToConsole and (player == console.player) then --player == console.player ensures that the console only prints once, even if the console was shared among all players
console:out(nil, 0, false, ...)
end
end
end
end
---Creates the triggers listening to "-console" and "-exec" chat input.
---Being executed within DebugUtils (MarkGameStart overwrite).
function IngameConsole.createTriggers()
--Exec
local execTrigger = CreateTrigger()
TriggerAddCondition(execTrigger, Condition(execCommand_Condition))
TriggerAddAction(execTrigger, execCommand_Actions)
--Real Console
local consoleTrigger = CreateTrigger()
TriggerAddAction(consoleTrigger, startIngameConsole)
--Events
for i = 0, GetBJMaxPlayers() -1 do
TriggerRegisterPlayerChatEvent(execTrigger, Player(i), "-exec ", false)
TriggerRegisterPlayerChatEvent(consoleTrigger, Player(i), "-console", true)
end
end
end
--[[
used by Ingame Console to determine multiboard size
every unknown char will be treated as having default width (see constants below)
--]]
do
----------------------------
----| String Width API |----
----------------------------
local multiboardCharTable = {} ---@type table -- saves the width in screen percent (on 1920 pixel width resolutions) that each char takes up, when displayed in a multiboard.
local DEFAULT_MULTIBOARD_CHAR_WIDTH = 1. / 128. ---@type number -- used for unknown chars (where we didn't define a width in the char table)
local MULTIBOARD_TO_PRINT_FACTOR = 1. / 36. ---@type number -- 36 is actually the lower border (longest width of a non-breaking string only consisting of the letter "i")
---Returns the width of a char in a multiboard, when inputting a char (string of length 1) and 0 otherwise.
---also returns 0 for non-recorded chars (like ` and ´ and ß and § and €)
---@param char string | integer integer bytecode representations of chars are also allowed, i.e. the results of string.byte().
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.charMultiboardWidth(char, textlanguage)
return multiboardCharTable[textlanguage or 'eng'][char] or DEFAULT_MULTIBOARD_CHAR_WIDTH
end
---returns the width of a string in a multiboard (i.e. output is in screen percent)
---unknown chars will be measured with default width (see constants above)
---@param multichar string
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.multiboardWidth(multichar, textlanguage)
local chartable = table.pack(multichar:byte(1,-1)) --packs all bytecode char representations into a table
local charWidth = 0.
for i = 1, chartable.n do
charWidth = charWidth + string.charMultiboardWidth(chartable[i], textlanguage)
end
return charWidth
end
---The function should match the following criteria: If the value returned by this function is smaller than 1.0, than the string fits into a single line on screen.
---The opposite is not necessarily true (but should be true in the majority of cases): If the function returns bigger than 1.0, the string doesn't necessarily break.
---@param char string | integer integer bytecode representations of chars are also allowed, i.e. the results of string.byte().
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.charPrintWidth(char, textlanguage)
return string.charMultiboardWidth(char, textlanguage) * MULTIBOARD_TO_PRINT_FACTOR
end
---The function should match the following criteria: If the value returned by this function is smaller than 1.0, than the string fits into a single line on screen.
---The opposite is not necessarily true (but should be true in the majority of cases): If the function returns bigger than 1.0, the string doesn't necessarily break.
---@param multichar string
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.printWidth(multichar, textlanguage)
return string.multiboardWidth(multichar, textlanguage) * MULTIBOARD_TO_PRINT_FACTOR
end
----------------------------------
----| String Width Internals |----
----------------------------------
---@param charset '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@param char string|integer either the char or its bytecode
---@param lengthInScreenWidth number
local function setMultiboardCharWidth(charset, char, lengthInScreenWidth)
multiboardCharTable[charset] = multiboardCharTable[charset] or {}
multiboardCharTable[charset][char] = lengthInScreenWidth
end
---numberPlacements says how often the char can be placed in a multiboard column, before reaching into the right bound.
---@param charset '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@param char string|integer either the char or its bytecode
---@param numberPlacements integer
local function setMultiboardCharWidthBase80(charset, char, numberPlacements)
setMultiboardCharWidth(charset, char, 0.8 / numberPlacements) --1-based measure. 80./numberPlacements would result in Screen Percent.
setMultiboardCharWidth(charset, char:byte(1,-1), 0.8 / numberPlacements)
end
-- Set Char Width for all printable ascii chars in screen width (1920 pixels). Measured on a 80percent screen width multiboard column by counting the number of chars that fit into it.
-- Font size differs by text install language and patch (1.32- vs. 1.33+)
if BlzGetUnitOrderCount then --identifies patch 1.33+
--German font size for patch 1.33+
setMultiboardCharWidthBase80('ger', "a", 144)
setMultiboardCharWidthBase80('ger', "b", 131)
setMultiboardCharWidthBase80('ger', "c", 144)
setMultiboardCharWidthBase80('ger', "d", 120)
setMultiboardCharWidthBase80('ger', "e", 131)
setMultiboardCharWidthBase80('ger', "f", 240)
setMultiboardCharWidthBase80('ger', "g", 120)
setMultiboardCharWidthBase80('ger', "h", 131)
setMultiboardCharWidthBase80('ger', "i", 288)
setMultiboardCharWidthBase80('ger', "j", 288)
setMultiboardCharWidthBase80('ger', "k", 144)
setMultiboardCharWidthBase80('ger', "l", 288)
setMultiboardCharWidthBase80('ger', "m", 85)
setMultiboardCharWidthBase80('ger', "n", 131)
setMultiboardCharWidthBase80('ger', "o", 120)
setMultiboardCharWidthBase80('ger', "p", 120)
setMultiboardCharWidthBase80('ger', "q", 120)
setMultiboardCharWidthBase80('ger', "r", 206)
setMultiboardCharWidthBase80('ger', "s", 160)
setMultiboardCharWidthBase80('ger', "t", 206)
setMultiboardCharWidthBase80('ger', "u", 131)
setMultiboardCharWidthBase80('ger', "v", 131)
setMultiboardCharWidthBase80('ger', "w", 96)
setMultiboardCharWidthBase80('ger', "x", 144)
setMultiboardCharWidthBase80('ger', "y", 131)
setMultiboardCharWidthBase80('ger', "z", 144)
setMultiboardCharWidthBase80('ger', "A", 103)
setMultiboardCharWidthBase80('ger', "B", 120)
setMultiboardCharWidthBase80('ger', "C", 111)
setMultiboardCharWidthBase80('ger', "D", 103)
setMultiboardCharWidthBase80('ger', "E", 144)
setMultiboardCharWidthBase80('ger', "F", 160)
setMultiboardCharWidthBase80('ger', "G", 96)
setMultiboardCharWidthBase80('ger', "H", 96)
setMultiboardCharWidthBase80('ger', "I", 240)
setMultiboardCharWidthBase80('ger', "J", 240)
setMultiboardCharWidthBase80('ger', "K", 120)
setMultiboardCharWidthBase80('ger', "L", 144)
setMultiboardCharWidthBase80('ger', "M", 76)
setMultiboardCharWidthBase80('ger', "N", 96)
setMultiboardCharWidthBase80('ger', "O", 90)
setMultiboardCharWidthBase80('ger', "P", 131)
setMultiboardCharWidthBase80('ger', "Q", 90)
setMultiboardCharWidthBase80('ger', "R", 120)
setMultiboardCharWidthBase80('ger', "S", 131)
setMultiboardCharWidthBase80('ger', "T", 144)
setMultiboardCharWidthBase80('ger', "U", 103)
setMultiboardCharWidthBase80('ger', "V", 120)
setMultiboardCharWidthBase80('ger', "W", 76)
setMultiboardCharWidthBase80('ger', "X", 111)
setMultiboardCharWidthBase80('ger', "Y", 120)
setMultiboardCharWidthBase80('ger', "Z", 120)
setMultiboardCharWidthBase80('ger', "1", 144)
setMultiboardCharWidthBase80('ger', "2", 120)
setMultiboardCharWidthBase80('ger', "3", 120)
setMultiboardCharWidthBase80('ger', "4", 120)
setMultiboardCharWidthBase80('ger', "5", 120)
setMultiboardCharWidthBase80('ger', "6", 120)
setMultiboardCharWidthBase80('ger', "7", 131)
setMultiboardCharWidthBase80('ger', "8", 120)
setMultiboardCharWidthBase80('ger', "9", 120)
setMultiboardCharWidthBase80('ger', "0", 120)
setMultiboardCharWidthBase80('ger', ":", 288)
setMultiboardCharWidthBase80('ger', ";", 288)
setMultiboardCharWidthBase80('ger', ".", 288)
setMultiboardCharWidthBase80('ger', "#", 120)
setMultiboardCharWidthBase80('ger', ",", 288)
setMultiboardCharWidthBase80('ger', " ", 286) --space
setMultiboardCharWidthBase80('ger', "'", 180)
setMultiboardCharWidthBase80('ger', "!", 180)
setMultiboardCharWidthBase80('ger', "$", 131)
setMultiboardCharWidthBase80('ger', "&", 90)
setMultiboardCharWidthBase80('ger', "/", 180)
setMultiboardCharWidthBase80('ger', "(", 240)
setMultiboardCharWidthBase80('ger', ")", 240)
setMultiboardCharWidthBase80('ger', "=", 120)
setMultiboardCharWidthBase80('ger', "?", 144)
setMultiboardCharWidthBase80('ger', "^", 144)
setMultiboardCharWidthBase80('ger', "<", 144)
setMultiboardCharWidthBase80('ger', ">", 144)
setMultiboardCharWidthBase80('ger', "-", 180)
setMultiboardCharWidthBase80('ger', "+", 120)
setMultiboardCharWidthBase80('ger', "*", 180)
setMultiboardCharWidthBase80('ger', "|", 287) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('ger', "~", 111)
setMultiboardCharWidthBase80('ger', "{", 240)
setMultiboardCharWidthBase80('ger', "}", 240)
setMultiboardCharWidthBase80('ger', "[", 240)
setMultiboardCharWidthBase80('ger', "]", 240)
setMultiboardCharWidthBase80('ger', "_", 144)
setMultiboardCharWidthBase80('ger', "\x25", 103) --percent
setMultiboardCharWidthBase80('ger', "\x5C", 205) --backslash
setMultiboardCharWidthBase80('ger', "\x22", 120) --double quotation mark
setMultiboardCharWidthBase80('ger', "\x40", 90) --at sign
setMultiboardCharWidthBase80('ger', "\x60", 144) --Gravis (Accent)
--English font size for patch 1.33+
setMultiboardCharWidthBase80('eng', "a", 144)
setMultiboardCharWidthBase80('eng', "b", 120)
setMultiboardCharWidthBase80('eng', "c", 131)
setMultiboardCharWidthBase80('eng', "d", 120)
setMultiboardCharWidthBase80('eng', "e", 120)
setMultiboardCharWidthBase80('eng', "f", 240)
setMultiboardCharWidthBase80('eng', "g", 120)
setMultiboardCharWidthBase80('eng', "h", 120)
setMultiboardCharWidthBase80('eng', "i", 288)
setMultiboardCharWidthBase80('eng', "j", 288)
setMultiboardCharWidthBase80('eng', "k", 144)
setMultiboardCharWidthBase80('eng', "l", 288)
setMultiboardCharWidthBase80('eng', "m", 80)
setMultiboardCharWidthBase80('eng', "n", 120)
setMultiboardCharWidthBase80('eng', "o", 111)
setMultiboardCharWidthBase80('eng', "p", 111)
setMultiboardCharWidthBase80('eng', "q", 111)
setMultiboardCharWidthBase80('eng', "r", 206)
setMultiboardCharWidthBase80('eng', "s", 160)
setMultiboardCharWidthBase80('eng', "t", 206)
setMultiboardCharWidthBase80('eng', "u", 120)
setMultiboardCharWidthBase80('eng', "v", 144)
setMultiboardCharWidthBase80('eng', "w", 90)
setMultiboardCharWidthBase80('eng', "x", 131)
setMultiboardCharWidthBase80('eng', "y", 144)
setMultiboardCharWidthBase80('eng', "z", 144)
setMultiboardCharWidthBase80('eng', "A", 103)
setMultiboardCharWidthBase80('eng', "B", 120)
setMultiboardCharWidthBase80('eng', "C", 103)
setMultiboardCharWidthBase80('eng', "D", 96)
setMultiboardCharWidthBase80('eng', "E", 131)
setMultiboardCharWidthBase80('eng', "F", 160)
setMultiboardCharWidthBase80('eng', "G", 96)
setMultiboardCharWidthBase80('eng', "H", 90)
setMultiboardCharWidthBase80('eng', "I", 240)
setMultiboardCharWidthBase80('eng', "J", 240)
setMultiboardCharWidthBase80('eng', "K", 120)
setMultiboardCharWidthBase80('eng', "L", 131)
setMultiboardCharWidthBase80('eng', "M", 76)
setMultiboardCharWidthBase80('eng', "N", 90)
setMultiboardCharWidthBase80('eng', "O", 85)
setMultiboardCharWidthBase80('eng', "P", 120)
setMultiboardCharWidthBase80('eng', "Q", 85)
setMultiboardCharWidthBase80('eng', "R", 120)
setMultiboardCharWidthBase80('eng', "S", 131)
setMultiboardCharWidthBase80('eng', "T", 144)
setMultiboardCharWidthBase80('eng', "U", 96)
setMultiboardCharWidthBase80('eng', "V", 120)
setMultiboardCharWidthBase80('eng', "W", 76)
setMultiboardCharWidthBase80('eng', "X", 111)
setMultiboardCharWidthBase80('eng', "Y", 120)
setMultiboardCharWidthBase80('eng', "Z", 111)
setMultiboardCharWidthBase80('eng', "1", 103)
setMultiboardCharWidthBase80('eng', "2", 111)
setMultiboardCharWidthBase80('eng', "3", 111)
setMultiboardCharWidthBase80('eng', "4", 111)
setMultiboardCharWidthBase80('eng', "5", 111)
setMultiboardCharWidthBase80('eng', "6", 111)
setMultiboardCharWidthBase80('eng', "7", 111)
setMultiboardCharWidthBase80('eng', "8", 111)
setMultiboardCharWidthBase80('eng', "9", 111)
setMultiboardCharWidthBase80('eng', "0", 111)
setMultiboardCharWidthBase80('eng', ":", 288)
setMultiboardCharWidthBase80('eng', ";", 288)
setMultiboardCharWidthBase80('eng', ".", 288)
setMultiboardCharWidthBase80('eng', "#", 103)
setMultiboardCharWidthBase80('eng', ",", 288)
setMultiboardCharWidthBase80('eng', " ", 286) --space
setMultiboardCharWidthBase80('eng', "'", 360)
setMultiboardCharWidthBase80('eng', "!", 288)
setMultiboardCharWidthBase80('eng', "$", 131)
setMultiboardCharWidthBase80('eng', "&", 120)
setMultiboardCharWidthBase80('eng', "/", 180)
setMultiboardCharWidthBase80('eng', "(", 206)
setMultiboardCharWidthBase80('eng', ")", 206)
setMultiboardCharWidthBase80('eng', "=", 111)
setMultiboardCharWidthBase80('eng', "?", 180)
setMultiboardCharWidthBase80('eng', "^", 144)
setMultiboardCharWidthBase80('eng', "<", 111)
setMultiboardCharWidthBase80('eng', ">", 111)
setMultiboardCharWidthBase80('eng', "-", 160)
setMultiboardCharWidthBase80('eng', "+", 111)
setMultiboardCharWidthBase80('eng', "*", 144)
setMultiboardCharWidthBase80('eng', "|", 479) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('eng', "~", 144)
setMultiboardCharWidthBase80('eng', "{", 160)
setMultiboardCharWidthBase80('eng', "}", 160)
setMultiboardCharWidthBase80('eng', "[", 206)
setMultiboardCharWidthBase80('eng', "]", 206)
setMultiboardCharWidthBase80('eng', "_", 120)
setMultiboardCharWidthBase80('eng', "\x25", 103) --percent
setMultiboardCharWidthBase80('eng', "\x5C", 180) --backslash
setMultiboardCharWidthBase80('eng', "\x22", 180) --double quotation mark
setMultiboardCharWidthBase80('eng', "\x40", 85) --at sign
setMultiboardCharWidthBase80('eng', "\x60", 206) --Gravis (Accent)
else
--German font size up to patch 1.32
setMultiboardCharWidthBase80('ger', "a", 144)
setMultiboardCharWidthBase80('ger', "b", 144)
setMultiboardCharWidthBase80('ger', "c", 144)
setMultiboardCharWidthBase80('ger', "d", 131)
setMultiboardCharWidthBase80('ger', "e", 144)
setMultiboardCharWidthBase80('ger', "f", 240)
setMultiboardCharWidthBase80('ger', "g", 120)
setMultiboardCharWidthBase80('ger', "h", 144)
setMultiboardCharWidthBase80('ger', "i", 360)
setMultiboardCharWidthBase80('ger', "j", 288)
setMultiboardCharWidthBase80('ger', "k", 144)
setMultiboardCharWidthBase80('ger', "l", 360)
setMultiboardCharWidthBase80('ger', "m", 90)
setMultiboardCharWidthBase80('ger', "n", 144)
setMultiboardCharWidthBase80('ger', "o", 131)
setMultiboardCharWidthBase80('ger', "p", 131)
setMultiboardCharWidthBase80('ger', "q", 131)
setMultiboardCharWidthBase80('ger', "r", 206)
setMultiboardCharWidthBase80('ger', "s", 180)
setMultiboardCharWidthBase80('ger', "t", 206)
setMultiboardCharWidthBase80('ger', "u", 144)
setMultiboardCharWidthBase80('ger', "v", 131)
setMultiboardCharWidthBase80('ger', "w", 96)
setMultiboardCharWidthBase80('ger', "x", 144)
setMultiboardCharWidthBase80('ger', "y", 131)
setMultiboardCharWidthBase80('ger', "z", 144)
setMultiboardCharWidthBase80('ger', "A", 103)
setMultiboardCharWidthBase80('ger', "B", 131)
setMultiboardCharWidthBase80('ger', "C", 120)
setMultiboardCharWidthBase80('ger', "D", 111)
setMultiboardCharWidthBase80('ger', "E", 144)
setMultiboardCharWidthBase80('ger', "F", 180)
setMultiboardCharWidthBase80('ger', "G", 103)
setMultiboardCharWidthBase80('ger', "H", 103)
setMultiboardCharWidthBase80('ger', "I", 288)
setMultiboardCharWidthBase80('ger', "J", 240)
setMultiboardCharWidthBase80('ger', "K", 120)
setMultiboardCharWidthBase80('ger', "L", 144)
setMultiboardCharWidthBase80('ger', "M", 80)
setMultiboardCharWidthBase80('ger', "N", 103)
setMultiboardCharWidthBase80('ger', "O", 96)
setMultiboardCharWidthBase80('ger', "P", 144)
setMultiboardCharWidthBase80('ger', "Q", 90)
setMultiboardCharWidthBase80('ger', "R", 120)
setMultiboardCharWidthBase80('ger', "S", 144)
setMultiboardCharWidthBase80('ger', "T", 144)
setMultiboardCharWidthBase80('ger', "U", 111)
setMultiboardCharWidthBase80('ger', "V", 120)
setMultiboardCharWidthBase80('ger', "W", 76)
setMultiboardCharWidthBase80('ger', "X", 111)
setMultiboardCharWidthBase80('ger', "Y", 120)
setMultiboardCharWidthBase80('ger', "Z", 120)
setMultiboardCharWidthBase80('ger', "1", 288)
setMultiboardCharWidthBase80('ger', "2", 131)
setMultiboardCharWidthBase80('ger', "3", 144)
setMultiboardCharWidthBase80('ger', "4", 120)
setMultiboardCharWidthBase80('ger', "5", 144)
setMultiboardCharWidthBase80('ger', "6", 131)
setMultiboardCharWidthBase80('ger', "7", 144)
setMultiboardCharWidthBase80('ger', "8", 131)
setMultiboardCharWidthBase80('ger', "9", 131)
setMultiboardCharWidthBase80('ger', "0", 131)
setMultiboardCharWidthBase80('ger', ":", 480)
setMultiboardCharWidthBase80('ger', ";", 360)
setMultiboardCharWidthBase80('ger', ".", 480)
setMultiboardCharWidthBase80('ger', "#", 120)
setMultiboardCharWidthBase80('ger', ",", 360)
setMultiboardCharWidthBase80('ger', " ", 288) --space
setMultiboardCharWidthBase80('ger', "'", 480)
setMultiboardCharWidthBase80('ger', "!", 360)
setMultiboardCharWidthBase80('ger', "$", 160)
setMultiboardCharWidthBase80('ger', "&", 96)
setMultiboardCharWidthBase80('ger', "/", 180)
setMultiboardCharWidthBase80('ger', "(", 288)
setMultiboardCharWidthBase80('ger', ")", 288)
setMultiboardCharWidthBase80('ger', "=", 160)
setMultiboardCharWidthBase80('ger', "?", 180)
setMultiboardCharWidthBase80('ger', "^", 144)
setMultiboardCharWidthBase80('ger', "<", 160)
setMultiboardCharWidthBase80('ger', ">", 160)
setMultiboardCharWidthBase80('ger', "-", 144)
setMultiboardCharWidthBase80('ger', "+", 160)
setMultiboardCharWidthBase80('ger', "*", 206)
setMultiboardCharWidthBase80('ger', "|", 480) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('ger', "~", 144)
setMultiboardCharWidthBase80('ger', "{", 240)
setMultiboardCharWidthBase80('ger', "}", 240)
setMultiboardCharWidthBase80('ger', "[", 240)
setMultiboardCharWidthBase80('ger', "]", 288)
setMultiboardCharWidthBase80('ger', "_", 144)
setMultiboardCharWidthBase80('ger', "\x25", 111) --percent
setMultiboardCharWidthBase80('ger', "\x5C", 206) --backslash
setMultiboardCharWidthBase80('ger', "\x22", 240) --double quotation mark
setMultiboardCharWidthBase80('ger', "\x40", 103) --at sign
setMultiboardCharWidthBase80('ger', "\x60", 240) --Gravis (Accent)
--English Font size up to patch 1.32
setMultiboardCharWidthBase80('eng', "a", 144)
setMultiboardCharWidthBase80('eng', "b", 120)
setMultiboardCharWidthBase80('eng', "c", 131)
setMultiboardCharWidthBase80('eng', "d", 120)
setMultiboardCharWidthBase80('eng', "e", 131)
setMultiboardCharWidthBase80('eng', "f", 240)
setMultiboardCharWidthBase80('eng', "g", 120)
setMultiboardCharWidthBase80('eng', "h", 131)
setMultiboardCharWidthBase80('eng', "i", 360)
setMultiboardCharWidthBase80('eng', "j", 288)
setMultiboardCharWidthBase80('eng', "k", 144)
setMultiboardCharWidthBase80('eng', "l", 360)
setMultiboardCharWidthBase80('eng', "m", 80)
setMultiboardCharWidthBase80('eng', "n", 131)
setMultiboardCharWidthBase80('eng', "o", 120)
setMultiboardCharWidthBase80('eng', "p", 120)
setMultiboardCharWidthBase80('eng', "q", 120)
setMultiboardCharWidthBase80('eng', "r", 206)
setMultiboardCharWidthBase80('eng', "s", 160)
setMultiboardCharWidthBase80('eng', "t", 206)
setMultiboardCharWidthBase80('eng', "u", 131)
setMultiboardCharWidthBase80('eng', "v", 144)
setMultiboardCharWidthBase80('eng', "w", 90)
setMultiboardCharWidthBase80('eng', "x", 131)
setMultiboardCharWidthBase80('eng', "y", 144)
setMultiboardCharWidthBase80('eng', "z", 144)
setMultiboardCharWidthBase80('eng', "A", 103)
setMultiboardCharWidthBase80('eng', "B", 120)
setMultiboardCharWidthBase80('eng', "C", 103)
setMultiboardCharWidthBase80('eng', "D", 103)
setMultiboardCharWidthBase80('eng', "E", 131)
setMultiboardCharWidthBase80('eng', "F", 160)
setMultiboardCharWidthBase80('eng', "G", 103)
setMultiboardCharWidthBase80('eng', "H", 96)
setMultiboardCharWidthBase80('eng', "I", 288)
setMultiboardCharWidthBase80('eng', "J", 240)
setMultiboardCharWidthBase80('eng', "K", 120)
setMultiboardCharWidthBase80('eng', "L", 131)
setMultiboardCharWidthBase80('eng', "M", 76)
setMultiboardCharWidthBase80('eng', "N", 96)
setMultiboardCharWidthBase80('eng', "O", 85)
setMultiboardCharWidthBase80('eng', "P", 131)
setMultiboardCharWidthBase80('eng', "Q", 85)
setMultiboardCharWidthBase80('eng', "R", 120)
setMultiboardCharWidthBase80('eng', "S", 131)
setMultiboardCharWidthBase80('eng', "T", 144)
setMultiboardCharWidthBase80('eng', "U", 103)
setMultiboardCharWidthBase80('eng', "V", 120)
setMultiboardCharWidthBase80('eng', "W", 76)
setMultiboardCharWidthBase80('eng', "X", 111)
setMultiboardCharWidthBase80('eng', "Y", 120)
setMultiboardCharWidthBase80('eng', "Z", 111)
setMultiboardCharWidthBase80('eng', "1", 206)
setMultiboardCharWidthBase80('eng', "2", 131)
setMultiboardCharWidthBase80('eng', "3", 131)
setMultiboardCharWidthBase80('eng', "4", 111)
setMultiboardCharWidthBase80('eng', "5", 131)
setMultiboardCharWidthBase80('eng', "6", 120)
setMultiboardCharWidthBase80('eng', "7", 131)
setMultiboardCharWidthBase80('eng', "8", 111)
setMultiboardCharWidthBase80('eng', "9", 120)
setMultiboardCharWidthBase80('eng', "0", 111)
setMultiboardCharWidthBase80('eng', ":", 360)
setMultiboardCharWidthBase80('eng', ";", 360)
setMultiboardCharWidthBase80('eng', ".", 360)
setMultiboardCharWidthBase80('eng', "#", 103)
setMultiboardCharWidthBase80('eng', ",", 360)
setMultiboardCharWidthBase80('eng', " ", 288) --space
setMultiboardCharWidthBase80('eng', "'", 480)
setMultiboardCharWidthBase80('eng', "!", 360)
setMultiboardCharWidthBase80('eng', "$", 131)
setMultiboardCharWidthBase80('eng', "&", 120)
setMultiboardCharWidthBase80('eng', "/", 180)
setMultiboardCharWidthBase80('eng', "(", 240)
setMultiboardCharWidthBase80('eng', ")", 240)
setMultiboardCharWidthBase80('eng', "=", 111)
setMultiboardCharWidthBase80('eng', "?", 180)
setMultiboardCharWidthBase80('eng', "^", 144)
setMultiboardCharWidthBase80('eng', "<", 131)
setMultiboardCharWidthBase80('eng', ">", 131)
setMultiboardCharWidthBase80('eng', "-", 180)
setMultiboardCharWidthBase80('eng', "+", 111)
setMultiboardCharWidthBase80('eng', "*", 180)
setMultiboardCharWidthBase80('eng', "|", 480) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('eng', "~", 144)
setMultiboardCharWidthBase80('eng', "{", 240)
setMultiboardCharWidthBase80('eng', "}", 240)
setMultiboardCharWidthBase80('eng', "[", 240)
setMultiboardCharWidthBase80('eng', "]", 240)
setMultiboardCharWidthBase80('eng', "_", 120)
setMultiboardCharWidthBase80('eng', "\x25", 103) --percent
setMultiboardCharWidthBase80('eng', "\x5C", 180) --backslash
setMultiboardCharWidthBase80('eng', "\x22", 206) --double quotation mark
setMultiboardCharWidthBase80('eng', "\x40", 96) --at sign
setMultiboardCharWidthBase80('eng', "\x60", 206) --Gravis (Accent)
end
end
if Debug and Debug.endFile then Debug.endFile() end
---@diagnostic disable: undefined-global
if Debug then Debug.beginFile 'TotalInitialization' end
--[[——————————————————————————————————————————————————————
Total Initialization version 5.3.1
Created by: Bribe
Contributors: Eikonium, HerlySQR, Tasyen, Luashine, Forsakn
Inspiration: Almia, ScorpioT1000, Troll-Brain
Hosted at: https://github.com/BribeFromTheHive/Lua/blob/master/TotalInitialization.lua
Debug library hosted at: https://www.hiveworkshop.com/threads/debug-utils-ingame-console-etc.330758/
————————————————————————————————————————————————————————————]]
---Calls the user's initialization function during the map's loading process. The first argument should either be the init function,
---or it should be the string to give the initializer a name (works similarly to a module name/identically to a vJass library name).
---
---To use requirements, call `Require.strict 'LibraryName'` or `Require.optional 'LibraryName'`. Alternatively, the OnInit callback
---function can take the `Require` table as a single parameter: `OnInit(function(import) import.strict 'ThisIsTheSameAsRequire' end)`.
---
-- - `OnInit.global` or just `OnInit` is called after InitGlobals and is the standard point to initialize.
-- - `OnInit.trig` is called after InitCustomTriggers, and is useful for removing hooks that should only apply to GUI events.
-- - `OnInit.map` is the last point in initialization before the loading screen is completed.
-- - `OnInit.final` occurs immediately after the loading screen has disappeared, and the game has started.
---@class OnInit
--
--Simple Initialization without declaring a library name:
---@overload async fun(initCallback: Initializer.Callback)
--
--Advanced initialization with a library name and an optional third argument to signal to Eikonium's DebugUtils that the file has ended.
---@overload async fun(libraryName: string, initCallback: Initializer.Callback, debugLineNum?: integer)
--
--A way to yield your library to allow other libraries in the same initialization sequence to load, then resume once they have loaded.
---@overload async fun(customInitializerName: string)
OnInit = {}
---@alias Initializer.Callback fun(require?: Requirement | {[string]: Requirement}):...?
---@alias Requirement async fun(reqName: string, source?: table): unknown
-- `Require` will yield the calling `OnInit` initialization function until the requirement (referenced as a string) exists. It will check the
-- global API (for example, does 'GlobalRemap' exist) and then check for any named OnInit resources which might use that same string as its name.
--
-- Due to the way Sumneko's syntax highlighter works, the return value will only be linted for defined @class objects (and doesn't work for regular
-- globals like `TimerStart`). I tried to request the functionality here: https://github.com/sumneko/lua-language-server/issues/1792 , however it
-- was closed. Presumably, there are other requests asking for it, but I wouldn't count on it.
--
-- To declare a requirement, use: `Require.strict 'SomeLibrary'` or (if you don't care about the missing linting functionality) `Require 'SomeLibrary'`
--
-- To optionally require something, use any other suffix (such as `.optionally` or `.nonstrict`): `Require.optional 'SomeLibrary'`
--
---@class Require: { [string]: Requirement }
---@overload async fun(reqName: string, source?: table): string
Require = {}
do
local library = {} --You can change this to false if you don't use `Require` nor the `OnInit.library` API.
--CONFIGURABLE LEGACY API FUNCTION:
---@param _ENV table
---@param OnInit any
local function assignLegacyAPI(_ENV, OnInit)
OnGlobalInit = OnInit; OnTrigInit = OnInit.trig; OnMapInit = OnInit.map; OnGameStart = OnInit.final --Global Initialization Lite API
--OnMainInit = OnInit.main; OnLibraryInit = OnInit.library; OnGameInit = OnInit.final --short-lived experimental API
--onGlobalInit = OnInit; onTriggerInit = OnInit.trig; onInitialization = OnInit.map; onGameStart = OnInit.final --original Global Initialization API
--OnTriggerInit = OnInit.trig; OnInitialization = OnInit.map --Forsakn's Ordered Indices API
end
--END CONFIGURABLES
local _G, rawget, insert =
_G, rawget, table.insert
local initFuncQueue = {}
---@param name string
---@param continue? function
local function runInitializers(name, continue)
--print('running:', name, tostring(initFuncQueue[name]))
if initFuncQueue[name] then
for _,func in ipairs(initFuncQueue[name]) do
coroutine.wrap(func)(Require)
end
initFuncQueue[name] = nil
end
if library then
library:resume()
end
if continue then
continue()
end
end
local function initEverything()
---@param hookName string
---@param continue? function
local function hook(hookName, continue)
local hookedFunc = rawget(_G, hookName)
if hookedFunc then
rawset(_G, hookName,
function()
hookedFunc()
runInitializers(hookName, continue)
end
)
else
runInitializers(hookName, continue)
end
end
hook(
'InitGlobals',
function()
hook(
'InitCustomTriggers',
function()
hook('RunInitializationTriggers')
end
)
end
)
hook(
'MarkGameStarted',
function()
if library then
for _,func in ipairs(library.queuedInitializerList) do
func(nil, true) --run errors for missing requirements.
end
for _,func in pairs(library.yieldedModuleMatrix) do
func(true) --run errors for modules that aren't required.
end
end
OnInit = nil
Require = nil
end
)
end
---@param initName string
---@param libraryName string | Initializer.Callback
---@param func? Initializer.Callback
---@param debugLineNum? integer
---@param incDebugLevel? boolean
local function addUserFunc(initName, libraryName, func, debugLineNum, incDebugLevel)
if not func then
---@cast libraryName Initializer.Callback
func = libraryName
else
assert(type(libraryName) == 'string')
if debugLineNum and Debug then
Debug.beginFile(libraryName, incDebugLevel and 3 or 2)
Debug.data.sourceMap[#Debug.data.sourceMap].lastLine = debugLineNum
end
if library then
func = library:create(libraryName, func)
end
end
assert(type(func) == 'function')
--print('adding user func: ' , initName , libraryName, debugLineNum, incDebugLevel)
initFuncQueue[initName] = initFuncQueue[initName] or {}
insert(initFuncQueue[initName], func)
if initName == 'root' or initName == 'module' then
runInitializers(initName)
end
end
---@param name string
local function createInit(name)
---@async
---@param libraryName string --Assign your callback a unique name, allowing other OnInit callbacks can use it as a requirement.
---@param userInitFunc Initializer.Callback --Define a function to be called at the chosen point in the initialization process. It can optionally take the `Require` object as a parameter. Its optional return value(s) are passed to a requiring library via the `Require` object (defaults to `true`).
---@param debugLineNum? integer --If the Debug library is present, you can call Debug.getLine() for this parameter (which should coincide with the last line of your script file). This will neatly tie-in with OnInit's built-in Debug library functionality to define a starting line and an ending line for your module.
---@overload async fun(userInitFunc: Initializer.Callback)
return function(libraryName, userInitFunc, debugLineNum)
addUserFunc(name, libraryName, userInitFunc, debugLineNum)
end
end
OnInit.global = createInit 'InitGlobals' -- Called after InitGlobals, and is the standard point to initialize.
OnInit.trig = createInit 'InitCustomTriggers' -- Called after InitCustomTriggers, and is useful for removing hooks that should only apply to GUI events.
OnInit.map = createInit 'RunInitializationTriggers' -- Called last in the script's loading screen sequence. Runs after the GUI "Map Initialization" events have run.
OnInit.final = createInit 'MarkGameStarted' -- Called immediately after the loading screen has disappeared, and the game has started.
do
---@param self table
---@param libraryNameOrInitFunc function | string
---@param userInitFunc function
---@param debugLineNum number
local function __call(
self,
libraryNameOrInitFunc,
userInitFunc,
debugLineNum
)
if userInitFunc or type(libraryNameOrInitFunc) == 'function' then
addUserFunc(
'InitGlobals', --Calling OnInit directly defaults to OnInit.global (AKA OnGlobalInit)
libraryNameOrInitFunc,
userInitFunc,
debugLineNum,
true
)
elseif library then
library:declare(libraryNameOrInitFunc) --API handler for OnInit "Custom initializer"
else
error(
"Bad OnInit args: "..
tostring(libraryNameOrInitFunc) .. ", " ..
tostring(userInitFunc)
)
end
end
setmetatable(OnInit --[[@as table]], { __call = __call })
end
do --if you don't need the initializers for 'root', 'config' and 'main', you can delete this do...end block.
local gmt = getmetatable(_G) or
getmetatable(setmetatable(_G, {}))
local rawIndex = gmt.__newindex or rawset
local hookMainAndConfig
---@param _G table
---@param key string
---@param fnOrDiscard unknown
function hookMainAndConfig(_G, key, fnOrDiscard)
if key == 'main' or key == 'config' then
---@cast fnOrDiscard function
if key == 'main' then
runInitializers 'root'
end
rawIndex(_G, key, function()
if key == 'config' then
fnOrDiscard()
elseif gmt.__newindex == hookMainAndConfig then
gmt.__newindex = rawIndex --restore the original __newindex if no further hooks on __newindex exist.
end
runInitializers(key)
if key == 'main' then
fnOrDiscard()
end
end)
else
rawIndex(_G, key, fnOrDiscard)
end
end
gmt.__newindex = hookMainAndConfig
OnInit.root = createInit 'root' -- Runs immediately during the Lua root, but is yieldable (allowing requirements) and pcalled.
OnInit.config = createInit 'config' -- Runs when `config` is called. Credit to @Luashine: https://www.hiveworkshop.com/threads/inject-main-config-from-we-trigger-code-like-jasshelper.338201/
OnInit.main = createInit 'main' -- Runs when `main` is called. Idea from @Tasyen: https://www.hiveworkshop.com/threads/global-initialization.317099/post-3374063
end
if library then
library.queuedInitializerList = {}
library.customDeclarationList = {}
library.yieldedModuleMatrix = {}
library.moduleValueMatrix = {}
function library:pack(name, ...)
self.moduleValueMatrix[name] = table.pack(...)
end
function library:resume()
if self.queuedInitializerList[1] then
local continue, tempQueue, forceOptional
::initLibraries::
repeat
continue=false
self.queuedInitializerList, tempQueue =
{}, self.queuedInitializerList
for _,func in ipairs(tempQueue) do
if func(forceOptional) then
continue=true --Something was initialized; therefore further systems might be able to initialize.
else
insert(self.queuedInitializerList, func) --If the queued initializer returns false, that means its requirement wasn't met, so we re-queue it.
end
end
until not continue or not self.queuedInitializerList[1]
if self.customDeclarationList[1] then
self.customDeclarationList, tempQueue =
{}, self.customDeclarationList
for _,func in ipairs(tempQueue) do
func() --unfreeze any custom initializers.
end
elseif not forceOptional then
forceOptional = true
else
return
end
goto initLibraries
end
end
local function declareName(name, initialValue)
assert(type(name) == 'string')
assert(library.moduleValueMatrix[name] == nil)
library.moduleValueMatrix[name] =
initialValue and { true, n = 1 }
end
function library:create(name, userFunc)
assert(type(userFunc) == 'function')
declareName(name, false) --declare itself as a non-loaded library.
return function()
self:pack(name, userFunc(Require)) --pack return values to allow multiple values to be communicated.
if self.moduleValueMatrix[name].n == 0 then
self:pack(name, true) --No values were returned; therefore simply package the value as `true`
end
end
end
---@async
function library:declare(name)
declareName(name, true) --declare itself as a loaded library.
local co = coroutine.running()
insert(
self.customDeclarationList,
function()
coroutine.resume(co)
end
)
coroutine.yield() --yields the calling function until after all currently-queued initializers have run.
end
local processRequirement
---@async
function processRequirement(
optional,
requirement,
explicitSource
)
if type(optional) == 'string' then
optional, requirement, explicitSource =
true, optional, requirement --optional requirement (processed by the __index method)
else
optional = false --strict requirement (processed by the __call method)
end
local source = explicitSource or _G
assert(type(source)=='table')
assert(type(requirement)=='string')
::reindex::
local subSource, subReq =
requirement:match("([\x25w_]+)\x25.(.+)") --Check if user is requiring using "table.property" syntax
if subSource and subReq then
source,
requirement =
processRequirement(subSource, source), --If the container is nil, yield until it is not.
subReq
if type(source)=='table' then
explicitSource = source
goto reindex --check for further nested properties ("table.property.subProperty.anyOthers").
else
return --The source table for the requirement wasn't found, so disregard the rest (this only happens with optional requirements).
end
end
local function loadRequirement(unpack)
local package = rawget(source, requirement) --check if the requirement exists in the host table.
if not package and not explicitSource then
if library.yieldedModuleMatrix[requirement] then
library.yieldedModuleMatrix[requirement]() --load module if it exists
end
package = library.moduleValueMatrix[requirement] --retrieve the return value from the module.
if unpack and type(package)=='table' then
return table.unpack(package, 1, package.n) --using unpack allows any number of values to be returned by the required library.
end
end
return package
end
local co, loaded
local function checkReqs(forceOptional, printErrors)
if not loaded then
loaded = loadRequirement()
loaded = loaded or optional and
(loaded==nil or forceOptional)
if loaded then
if co then coroutine.resume(co) end --resume only if it was yielded in the first place.
return loaded
elseif printErrors then
coroutine.resume(co, true)
end
end
end
if not checkReqs() then --only yield if the requirement doesn't already exist.
co = coroutine.running()
insert(library.queuedInitializerList, checkReqs)
if coroutine.yield() then
error("Missing Requirement: "..requirement) --handle the error within the user's function to get an accurate stack trace via the `try` function.
end
end
return loadRequirement(true)
end
---@type Requirement
function Require.strict(name, explicitSource)
return processRequirement(nil, name, explicitSource)
end
setmetatable(Require --[[@as table]], {
__call = processRequirement,
__index = function()
return processRequirement
end
})
local module = createInit 'module'
--- `OnInit.module` will only call the OnInit function if the module is required by another resource, rather than being called at a pre-
--- specified point in the loading process. It works similarly to Go, in that including modules in your map that are not actually being
--- required will throw an error message.
---@param name string
---@param func fun(require?: Initializer.Callback):any
---@param debugLineNum? integer
OnInit.module = function(name, func, debugLineNum)
if func then
local userFunc = func
func = function(require)
local co = coroutine.running()
library.yieldedModuleMatrix[name] =
function(failure)
library.yieldedModuleMatrix[name] = nil
coroutine.resume(co, failure)
end
if coroutine.yield() then
error("Module declared but not required: ")
end
return userFunc(require)
end
end
module(name, func, debugLineNum)
end
end
if assignLegacyAPI then --This block handles legacy code.
---Allows packaging multiple requirements into one table and queues the initialization for later.
---@deprecated
---@param initList string | table
---@param userFunc function
function OnInit.library(initList, userFunc)
local typeOf = type(initList)
assert(typeOf=='table' or typeOf=='string')
assert(type(userFunc) == 'function')
local function caller(use)
if typeOf=='string' then
use(initList)
else
for _,initName in ipairs(initList) do
use(initName)
end
if initList.optional then
for _,initName in ipairs(initList.optional) do
use.lazily(initName)
end
end
end
end
if initList[name] then
OnInit(initList[name], caller)
else
OnInit(caller)
end
end
local legacyTable = {}
assignLegacyAPI(legacyTable, OnInit)
for key,func in pairs(legacyTable) do
rawset(_G, key, func)
end
OnInit.final(function()
for key in pairs(legacyTable) do
rawset(_G, key, nil)
end
end)
end
initEverything()
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "Hook" end
--——————————————————————————————————————
-- Hook version 7.1.0.1
-- Created by: Bribe
-- Contributors: Eikonium, Jampion, MyPad, Wrda
--—————————————————————————————————————————————
---@class Hook.property
---@field next function|Hook.property --Call the next/native function. Also works with any given name (old/native/original/etc.). The args and return values align with the original function.
---@field remove fun(all?: boolean) --Remove the hook. Pass the boolean "true" to remove all hooks.
---@field package tree HookTree --Reference to the tree storing each hook on that particular key in that particular host.
---@field package priority number
---@field package index integer
---@field package hookAsBasicFn? function
----@field package debugId? string
----@field package debugNext? string
---@class Hook: {[integer]: Hook.property, [string]: function}
Hook = {}
do
local looseValuesMT = { __mode = "v" }
local hostKeyTreeMatrix = ---@type table<table, table<any, HookTree>>
setmetatable({
--Already add a hook matrix for _G right away.
[_G] = setmetatable({}, looseValuesMT)
}, looseValuesMT)
---@class HookTree: { [number]: Hook.property }
---@field host table
---@field key unknown --What the function was indexed to (_G items are typically indexed via strings)
---@field hasHookAsBasicFn boolean
---Reindexes a HookTree, inserting or removing a hook and updating the properties of each hook.
---@param tree HookTree
---@param index integer
---@param newHook? table
local function reindexTree(tree, index, newHook)
if newHook then
table.insert(tree, index, newHook)
else
table.remove(tree, index)
end
local top = #tree
local prevHook = tree[index - 1]
-- `table.insert` and `table.remove` shift the elements upwards or downwards,
-- so this loop manually aligns the tree elements with this shift.
for i = index, top do
local currentHook = tree[i]
currentHook.index = i
currentHook.next = (i > 1) and
rawget(prevHook, 'hookAsBasicFn') or
prevHook
--currentHook.debugNext = tostring(currentHook.next)
prevHook = currentHook
end
local topHookBasicFn = rawget(tree[top], 'hookAsBasicFn')
if topHookBasicFn then
if not tree.hasHookAsBasicFn or rawget(tree.host, tree.key) ~= topHookBasicFn then
tree.hasHookAsBasicFn = true
--a different basic function should be called for this hook
--instead of the one that was previously there.
tree.host[tree.key] = topHookBasicFn
end
else
--The below comparison rules out 'nil' and 'true'.
--Q: Why rule out nil?
--A: There is no need to reassign a host hook handler if there is already one in place.
if tree.hasHookAsBasicFn ~= false then
tree.host[tree.key] = function(...)
return tree[#tree](...)
end
end
tree.hasHookAsBasicFn = false
end
end
---@param hookProperty Hook.property
---@param deleteAllHooks? boolean
function Hook.delete(hookProperty, deleteAllHooks)
local tree = hookProperty.tree
hookProperty.tree = nil
if deleteAllHooks or #tree == 1 then
--Reset the host table's native behavior for the hooked key.
tree.host[tree.key] =
(tree[0] ~= DoNothing) and
tree[0] or
nil
hostKeyTreeMatrix[tree.host][tree.key] = nil
else
reindexTree(tree, hookProperty.index)
end
end
---@param hostTableToHook? table
---@param defaultNativeBehavior? function
---@param hookedTableIsMetaTable? boolean
local function setupHostTable(hostTableToHook, defaultNativeBehavior, hookedTableIsMetaTable)
hostTableToHook = hostTableToHook or _G
if hookedTableIsMetaTable or
(defaultNativeBehavior and hookedTableIsMetaTable == nil)
then
hostTableToHook = getmetatable(hostTableToHook) or
getmetatable(setmetatable(hostTableToHook, {}))
end
return hostTableToHook
end
---@param tree HookTree
---@param priority number
local function huntThroughPriorityList(tree, priority)
local index = 1
local topIndex = #tree
repeat
if priority <= tree[index].priority then
break
end
index = index + 1
until index > topIndex
return index
end
---@param hostTableToHook table
---@param key unknown
---@param defaultNativeBehavior? function
---@return HookTree | nil
local function createHookTree(hostTableToHook, key, defaultNativeBehavior)
local nativeFn = rawget(hostTableToHook, key) or
defaultNativeBehavior or
((hostTableToHook ~= _G or type(key) ~= "string") and
DoNothing)
if not nativeFn then
--Logging is used here instead of directly throwing an error, because
--no one can be sure that we're running within a debug-friendly thread.
(Debug and Debug.throwError or print)("Hook Error: No value found for key: " .. tostring(key))
return
end
---@class HookTree
local tree = {
host = hostTableToHook,
key = key,
[0] = nativeFn,
--debugNativeId = tostring(nativeFn)
}
hostKeyTreeMatrix[hostTableToHook][key] = tree
return tree
end
---@param self Hook.property
local function __index(self)
return self.next
end
---@param key unknown Usually `string` (the name of the native you wish to hook)
---@param callbackFn fun(Hook, ...):any The function you want to run when the native is called. The first parameter is type "Hook", and the remaining parameters (and return value(s)) align with the original function.
---@param priority? number Defaults to 0. Hooks are called in order of highest priority down to lowest priority. The native itself has the lowest priority.
---@param hostTableToHook? table Defaults to _G (the table that stores all global variables).
---@param defaultNativeBehavior? function If the native does not exist in the host table, use this default instead.
---@param hookedTableIsMetaTable? boolean Whether to store into the host's metatable instead. Defaults to true if the "default" parameter is given.
---@param hookAsBasicFn? boolean When adding a hook instance, the default behavior is to use the __call metamethod in metatables to govern callbacks. If this is `true`, it will instead use normal function callbacks.
---@return Hook.property
function Hook.add(
key,
callbackFn,
priority,
hostTableToHook,
defaultNativeBehavior,
hookedTableIsMetaTable,
hookAsBasicFn
)
priority = priority or 0
hostTableToHook = setupHostTable(hostTableToHook, defaultNativeBehavior, hookedTableIsMetaTable)
hostKeyTreeMatrix[hostTableToHook] =
hostKeyTreeMatrix[hostTableToHook] or
setmetatable({}, looseValuesMT)
local index = 1
local tree = hostKeyTreeMatrix[hostTableToHook][key]
if tree then
index = huntThroughPriorityList(tree, priority)
else
---@diagnostic disable-next-line: cast-local-type
tree = createHookTree(hostTableToHook, key, defaultNativeBehavior)
if not tree then
return ---@diagnostic disable-line: missing-return-value
end
end
local new = {
priority = priority,
tree = tree
}
function new.remove(deleteAllHooks)
Hook.delete(new, deleteAllHooks)
end
--new.debugId = tostring(callbackFn) .. ' and ' .. tostring(new)
if hookAsBasicFn then
new.hookAsBasicFn = callbackFn
else
setmetatable(new, {
__call = callbackFn,
__index = __index
})
end
reindexTree(tree, index, new)
return new
end
end
---Hook.basic avoids creating a metatable for the hook.
---This is necessary for adding hooks to metatable methods such as __index.
---The main difference versus Hook.add is in the parameters passed to callbackFn;
---Hook.add has a 'self' argument which points to the hook, whereas Hook.basic does not.
---@param key unknown
---@param callbackFn fun(Hook, ...):any
---@param priority? number
---@param hostTableToHook? table
---@param defaultNativeBehavior? function
---@param hookedTableIsMetaTable? boolean
function Hook.basic(key, callbackFn, priority, hostTableToHook, defaultNativeBehavior, hookedTableIsMetaTable)
return Hook.add(key, callbackFn, priority, hostTableToHook, defaultNativeBehavior, hookedTableIsMetaTable, true)
end
---@deprecated
---@see Hook.add for args
function AddHook(...)
local new = Hook.basic(...)
return function(...)
return new.next(...)
end, new.remove
end
setmetatable(Hook, {
__newindex = function(_, key, callback)
Hook.add(key, callback)
end
})
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "PrecomputedHeightMap" end ---@diagnostic disable: param-type-mismatch
do
--[[
===============================================================================================================================================================
Precomputed Height Map
by Antares
===============================================================================================================================================================
GetLocZ(x, y) Returns the same value as GetLocationZ(x, y).
GetTerrainZ(x, y) Returns the exact height of the terrain geometry.
GetUnitZ(whichUnit) Returns the same value as BlzGetUnitZ(whichUnit).
GetUnitCoordinates(whichUnit) Returns x, y, and z-coordinates of a unit.
===============================================================================================================================================================
Computes the terrain height of your map on map initialization for later use. The function GetLocZ replaces the traditional GetLocZ, defined as:
function GetLocZ(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
The function provided in this library cannot cause desyncs and is approximately twice as fast. GetTerrainZ is a variation of GetLocZ that returns the exact height
of the terrain geometry (around cliffs, it has to approximate).
Note: PrecomputedHeightMap initializes OnitInit.final, because otherwise walkable doodads would not be registered.
===============================================================================================================================================================
You have the option to save the height map to a file on map initialization. You can then reimport the data into the map to load the height map from that data.
This will make the use of Z-coordinates completely safe, as all clients are guaranteed to use exactly the same data. It is recommended to do this once for the
release version of your map.
To do this, set the flag for WRITE_HEIGHT_MAP and launch your map. The terrain height map will be generated on map initialization and saved to a file in your
Warcraft III\CustomMapData\ folder. Open that file in a text editor, then remove all occurances of
call Preload( "
" )
with find and replace (including the quotation marks and tab space). Then, remove
function PreloadFiles takes nothing returns nothing
call PreloadStart()
at the beginning of the file and
call PreloadEnd( 0.0 )
endfunction
at the end of the file. Finally, remove all line breaks by removing \n and \r. The result should be something like
HeightMapCode = "|pk44mM-b+b1-dr|krjdhWcy1aa1|eWcyaa"
except much longer.
Copy the entire string and paste it anywhere into the Lua root in your map, for example into the Config section of this library. Now, every time your map is
launched, the height map will be read from the string instead of being generated, making it guaranteed to be synced.
To check if the code has been generated correctly, launch your map one more time in single-player. The height map generated from the code will be checked against
one generated in the traditional way.
--=============================================================================================================================================================
C O N F I G
--=============================================================================================================================================================
]]
local SUBFOLDER = "PrecomputedHeightMap"
--Where to store data when exporting height map.
local STORE_CLIFF_DATA = true
--If set to false, GetTerrainZ will be less accurate around cliffs, but slightly faster.
local WRITE_HEIGHT_MAP = false
--Write height map to file?
local VALIDATE_HEIGHT_MAP = true
--Check if height map read from string is accurate.
local VISUALIZE_HEIGHT_MAP = false
--Create a special effect at each grid point to double-check if the height map is correct.
--=============================================================================================================================================================
local heightMap = {} ---@type table[]
local terrainHasCliffs = {} ---@type table[]
local terrainCliffLevel = {} ---@type table[]
local moveableLoc = nil ---@type location
local MINIMUM_Z = -256 ---@type number
local CLIFF_HEIGHT = 128 ---@type number
local worldMinX
local worldMinY
local worldMaxX
local worldMaxY
local iMax
local jMax
local chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
local NUMBER_OF_CHARS = 52
---@param x number
---@param y number
---@return number
function GetLocZ(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
GetTerrainZ = GetLocZ
---@param whichUnit unit
---@return number
function GetUnitZ(whichUnit)
return GetLocZ(GetUnitX(whichUnit), GetUnitY(whichUnit)) + GetUnitFlyHeight(whichUnit)
end
---@param whichUnit unit
---@return number, number, number
function GetUnitCoordinates(whichUnit)
local x = GetUnitX(whichUnit)
local y = GetUnitY(whichUnit)
return x, y, GetLocZ(x, y) + GetUnitFlyHeight(whichUnit)
end
local function OverwriteHeightFunctions()
---@param x number
---@param y number
---@return number
GetLocZ = function(x, y)
local rx = (x - worldMinX)*0.0078125 + 1
local ry = (y - worldMinY)*0.0078125 + 1
local i = rx // 1
local j = ry // 1
rx = rx - i
ry = ry - j
if i < 1 then
i = 1
rx = 0
elseif i > iMax then
i = iMax
rx = 1
end
if j < 1 then
j = 1
ry = 0
elseif j > jMax then
j = jMax
ry = 1
end
local heightMapI = heightMap[i]
local heightMapIp1 = heightMap[i+1]
return (1 - ry)*((1 - rx)*heightMapI[j] + rx*heightMapIp1[j]) + ry*((1 - rx)*heightMapI[j+1] + rx*heightMapIp1[j+1])
end
GetLocZ2 = function(x, y)
local rx = (x - worldMinX)/128 + 1
local ry = (y - worldMinY)/128 + 1
local i = rx // 1
local j = ry // 1
rx = rx - i
ry = ry - j
if i < 1 then
i = 1
rx = 0
elseif i > iMax then
i = iMax
rx = 1
end
if j < 1 then
j = 1
ry = 0
elseif j > jMax then
j = jMax
ry = 1
end
local heightMapI = heightMap[i]
local heightMapIp1 = heightMap[i+1]
return (1 - ry)*((1 - rx)*heightMapI[j] + rx*heightMapIp1[j]) + ry*((1 - rx)*heightMapI[j+1] + rx*heightMapIp1[j+1])
end
if STORE_CLIFF_DATA then
---@param x number
---@param y number
---@return number
function GetTerrainZ(x, y)
local rx = (x - worldMinX)/128 + 1
local ry = (y - worldMinY)/128 + 1
local i = rx // 1
local j = ry // 1
rx = rx - i
ry = ry - j
if i < 1 then
i = 1
rx = 0
elseif i > iMax then
i = iMax
rx = 1
end
if j < 1 then
j = 1
ry = 0
elseif j > jMax then
j = jMax
ry = 1
end
if terrainHasCliffs[i][j] then
if rx < 0.5 then
if ry < 0.5 then
return (1 - rx - ry)*heightMap[i][j] + (rx*(heightMap[i+1][j] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j] - terrainCliffLevel[i][j])) + ry*(heightMap[i][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i][j+1] - terrainCliffLevel[i][j])))
elseif rx + ry > 1 then
return (rx + ry - 1)*(heightMap[i+1][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j+1] - terrainCliffLevel[i][j+1])) + ((1 - rx)*heightMap[i][j+1] + (1 - ry)*(heightMap[i+1][j] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j] - terrainCliffLevel[i][j+1])))
else
return (1 - rx - ry)*(heightMap[i][j] - CLIFF_HEIGHT*(terrainCliffLevel[i][j] - terrainCliffLevel[i][j+1])) + (rx*(heightMap[i+1][j] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j] - terrainCliffLevel[i][j+1])) + ry*heightMap[i][j+1])
end
elseif ry < 0.5 then
if rx + ry > 1 then
return (rx + ry - 1)*(heightMap[i+1][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j+1] - terrainCliffLevel[i+1][j])) + ((1 - rx)*(heightMap[i][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i][j+1] - terrainCliffLevel[i+1][j])) + (1 - ry)*heightMap[i+1][j])
else
return (1 - rx - ry)*(heightMap[i][j] - CLIFF_HEIGHT*(terrainCliffLevel[i][j] - terrainCliffLevel[i+1][j])) + (rx*heightMap[i+1][j] + ry*(heightMap[i][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i][j+1] - terrainCliffLevel[i+1][j])))
end
else
return (rx + ry - 1)*heightMap[i+1][j+1] + ((1 - rx)*(heightMap[i][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i][j+1] - terrainCliffLevel[i+1][j+1])) + (1 - ry)*(heightMap[i+1][j] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j] - terrainCliffLevel[i+1][j+1])))
end
else
if rx + ry > 1 then --In top-right triangle
return (rx + ry - 1)*heightMap[i+1][j+1] + ((1 - rx)*heightMap[i][j+1] + (1 - ry)*heightMap[i+1][j])
else
return (1 - rx - ry)*heightMap[i][j] + (rx*heightMap[i+1][j] + ry*heightMap[i][j+1])
end
end
end
else
---@param x number
---@param y number
---@return number
GetTerrainZ = function(x, y)
local rx = (x - worldMinX)/128 + 1
local ry = (y - worldMinY)/128 + 1
local i = rx // 1
local j = ry // 1
rx = rx - i
ry = ry - j
if i < 1 then
i = 1
rx = 0
elseif i > iMax then
i = iMax
rx = 1
end
if j < 1 then
j = 1
ry = 0
elseif j > jMax then
j = jMax
ry = 1
end
if rx + ry > 1 then --In top-right triangle
return (rx + ry - 1)*heightMap[i+1][j+1] + ((1 - rx)*heightMap[i][j+1] + (1 - ry)*heightMap[i+1][j])
else
return (1 - rx - ry)*heightMap[i][j] + (rx*heightMap[i+1][j] + ry*heightMap[i][j+1])
end
end
end
end
local function CreateHeightMap()
local xMin = (worldMinX // 128)*128
local yMin = (worldMinY // 128)*128
local xMax = (worldMaxX // 128)*128 + 1
local yMax = (worldMaxY // 128)*128 + 1
local x = xMin
local y
local i = 1
local j
while x <= xMax do
heightMap[i] = {}
if STORE_CLIFF_DATA then
terrainHasCliffs[i] = {}
terrainCliffLevel[i] = {}
end
y = yMin
j = 1
while y <= yMax do
heightMap[i][j] = GetLocZ(x,y)
if VISUALIZE_HEIGHT_MAP then
BlzSetSpecialEffectZ(AddSpecialEffect("Doodads\\Cinematic\\GlowingRunes\\GlowingRunes0", x, y), heightMap[i][j] - 40)
end
if STORE_CLIFF_DATA then
local level1 = GetTerrainCliffLevel(x, y)
local level2 = GetTerrainCliffLevel(x, y + 128)
local level3 = GetTerrainCliffLevel(x + 128, y)
local level4 = GetTerrainCliffLevel(x + 128, y + 128)
if level1 ~= level2 or level1 ~= level3 or level1 ~= level4 then
terrainHasCliffs[i][j] = true
end
terrainCliffLevel[i][j] = level1
end
j = j + 1
y = y + 128
end
i = i + 1
x = x + 128
end
iMax = i - 2
jMax = j - 2
OverwriteHeightFunctions()
end
local function ValidateHeightMap()
local xMin = (worldMinX // 128)*128
local yMin = (worldMinY // 128)*128
local xMax = (worldMaxX // 128)*128 + 1
local yMax = (worldMaxY // 128)*128 + 1
local numOutdated = 0
local x = xMin
local y
local i = 1
local j
while x <= xMax do
y = yMin
j = 1
while y <= yMax do
if heightMap[i][j] then
if VISUALIZE_HEIGHT_MAP then
BlzSetSpecialEffectZ(AddSpecialEffect("Doodads\\Cinematic\\GlowingRunes\\GlowingRunes0", x, y), heightMap[i][j] - 40)
end
if bj_isSinglePlayer and math.abs(heightMap[i][j] - GetLocZ(x, y)) > 1 then
numOutdated = numOutdated + 1
end
else
print("Height Map nil at x = " .. x .. ", y = " .. y)
end
j = j + 1
y = y + 128
end
i = i + 1
x = x + 128
end
if numOutdated > 0 then
print("|cffff0000Warning:|r Height Map is outdated at " .. numOutdated .. " locations...")
end
end
local function ReadHeightMap()
local charPos = 0
local numRepetitions = 0
local charValues = {}
for i = 1, string.len(chars) do
charValues[string.sub(chars, i, i)] = i - 1
end
local firstChar = nil
local PLUS = 0
local MINUS = 1
local ABS = 2
local segmentType = ABS
for i = 1, #heightMap do
for j = 1, #heightMap[i] do
if numRepetitions > 0 then
heightMap[i][j] = heightMap[i][j-1]
numRepetitions = numRepetitions - 1
else
local valueDetermined = false
while not valueDetermined do
charPos = charPos + 1
local char = string.sub(HeightMapCode, charPos, charPos)
if char == "+" then
segmentType = PLUS
charPos = charPos + 1
char = string.sub(HeightMapCode, charPos, charPos)
elseif char == "-" then
segmentType = MINUS
charPos = charPos + 1
char = string.sub(HeightMapCode, charPos, charPos)
elseif char == "|" then
segmentType = ABS
charPos = charPos + 1
char = string.sub(HeightMapCode, charPos, charPos)
end
if tonumber(char) then
local k = 0
while tonumber(string.sub(HeightMapCode, charPos + k + 1, charPos + k + 1)) do
k = k + 1
end
numRepetitions = tonumber(string.sub(HeightMapCode, charPos, charPos + k)) - 1
charPos = charPos + k
valueDetermined = true
heightMap[i][j] = heightMap[i][j-1]
else
if segmentType == PLUS then
heightMap[i][j] = heightMap[i][j-1] + charValues[char]
valueDetermined = true
elseif segmentType == MINUS then
heightMap[i][j] = heightMap[i][j-1] - charValues[char]
valueDetermined = true
elseif firstChar then
if charValues[firstChar] and charValues[char] then
heightMap[i][j] = charValues[firstChar]*NUMBER_OF_CHARS + charValues[char] + MINIMUM_Z
else
heightMap[i][j] = 0
end
firstChar = nil
valueDetermined = true
else
firstChar = char
end
end
end
end
end
end
HeightMapCode = nil
end
local function WriteHeightMap(subfolder)
PreloadGenClear()
PreloadGenStart()
local numRepetitions = 0
local firstChar
local secondChar
local stringLength = 0
local lastValue = 0
local PLUS = 0
local MINUS = 1
local ABS = 2
local segmentType = ABS
local preloadString = {'HeightMapCode = "'}
for i = 1, #heightMap do
for j = 1, #heightMap[i] do
if j > 1 then
local diff = (heightMap[i][j] - lastValue)//1
if diff == 0 then
numRepetitions = numRepetitions + 1
else
if numRepetitions > 0 then
table.insert(preloadString, numRepetitions)
end
numRepetitions = 0
if diff > 0 and diff < NUMBER_OF_CHARS then
if segmentType ~= PLUS then
segmentType = PLUS
table.insert(preloadString, "+")
end
elseif diff < 0 and diff > -NUMBER_OF_CHARS then
if segmentType ~= MINUS then
segmentType = MINUS
table.insert(preloadString, "-")
end
else
if segmentType ~= ABS then
segmentType = ABS
table.insert(preloadString, "|")
end
end
if segmentType == ABS then
firstChar = (heightMap[i][j] - MINIMUM_Z) // NUMBER_OF_CHARS + 1
secondChar = heightMap[i][j]//1 - MINIMUM_Z - (heightMap[i][j]//1 - MINIMUM_Z)//NUMBER_OF_CHARS*NUMBER_OF_CHARS + 1
table.insert(preloadString, string.sub(chars, firstChar, firstChar) .. string.sub(chars, secondChar, secondChar))
elseif segmentType == PLUS then
firstChar = diff//1 + 1
table.insert(preloadString, string.sub(chars, firstChar, firstChar))
elseif segmentType == MINUS then
firstChar = -diff//1 + 1
table.insert(preloadString, string.sub(chars, firstChar, firstChar))
end
end
else
if numRepetitions > 0 then
table.insert(preloadString, numRepetitions)
end
segmentType = ABS
table.insert(preloadString, "|")
numRepetitions = 0
firstChar = (heightMap[i][j] - MINIMUM_Z) // NUMBER_OF_CHARS + 1
secondChar = heightMap[i][j]//1 - MINIMUM_Z - (heightMap[i][j]//1 - MINIMUM_Z)//NUMBER_OF_CHARS*NUMBER_OF_CHARS + 1
table.insert(preloadString, string.sub(chars, firstChar, firstChar) .. string.sub(chars, secondChar, secondChar))
end
lastValue = heightMap[i][j]//1
stringLength = stringLength + 1
if stringLength == 100 then
Preload(table.concat(preloadString))
stringLength = 0
for k, __ in ipairs(preloadString) do
preloadString[k] = nil
end
end
end
end
if numRepetitions > 0 then
table.insert(preloadString, numRepetitions)
end
table.insert(preloadString, '"')
Preload(table.concat(preloadString))
PreloadGenEnd(subfolder .. "\\heightMap.txt")
print("Written Height Map to CustomMapData\\" .. subfolder .. "\\heightMap.txt")
end
local function InitHeightMap()
local xMin = (worldMinX // 128)*128
local yMin = (worldMinY // 128)*128
local xMax = (worldMaxX // 128)*128 + 1
local yMax = (worldMaxY // 128)*128 + 1
local x = xMin
local y
local i = 1
local j
while x <= xMax do
heightMap[i] = {}
if STORE_CLIFF_DATA then
terrainHasCliffs[i] = {}
terrainCliffLevel[i] = {}
end
y = yMin
j = 1
while y <= yMax do
heightMap[i][j] = 0
if STORE_CLIFF_DATA then
local level1 = GetTerrainCliffLevel(x, y)
local level2 = GetTerrainCliffLevel(x, y + 128)
local level3 = GetTerrainCliffLevel(x + 128, y)
local level4 = GetTerrainCliffLevel(x + 128, y + 128)
if level1 ~= level2 or level1 ~= level3 or level1 ~= level4 then
terrainHasCliffs[i][j] = true
end
terrainCliffLevel[i][j] = level1
end
j = j + 1
y = y + 128
end
i = i + 1
x = x + 128
end
end
OnInit.final("PrecomputedHeightMap", function()
local worldBounds = GetWorldBounds()
worldMinX = GetRectMinX(worldBounds)
worldMinY = GetRectMinY(worldBounds)
worldMaxX = GetRectMaxX(worldBounds)
worldMaxY = GetRectMaxY(worldBounds)
moveableLoc = Location(0, 0)
if HeightMapCode then
InitHeightMap()
ReadHeightMap()
if VALIDATE_HEIGHT_MAP then
ValidateHeightMap()
end
else
CreateHeightMap()
if WRITE_HEIGHT_MAP then
WriteHeightMap(SUBFOLDER)
end
end
end)
end
if Debug then Debug.beginFile "PathingWizard" end
do
--[[
=============================================================================================================================================================
Pathing Wizard
by Antares
Automatically generate pathing map and determine which points are accessible.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
Hook (optional) https://www.hiveworkshop.com/threads/hook.339153/
=============================================================================================================================================================
To import, copy this library and the Walkability Check Item.
Go through the config to see which features you want to enable. If you want to use seed points, define one for each section of your map. Using multiple seed
points per section will slow down initialization, not make it faster.
You can define rects that enable/disable pathing within that area. To do so, create rects using the World Editor's Region tool. All rects named "pathable1",
"pathable2" etc. will make the system ignore all tiles within that area. All rects named "unpathable1", "unpathable2" etc. will disable pathing within that
area. The list has to be without holes (if you have a pathable3, there has to be a pathable2).
DebugUtils might throw undeclared global warning. Disable WARNING_FOR_UNDECLARED_GLOBALS or ignore those messages.
Enable VISUALIZE_MAP and check if the reachability map has been created correctly. Check for any "leaks".
=============================================================================================================================================================
F U N C T I O N S
=============================================================================================================================================================
IsPointAccessible(x, y) Returns whether the terrain at the specified point is accessible.
GetClosestAccessiblePoint(x, y) Returns the location of the closest point that is on accessible terrain.
ArePointsConnected(xOrigin, yOrigin, xDestination, yDestination) Returns whether the destination point can be reached from the origin point.
GetSection(x, y) Returns the section index of the specified point. A value of -1 indicates inaccessible
terrain.
GetSectionSize(x, y) Returns the size of the section at the specified point (in 64x64 tiles).
GetSectionMapIndizes(x, y) Converts coordinates into array indices. The third return value denotes whether the
queried point is outside of the map bounds.
GetSectionMap() Returns the internal section map.
GetFurthestAccessiblePoint(xStart, yStart, xEnd, yEnd) Returns the furthest point that is accessible by traveling a straight line from the
specified start point to the specified end point. The third return value denotes whether
the end point was reached.
InitPathingWizard() Initializes the section map. Only necessary if AUTO_RUN_AT is disabled.
OnPathabilityUpdate(whichFunc) Executes the specified function whenever the pathing map is updated due to a
destructable being destroyed. Executes for each tile that was reevaluated. The function
is called with the parameters func(x, y, isPathable).
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local TEST_ITEM_TYPE = "Itst" ---@constant string
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Settings
--When using seed points, the reachability of a point is only checked with respect to the specified seed points. That means, a patch of walkable terrain is
--not considered reachable if there is no path to it from at least one of the seed points.
local USE_SEED_POINTS = true ---@constant boolean
--Declare the seed points of the reachability map. The table entries are x- and y-values alternatingly (x1, y1, x2, y2...).
local SEED_POINTS = { ---@constant number[]
750, -12200,
-5600, -8650
}
--Automatically disables walkability for these terrain types.
local UNPATHABLE_TERRAIN_TYPES = { ---@constant string[]
"Vrck"
}
--Create pathing blockers around the borders of areas for which the pathing has been manually disabled with unpathable rects or unpathable terrain types.
--This improves the pathfinding of units.
local CREATE_PATHING_BLOCKERS = true ---@constant boolean
--If set to true, all units and items are briefly hidden before checking pathability so that they don't mess up the result.
local HIDE_UNITS_AND_ITEMS = true ---@constant boolean
--Turns off walkability on all unreachable tiles. Only makes sense to enable this when seed points are used. Potential issue: No units can be preplaced in
--areas that should become accessible later on.
local TURN_OFF_WALKABILITY = true ---@constant boolean
--Reevaluates the pathing map around a destructable when it is destroyed. Also creates a hook for RemoveDestructable. Potential issue: Unit pathing may take
--some time to update when TURN_OFF_WALKABILITY is used.
local REDRAW_ON_DESTRUCTABLE_DEATH = true ---@constant boolean
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Initialization
--Automatically initialize the reachability map at the specified initialization point. The order of OnInits is global -> trig -> map -> final. OnInit.main will
--not work. If set to nil, you have to run it manually with InitPathingWizard().
local AUTO_RUN_AT = "global" ---@constant string
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Debugging
--Create colored runes on the ground to visualize connected areas. White runes indicate accessible areas while red runes indicated inaccessible areas. Can
--cause long stutters when used in combination with REDRAW_ON_DESTRUCTABLE_DEATH.
local VISUALIZE_MAP = false ---@constant boolean
local SHOW_COMPUTATION_TIME = false ---@constant boolean
--[[
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
local sectionOfTile = {} ---@type integer[][]
local overwriteable = {} ---@type boolean[][]
local explicitlyPathable = {} ---@type boolean[][]
local explicitlyUnpathable = {} ---@type boolean[][]
local hasPathingBlocker = {} ---@type boolean[][]
local alreadyEvaluated = {} ---@type boolean[][]
local sectionSizeOfTile = {} ---@type integer[][]
local visualizer = {} ---@type effect[][]
local worldMinX, worldMinY ---@type number, number
local worldMaxX, worldMaxY ---@type number, number
local mapMaxi, mapMaxj ---@type integer, integer
local currentI, currentJ = {}, {} ---@type integer[], integer[]
local nextI, nextJ = {}, {} ---@type integer[], integer[]
local firstI, firstJ = {}, {} ---@type integer[], integer[]
local evaluatedI, evaluatedJ = {}, {} ---@type integer[], integer[]
local highestSection ---@type integer
local sectionSize ---@type integer
local resetTileSizes = false ---@type boolean
local min = math.min
local max = math.max
local sqrt = math.sqrt
local UNPATHABLE_TERRAIN_IDS = {} ---@type integer[]
local SMALL_BLOCKER ---@type integer
local LARGE_BLOCKER ---@type integer
local onUpdateHooks = {} ---@type function[]
local testItem ---@type item
--===========================================================================================================================================================
--Utility
--===========================================================================================================================================================
local function CreateVisualizers()
local section
for i = 1, mapMaxi do
for j = 1, mapMaxj do
section = sectionOfTile[i][j]
if i == mapMaxi or sectionOfTile[i+1][j] ~= section or j == mapMaxj or sectionOfTile[i][j+1] ~= section or i == 1 or sectionOfTile[i-1][j] ~= section or j == 1 or sectionOfTile[i][j-1] ~= section then
if section > 0 then
visualizer[i][j] = AddSpecialEffect("Doodads\\Cinematic\\GlowingRunes\\GlowingRunes2", worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64)
else
visualizer[i][j] = AddSpecialEffect("Doodads\\Cinematic\\GlowingRunes\\GlowingRunes0", worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64)
end
end
BlzSetSpecialEffectZ(visualizer[i][j], BlzGetLocalSpecialEffectZ(visualizer[i][j]) - 30)
end
end
end
--[[
[2][2][2][1]
[3][ ][ ][1]
[3][X][ ][1]
[3][4][4][4]
]]
local function BorderAreaOf2x2TileIsPathable(I, J)
if I < mapMaxi - 1 then
for j = J, J >= mapMaxj - 1 and mapMaxj or J + 2 do
if not explicitlyUnpathable[I+2][j] then
return true
end
end
end
if J < mapMaxj - 1 then
for i = I == 1 and 1 or I - 1, I == mapMaxi and mapMaxi or I + 1 do
if not explicitlyUnpathable[i][J+2] then
return true
end
end
end
if I > 1 then
for j = J == 1 and 1 or J - 1, J == mapMaxj and mapMaxj or J + 1 do
if not explicitlyUnpathable[I-1][j] then
return true
end
end
end
if J > 1 then
for i = I, I >= mapMaxi - 1 and mapMaxi or I + 2 do
if not explicitlyUnpathable[i][J-1] then
return true
end
end
end
return false
end
--===========================================================================================================================================================
--Flood Fill
--===========================================================================================================================================================
local function IsPathable(i, j)
if explicitlyUnpathable[i][j] then
return false
elseif explicitlyPathable[i][j] then
return true
end
local x, y = worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64
SetItemPosition(testItem, x, y)
local dx, dy = x - GetItemX(testItem), y - GetItemY(testItem)
return dx <= 1 and dx >= -1 and dy <= 1 and dy >= -1
end
local function WriteTile(i, j, section, isUpdate)
local nextSection = sectionOfTile[i][j]
if nextSection == nil then
--Not yet processed
if not IsPathable(i, j) then
if section > 0 then
--Hit edge of inaccessible region.
sectionOfTile[i][j] = -1
else
--Region continues to be inaccessible.
sectionOfTile[i][j] = section
end
elseif USE_SEED_POINTS and section == -1 then
--Hit edge of pathable region, but not clear if connected to seed point.
sectionOfTile[i][j] = section
overwriteable[i][j] = true
else
if section > 0 then
--Region continues to be accessible.
sectionOfTile[i][j] = section
else
--Hit edge of accessible region. No seed points.
highestSection = highestSection + 1
sectionOfTile[i][j] = highestSection
end
end
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
if isUpdate then
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
end
elseif section > 0 and nextSection > section then
--Merge two accessible regions
sectionOfTile[i][j] = section
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
if isUpdate then
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
end
elseif section > 0 and overwriteable[i][j] then
--Flip unaccessible tile to accessible now that it is known that it is connected to a seed point.
sectionOfTile[i][j] = section
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
overwriteable[i][j] = nil
if isUpdate then
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
end
end
end
local function ClearTile(i, j, __, __)
local nextSection = sectionOfTile[i][j]
if alreadyEvaluated[i][j] then
return
end
if nextSection and nextSection > 0 then
firstI[#firstI + 1], firstJ[#firstJ + 1] = i, j
elseif overwriteable[i][j] then
firstI[#firstI + 1], firstJ[#firstJ + 1] = i, j
elseif nextSection then
sectionOfTile[i][j] = nil
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
end
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
alreadyEvaluated[i][j] = true
end
local function SumTile(i, j, section, __)
if alreadyEvaluated[i][j] then
return
end
if sectionOfTile[i][j] == section then
sectionSize = sectionSize + 1
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
end
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
alreadyEvaluated[i][j] = true
end
local function FloodFill(whichFunc, isUpdate)
local i, j, nexti, nextj, section
for k = 1, #currentI do
i, j = currentI[k], currentJ[k]
section = sectionOfTile[i][j]
if i < mapMaxi then
nexti = i + 1
nextj = j
whichFunc(nexti, nextj, section, isUpdate)
end
if j < mapMaxj then
nexti = i
nextj = j + 1
whichFunc(nexti, nextj, section, isUpdate)
end
if i > 1 then
nexti = i - 1
nextj = j
whichFunc(nexti, nextj, section, isUpdate)
end
if j > 1 then
nexti = i
nextj = j - 1
whichFunc(nexti, nextj, section, isUpdate)
end
end
for k = #nextI + 1, #currentI do
currentI[k], currentJ[k] = nil, nil
end
for k = 1, #nextI do
currentI[k], currentJ[k] = nextI[k], nextJ[k]
nextI[k], nextJ[k] = nil, nil
end
if #currentI > 0 then
FloodFill(whichFunc, isUpdate)
end
end
--===========================================================================================================================================================
--Destructable Death
--===========================================================================================================================================================
local function ReevaluateMapAt(x, y)
local i = ((x - worldMinX)/64 + 0.5) // 1
local j = ((y - worldMinY)/64 + 0.5) // 1
if i < 1 or i > mapMaxi or j < 1 or j > mapMaxj then
return
end
testItem = CreateItem(FourCC(TEST_ITEM_TYPE), 0, 0)
if IsPathable(i, j) and sectionOfTile[i][j] == -1 then
for k = 1, #currentI do
currentI[k], currentJ[k] = nil, nil
end
currentI[1], currentJ[1] = i, j
sectionOfTile[i][j] = nil
FloodFill(ClearTile, true)
for k = 1, #evaluatedI do
alreadyEvaluated[evaluatedI[k]][evaluatedJ[k]] = nil
evaluatedI[k], evaluatedJ[k] = nil, nil
end
currentI[1], currentJ[1] = nil, nil
for k = 1, #firstI do
currentI[k], currentJ[k] = firstI[k], firstJ[k]
firstI[k], firstJ[k] = nil, nil
end
FloodFill(WriteTile, true)
local numHooks = #onUpdateHooks
for k = 1, #evaluatedI do
i, j = evaluatedI[k], evaluatedJ[k]
x, y = worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64
for l = 1, numHooks do
onUpdateHooks[l](x, y, sectionOfTile[i][j] > 0)
end
alreadyEvaluated[i][j] = nil
evaluatedI[k], evaluatedJ[k] = nil, nil
if TURN_OFF_WALKABILITY then
SetTerrainPathable(worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64, PATHING_TYPE_WALKABILITY, sectionOfTile[i][j] > 0)
end
end
if VISUALIZE_MAP then
for i = 1, mapMaxi do
for j = 1, mapMaxj do
if visualizer[i][j] then
DestroyEffect(visualizer[i][j])
end
end
end
CreateVisualizers()
end
end
resetTileSizes = true
RemoveItem(testItem)
end
local function OnDestructableDeath()
local d = GetTriggerDestructable()
ReevaluateMapAt(GetDestructableX(d), GetDestructableY(d))
end
--===========================================================================================================================================================
--Init
--===========================================================================================================================================================
local function Init()
local startTime = os.clock()
local hook = Require.optionally "Hook"
for index, type in ipairs(UNPATHABLE_TERRAIN_TYPES) do
UNPATHABLE_TERRAIN_IDS[index] = FourCC(type)
end
SMALL_BLOCKER = FourCC "YTpb"
LARGE_BLOCKER = FourCC "YTpc"
worldMinX = GetRectMinX(bj_mapInitialPlayableArea)
worldMinY = GetRectMinY(bj_mapInitialPlayableArea)
worldMaxX = GetRectMaxX(bj_mapInitialPlayableArea)
worldMaxY = GetRectMaxY(bj_mapInitialPlayableArea)
if ALICE_ExcludeTypes then
ALICE_ExcludeTypes(TEST_ITEM_TYPE)
end
testItem = CreateItem(FourCC(TEST_ITEM_TYPE), 0, 0)
if testItem == nil then
error("Walkability Check Item has not been imported.")
end
--Hide Units
local G
if HIDE_UNITS_AND_ITEMS then
G = CreateGroup()
GroupEnumUnitsInRect(G, GetWorldBounds(), nil)
local u = BlzGroupUnitAt(G, 0)
local g = 0
while u do
ShowUnit(u, false)
g = g + 1
u = BlzGroupUnitAt(G, g)
end
end
--HideItems
EnumItemsInRect(GetWorldBounds(), nil, function()
SetItemVisible(GetEnumItem(), false)
end)
--Init 2D Tables
mapMaxi = (worldMaxX - worldMinX) // 64
mapMaxj = (worldMaxY - worldMinY) // 64
for i = 1, mapMaxi do
overwriteable[i] = {}
sectionOfTile[i] = {}
sectionSizeOfTile[i] = {}
explicitlyPathable[i] = {}
explicitlyUnpathable[i] = {}
alreadyEvaluated[i] = {}
if VISUALIZE_MAP then
visualizer[i] = {}
end
if CREATE_PATHING_BLOCKERS then
hasPathingBlocker[i] = {}
end
end
--Process Terrain Types
local unpathableIds = #UNPATHABLE_TERRAIN_IDS
local terrainType
if unpathableIds > 0 then
for x = worldMinX, worldMaxX - 64, 64 do
for y = worldMinY, worldMaxY - 64, 64 do
terrainType = GetTerrainType(x, y)
for t = 1, unpathableIds do
if terrainType == UNPATHABLE_TERRAIN_IDS[t] then
explicitlyUnpathable[((x - worldMinX)/64) // 1 + 1][((y - worldMinY)/64) // 1 + 1] = true
break
end
end
end
end
end
--Process pathable rects
local r = 1
local minI, minJ, maxI, maxJ
local rect = _G["gg_rct_pathable" .. r]
while rect do
minI = max(1, min(mapMaxi, ((GetRectMinX(rect) - worldMinX)/64) // 1 + 1))
minJ = max(1, min(mapMaxj, ((GetRectMinY(rect) - worldMinY)/64) // 1 + 1))
maxI = max(1, min(mapMaxi, ((GetRectMaxX(rect) - worldMinX)/64) // 1))
maxJ = max(1, min(mapMaxj, ((GetRectMaxY(rect) - worldMinY)/64) // 1))
for i = minI, maxI do
for j = minJ, maxJ do
explicitlyPathable[i][j] = true
end
end
r = r + 1
rect = _G["gg_rct_pathable" .. r]
end
--Process unpathable rects
r = 1
rect = _G["gg_rct_unpathable" .. r]
while rect do
minI = max(1, min(mapMaxi, ((GetRectMinX(rect) - worldMinX)/64) // 1 + 1))
minJ = max(1, min(mapMaxj, ((GetRectMinY(rect) - worldMinY)/64) // 1 + 1))
maxI = max(1, min(mapMaxi, ((GetRectMaxX(rect) - worldMinX)/64) // 1))
maxJ = max(1, min(mapMaxj, ((GetRectMaxY(rect) - worldMinY)/64) // 1))
for i = minI, maxI do
for j = minJ, maxJ do
explicitlyUnpathable[i][j] = true
end
end
r = r + 1
rect = _G["gg_rct_unpathable" .. r]
end
--Init FloodFill
if USE_SEED_POINTS then
highestSection = 0
for k = 1, #SEED_POINTS, 2 do
local i = ((SEED_POINTS[k] - worldMinX)/64 + 0.5) // 1
local j = ((SEED_POINTS[k+1] - worldMinY)/64 + 0.5) // 1
if i < 1 or i > mapMaxi or j < 1 or j > mapMaxj then
print("|cffff0000Warning:|r Seed point is outside of playable map area.")
else
highestSection = highestSection + 1
sectionOfTile[i][j] = highestSection
currentI[#currentI + 1] = i
currentJ[#currentJ + 1] = j
end
end
else
if IsPathable(1, 1) then
sectionOfTile[1][1] = 1
highestSection = 1
else
sectionOfTile[1][1] = -1
highestSection = 0
end
currentI[1], currentJ[1] = 1, 1
end
--Main
FloodFill(WriteTile, false)
if VISUALIZE_MAP then
CreateVisualizers()
end
--Finalize
if TURN_OFF_WALKABILITY then
for i = 1, mapMaxi do
for j = 1, mapMaxj do
if sectionOfTile[i][j] == -1 then
SetTerrainPathable(worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64, PATHING_TYPE_WALKABILITY, false)
end
end
end
end
local explicitlyUnpathable_i
if CREATE_PATHING_BLOCKERS then
for i = 1, mapMaxi do
explicitlyUnpathable_i = explicitlyUnpathable[i]
for j = 1, mapMaxj do
if explicitlyUnpathable_i[j] and not hasPathingBlocker[i][j] then
if i < mapMaxi and j < mapMaxj and explicitlyUnpathable[i+1][j] and explicitlyUnpathable[i+1][j+1] and explicitlyUnpathable_i[j] and BorderAreaOf2x2TileIsPathable(i, j) then
CreateDestructable(LARGE_BLOCKER, worldMinX + i*64, worldMinY + j*64, 0, 1, 0)
hasPathingBlocker[i][j] = true
hasPathingBlocker[i+1][j] = true
hasPathingBlocker[i][j+1] = true
hasPathingBlocker[i+1][j+1] = true
elseif not explicitlyUnpathable[i == mapMaxi and i or i+1][j+1] or not explicitlyUnpathable_i[j == mapMaxj and j or j+1] or not explicitlyUnpathable[i == 1 and 1 or i-1][j] or not explicitlyUnpathable_i[j == 1 and 1 or j-1] then
CreateDestructable(SMALL_BLOCKER, worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64, 0, 1, 0)
hasPathingBlocker[i][j] = true
end
end
end
end
end
--Show Units
if HIDE_UNITS_AND_ITEMS then
local u = BlzGroupUnitAt(G, 0)
local g = 0
while u do
ShowUnit(u, true)
g = g + 1
u = BlzGroupUnitAt(G, g)
end
DestroyGroup(G)
end
--Show Items
EnumItemsInRect(GetWorldBounds(), nil, function()
SetItemVisible(GetEnumItem(), true)
end)
--Create Destructable Triggers
if REDRAW_ON_DESTRUCTABLE_DEATH then
local trig = CreateTrigger()
EnumDestructablesInRect(bj_mapInitialPlayableArea, nil, function()
TriggerRegisterDeathEvent(trig, GetEnumDestructable())
end)
TriggerAddAction(trig, OnDestructableDeath)
if hook then
---@diagnostic disable-next-line: duplicate-set-field
function Hook:RemoveDestructable(whichDestructable)
local x, y = GetDestructableX(whichDestructable), GetDestructableY(whichDestructable)
self.old(whichDestructable)
ReevaluateMapAt(x, y)
end
end
end
RemoveItem(testItem)
local endTime = os.clock()
if SHOW_COMPUTATION_TIME then
print("Reachability Map evaluation time was " .. string.format("\x25.3f", endTime - startTime) .. " seconds.")
end
end
if AUTO_RUN_AT then
OnInit[AUTO_RUN_AT]("PathingWizard", Init)
end
--===========================================================================================================================================================
--API
--===========================================================================================================================================================
---Returns whether the terrain at the specified point is accessible.
---@param x number
---@param y number
---@return boolean
function IsPointAccessible(x, y)
local i = ((x - worldMinX)/64 + 1) // 1
if i > mapMaxi or i < 1 then
return false
end
local j = ((y - worldMinY)/64 + 1) // 1
if j > mapMaxj or j < 1 then
return false
end
return sectionOfTile[i][j] > 0
end
---Returns the location of the closest point that is on accessible terrain.
---@param x number
---@param y number
---@return number, number
function GetClosestAccessiblePoint(x, y)
local I = max(1, min(mapMaxi, ((x - worldMinX)/64 + 1) // 1))
local J = max(1, min(mapMaxj, ((y - worldMinY)/64 + 1) // 1))
if sectionOfTile[I][J] > 0 then
return x, y
end
local delta = 1
local dist
local lowestDist = max(mapMaxj, mapMaxi)
local lowesti, lowestj
while delta < lowestDist do
local j = min(mapMaxj, J + delta)
for i = max(1, I - delta), min(mapMaxi, I + delta) do
if sectionOfTile[i][j] > 0 then
dist = sqrt((I - i)^2 + delta*delta)
if lowestDist > dist then
lowestDist = dist
lowesti, lowestj = i, j
end
end
end
j = max(1, J - delta)
for i = max(1, I - delta), min(mapMaxi, I + delta) do
if sectionOfTile[i][j] > 0 then
dist = sqrt((I - i)^2 + delta*delta)
if lowestDist > dist then
lowestDist = dist
lowesti, lowestj = i, j
end
end
end
local i = min(mapMaxi, I + delta)
for j = max(1, J - delta), min(mapMaxj, J + delta) do
if sectionOfTile[i][j] > 0 then
dist = sqrt((J - j)^2 + delta*delta)
if lowestDist > dist then
lowestDist = dist
lowesti, lowestj = i, j
end
end
end
i = max(1, I - delta)
for j = max(1, J - delta), min(mapMaxj, J + delta) do
if sectionOfTile[i][j] > 0 then
dist = sqrt((J - j)^2 + delta*delta)
if lowestDist > dist then
lowestDist = dist
lowesti, lowestj = i, j
end
end
end
delta = delta + 1
end
if lowesti then
return worldMinX + (lowesti - 0.5)*64, worldMinY + (lowestj - 0.5)*64
else
return 0, 0
end
end
---Returns whether the destination point can be reached from the origin point.
---@param xOrigin number
---@param yOrigin number
---@param xDestination number
---@param yDestination number
---@return boolean
function ArePointsConnected(xOrigin, yOrigin, xDestination, yDestination)
local i = ((xDestination - worldMinX)/64 + 1) // 1
if i > mapMaxi or i < 1 then
return false
end
local j = ((yDestination - worldMinY)/64 + 1) // 1
if j > mapMaxj or j < 1 then
return false
end
local destinationSection = sectionOfTile[i][j]
if destinationSection <= 0 then
return false
end
i = ((xOrigin - worldMinX)/64 + 1) // 1
if i > mapMaxi or i < 1 then
return false
end
j = ((yOrigin - worldMinY)/64 + 1) // 1
if j > mapMaxj or j < 1 then
return false
end
return sectionOfTile[i][j] == destinationSection
end
---Returns the section index of the specified point. A value of -1 indicates inaccessible terrain.
---@param x number
---@param y number
---@return integer
function GetSectionOfPoint(x, y)
local i = ((x - worldMinX)/64 + 1) // 1
if i > mapMaxi or i < 1 then
return 0
end
local j = ((y - worldMinY)/64 + 1) // 1
if j > mapMaxj or j < 1 then
return 0
end
return sectionOfTile[i][j]
end
---Returns the size of the section at the specified point (in 64x64 tiles).
---@param x number
---@param y number
---@return integer
function GetSectionSize(x, y)
local I = ((x - worldMinX)/64 + 1) // 1
local J = ((y - worldMinY)/64 + 1) // 1
if I > mapMaxi or I < 1 or J > mapMaxj or J < 1 then
return 0
end
if resetTileSizes then
for i = 1, mapMaxi do
for j = 1, mapMaxj do
sectionSizeOfTile[i][j] = nil
end
end
resetTileSizes = false
end
if sectionSizeOfTile[I][J] then
return sectionSizeOfTile[I][J]
end
sectionSize = 0
currentI[1], currentJ[1] = I, J
FloodFill(SumTile, false)
for k = 1, #evaluatedI do
sectionSizeOfTile[evaluatedI[k]][evaluatedJ[k]] = sectionSize
alreadyEvaluated[evaluatedI[k]][evaluatedJ[k]] = nil
evaluatedI[k], evaluatedJ[k] = nil, nil
end
return sectionSize
end
---Converts coordinates into array indices. The third return value denotes whether the queried point is outside of the map bounds.
---@param x number
---@param y number
---@return integer, integer, boolean
function GetSectionMapIndizes(x, y)
local i, j = ((x - worldMinX)/64 + 1) // 1, ((y - worldMinY)/64 + 1) // 1
local outsideOfBounds = false
if i < 1 then
i = 1
outsideOfBounds = true
elseif i > mapMaxi then
i = mapMaxi
outsideOfBounds = true
end
if j < 1 then
j = 1
outsideOfBounds = true
elseif j > mapMaxj then
j = mapMaxj
outsideOfBounds = true
end
return i, j, outsideOfBounds
end
---Returns the furthest point that is accessible by traveling a straight line from the specified start point to the specified end point. The third return value denotes whether the end point was reached.
---@param xStart number
---@param yStart number
---@param xEnd number
---@param yEnd number
---@return number, number, boolean
function GetFurthestAccessiblePoint(xStart, yStart, xEnd, yEnd)
local iStart, jStart = GetSectionMapIndizes(xStart, yStart)
local section = sectionOfTile[iStart][jStart]
if section < 0 then
return xStart, yStart, false
end
local iEnd, jEnd, outsideOfMapBounds = GetSectionMapIndizes(xEnd, yEnd)
local di = iEnd - iStart
local dj = jEnd - jStart
local adi = di
local adj = dj
local sdi = 0
local sdj = 0
local pdi
local pdj
local ddi
local ddy
local es
local el
local error
local i = iStart
local j = jStart
--calculate abs values and signs
if adi < 0 then
adi = -adi
sdi = -1
elseif adi > 0 then
sdi = 1
end
if adj < 0 then
adj = -adj
sdj = -1
elseif adj > 0 then
sdj = 1
end
if adi > adj then
pdi = sdi
pdj = 0
es = adj
el = adi
else
pdi = 0
pdj = sdj
es = adi
el = adj
end
ddi = sdi
ddy = sdj
error = el/2
local lastPathableI = iStart
local lastPathableJ = jStart
for __ = 1, el do
error = error - es
lastPathableI = i
lastPathableJ = j
if error < 0 then
di = i + ddi - pdi
dj = j + ddy - pdj
if di < 1 or di > mapMaxi or dj < 1 or dj > mapMaxj or sectionOfTile[di][dj] ~= section then
return worldMinX + (lastPathableI - 0.5)*64, worldMinY + (lastPathableJ - 0.5)*64, false
end
error = error + el
i = i + ddi
j = j + ddy
else
i = i + pdi
j = j + pdj
end
if i < 1 or i > mapMaxi or j < 1 or j > mapMaxj or sectionOfTile[i][j] ~= section then
return worldMinX + (lastPathableI - 0.5)*64, worldMinY + (lastPathableJ - 0.5)*64, false
end
end
if not outsideOfMapBounds then
return xEnd, yEnd, true
else
return worldMinX + (lastPathableI - 0.5)*64, worldMinY + (lastPathableJ - 0.5)*64, false
end
end
---Returns the internal section map.
---@return integer[][]
function GetSectionMap()
return sectionOfTile
end
---Initializes the section map. Only necessary if AUTO_RUN_AT is disabled.
function InitPathingWizard()
Init()
end
---Executes the specified function whenever the pathing map is updated due to a destructable being destroyed. Executes for each tile that was reevaluated. The function is called with the parameters func(x, y, isPathable).
---@param whichFunc function
function OnPathabilityUpdate(whichFunc)
table.insert(onUpdateHooks, whichFunc)
end
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile("HandleType") end
do
--[[
===============================================================================================================================================================
Handle Type
by Antares
===============================================================================================================================================================
Determine the type of a Wacraft 3 object (handle). The result is stored in a table on the first execution to increase performance.
HandleType[whichHandle] -> string Returns an empty string if variable is not a handle.
IsHandle[whichHandle] -> boolean
IsWidget[whichHandle] -> boolean
IsUnit[whichHandle] -> boolean
These can also be called as a function, which has a nil-check, but is slower than the table-lookup
===============================================================================================================================================================
]]
local widgetTypes = {
unit = true,
destructable = true,
item = true
}
HandleType = setmetatable({}, {
__mode = "k",
__index = function(self, key)
if type(key) == "userdata" then
local str = tostring(key)
self[key] = str:sub(1, (str:find(":", nil, true) or 0) - 1)
return self[key]
else
self[key] = ""
return ""
end
end,
__call = function(self, key)
if key then
return self[key]
else
return ""
end
end
})
IsHandle = setmetatable({}, {
__mode = "k",
__index = function(self, key)
self[key] = HandleType[key] ~= ""
return self[key]
end,
__call = function(self, key)
if key then
return self[key]
else
return false
end
end
})
IsWidget = setmetatable({}, {
__mode = "k",
__index = function(self, key)
self[key] = widgetTypes[HandleType[key]] == true
return self[key]
end,
__call = function(self, key)
if key then
return self[key]
else
return false
end
end
})
IsUnit = setmetatable({}, {
__mode = "k",
__index = function(self, key)
self[key] = HandleType[key] == "unit"
return self[key]
end,
__call = function(self, key)
if key then
return self[key]
else
return false
end
end
})
end
if Debug then Debug.endFile() end
--[[
====================================================================================================================================================================
B A S I C A P I
====================================================================================================================================================================
• All object functions use keyword as an optional parameter. This parameter is only needed if
you create multiple actors for one host. It searches for the actor that has that keyword in
its identifier.
• All functions starting with ALICE_Pair are only accessible within user-defined functions
called by ALICE.
• All functions starting with ALICE_Func can be called from the Lua root, as long as ALICE is
above.
• All functions other than debug functions are async-safe as long as the code executed with
them is also async-safe.
-----CORE API------
ALICE_Create(host, identifier, interactions, flags) Create an actor for the object host and add it to the cycle. If the host is a table and is
provided as the only input argument, all other arguments will be retrieved directly from
that table.
ALICE_Destroy(whichObject) Destroy the actor of the specified object.
ALICE_Kill(whichObject) Calls the appropriate function to destroy the object, then destroys all actors attached to
it. If the object is a table, the object:destroy() method will be called. If no destroy
function exists, it will try to destroy the table's visual, which can be an effect, a unit,
or an image.
-----MATH API-----
ALICE_PairGetDistance2D() Returns the distance between the objects of the pair currently being evaluated in two
dimensions.
ALICE_PairGetDistance3D() The same, but takes z into account.
ALICE_PairGetAngle2D() Returns the angle from object A to object B of the pair currently being evaluated.
ALICE_PairGetAngle3D() Returns the horizontal and vertical angles from object A to object B.
ALICE_PairGetCoordinates2D() Returns the coordinates of the objects in the pair currently being evaluated in the order
x1, y1, x2, y2.
ALICE_PairGetCoordinates3D() Returns the coordinates of the objects in the pair currently being evaluated in the order
x1, y1, z1, x2, y2, z2.
ALICE_GetCoordinates2D(whichObject) Returns the coordinates x, y of an object.
ALICE_GetCoordinates3D(whichObject) Returns the coordinates x, y, z of an object.
• Enum functions return a table with all objects that have the specified identifier. Identifier
can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or
MATCHING_TYPE_ALL. Optional condition function to further filter out objects with additional
arguments passed to enum function being passed to condition function. For example, this will
return all flying units that are owned by red:
function IsOwnedByPlayer(object, whichPlayer)
return GetOwningPlayer(object) == whichPlayer
end
ALICE_EnumObjects({"unit", "flying", MATCHING_TYPE_ALL}, IsOwnedByPlayer, Player(0))
-----ENUM API-----
ALICE_EnumObjects(identifier, condition)
ALICE_EnumObjectsInRange(x, y, range, identifier, condition)
ALICE_EnumObjectsInRect(minx, miny, maxx, maxy, identifier, condition)
ALICE_EnumObjectsInLineSegment(x1, y1, x2, y2, halfWidth, condition)
ALICE_ForAllObjectsDo(action, identifier, condition)
ALICE_ForAllObjectsInRangeDo(action, x, y, range, identifier, condition)
ALICE_ForAllObjectsInRectDo(action, minx, miny, maxx, maxy, identifier, condition)
ALICE_ForAllObjectsInLineSegmentDo(action, x1, y1, x2, y2, halfWidth, condition)
ALICE_GetClosestObject(x, y, identifier, cutOffDistance, condition)
• The Callback API allows for convenient creation of delayed callbacks of any kind, with the
added benefit that callbacks will be delayed if ALICE is paused or slowed down. This allows
the pausing of the entire game for debugging or other purposes.
-----CALLBACK API-----
ALICE_CallDelayed(callback, delay) Invokes the callback function after the specified delay, passing additional arguments into
the callback function.
ALICE_PairCallDelayed(callback, delay) Invokes the callback function after the specified delay, passing the hosts of the current
pair as arguments. A third parameter is passed into the callback, specifying whether you
have access to the ALICE_Pair functions. You will not if the current pair has been
destroyed after the callback was queued up.
ALICE_CallPeriodic(callback, delay) Periodically invokes the callback function. Optional delay parameter to delay the first
execution. Additional arguments are passed into the callback function. The return value of
the callback function specifies the interval until next execution.
ALICE_CallRepeated(callback, howOften, delay) Periodically invokes the callback function up to howOften times. Optional delay parameter to
delay the first execution. The arguments passed into the callback function are the current
iteration, followed by any additional arguments. The return value of the callback function
specifies the interval until next execution.
ALICE_DisableCallback(callback) Disables a callback returned by ALICE_CallDelayed, ALICE_CallPeriodic, or ALICE_CallRepeated.
If called from within a periodic callback function itself, the parameter can be omitted.
ALICE_PauseCallback(callback, enable) Pauses or unpauses a callback returned by ALICE_CallDelayed, ALICE_CallPeriodic, or
ALICE_CallRepeated. If a periodic callback is unpaused this way, the next iteration will be
executed immediately. Otherwise, the remaining time will be waited. If called from within a
periodic callback function itself, the callback parameter can be omitted.
====================================================================================================================================================================
A D V A N C E D A P I
====================================================================================================================================================================
• Type "downtherabbithole" in-game to enable debug mode. In debug mode, you can click near an
object to visualize its actor, its interactions, and see all attributes of that actor. The
actor tooltips require CustomTooltip.fdf and CustomTooltip.toc
-----DEBUG API------
ALICE_Debug() Enable or disable debug mode.
ALICE_ListGlobals() List all global actors.
ALICE_Select(whichActor) Select the actor of the specified object if qualifier is an object, the first actor
encountered with the specified identifier if qualifier is a string, or the actor with the
specified unique number if qualifier is an integer. Requires debug mode.
ALICE_PairIsSelected() Returns true if one of the actors in the current pair is selected.
ALICE_PairVisualize(duration) Create a lightning effect between the objects of the current pair. Useful to check
if objects are interacting as intended. Optional lightning type parameter.
ALICE_Halt(pauseGame) Halt the entire cycle. Optional pauseGame parameter to pause all units on the map.
ALICE_Resume() Resume the entire cycle.
ALICE_Statistics() Prints out statistics showing which functions are occupying which percentage of the
calculations.
ALICE_Benchmark() Continuously prints the cycle evaluation time and the number of actors, pair interactions,
and cell checks until disabled.
ALICE_TrackVariables(whichVar) Prints the values of _G.whichVar[host], if _G.whichVar exists, as well as host.whichVar,
if the host is a table, in the actor tooltips in debug mode. You can list multiple
variables.
ALICE_GetPairState(objectA, objectB) Attempts to find the pair of the specified objects and prints the state of that pair.
Pass integers to access actors by unique numbers. Possible return values are "active",
"paused", "outofrange", "disabled", and "uninitialized".
ALICE_VisualizeAllCells() Create lightning effects around all cells.
ALICE_VisualizeAllActors() Creates arrows above all non-global actors.
ALICE_FuncRequireFields(whichFunc, requireMale, requireFemale, whichFields) Display warnings in the actor tooltips and crash messages of actors interacting with the
specified function or list of functions if the listed fields are not present in the host
table. requiredOnMale and requiredOnFemale control whether the field is expected to exist
in the host table of the initiating (male) or receiving (female) actor of the interaction.
Strings or string sequences specify fields that always need to be present. A table entry
{optionalField = requiredField} denotes that requiredField must be present only if
optionalField is also present in the table. requiredField can be a string or string
sequence.
ALICE_FuncSetName(whichFunc, name) Sets the name of a function when displayed in debug mode.
-----PAIR UTILITY API-----
ALICE_PairIsFriend() Returns true if the owners of the objects in the current pair are allies.
ALICE_PairIsEnemy() Returns true if the owners of the objects in the current pair are enemies.
ALICE_PairDisable() Disables interactions between the actors of the current pair after this one.
ALICE_PairPreciseInterval(number) Modifies the return value of an interactionFunc so that, on average, the interval is the
specified value, even if it isn't an integer multiple of the minimum interval.
ALICE_PairIsUnoccupied() Returns false if this function was invoked for another pair that has the same
interactionFunc and the same receiving actor. Otherwise, returns true. In other words,
only one pair can execute the code within an ALICE_PairIsUnoccupied() block. Useful for
creating non-stacking effects.
ALICE_PairCooldown(duration) Returns the remaining cooldown for this pair, then invokes a cooldown of the specified
duration. Optional cooldownType parameter to create and differentiate between multiple
separate cooldowns.
ALICE_PairLoadData() Returns a table unique to the pair currently being evaluated, which can be used to read
and write data. Optional argument to set a metatable for the data table.
ALICE_PairIsFirstContact() Returns true if this is the first time this function was invoked for the current pair,
otherwise false. Resets when the objects in the pair leave the interaction range.
ALICE_FuncSetInit(whichFunc, initFunc) Calls the initFunc(hostA, hostB) whenever a pair is created with the specified
interactionFunc.
ALICE_FuncSetOnDestroy(whichFunc, onDestroyFunc) Executes the function onDestroyFunc(objectA, objectB, pairData) when a pair using the
specified function is destroyed or a callback using that function expires or is disabled.
Only one callback per function.
ALICE_FuncSetOnBreak(whichFunc, onBreakFunc) Executes the function onBreakFunc(objectA, objectB, pairData, wasDestroyed) when a pair
using the specified function is destroyed or the actors leave interaction range. Only one
callback per function.
ALICE_FuncSetOnReset(whichFunc, onResetFunc) Executes the function onResetFunc(objectA, objectB, pairData, wasDestroyed) when a pair
using the specified function is destroyed, the actors leave interaction range, or the
ALICE_PairReset function is called, but only if ALICE_PairIsFirstContact has been called
previously. Only one callback per function.
ALICE_PairReset() Resets ALICE_PairIsFirstContact and calls the onReset function if it was reset. Also
resets the ALICE_IsUnoccupied function.
ALICE_PairInterpolate() Repeatedly calls the interaction function of the current pair at a rate of the
ALICE_Config.INTERPOLATION_INTERVAL until the next main step. A true is passed into the
interaction function as the third parameter if it is called from within the interpolation loop.
------WIDGET API-----
ALICE_IncludeTypes(whichType) Widgets with the specified fourCC codes will always receive actors, indepedent of the config.
ALICE_ExcludeTypes(whichType) Widgets with the specified fourCC codes will not receive actors, indepedent of the config.
ALICE_OnWidgetEvent(hookTable) Injects the functions listed in the hookTable into the hooks created by ALICE. The hookTable
can have the following keys: onUnitEnter - The listed function is called for all preplaced
units and whenever a unit enters the map or a hero is revived. onUnitDeath - The listed
function is called when a unit dies. onUnitRevive - The listed function is called when a
nonhero unit is revived. onUnitChangeOwner - The listed function is called when a unit changes
owner. onUnitRemove - The listed function is called when a unit is removed from the game or its
corpse decays fully. onDestructableEnter - The listed function is called for all preplaced
destructables and whenever a destructable is created. onDestructableDestroy - The listed
function is called when a destructable dies or is removed. onItemEnter - The listed function is
called for all preplaced items and whenever an item first appears on the map. onItemDestroy -
The listed function is called when an item is destroyed or removed.
-----IDENTIFIER API------
ALICE_AddIdentifier(whichObject, whichIdentifier) Add identifier(s) to an object and pair it with all other objects it is now eligible to be
paired with.
ALICE_RemoveIdentifier(whichObject, whichIdentifier) Remove identifier(s) from an object and remove all pairings with objects it is no longer
eligible to be paired with.
ALICE_SwapIdentifier(whichObject, oldIdentifier, newIdentifier) Exchanges one of the object's identifier with another. If the old identifier is not found,
the new one won't be added.
ALICE_SetIdentifier(whichObject, newIdentifier) Sets the object's identifier to a string or string sequence.
ALICE_HasIdentifier(whichObject, identifier) Checks if the object has the specified identifiers. Identifier can be a string or a table.
If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL.
ALICE_GetIdentifier(whichObject) Compiles the identifiers of an object into the provided table or a new table.
ALICE_FindIdentifier(whichObject, whichIdentifiers) Returns the first entry in the given list of identifiers for which an actor exists for the
specified object.
ALICE_FindField(table, object) If table is a table with identifier keys, returns the field that matches with the specified
object's identifier. If no match is found, returns table.other. If table is not a table,
returns the variable itself.
-----INTERACTION API-----
ALICE_SetInteractionFunc(whichObject, target, interactionFunc) Changes the interaction function of the specified object towards the target identifier to
the specified function or removes it.
ALICE_AddSelfInteraction(whichObject, whichFunc) Adds a self-interaction with the specified function to the object. If a self-interaction
with that function already exists, nothing happens. Optional data parameter to initialize
a data table that can be accessed with ALICE_PairLoadData.
ALICE_RemoveSelfInteraction(whichObject, whichFunc) Removes the self-interaction with the specified function from the object.
ALICE_HasSelfInteraction(whichObject, whichFunc) Checks if the object has a self-interaction with the specified function.
ALICE_PairSetInteractionFunc(whichFunc) Changes the interactionFunc of the pair currently being evaluated. You cannot replace a
function with a return value with one that has no return value and vice versa.
-----MISC API-----
ALICE_FuncSetDelay(whichFunc, delay) The first interaction of all pairs using this function will be delayed by the specified
number.
ALICE_FuncSetUnbreakable(whichFunc) Changes the behavior of pairs using the specified function so that the interactions
continue to be evaluated when the two objects leave their interaction range. Also changes
the behavior of ALICE_PairDisable to not prevent the two object from pairing again.
ALICE_FuncSetUnsuspendable(whichFunc) Changes the behavior of the specified function such that pairs using this function will
persist if a unit is loaded into a transport or an item is picked up by a unit.
ALICE_HasActor(object, identifier) Checks if an actor exists with the specified identifier for the specified object. Optional
strict flag to exclude actors that are anchored to that object.
ALICE_GetAnchor(object) Returns the object the specified object is anchored to or itself if there is no anchor.
ALICE_GetFlag(object, whichFlag) Returns the value stored for the specified flag of the specified actor.
ALICE_SetFlag(object, whichFlag, value) Sets the value of a flag for the actor of an object to the specified value. To change the
isStationary flag, use ALICE_SetStationary instead. Cannot change hasInfiniteRange flag.
ALICE_GetAnchoredObject(object, identifier) Accesses all objects anchored to the specified object and returns the one with the
specified identifier.
ALICE_GetOwner(object) Returns the owner of the specified object. Faster than GetOwningPlayer.
ALICE_TimeElapsed The time elapsed since the start of the game. Useful to store the time of the last
interaction between two objects.
ALICE_CPULoad The fraction of time the game is occupied running the ALICE cycle. Asynchronous!
====================================================================================================================================================================
S U P E R A D V A N C E D A P I
====================================================================================================================================================================
-----OPTIMIZATION API-----
ALICE_PairPause() Pauses interactions of the current pair after this one. Resume with ALICE_Unpause.
ALICE_Unpause(whichObject, whichFunctions) Unpauses all paused interactions of the object. Optional whichFunctions parameter, which
can be a function or a function sequence, to limit unpausing to pairs using those functions.
ALICE_FuncPauseOnStationary(whichFunc) Automatically pauses and unpauses all pairs using the specified function whenever the
initiating (male) actor is set to stationary/not stationary.
ALICE_SetStationary(whichObject, enable) Sets an object to stationary/not stationary. Will affect all actors attached to the object.
ALICE_IsStationary(whichObject) Returns whether the specified object is set to stationary.
ALICE_FuncDistribute(whichFunc, interval) The first interaction of all pairs using this function will be delayed by up to the specified
number, distributing individual calls over the interval to prevent computation spikes.
• The Modular API allows libraries to change the behavior of existing libraries, including
the in-built widget libraries and add new functionality. Functions must be called before
OnInit.final to affect preplaced widgets.
• OnCreation hooks are executed in the order OnCreation -> OnCreationAddFlag ->
OnCreationAddIdentifier -> OnCreationAddInteraction, OnCreationAddSelfInteraction,
taking into account the changes made by previous hooks.
-----MODULAR API-----
ALICE_OnCreation(matchingIdentifier, whichFunc) Executes the specified function before an object with the specified identifier is created.
The function is called with the host as the parameter.
ALICE_OnCreationAddFlag(matchingIdentifier, flag, value) Add a flag with the specified value to objects with matchingIdentifier as they are created.
Flags that can be modified are radius, cellCheckInterval, radius, isStationary, priority,
onActorDestroy, and zOffset. If a function is set for value, the function will be called
with the host as the argument and the return value used for the flag. If a function is
provided for value, the returned value of the function will be added.
ALICE_OnCreationAddIdentifier(matchingIdentifier, additionalIdentifier) Adds an additional identifier to objects with matchingIdentifier as they are created.
If a function is provided for value, the returned string of the function will be added.
ALICE_OnCreationAddInteraction(matchingIdentifier, keyword, interactionFunc) Adds an interaction to all objects with matchingIdentifier as they are created towards
objects with the specified keyword in their identifier. To add a self-interaction, use
ALICE_OnCreationAddSelfInteraction instead.
ALICE_OnCreationAddSelfInteraction(matchingIdentifier, selfInteractionFunc) Adds a self-interaction to all objects with matchingIdentifier as they are created.
• The Pair Access API allows external functions to influence pairs and to access pair data.
-----PAIR ACCESS API-----
ALICE_Enable(objectA, objectB) Restore a pair that has been previously destroyed with ALICE_PairDisable. Returns two
booleans. The first denotes whether a pair now exists and the second if it was just created.
ALICE_AccessData(objectA, objectB) Access the pair for objects A and B and, if it exists, return the data table stored for that
pair. If objectB is a function, returns the data of the self-interaction of objectA using the
specified function.
ALICE_UnpausePair(objectA, objectB) Access the pair for objects A and B and, if it is paused, unpause it. If objectB is a function,
unpauses the self-interaction of objectA using the specified function.
ALICE_GetPairAndDo(action, objectA, objectB) Access the pair for objects A and B and, if it exists, perform the specified action. Returns
the return value of the action function. The hosts of the pair as well as any additional
parameters are passed into the action function. If objectB is a function, accesses the
self-interaction of objectA using the specified function.
ALICE_ForAllPairsDo(action, object, whichFunc) Access all pairs active for the object using the specified interactionFunc and perform the
specified action. The hosts of the pairs as well as any additional parameters are passed into
the action function.
====================================================================================================================================================================
]]
if Debug then Debug.beginFile "ALICE" end
---@diagnostic disable: need-check-nil
do
--[[
=============================================================================================================================================================
A Limitless Interaction Caller Engine
by Antares
v2.7.2
A Lua system to easily create highly performant checks and interactions, between any type of objects.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
Hook https://www.hiveworkshop.com/threads/hook.339153/
HandleType https://www.hiveworkshop.com/threads/get-handle-type.354436/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
For tutorials & documentation, see here:
https://www.hiveworkshop.com/threads/.353126/
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
ALICE_Config = {
--Minimum interval between interactions in seconds. Sets the time step of the timer. All interaction intervals are an integer multiple of this value.
MIN_INTERVAL = 0.02 ---@constant number
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Debugging
--Print out warnings, errors, and enable the "downtherabbithole" cheat code for the players with these names. #XXXX not required.
,MAP_CREATORS = { ---@constant string[]
"Antares",
"WorldEdit"
}
--Abort the cycle the first time it crashes. Makes it easier to identify a bug if downstream errors are prevented. Disable for release version.
,HALT_ON_FIRST_CRASH = true ---@constant boolean
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Optimization
--Maximum interval between interactions in seconds.
,MAX_INTERVAL = 10.0 ---@constant number
--This interval is used by a second, faster timer that can be used to update visual effects at a faster rate than the MIN_INTERVAL with ALICE_PairInterpolate.
--Set to nil to disable.
,INTERPOLATION_INTERVAL = 0.005 ---@constant number
--The playable map area is divided into cells of this size. Objects only interact with other objects that share a cell with them. Smaller cells increase the
--efficiency of interactions at the cost of increased memory usage and overhead.
,CELL_SIZE = 256 ---@constant number
--How often the system checks if objects left their current cell. Should be overwritten with the cellCheckInterval flag for fast-moving objects.
,DEFAULT_CELL_CHECK_INTERVAL = 0.1 ---@constant number
--How large an actor is when it comes to determining in which cells it is in and its maximum interaction range. Should be overwritten with the radius flag for
--objects with a larger interaction range.
,DEFAULT_OBJECT_RADIUS = 75 ---@constant number
--You can integrate ALICE's internal table recycling system into your own by setting the GetTable and ReturnTable functions here.
,TABLE_RECYCLER_GET = nil ---@constant function
,TABLE_RECYCLER_RETURN = nil ---@constant function
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Automatic actor creation for widgets
--Actor creation for user-defined objects is up to you. For widgets, ALICE offers automatic actor creation and destruction.
--Determine which widget types will automatically receive actors and be registered with ALICE. The created actors are passive and only receive pairs. You can
--add exceptions with ALICE_IncludeType and ALICE_ExcludeType.
,NO_UNIT_ACTOR = false ---@constant boolean
,NO_DESTRUCTABLE_ACTOR = false ---@constant boolean
,NO_ITEM_ACTOR = false ---@constant boolean
--Add widget names (converted to camelCase) as identifiers to widget actors. Note that the names of widgets are localized and you risk a desync if you reference
--a widget by name unless it's a custom name.
,ADD_WIDGET_NAMES = false ---@constant boolean
--Disable to destroy unit actors on death. Units will not regain an actor when revived.
,UNITS_LEAVE_BEHIND_CORPSES = true ---@constant boolean
--Disable if corpses are relevant and you're moving them around.
,UNIT_CORPSES_ARE_STATIONARY = true ---@constant boolean
--Add identifiers such as "hero" or "mechanical" to units if they have the corresponding classification and "nonhero", "nonmechanical" etc. if they do not.
--The identifiers will not get updated automatically when a unit gains or loses classifications and you must update them manually with ALICE_SwapIdentifier.
,UNIT_ADDED_CLASSIFICATIONS = { ---@constant unittype[]
UNIT_TYPE_HERO,
UNIT_TYPE_STRUCTURE
}
--The radius of the unit actors. Set to nil to use DEFAULT_OBJECT_RADIUS.
,DEFAULT_UNIT_RADIUS = nil ---@constant number
--The radius of the destructable actors. Set to nil to use DEFAULT_OBJECT_RADIUS.
,DEFAULT_DESTRUCTABLE_RADIUS = nil ---@constant number
--Disable if items are relevant and you're moving them around.
,ITEMS_ARE_STATIONARY = true ---@constant boolean
--The radius of the item actors. Set to nil to use DEFAULT_OBJECT_RADIUS.
,DEFAULT_ITEM_RADIUS = nil ---@constant number
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--For EmmyLua annotations. If you're passing any types into object functions other than these types, add them here to disable warnings.
---@alias Object unit | destructable | item | table
--[[
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
--#region Variables
ALICE_TimeElapsed = 0.0 ---@type number
ALICE_CPULoad = 0 ---@type number
MATCHING_TYPE_ANY = {} ---@constant table
MATCHING_TYPE_ALL = {} ---@constant table
local max = math.max
local min = math.min
local sqrt = math.sqrt
local atan = math.atan
local insert = table.insert
local concat = table.concat
local sort = table.sort
local pack = table.pack
local unpack = table.unpack
local config = ALICE_Config
local timers = {} ---@type timer[]
local MAX_STEPS = 0 ---@type integer
local CYCLE_LENGTH = 0 ---@type integer
local DO_NOT_EVALUATE = 0 ---@type integer
local MAP_MIN_X ---@type number
local MAP_MAX_X ---@type number
local MAP_MIN_Y ---@type number
local MAP_MAX_Y ---@type number
local MAP_SIZE_X ---@type number
local MAP_SIZE_Y ---@type number
local NUM_CELLS_X ---@type integer
local NUM_CELLS_Y ---@type integer
local CELL_MIN_X = {} ---@type number[]
local CELL_MIN_Y = {} ---@type number[]
local CELL_MAX_X = {} ---@type number[]
local CELL_MAX_Y = {} ---@type number[]
local CELL_LIST = {} ---@type Cell[][]
--[[Array indices for pair fields. Storing as a sequence up to 8 reduces memory usage. Constants have been inlined because of local variable limit. Hexadecimals to be able to revert with find&replace.
ACTOR A = 0x1
ACTOR_B = 0x2
HOST_A = 0x3
HOST_B = 0x4
CURRENT_POSITION / NEXT = 0x5
POSITION_IN_STEP / PREVIOUS = 0x6
EVERY_STEP = 0x7
INTERACTION_FUNC = 0x8
]]
local EMPTY_TABLE = {} ---@constant table
local SELF_INTERACTION_ACTOR ---@type Actor
local DUMMY_PAIR ---@constant Pair
= {destructionQueued = true}
local OUTSIDE_OF_CYCLE = ---@constant Pair
setmetatable({}, {__index = function()
error("Attempted to call Pair API function from outside of allowed functions.")
end})
local cycle = {
counter = 0, ---@type integer
unboundCounter = 0, ---@type integer
isHalted = false, ---@type boolean
isCrash = false, ---@type boolean
freezeCounter = 0, ---@type number
}
local currentPair = OUTSIDE_OF_CYCLE ---@type Pair | nil
local totalActors = 0 ---@type integer
local moveableLoc ---@type location
local numPairs = {} ---@type integer[]
local whichPairs = {} ---@type table[]
local firstEveryStepPair = DUMMY_PAIR ---@type Pair
local lastEveryStepPair = DUMMY_PAIR ---@type Pair
local numEveryStepPairs = 0 ---@type integer
local actorList = {} ---@type Actor[]
local celllessActorList = {} ---@type Actor[]
local pairList = {} ---@type Pair[]
local pairingExcluded = {} ---@type table[]
local numCellChecks = {} ---@type integer[]
local cellCheckedActors = {} ---@type Actor[]
local actorAlreadyChecked = {} ---@type boolean[]
local unusedPairs = {} ---@type Pair[]
local unusedActors = {} ---@type Actor[]
local unusedTables = {} ---@type table[]
local additionalFlags = {} ---@type table
local destroyedActors = {} ---@type Actor[]
local actorOf = {} ---@type Actor[]
local alreadyEnumerated = {} ---@type any[]
local interpolatedPairs = {} ---@type Pair[]
local isInterpolated ---@type boolean
local interpolationCounter = 10 ---@type integer
local functionIsEveryStep = {} ---@type table<function,boolean>
local functionIsUnbreakable = {} ---@type table<function,boolean>
local functionIsUnsuspendable = {} ---@type table<function,boolean>
local functionInitializer = {} ---@type table<function,function>
local functionDelay = {} ---@type table<function,number>
local functionDelayIsDistributed = {} ---@type table<function,boolean>
local functionDelayCurrent = {} ---@type table<function,number>
local functionOnDestroy = {} ---@type table<function,function>
local functionOnBreak = {} ---@type table<function,function>
local functionOnReset = {} ---@type table<function,function>
local functionPauseOnStationary = {} ---@type table<function,boolean>
local functionRequiredFields = {} ---@type table<function,table>
local functionKey = {} ---@type table<function,integer>
local highestFunctionKey = 0 ---@type integer
local delayedCallbackFunctions = {} ---@type function[]
local delayedCallbackArgs = {} ---@type table[]
local unitOwnerFunc = {} ---@type function[]
local userCallbacks = {} ---@type table[]
local pairingFunctions = {} ---@type table[]
local objectIsStationary ---@type table<any,boolean>
= setmetatable({}, {__mode = "k"})
local widgets = {
bindChecks = {}, ---@type Actor[]
deathTriggers ---@type table<destructable|item,trigger>
= setmetatable({}, {__mode = "k"}),
reviveTriggers = {}, ---@type table<unit,trigger>
idExclusions = {}, ---@type table<integer,boolean>
idInclusions = {}, ---@type table<integer,boolean>
hash = nil ---@type hashtable
}
local onCreation = { ---@type table
flags = {}, ---@type table<string,table>
funcs = {}, ---@type table<string,table>
identifiers = {}, ---@type table<string,table>
interactions = {}, ---@type table<string,table>
selfInteractions = {} ---@type table<string,table>
}
local INV_MIN_INTERVAL ---@constant number
= 1/config.MIN_INTERVAL - 0.001
local OVERWRITEABLE_FLAGS = { ---@constant table<string,boolean>
priority = true,
zOffset = true,
cellCheckInterval = true,
isStationary = true,
radius = true,
persistOnDeath = true,
onActorDestroy = true,
hasInfiniteRange = true,
isUnselectable = true,
}
local RECOGNIZED_FLAGS = { ---@constant table<string,boolean>
anchor = true,
zOffset = true,
cellCheckInterval = true,
isStationary = true,
radius = true,
persistOnDeath = true,
width = true,
height = true,
bindToBuff = true,
bindToOrder = true,
onActorDestroy = true,
hasInfiniteRange = true,
isGlobal = true,
isAnonymous = true,
isUnselectable = true
}
local UNIT_CLASSIFICATION_NAMES = { ---@constant table<unittype,string>
[UNIT_TYPE_HERO] = "hero",
[UNIT_TYPE_STRUCTURE] = "structure",
[UNIT_TYPE_MECHANICAL] = "mechanical",
[UNIT_TYPE_UNDEAD] = "undead",
[UNIT_TYPE_TAUREN] = "tauren",
[UNIT_TYPE_ANCIENT] = "ancient",
[UNIT_TYPE_SAPPER] = "sapper",
[UNIT_TYPE_PEON] = "worker",
[UNIT_TYPE_FLYING] = "flying",
[UNIT_TYPE_GIANT] = "giant",
[UNIT_TYPE_SUMMONED] = "summoned",
[UNIT_TYPE_TOWNHALL] = "townhall",
}
local GetTable ---@type function
local ReturnTable ---@type function
local Create ---@type function
local Destroy ---@type function
local Release ---@type function
local CreateReference ---@type function
local RemoveReference ---@type function
local SetCoordinateFuncs ---@type function
local SetOwnerFunc ---@type function
local InitCells ---@type function
local InitCellChecks ---@type function
local AssignActorClass ---@type function
local Flicker ---@type function
local SharesCellWith ---@type function
local CreateBinds ---@type function
local DestroyObsoletePairs ---@type function
local Unpause ---@type function
local SetStationary ---@type function
local VisualizeCells ---@type function
local RedrawCellVisualizers ---@type function
local Suspend ---@type function
local Deselect ---@type function
local Select ---@type function
local GetMissingRequiredFieldsString ---@type function
local GetDescription ---@type function
local CreateVisualizer ---@type function
local EnterCell ---@type function
local RemoveCell ---@type function
local LeaveCell ---@type function
local VisualizationLightning ---@type function
local GetTerrainZ ---@type function
local GetActor ---@type function
local EnableDebugMode ---@type function
local UpdateSelectedActor ---@type function
local OnDestructableDeath ---@type function
local OnItemDeath ---@type function
local debug = {} ---@type table
debug.enabled = false ---@type boolean
debug.mouseClickTrigger = nil ---@type trigger
debug.cycleSelectTrigger = nil ---@type trigger
debug.nextStepTrigger = nil ---@type trigger
debug.lockSelectionTrigger = nil ---@type trigger
debug.haltTrigger = nil ---@type trigger
debug.printFunctionsTrigger = nil ---@type trigger
debug.selectedActor = nil ---@type Actor | nil
debug.tooltip = nil ---@type framehandle
debug.tooltipText = nil ---@type framehandle
debug.tooltipTitle = nil ---@type framehandle
debug.visualizationLightnings = {} ---@type lightning[]
debug.selectionLocked = false ---@type boolean
debug.benchmark = false ---@type boolean
debug.visualizeAllActors = false ---@type boolean
debug.visualizeAllCells = false ---@type boolean
debug.printFunctionNames = false ---@type boolean
debug.evaluationTime = {} ---@type table
debug.gameIsPaused = nil ---@type boolean
debug.trackedVariables = {} ---@type table<string,boolean>
debug.functionName = {} ---@type table<function,string>
local eventHooks = { ---@type table[]
onUnitEnter = {},
onUnitDeath = {},
onUnitRevive = {},
onUnitRemove = {},
onUnitChangeOwner = {},
onDestructableEnter = {},
onDestructableDestroy = {},
onItemEnter = {},
onItemDestroy = {}
}
--#endregion
--===========================================================================================================================================================
--Filter Functions
--===========================================================================================================================================================
--#region Filter Functions
---For debug functions.
---@param whichIdentifier string | string[] | nil
local function Identifier2String(whichIdentifier)
local toString = "("
local i = 1
for key, __ in pairs(whichIdentifier) do
if i > 1 then
toString = toString .. ", "
end
toString = toString .. key
i = i + 1
end
toString = toString .. ")"
return toString
end
local function HasIdentifierFromTable(actor, whichIdentifier)
if whichIdentifier[#whichIdentifier] == MATCHING_TYPE_ANY then
for i = 1, #whichIdentifier - 1 do
if actor.identifier[whichIdentifier[i]] then
return true
end
end
return false
elseif whichIdentifier[#whichIdentifier] == MATCHING_TYPE_ALL then
for i = 1, #whichIdentifier - 1 do
if not actor.identifier[whichIdentifier[i]] then
return false
end
end
return true
elseif type(whichIdentifier[#whichIdentifier]) == "string" then
error("Matching type missing in identifier table.")
else
error("Invalid matching type specified in identifier table.")
end
end
--#endregion
--===========================================================================================================================================================
--Utility
--===========================================================================================================================================================
--#region Utility
local function Warning(whichWarning)
for __, name in ipairs(config.MAP_CREATORS) do
if string.find(GetPlayerName(GetLocalPlayer()), name) then
print(whichWarning)
end
end
end
local function AddDelayedCallback(func, arg1, arg2, arg3)
local index = #delayedCallbackFunctions + 1
delayedCallbackFunctions[index] = func
local args = delayedCallbackArgs[index] or {}
args[1], args[2], args[3] = arg1, arg2, arg3
delayedCallbackArgs[index] = args
end
local function RemoveUserCallbackFromList(self)
if self == userCallbacks.first then
if self.next then
self.next.previous = nil
else
userCallbacks.last = nil
end
userCallbacks.first = self.next
elseif self == userCallbacks.last then
userCallbacks.last = self.previous
self.previous.next = nil
else
self.previous.next = self.next
self.next.previous = self.previous
end
end
local function ExecuteUserCallback(self)
if self.pair then
if self.pair[0x3] == self.hostA and self.pair[0x4] == self.hostB then
currentPair = self.pair
self.callback(self.hostA, self.hostB, true)
if functionOnDestroy[self.callback] then
functionOnDestroy[self.callback](self.hostA, self.hostB, true)
end
currentPair = OUTSIDE_OF_CYCLE
else
self.callback(self.hostA, self.hostB, false)
if functionOnDestroy[self.callback] then
functionOnDestroy[self.callback](self.hostA, self.hostB, false)
end
end
elseif self.args then
if self.unpack then
self.callback(unpack(self.args))
if functionOnDestroy[self.callback] then
functionOnDestroy[self.callback](unpack(self.args))
end
ReturnTable(self.args)
else
self.callback(self.args)
if functionOnDestroy[self.callback] then
functionOnDestroy[self.callback](self.args)
end
end
else
self.callback()
if functionOnDestroy[self.callback] then
functionOnDestroy[self.callback]()
end
end
RemoveUserCallbackFromList(self)
for key, __ in pairs(self) do
self[key] = nil
end
end
local function AddUserCallback(self)
if userCallbacks.first == nil then
userCallbacks.first = self
userCallbacks.last = self
else
local node = userCallbacks.last
local callCounter = self.callCounter
while node and node.callCounter > callCounter do
node = node.previous
end
if node == nil then
--Insert at the beginning
userCallbacks.first.previous = self
self.next = userCallbacks.first
userCallbacks.first = self
else
if node == userCallbacks.last then
--Insert at the end
userCallbacks.last = self
else
--Insert in the middle
self.next = node.next
self.next.previous = self
end
self.previous = node
node.next = self
end
end
end
local function PeriodicWrapper(caller)
if caller.excess > 0 then
local returnValue = caller.excess
caller.excess = caller.excess - config.MAX_INTERVAL
return returnValue
end
local returnValue = caller.callback(unpack(caller))
if returnValue and returnValue > config.MAX_INTERVAL then
caller.excess = returnValue - config.MAX_INTERVAL
end
return returnValue
end
local function RepeatedWrapper(caller)
if caller.excess > 0 then
local returnValue = caller.excess
caller.excess = caller.excess - config.MAX_INTERVAL
return returnValue
end
caller.currentExecution = caller.currentExecution + 1
local returnValue = caller.callback(caller.currentExecution, unpack(caller))
if caller.currentExecution == caller.howOften then
ALICE_DisableCallback()
end
if returnValue and returnValue > config.MAX_INTERVAL then
caller.excess = returnValue - config.MAX_INTERVAL
end
return returnValue
end
local function ToUpperCase(__, letter)
return letter:upper()
end
local toCamelCase = setmetatable({}, {
__index = function(self, whichString)
whichString = whichString:gsub("|[cC]\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x", "") --remove color codes
whichString = whichString:gsub("|[rR]", "") --remove closing color codes
whichString = whichString:gsub("(\x25s)(\x25a)", ToUpperCase) --remove spaces and convert to upper case after space
whichString = whichString:gsub("[^\x25w]", "") --remove special characters
self[whichString] = string.lower(whichString:sub(1,1)) .. string.sub(whichString,2) --converts first character to lower case
return self[whichString]
end
})
--For debug mode
local function Function2String(func)
if debug.functionName[func] then
return debug.functionName[func]
end
local string = string.gsub(tostring(func), "function: ", "")
if string.sub(string,1,1) == "0" then
return string.sub(string, string.len(string) - 3, string.len(string))
else
return string
end
end
--For debug mode
local function Object2String(object)
if IsHandle[object] then
if IsWidget[object] then
if HandleType[object] == "unit" then
local str = string.gsub(tostring(object), "unit: ", "")
if str:sub(1,1) == "0" then
return GetUnitName(object) .. ": " .. str:sub(str:len() - 3, str:len())
else
return str
end
elseif HandleType[object] == "destructable" then
local str = string.gsub(tostring(object), "destructable: ", "")
if str:sub(1,1) == "0" then
return GetDestructableName(object) .. ": " .. str:sub(str:len() - 3, str:len())
else
return str
end
else
local str = string.gsub(tostring(object), "item: ", "")
if str:sub(1,1) == "0" then
return GetItemName(object) .. ": " .. str:sub(str:len() - 3, str:len())
else
return str
end
end
else
local str = tostring(object)
local address = str:sub((str:find(":", nil, true) or 0) + 2, str:len())
return HandleType[object] .. " " .. (address:sub(1,1) == "0" and address:sub(address:len() - 3, address:len()))
end
elseif object.__name then
local str = string.gsub(tostring(object), object.__name .. ": ", "")
str = string.sub(str, string.len(str) - 3, string.len(str))
return object.__name .. " " .. str
else
local str = tostring(object)
if string.sub(str,8,8) == "0" then
return "table: " .. string.sub(str, string.len(str) - 3, string.len(str))
else
return str
end
end
end
local function OnUnitChangeOwner()
local u = GetTriggerUnit()
local newOwner = GetOwningPlayer(u)
unitOwnerFunc[newOwner] = unitOwnerFunc[newOwner] or function() return newOwner end
if actorOf[u] then
if actorOf[u].isActor then
actorOf[u].getOwner = unitOwnerFunc[newOwner]
else
for __, actor in ipairs(actorOf[u]) do
actor.getOwner = unitOwnerFunc[newOwner]
end
end
end
for __, func in ipairs(eventHooks.onUnitChangeOwner) do
func(u)
end
end
--#endregion
--===========================================================================================================================================================
--Getter functions
--===========================================================================================================================================================
--#region Getter Functions
--x and y are stored with an anchor key because GetUnitX etc. cannot take an actor as an argument and they are identical for all actors anchored to the same
--object. z is stored with an actor key because it requires zOffset, which is stored on the actor, and the z-values are not guaranteed to be identical for all
--actors anchored to the same object.
local coord = {
classX = setmetatable({}, {__index = function(self, key) self[key] = key.x return self[key] end}),
classY = setmetatable({}, {__index = function(self, key) self[key] = key.y return self[key] end}),
classZ = setmetatable({}, {__index = function(self, key) self[key] = key.anchor.z + key.zOffset return self[key] end}),
unitX = setmetatable({}, {__index = function(self, key) self[key] = GetUnitX(key) return self[key] end}),
unitY = setmetatable({}, {__index = function(self, key) self[key] = GetUnitY(key) return self[key] end}),
unitZ = setmetatable({}, {__index = function(self, key) self[key] = GetTerrainZ(key.x[key.anchor], key.y[key.anchor]) + GetUnitFlyHeight(key.anchor) + key.zOffset return self[key] end}),
destructableX = setmetatable({}, {__index = function(self, key) self[key] = GetDestructableX(key) return self[key] end}),
destructableY = setmetatable({}, {__index = function(self, key) self[key] = GetDestructableY(key) return self[key] end}),
destructableZ = setmetatable({}, {__index = function(self, key) self[key] = GetTerrainZ(key.x[key.anchor], key.y[key.anchor]) + key.zOffset return self[key] end}),
itemX = setmetatable({}, {__index = function(self, key) self[key] = GetItemX(key) return self[key] end}),
itemY = setmetatable({}, {__index = function(self, key) self[key] = GetItemY(key) return self[key] end}),
itemZ = setmetatable({}, {__index = function(self, key) self[key] = GetTerrainZ(key.x[key.anchor], key.y[key.anchor]) + key.zOffset return self[key] end}),
terrainZ = setmetatable({}, {__index = function(self, key) self[key] = GetTerrainZ(key.x[key.anchor], key.y[key.anchor]) return self[key] end}),
globalXYZ = setmetatable({}, {__index = function(self, key) self[key] = 0 return 0 end})
}
local function GetClassOwner(source)
return source.owner
end
local function GetClassOwnerById(source)
return Player(source.owner - 1)
end
--#endregion
--===========================================================================================================================================================
--Pair Class
--===========================================================================================================================================================
--#region Pair
---@class Pair
local Pair = {
destructionQueued = nil, ---@type boolean
userData = nil, ---@type table
hadContact = nil, ---@type boolean
cooldown = nil, ---@type number
paused = nil, ---@type boolean
}
local function GetInteractionFunc(male, female)
local func = pairingFunctions[female.identifierClass][male.interactionsClass]
if func ~= nil then
return func
end
local identifier = female.identifier
local level = 0
local conflict = false
for key, value in pairs(male.interactions) do
if type(key) == "string" then
if identifier[key] then
if level < 1 then
func = value
level = 1
elseif level == 1 then
conflict = true
end
end
else
local match = true
for __, tableKey in ipairs(key) do
if not identifier[tableKey] then
match = false
break
end
end
if match then
if #key > level then
func = value
level = #key
conflict = false
elseif #key == level then
conflict = true
end
end
end
end
if conflict then
error("InteractionFunc ambiguous for actors with identifiers " .. Identifier2String(male.identifier) .. " and " .. Identifier2String(female.identifier) .. ".")
end
if func then
pairingFunctions[female.identifierClass][male.interactionsClass] = func
return func
else
pairingFunctions[female.identifierClass][male.interactionsClass] = false
return false
end
end
---@param whichPair Pair
local function AddPairToEveryStepList(whichPair)
whichPair[0x6] = lastEveryStepPair
whichPair[0x5] = nil
lastEveryStepPair[0x5] = whichPair
lastEveryStepPair = whichPair
numEveryStepPairs = numEveryStepPairs + 1
end
---@param whichPair Pair
local function RemovePairFromEveryStepList(whichPair)
if whichPair[0x6] == nil then
return
end
if whichPair[0x5] then
whichPair[0x5][0x6] = whichPair[0x6]
else
lastEveryStepPair = whichPair[0x6]
end
whichPair[0x6][0x5] = whichPair[0x5]
whichPair[0x6] = nil
numEveryStepPairs = numEveryStepPairs - 1
end
---@param actorA Actor
---@param actorB Actor
---@param interactionFunc function
---@return Pair | nil
local function CreatePair(actorA, actorB, interactionFunc)
if pairingExcluded[actorA][actorB] or interactionFunc == nil or actorA.host == actorB.host or actorA.originalAnchor == actorB.originalAnchor then
pairingExcluded[actorA][actorB] = true
pairingExcluded[actorB][actorA] = true
return nil
end
if (actorA.isSuspended or actorB.isSuspended) and not functionIsUnsuspendable[interactionFunc] then
return nil
end
local self ---@type Pair
if #unusedPairs == 0 then
self = {}
else
self = unusedPairs[#unusedPairs]
unusedPairs[#unusedPairs] = nil
end
self[0x1] = actorA
self[0x2] = actorB
self[0x3] = actorA.host
if actorB == SELF_INTERACTION_ACTOR then
self[0x4] = actorA.host
else
self[0x4] = actorB.host
end
self[0x8] = interactionFunc
local lastPair = actorA.lastPair
actorA.previousPair[self] = lastPair
actorA.nextPair[lastPair] = self
actorA.lastPair = self
lastPair = actorB.lastPair
actorB.previousPair[self] = lastPair
actorB.nextPair[lastPair] = self
actorB.lastPair = self
self.destructionQueued = nil
pairList[actorA][actorB] = self
if functionInitializer[interactionFunc] then
local tempPair = currentPair
currentPair = self
functionInitializer[interactionFunc](self[0x3], self[0x4])
currentPair = tempPair
end
if (functionPauseOnStationary[interactionFunc] and actorA.isStationary) then
if functionIsEveryStep[interactionFunc] then
self[0x7] = true
else
self[0x5] = DO_NOT_EVALUATE
end
self.paused = true
elseif functionIsEveryStep[interactionFunc] then
AddPairToEveryStepList(self)
self[0x7] = true
else
local firstStep
if functionDelay[interactionFunc] then
if functionDelayIsDistributed[interactionFunc] then
functionDelayCurrent[interactionFunc] = functionDelayCurrent[interactionFunc] + config.MIN_INTERVAL
if functionDelayCurrent[interactionFunc] > functionDelay[interactionFunc] then
functionDelayCurrent[interactionFunc] = functionDelayCurrent[interactionFunc] - functionDelay[interactionFunc]
end
firstStep = cycle.counter + (functionDelayCurrent[interactionFunc]*INV_MIN_INTERVAL + 1) // 1
else
firstStep = cycle.counter + (functionDelay[interactionFunc]*INV_MIN_INTERVAL + 1) // 1
end
else
firstStep = cycle.counter + 1
end
if firstStep > CYCLE_LENGTH then
firstStep = firstStep - CYCLE_LENGTH
end
numPairs[firstStep] = numPairs[firstStep] + 1
whichPairs[firstStep][numPairs[firstStep]] = self
self[0x5] = firstStep
self[0x6] = numPairs[firstStep]
end
return self
end
local function DestroyPair(self)
if self[0x7] then
RemovePairFromEveryStepList(self)
else
whichPairs[self[0x5]][self[0x6]] = DUMMY_PAIR
end
self[0x5] = nil
self[0x6] = nil
self.destructionQueued = true
local tempPair = currentPair
currentPair = self
if self.hadContact then
if functionOnReset[self[0x8]] and not cycle.isCrash then
functionOnReset[self[0x8]](self[0x3], self[0x4], self.userData, true)
end
self.hadContact = nil
end
if functionOnBreak[self[0x8]] and not cycle.isCrash then
functionOnBreak[self[0x8]](self[0x3], self[0x4], self.userData, true)
end
if functionOnDestroy[self[0x8]] and not cycle.isCrash then
functionOnDestroy[self[0x8]](self[0x3], self[0x4], self.userData)
end
if self.userData then
ReturnTable(self.userData)
end
currentPair = tempPair
--Reset ALICE_PairIsUnoccupied()
if self[0x2][self[0x8]] == self then
self[0x2][self[0x8]] = nil
end
if self[0x2] == SELF_INTERACTION_ACTOR then
self[0x1].selfInteractions[self[0x8]] = nil
end
local actorA = self[0x1]
local previous = actorA.previousPair
local next = actorA.nextPair
if next[self] then
previous[next[self]] = previous[self]
else
actorA.lastPair = previous[self]
end
next[previous[self]] = next[self]
previous[self] = nil
next[self] = nil
local actorB = self[0x2]
previous = actorB.previousPair
next = actorB.nextPair
if next[self] then
previous[next[self]] = previous[self]
else
actorB.lastPair = previous[self]
end
next[previous[self]] = next[self]
previous[self] = nil
next[self] = nil
unusedPairs[#unusedPairs + 1] = self
pairList[actorA][actorB] = nil
pairList[actorB][actorA] = nil
self.userData = nil
self.hadContact = nil
self[0x7] = nil
self.paused = nil
if self.cooldown then
ReturnTable(self.cooldown)
self.cooldown = nil
end
end
local function PausePair(self)
if self.destructionQueued then
return
end
if self[0x7] then
RemovePairFromEveryStepList(self)
else
if self[0x5] ~= DO_NOT_EVALUATE then
whichPairs[self[0x5]][self[0x6]] = DUMMY_PAIR
local nextStep = DO_NOT_EVALUATE
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = self
self[0x5] = nextStep
self[0x6] = numPairs[nextStep]
end
end
self.paused = true
end
local function UnpausePair(self)
if self.destructionQueued then
return
end
local actorA = self[0x1]
local actorB = self[0x2]
if self[0x7] then
if self[0x6] == nil and (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
AddPairToEveryStepList(self)
end
else
if self[0x5] == DO_NOT_EVALUATE and (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
local nextStep = cycle.counter + 1
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = self
self[0x5] = nextStep
self[0x6] = numPairs[nextStep]
end
end
self.paused = nil
end
--#endregion
--===========================================================================================================================================================
--Actor Class
--===========================================================================================================================================================
local function GetUnusedActor()
local self
if #unusedActors == 0 then
--Actors have their own table recycling system. These fields do not get nilled on destroy.
self = {} ---@type Actor
self.isActor = true
self.identifier = {}
self.firstPair = {}
self.lastPair = self.firstPair
self.nextPair = {}
self.previousPair = {}
self.isInCell = {}
self.nextInCell = {}
self.previousInCell = {}
self.interactions = {}
self.selfInteractions = {}
self.references = {}
pairList[self] = {}
pairingExcluded[self] = {}
else
self = unusedActors[#unusedActors]
unusedActors[#unusedActors] = nil
end
return self
end
GetActor = function(object, keyword)
if object == nil then
if debug.selectedActor then
return debug.selectedActor
end
return nil
end
local actorOf = actorOf[object]
if actorOf then
if actorOf.isActor then
if keyword == nil or actorOf.identifier[keyword] then
return actorOf
else
return nil
end
elseif keyword == nil then
--If called within interactionFunc and keyword is not specified, prioritize returning actor that's in the current pair, then an actor for which the object is the
--host, not the anchor.
if currentPair ~= OUTSIDE_OF_CYCLE then
if object == currentPair[0x3] then
return currentPair[0x1]
elseif object == currentPair[0x4] then
return currentPair[0x2]
end
end
for __, actor in ipairs(actorOf) do
if actor.host == object then
return actor
end
end
return actorOf[1]
else
for __, actor in ipairs(actorOf) do
if actor.identifier[keyword] then
return actor
end
end
return nil
end
elseif type(object) == "table" and object.isActor then
return object
end
return nil
end
--#region Actor
---@class Actor
local Actor = {
--Main:
isActor = nil, ---@type boolean
host = nil, ---@type any
anchor = nil, ---@type any
originalAnchor = nil, ---@type any
getOwner = nil, ---@type function
interactions = nil, ---@type function | table | nil
selfInteractions = nil, ---@type table
identifier = nil, ---@type table
visualizer = nil, ---@type effect
alreadyDestroyed = nil, ---@type boolean
causedCrash = nil, ---@type boolean
isSuspended = nil, ---@type boolean
identifierClass = nil, ---@type string
interactionsClass = nil, ---@type string
references = nil, ---@type table
periodicPair = nil, ---@type Pair
--Pairs:
firstPair = nil, ---@type table
lastPair = nil, ---@type table
nextPair = nil, ---@type table
previousPair = nil, ---@type table
--Coordinates:
x = nil, ---@type table
y = nil, ---@type table
z = nil, ---@type table
lastX = nil, ---@type number
lastY = nil, ---@type number
zOffset = nil, ---@type number
--Flags:
priority = nil, ---@type integer
index = nil, ---@type integer
isStationary = nil, ---@type boolean
unique = nil, ---@type integer
bindToBuff = nil, ---@type string | nil
persistOnDeath = nil, ---@type boolean
unit = nil, ---@type unit | nil
waitingForBuff = nil, ---@type boolean
bindToOrder = nil, ---@type integer | nil
onDestroy = nil, ---@type function | nil
isUnselectable = nil, ---@type boolean
isAnonymous = nil, ---@type boolean
--Cell interaction:
isGlobal = nil, ---@type boolean
usesCells = nil, ---@type boolean
halfWidth = nil, ---@type number
halfHeight = nil, ---@type number
minX = nil, ---@type integer
minY = nil, ---@type integer
maxX = nil, ---@type integer
maxY = nil, ---@type integer
cellCheckInterval = nil, ---@type integer
nextCellCheck = nil, ---@type integer
positionInCellCheck = nil, ---@type integer
isInCell = nil, ---@type boolean[]
nextInCell = nil, ---@type Actor[]
previousInCell = nil, ---@type Actor[]
cellsVisualized = nil, ---@type boolean
cellVisualizers = nil, ---@type lightning[]
}
---@param host any
---@param identifier string | string[]
---@param interactions table | nil
---@param flags table
---@return Actor | nil
Create = function(host, identifier, interactions, flags)
local identifierType = type(identifier)
local tempIdentifier = GetTable()
if identifierType == "string" then
tempIdentifier[1] = identifier
elseif identifierType == "table" then
for i = 1, #identifier do
tempIdentifier[i] = identifier[i]
end
else
if identifier == nil then
error("Object identifier is nil.")
else
error("Object identifier must be string or table, but was " .. identifierType)
end
end
local self = GetUnusedActor()
totalActors = totalActors + 1
self.unique = totalActors
self.causedCrash = nil
self.host = host or EMPTY_TABLE
if flags.anchor then
local anchor = flags.anchor
while type(anchor) == "table" and anchor.anchor do
CreateReference(self, anchor)
anchor = anchor.anchor --Sup dawg, I heard you like anchors.
end
self.anchor = anchor
CreateReference(self, anchor)
if host then
CreateReference(self, host)
end
elseif host then
self.anchor = host
CreateReference(self, host)
end
self.originalAnchor = self.anchor
--Execute onCreation functions before flags are initialized.
for __, keyword in ipairs(tempIdentifier) do
if onCreation.funcs[keyword] then
for __, func in ipairs(onCreation.funcs[keyword]) do
func(self.host)
end
end
end
--Add additional flags from onCreation hooks.
for __, keyword in ipairs(tempIdentifier) do
if onCreation.flags[keyword] then
local onCreationFlags = onCreation.flags[keyword]
for key, __ in pairs(OVERWRITEABLE_FLAGS) do
if onCreationFlags[key] then
if type(onCreationFlags[key]) == "function" then
additionalFlags[key] = onCreationFlags[key](host)
else
additionalFlags[key] = onCreationFlags[key]
end
end
end
end
end
--Transform identifier sequence into hashmap.
local onCreationIdentifiers
for __, keyword in ipairs(tempIdentifier) do
self.identifier[keyword] = true
if onCreation.identifiers[keyword] then
onCreationIdentifiers = GetTable()
for __, newIdentifier in ipairs(onCreation.identifiers[keyword]) do
if type(newIdentifier) == "function" then
onCreationIdentifiers[#onCreationIdentifiers + 1] = newIdentifier(self.host)
else
onCreationIdentifiers[#onCreationIdentifiers + 1] = newIdentifier
end
end
end
end
if onCreationIdentifiers then
for __, keyword in ipairs(onCreationIdentifiers) do
self.identifier[keyword] = true
end
end
--Copy interactions.
if interactions then
for keyword, func in pairs(interactions) do
if keyword ~= "self" then
self.interactions[keyword] = func
end
end
end
--Add additional interactions from onCreation hooks.
for keyword, __ in pairs(self.identifier) do
if onCreation.interactions[keyword] then
for target, func in pairs(onCreation.interactions[keyword]) do
self.interactions[target] = func
end
end
end
AssignActorClass(self, true, true)
self.zOffset = additionalFlags.zOffset or flags.zOffset or 0
SetOwnerFunc(self, host)
--Set or inherit stationary.
if objectIsStationary[self.anchor] then
self.isStationary = true
elseif additionalFlags.isStationary or flags.isStationary then
if not objectIsStationary[self.anchor] then
objectIsStationary[self.anchor] = true
if not actorOf[self.anchor].isActor then
for __, actor in ipairs(actorOf[self.anchor]) do
if actor ~= self then
SetStationary(actor, true)
end
end
end
end
self.isStationary = true
else
self.isStationary = nil
end
--Set coordinate getter functions.
SetCoordinateFuncs(self)
if flags.isAnonymous then
if interactions then
error("An anonymous actor cannot carry an interactions table. To add self-interactions, use the selfInteractions flag.")
end
self.isAnonymous = true
end
self.isGlobal = flags.isGlobal or (self.x == coord.globalXYZ or self.x == nil) or self.isAnonymous or nil
self.usesCells = not self.isGlobal and not additionalFlags.hasInfiniteRange and not flags.hasInfiniteRange
if not self.isGlobal then
self.lastX = self.x[self.anchor]
self.lastY = self.y[self.anchor]
end
self.priority = additionalFlags.priority or flags.priority or 0
--Pair with global actors or all actors if self is global.
local selfFunc, actorFunc
for __, actor in ipairs(self.usesCells and celllessActorList or actorList) do
selfFunc = GetInteractionFunc(self, actor)
actorFunc = GetInteractionFunc(actor, self)
if selfFunc and actorFunc then
if self.priority < actor.priority then
CreatePair(actor, self, actorFunc)
else
CreatePair(self, actor, selfFunc)
end
elseif selfFunc then
CreatePair(self, actor, selfFunc)
elseif actorFunc then
CreatePair(actor, self, actorFunc)
end
end
--Create self-interactions.
local selfInteractions = interactions and interactions.self or flags.selfInteractions
if selfInteractions then
if type(selfInteractions) == "table" then
for __, func in ipairs(selfInteractions) do
self.selfInteractions[func] = CreatePair(self, SELF_INTERACTION_ACTOR, func)
end
else
self.selfInteractions[selfInteractions] = CreatePair(self, SELF_INTERACTION_ACTOR, selfInteractions)
end
self.interactions.self = nil
end
--Add additional self-interactions from onCreation hooks.
for __, keyword in ipairs(tempIdentifier) do
if onCreation.selfInteractions[keyword] then
for __, func in ipairs(onCreation.selfInteractions[keyword]) do
self.selfInteractions[func] = CreatePair(self, SELF_INTERACTION_ACTOR, func)
end
end
end
--Add additional self-interactions from onCreation hooks to onCreation identifiers.
if onCreationIdentifiers then
for __, keyword in ipairs(onCreationIdentifiers) do
if onCreation.selfInteractions[keyword] then
for __, func in ipairs(onCreation.selfInteractions[keyword]) do
self.selfInteractions[func] = CreatePair(self, SELF_INTERACTION_ACTOR, func)
end
end
end
ReturnTable(onCreationIdentifiers)
end
--Set actor size and initialize cells and cell checks.
if not self.isGlobal then
if flags.width then
self.halfWidth = flags.width/2
if flags.height then
self.halfHeight = flags.height/2
else
Warning("|cffff0000Warning:|r width flag set for actor, but not height flag.")
self.halfHeight = flags.width/2
end
else
local radius = additionalFlags.radius or flags.radius
if radius then
self.halfWidth = radius
self.halfHeight = radius
else
self.halfWidth = config.DEFAULT_OBJECT_RADIUS
self.halfHeight = config.DEFAULT_OBJECT_RADIUS
end
end
InitCells(self)
if self.isStationary then
self.nextCellCheck = DO_NOT_EVALUATE
local interval = additionalFlags.cellCheckInterval or flags.cellCheckInterval or config.DEFAULT_CELL_CHECK_INTERVAL
self.cellCheckInterval = min(MAX_STEPS, max(1, (interval*INV_MIN_INTERVAL) // 1 + 1))
else
InitCellChecks(self, additionalFlags.cellCheckInterval or flags.cellCheckInterval or config.DEFAULT_CELL_CHECK_INTERVAL)
end
end
--Create onDeath trigger.
self.persistOnDeath = flags.persistOnDeath
if (HandleType[self.anchor] == "destructable" or HandleType[self.anchor] == "item") and widgets.deathTriggers[self.anchor] == nil then
widgets.deathTriggers[self.anchor] = CreateTrigger()
TriggerRegisterDeathEvent(widgets.deathTriggers[self.anchor], self.anchor)
if HandleType[self.anchor] == "destructable" then
TriggerAddAction(widgets.deathTriggers[self.anchor], OnDestructableDeath)
else
TriggerAddAction(widgets.deathTriggers[self.anchor], OnItemDeath)
end
end
--Create binds.
if flags.bindToBuff then
CreateBinds(self, flags.bindToBuff, nil)
elseif flags.bindToOrder then
CreateBinds(self, nil, flags.bindToOrder)
end
--Misc.
self.onDestroy = additionalFlags.onActorDestroy or flags.onActorDestroy
if debug.visualizeAllActors and not self.isGlobal then
CreateVisualizer(self)
end
self.alreadyDestroyed = nil
actorList[#actorList + 1] = self
if not self.usesCells and not self.isAnonymous then
celllessActorList[#celllessActorList + 1] = self
end
self.index = #actorList
self.isUnselectable = additionalFlags.isUnselectable or flags.isUnselectable
for key, __ in pairs(additionalFlags) do
additionalFlags[key] = nil
end
ReturnTable(tempIdentifier)
return self
end
Destroy = function(self)
if self == nil or self.alreadyDestroyed then
return
end
self.alreadyDestroyed = true
destroyedActors[#destroyedActors + 1] = self
if self.onDestroy then
self.onDestroy(self.host)
self.onDestroy = nil
end
local next = self.nextPair
local pair = next[self.firstPair]
while pair do
pair.destructionQueued = true
pair = next[pair]
end
if self.index then
actorList[#actorList].index = self.index
actorList[self.index] = actorList[#actorList]
actorList[#actorList] = nil
end
if not self.usesCells and not self.isAnonymous then
for i, actor in ipairs(celllessActorList) do
if self == actor then
celllessActorList[i] = celllessActorList[#celllessActorList]
celllessActorList[#celllessActorList] = nil
break
end
end
end
if not self.isGlobal then
local nextCheck = self.nextCellCheck
if nextCheck ~= DO_NOT_EVALUATE then
local actorAtHighestPosition = cellCheckedActors[nextCheck][numCellChecks[nextCheck]]
actorAtHighestPosition.positionInCellCheck = self.positionInCellCheck
cellCheckedActors[nextCheck][self.positionInCellCheck] = actorAtHighestPosition
numCellChecks[nextCheck] = numCellChecks[nextCheck] - 1
end
for X = self.minX, self.maxX do
for Y = self.minY, self.maxY do
RemoveCell(CELL_LIST[X][Y], self)
end
end
end
if debug.visualizeAllActors and not self.isGlobal then
DestroyEffect(self.visualizer)
end
if self == debug.selectedActor then
DestroyEffect(self.visualizer)
debug.selectedActor = nil
end
end
Release = function(self)
for key, __ in pairs(self.interactions) do
self.interactions[key] = nil
end
for key, __ in pairs(self.identifier) do
self.identifier[key] = nil
end
for key, __ in pairs(self.selfInteractions) do
self.selfInteractions[key] = nil
end
for key, __ in pairs(pairingExcluded[self]) do
pairingExcluded[self][key] = nil
pairingExcluded[key][self] = nil
end
for object, __ in pairs(self.references) do
RemoveReference(self, object)
end
if self.host ~= EMPTY_TABLE then
self.host = nil
self.x[self.anchor] = nil
self.y[self.anchor] = nil
self.z[self] = nil
self.anchor = nil
end
if self.cellsVisualized then
for __, bolt in ipairs(self.cellVisualizers) do
DestroyLightning(bolt)
end
self.cellsVisualized = nil
end
self.x = nil
self.y = nil
self.z = nil
self.lastX = nil
self.lastY = nil
self.bindToBuff = nil
self.bindToOrder = nil
self.isSuspended = nil
unusedActors[#unusedActors + 1] = self
end
---Create a reference to the actor. If more than one actor, transform into a table and store actors in a sequence.
CreateReference = function(self, object)
if actorOf[object] == nil then
actorOf[object] = self
elseif actorOf[object].isActor then
actorOf[object] = {actorOf[object], self}
else
actorOf[object][#actorOf[object] + 1] = self
end
self.references[object] = true
end
RemoveReference = function(self, object)
if actorOf[object].isActor then
actorOf[object] = nil
else
for j, v in ipairs(actorOf[object]) do
if self == v then
table.remove(actorOf[object], j)
end
end
if #actorOf[object] == 1 then
actorOf[object] = actorOf[object][1]
end
end
self.references[object] = nil
end
SetCoordinateFuncs = function(self)
if self.anchor ~= nil then
if IsHandle[self.anchor] then
local type = HandleType[self.anchor]
if type == "unit" then
self.x = coord.unitX
self.y = coord.unitY
self.z = coord.unitZ
elseif type == "destructable" then
self.x = coord.destructableX
self.y = coord.destructableY
self.z = coord.destructableZ
elseif type == "item" then
self.x = coord.itemX
self.y = coord.itemY
self.z = coord.itemZ
else
self.x = coord.globalXYZ
self.y = coord.globalXYZ
self.z = coord.globalXYZ
end
elseif self.anchor.x then
self.x = coord.classX
self.y = coord.classY
if self.anchor.z then
self.z = coord.classZ
else
self.z = coord.terrainZ
end
else
self.x = coord.globalXYZ
self.y = coord.globalXYZ
self.z = coord.globalXYZ
end
self.x[self.anchor] = nil
self.y[self.anchor] = nil
self.z[self] = nil
end
end
SetOwnerFunc = function(self, source)
if source then
if IsHandle[source] then
if HandleType[source] == "unit" then
local owner = GetOwningPlayer(source)
unitOwnerFunc[owner] = unitOwnerFunc[owner] or function() return owner end
self.getOwner = unitOwnerFunc[owner]
else
self.getOwner = DoNothing
end
elseif type(source) == "table" then
if type(source.owner) == "number" then
self.getOwner = GetClassOwnerById
elseif source.owner then
self.getOwner = GetClassOwner
else
self.getOwner = DoNothing
end
end
end
end
InitCells = function(self)
local x = self.x[self.anchor]
local y = self.y[self.anchor]
self.minX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x - self.halfWidth - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
self.minY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y - self.halfHeight - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
self.maxX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x + self.halfWidth - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
self.maxY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y + self.halfHeight - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
for key, __ in pairs(actorAlreadyChecked) do
actorAlreadyChecked[key] = nil
end
actorAlreadyChecked[self] = true
for X = self.minX, self.maxX do
for Y = self.minY, self.maxY do
EnterCell(CELL_LIST[X][Y], self)
end
end
end
InitCellChecks = function(self, interval)
self.cellCheckInterval = min(MAX_STEPS, max(1, (interval*INV_MIN_INTERVAL) // 1 + 1))
local nextStep = cycle.counter + self.cellCheckInterval
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numCellChecks[nextStep] = numCellChecks[nextStep] + 1
cellCheckedActors[nextStep][numCellChecks[nextStep]] = self
self.nextCellCheck = nextStep
self.positionInCellCheck = numCellChecks[nextStep]
end
AssignActorClass = function(self, doIdentifier, doInteractions)
--Concatenates all identifiers and interaction table keys to generate a unique string for an interactionFunc lookup table.
if doIdentifier then
local i = 1
local identifierClass = GetTable()
for id, __ in pairs(self.identifier) do
identifierClass[i] = id
i = i + 1
end
sort(identifierClass)
self.identifierClass = concat(identifierClass)
pairingFunctions[self.identifierClass] = pairingFunctions[self.identifierClass] or {}
ReturnTable(identifierClass)
end
if doInteractions then
local j = 1
local first, entry
local interactionsClass = GetTable()
for target, func in pairs(self.interactions) do
if type(target) == "string" then
if not functionKey[func] then
highestFunctionKey = highestFunctionKey + 1
functionKey[func] = highestFunctionKey
end
interactionsClass[j] = target .. functionKey[func]
elseif type(target) == "table" then
first = true
entry = ""
for __, subtarget in ipairs(target) do
if not first then
entry = entry .. "+"
else
first = false
end
if not functionKey[func] then
highestFunctionKey = highestFunctionKey + 1
functionKey[func] = highestFunctionKey
end
entry = entry .. subtarget
end
interactionsClass[j] = entry .. functionKey[func]
else
error("Interactions table key must be string or table, but was " .. type(target) .. ".")
end
j = j + 1
end
sort(interactionsClass)
self.interactionsClass = concat(interactionsClass)
ReturnTable(interactionsClass)
end
end
--Repair with all actors currently in interaction range.
Flicker = function(self)
if self.alreadyDestroyed then
return
end
if not self.isGlobal then
for key, __ in pairs(actorAlreadyChecked) do
actorAlreadyChecked[key] = nil
end
actorAlreadyChecked[self] = true
for cell, __ in pairs(self.isInCell) do
LeaveCell(cell, self)
end
InitCells(self)
if self.cellsVisualized then
RedrawCellVisualizers(self)
end
end
local selfFunc, actorFunc
for __, actor in ipairs(self.usesCells and celllessActorList or actorList) do
if not pairList[actor][self] and not pairList[self][actor] then
selfFunc = GetInteractionFunc(self, actor)
actorFunc = GetInteractionFunc(actor, self)
if selfFunc and actorFunc then
if self.priority < actor.priority then
CreatePair(actor, self, actorFunc)
else
CreatePair(self, actor, selfFunc)
end
elseif selfFunc then
CreatePair(self, actor, selfFunc)
elseif actorFunc then
CreatePair(actor, self, actorFunc)
end
end
end
end
SharesCellWith = function(self, actor)
if self.halfWidth < actor.halfWidth then
for cellA in pairs(self.isInCell) do
if actor.isInCell[cellA] then
return true
end
end
return false
else
for cellB in pairs(actor.isInCell) do
if self.isInCell[cellB] then
return true
end
end
return false
end
end
CreateBinds = function(self, bindToBuff, bindToOrder)
if bindToBuff then
self.bindToBuff = type(bindToBuff) == "number" and bindToBuff or FourCC(bindToBuff)
self.waitingForBuff = true
insert(widgets.bindChecks, self)
elseif bindToOrder then
self.bindToOrder = type(bindToOrder) == "number" and bindToOrder or OrderId(bindToOrder)
insert(widgets.bindChecks, self)
end
if HandleType[self.host] == "unit" then
self.unit = self.host
elseif HandleType[self.anchor] == "unit" then
self.unit = self.anchor
else
Warning("|cffff0000Warning:|r Attempted to bind actor with identifier " .. Identifier2String(self.identifier) .. " to a buff or order, but that actor doesn't have a unit host or anchor.")
end
end
DestroyObsoletePairs = function(self)
if self.alreadyDestroyed then
return
end
local actor
local next = self.nextPair
local pair = next[self.firstPair]
local thisPair
while pair do
if pair[0x2] ~= SELF_INTERACTION_ACTOR then
if self == pair[0x1] then
actor = pair[0x2]
else
actor = pair[0x1]
end
if not actor.alreadyDestroyed and not GetInteractionFunc(self, actor) and not GetInteractionFunc(actor, self) then
thisPair = pair
pair = next[pair]
DestroyPair(thisPair)
else
pair = next[pair]
end
else
pair = next[pair]
end
end
end
Unpause = function(self, whichFunctions)
local actorA, actorB, nextStep
local DO_NOT_EVALUATE = DO_NOT_EVALUATE
local CYCLE_LENGTH = CYCLE_LENGTH
local next = self.nextPair
local pair = next[self.firstPair]
while pair do
if whichFunctions == nil or whichFunctions[pair[0x8]] then
actorA = pair[0x1]
actorB = pair[0x2]
if pair[0x7] then
if pair[0x6] == nil and (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
AddPairToEveryStepList(pair)
end
else
if pair[0x5] == DO_NOT_EVALUATE and (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
nextStep = cycle.counter + 1
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = pair
pair[0x5] = nextStep
pair[0x6] = numPairs[nextStep]
end
end
pair.paused = nil
end
pair = next[pair]
end
end
SetStationary = function(self, enable)
if (self.isStationary == true) == enable then
return
end
self.isStationary = enable
if enable then
local nextCheck = self.nextCellCheck
local actorAtHighestPosition = cellCheckedActors[nextCheck][numCellChecks[nextCheck]]
actorAtHighestPosition.positionInCellCheck = self.positionInCellCheck
cellCheckedActors[nextCheck][self.positionInCellCheck] = actorAtHighestPosition
numCellChecks[nextCheck] = numCellChecks[nextCheck] - 1
self.nextCellCheck = DO_NOT_EVALUATE
local next = self.nextPair
local thisPair = next[self.firstPair]
while thisPair do
if functionPauseOnStationary[thisPair[0x8]] and self == thisPair[0x1] then
AddDelayedCallback(PausePair, thisPair)
end
thisPair = next[thisPair]
end
else
local nextStep = cycle.counter + 1
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numCellChecks[nextStep] = numCellChecks[nextStep] + 1
cellCheckedActors[nextStep][numCellChecks[nextStep]] = self
self.nextCellCheck = nextStep
self.positionInCellCheck = numCellChecks[nextStep]
AddDelayedCallback(Unpause, self, functionPauseOnStationary)
end
SetCoordinateFuncs(self)
end
---For debug mode.
VisualizeCells = function(self, enable)
if enable == self.cellsVisualized then
return
end
if self.cellsVisualized then
self.cellsVisualized = false
DestroyLightning(self.cellVisualizers[1])
DestroyLightning(self.cellVisualizers[2])
DestroyLightning(self.cellVisualizers[3])
DestroyLightning(self.cellVisualizers[4])
elseif not self.isGlobal then
self.cellVisualizers = {}
self.cellsVisualized = true
local minx = CELL_MIN_X[self.minX]
local miny = CELL_MIN_Y[self.minY]
local maxx = CELL_MAX_X[self.maxX]
local maxy = CELL_MAX_Y[self.maxY]
self.cellVisualizers[1] = AddLightning("LEAS", false, maxx, miny, maxx, maxy)
self.cellVisualizers[2] = AddLightning("LEAS", false, maxx, maxy, minx, maxy)
self.cellVisualizers[3] = AddLightning("LEAS", false, minx, maxy, minx, miny)
self.cellVisualizers[4] = AddLightning("LEAS", false, minx, miny, maxx, miny)
end
end
---For debug mode.
RedrawCellVisualizers = function(self)
local minx = CELL_MIN_X[self.minX]
local miny = CELL_MIN_Y[self.minY]
local maxx = CELL_MAX_X[self.maxX]
local maxy = CELL_MAX_Y[self.maxY]
MoveLightning(self.cellVisualizers[1], false, maxx, miny, maxx, maxy)
MoveLightning(self.cellVisualizers[2], false, maxx, maxy, minx, maxy)
MoveLightning(self.cellVisualizers[3], false, minx, maxy, minx, miny)
MoveLightning(self.cellVisualizers[4], false, minx, miny, maxx, miny)
end
---Called when an object is loaded into a transport actor crashes a thread.
Suspend = function(self, enable)
if enable then
local pair
for __, actor in ipairs(actorList) do
pair = pairList[actor][self] or pairList[self][actor]
if pair and not functionIsUnsuspendable[pair[0x8]] then
DestroyPair(pair)
end
end
self.isSuspended = true
else
self.isSuspended = false
AddDelayedCallback(Flicker, self)
end
end
---For debug mode.
Deselect = function(self)
debug.selectedActor = nil
if not debug.visualizeAllActors then
DestroyEffect(self.visualizer)
end
VisualizeCells(self, false)
BlzFrameSetVisible(debug.tooltip, false)
end
GetMissingRequiredFieldsString = function(self, func, isMaleInFunc, isFemaleInFunc)
local description = ""
if functionRequiredFields[func] then
local first = true
if functionRequiredFields[func] then
if isMaleInFunc and functionRequiredFields[func].male then
for field, value in pairs(functionRequiredFields[func].male) do
if not self.host[field] and (value == true or self.host[value]) then
if first then
first = false
else
description = description .. ", "
end
description = description .. field
end
end
end
if isFemaleInFunc and functionRequiredFields[func].female then
for field, value in pairs(functionRequiredFields[func].female) do
if not self.host[field] and (value == true or self.host[value]) then
if first then
first = false
else
description = description .. ", "
end
description = description .. field
end
end
end
end
end
return description
end
---For debug mode.
GetDescription = function(self)
local description = setmetatable({}, {__add = function(old, new) old[#old + 1] = new return old end})
description = description + "|cffffcc00Identifiers:|r "
local first = true
for key, __ in pairs(self.identifier) do
if not first then
description = description + ", "
else
first = false
end
description = description + key
end
if self.host ~= EMPTY_TABLE then
description = description + "\n\n|cffffcc00Host:|r " + Object2String(self.host)
end
if self.originalAnchor ~= self.host then
description = description + "\n|cffffcc00Anchor:|r " + Object2String(self.originalAnchor)
end
description = description + "\n|cffffcc00Interactions:|r "
first = true
for key, func in pairs(self.interactions) do
if not first then
description = description + ", "
end
if type(key) == "string" then
description = description + key + " - " + Function2String(func)
else
local subFirst = true
for __, word in ipairs(key) do
if not subFirst then
description = description + " + "
end
description = description + word
subFirst = false
end
description = description + " - " + Function2String(func)
end
first = false
end
if next(self.selfInteractions) then
description = description + "\n|cffffcc00Self-Interactions:|r "
first = true
for key, __ in pairs(self.selfInteractions) do
if not first then
description = description + ", "
end
first = false
description = description + Function2String(key)
end
end
if self.priority ~= 0 then
description = description + "\n|cffffcc00Priority:|r " + self.priority
end
if self.cellCheckInterval and math.abs(self.cellCheckInterval*config.MIN_INTERVAL - config.DEFAULT_CELL_CHECK_INTERVAL) > 0.001 then
description = description + "\n|cffffcc00Cell Check Interval:|r " + self.cellCheckInterval*config.MIN_INTERVAL
end
if self.isStationary then
description = description + "\n|cffffcc00Stationary:|r true"
end
if not self.isGlobal and not self.usesCells then
description = description + "\n|cffffcc00Has infinite range:|r true"
end
if self.halfWidth and self.halfWidth ~= config.DEFAULT_OBJECT_RADIUS then
if self.halfWidth ~= self.halfHeight then
description = description + "\n|cffffcc00Width:|r " + 2*self.halfWidth
description = description + "\n|cffffcc00Height:|r " + 2*self.halfHeight
else
description = description + "\n|cffffcc00Radius:|r " + self.halfWidth
end
end
if self.getOwner(self.host) then
description = description + "\n|cffffcc00Owner:|r Player " + (GetPlayerId(self.getOwner(self.host)) + 1)
end
if self.bindToBuff then
description = description + "\n|cffffcc00Bound to buff:|r " + string.pack(">I4", self.bindToBuff)
if self.waitingForBuff then
description = description + " |cffaaaaaa(waiting for buff to be applied)|r"
end
end
if self.bindToOrder then
description = description + "\n|cffffcc00Bound to order:|r " + OrderId2String(self.bindToOrder) + " |cffaaaaaa(current order = " + OrderId2String(GetUnitCurrentOrder(self.anchor)) + ")|r"
end
if self.onDestroy then
description = description + "\n|cffffcc00On Destroy:|r " + Function2String(self.onDestroy)
end
description = description + "\n\n|cffffcc00Unique Number:|r " + self.unique
local numOutgoing = 0
local numIncoming = 0
local hasError = false
local outgoingFuncs = {}
local incomingFuncs = {}
local funcs = {}
local isMaleInFunc = {}
local isFemaleInFunc = {}
local nextPair = self.nextPair
local pair = nextPair[self.firstPair]
while pair do
if pair[0x2] ~= SELF_INTERACTION_ACTOR then
if pair[0x1] == self then
numOutgoing = numOutgoing + 1
outgoingFuncs[pair[0x8]] = (outgoingFuncs[pair[0x8]] or 0) + 1
elseif pair[0x2] == self then
numIncoming = numIncoming + 1
incomingFuncs[pair[0x8]] = (incomingFuncs[pair[0x8]] or 0) + 1
else
hasError = true
end
end
funcs[pair[0x8]] = true
if pair[0x1] == self then
isMaleInFunc[pair[0x8]] = true
else
isFemaleInFunc[pair[0x8]] = true
end
pair = nextPair[pair]
end
description = description + "\n|cffffcc00Outgoing pairs:|r " + numOutgoing
if numOutgoing > 0 then
first = true
description = description + "|cffaaaaaa ("
for key, number in pairs(outgoingFuncs) do
if not first then
description = description + ", |r"
end
description = description + "|cffffcc00" + number + "|r |cffaaaaaa" + Function2String(key)
first = false
end
description = description + ")|r"
end
description = description + "\n|cffffcc00Incoming pairs:|r " + numIncoming
if numIncoming > 0 then
first = true
description = description + "|cffaaaaaa ("
for key, number in pairs(incomingFuncs) do
if not first then
description = description + ", |r"
end
description = description + "|cffffcc00" + number + "|r |cffaaaaaa" + Function2String(key)
first = false
end
description = description + ")|r"
end
if not self.isGlobal then
local x, y = self.x[self.anchor], self.y[self.anchor]
description = description + "\n\n|cffffcc00x:|r " + x
description = description + "\n|cffffcc00y:|r " + y
description = description + "\n|cffffcc00z:|r " + self.z[self]
end
if hasError then
description = description + "\n\n|cffff0000DESYNCED PAIR DETECTED!|r"
end
if self.causedCrash then
description = description + "\n\n|cffff0000CAUSED CRASH!|r"
end
if type(self.host) == "table" then
first = true
local requiredFieldString
for func, __ in pairs(funcs) do
requiredFieldString = GetMissingRequiredFieldsString(self, func, isMaleInFunc[func], isFemaleInFunc[func])
if requiredFieldString ~= "" then
if first then
description = description + "\n\n|cffff0000Missing required fields:|r"
first = false
end
description = description + "\n" + requiredFieldString + " |cffaaaaaa(" + Function2String(func) + ")|r"
end
end
end
if next(debug.trackedVariables) then
description = description + "\n\n|cffff0000Tracked variables:|r"
for key, __ in pairs(debug.trackedVariables) do
if type(self.host) == "table" and self.host[key] then
description = description + "\n|cffffcc00" + key + "|r: " + tostring(self.host[key])
end
if self.host ~= self.anchor and type(self.anchor) == "table" and self.anchor[key] then
description = description + "\n|cffffcc00" + key + "|r: " + tostring(self.host[key])
end
if _G[key] then
if _G[key][self.host] then
description = description + "\n|cffffcc00" + key + "|r: " + tostring(_G[key][self.host])
end
if self.host ~= self.anchor and _G[key][self.anchor] then
description = description + "\n|cffffcc00" + key + "|r: " + tostring(_G[key][self.anchor])
end
end
end
end
local str = concat(description)
if self.isGlobal then
return str, "|cff00bb00Global Actor|r"
else
if numOutgoing == 0 and numIncoming == 0 then
return str, "|cffaaaaaaUnpaired Actor|r"
elseif numOutgoing == 0 then
return str, "|cffffc0cbFemale Actor|r"
elseif numIncoming == 0 then
return str, "|cff90b5ffMale Actor|r"
else
return str, "|cffffff00Hybrid Actor|r"
end
end
end
---For debug mode.
Select = function(self)
debug.selectedActor = self
local description, title = GetDescription(self)
BlzFrameSetText(debug.tooltipText, description)
BlzFrameSetText(debug.tooltipTitle, title )
BlzFrameSetSize(debug.tooltipText, 0.28, 0.0)
BlzFrameSetSize(debug.tooltip, 0.29, BlzFrameGetHeight(debug.tooltipText) + 0.0315)
BlzFrameSetVisible(debug.tooltip, true)
if not self.isGlobal then
VisualizeCells(self, true)
if not self.isGlobal and not debug.visualizeAllActors then
CreateVisualizer(self)
end
end
end
---For debug mode.
CreateVisualizer = function(self)
local x, y = self.x[self.anchor], self.y[self.anchor]
self.visualizer = AddSpecialEffect("Abilities\\Spells\\Other\\Aneu\\AneuTarget.mdl", x, y)
BlzSetSpecialEffectColorByPlayer(self.visualizer, self.getOwner(self.host) or Player(21))
BlzSetSpecialEffectZ(self.visualizer, self.z[self] + 75)
end
--#endregion
--Stub actors are used by periodic callers.
CreateStub = function(host)
local actor = GetUnusedActor()
actor.host = host
actor.anchor = host
actor.isGlobal = true
actor.x = coord.globalXYZ
actor.y = coord.globalXYZ
actor.z = coord.globalXYZ
actor.unique = 0
actor.alreadyDestroyed = nil
actorOf[host] = actor
return actor
end
DestroyStub = function(self)
if self == nil or self.alreadyDestroyed then
return
end
self.periodicPair = nil
actorOf[self.host] = nil
self.host = nil
self.anchor = nil
self.isGlobal = nil
self.x = nil
self.y = nil
self.z = nil
self.alreadyDestroyed = true
unusedActors[#unusedActors + 1] = self
end
local SetFlag = {
radius = function(self, radius)
self.halfWidth = radius
self.halfHeight = radius
AddDelayedCallback(Flicker, self)
end,
anchor = function(self, anchor)
if anchor == self.originalAnchor then
return
end
for object, __ in pairs(self.references) do
if object ~= self.host then
RemoveReference(self, object)
end
end
if anchor then
while type(anchor) == "table" and anchor.anchor do
CreateReference(self, anchor)
anchor = anchor.anchor
end
self.anchor = anchor
self.originalAnchor = self.anchor
CreateReference(self, anchor)
SetCoordinateFuncs(self)
else
local oldAnchor = self.anchor
self.anchor = self.host
self.originalAnchor = self.anchor
if type(self.host) == "table" then
self.host.x, self.host.y, self.host.z = ALICE_GetCoordinates3D(oldAnchor)
end
SetCoordinateFuncs(self)
end
AddDelayedCallback(Flicker, self)
end,
width = function(self, width)
self.halfWidth = width/2
AddDelayedCallback(Flicker, self)
end,
height = function(self, height)
self.halfHeight = height/2
AddDelayedCallback(Flicker, self)
end,
cellCheckInterval = function(self, cellCheckInterval)
self.cellCheckInterval = min(MAX_STEPS, max(1, (cellCheckInterval*INV_MIN_INTERVAL) // 1 + 1))
end,
onActorDestroy = function(self, onActorDestroy)
self.onActorDestroy = onActorDestroy
end,
isUnselectable = function(self, isUnselectable)
self.isUnselectable = isUnselectable
end,
persistOnDeath = function(self, persistOnDeath)
self.persistOnDeath = persistOnDeath
end,
priority = function(self, priority)
self.priority = priority
end,
zOffset = function(self, zOffset)
self.zOffset = zOffset
self.z[self] = nil
end,
bindToBuff = function(self, buff)
if self.bindToBuff then
self.bindToBuff = type(buff) == "number" and buff or FourCC(buff)
else
CreateBinds(self, buff, nil)
end
end,
bindToOrder = function(self, order)
if self.bindToOrder then
self.bindToorder = type(order) == "number" and order or OrderId(order)
else
CreateBinds(self, nil, order)
end
end
}
--===========================================================================================================================================================
--Cell Class
--===========================================================================================================================================================
--#region Cell
---@class Cell
local Cell = {
horizontalLightning = nil, ---@type lightning
verticalLightning = nil, ---@type lightning
first = nil, ---@type Actor
last = nil, ---@type Actor
numActors = nil ---@type integer
}
EnterCell = function(self, actorA)
local aFunc, bFunc
actorA.isInCell[self] = true
actorA.nextInCell[self] = nil
actorA.previousInCell[self] = self.last
if self.first == nil then
self.first = actorA
else
self.last.nextInCell[self] = actorA
end
self.last = actorA
if actorA.hasInfiniteRange then
return
end
local DO_NOT_EVALUATE = DO_NOT_EVALUATE
local CYCLE_LENGTH = CYCLE_LENGTH
local actorB = self.first
for __ = 1, self.numActors do
if not actorAlreadyChecked[actorB] then
actorAlreadyChecked[actorB] = true
local thisPair = pairList[actorA][actorB] or pairList[actorB][actorA]
if thisPair then
if not thisPair.paused then
if thisPair[0x7] then
if thisPair[0x6] == nil then
AddPairToEveryStepList(thisPair)
end
elseif thisPair[0x5] == DO_NOT_EVALUATE then
local nextStep
if functionDelay[0x8] then
local interactionFunc = thisPair[0x8]
if functionDelayIsDistributed[interactionFunc] then
functionDelayCurrent[interactionFunc] = functionDelay[interactionFunc] + config.MIN_INTERVAL
if functionDelayCurrent[interactionFunc] > functionDelay[interactionFunc] then
functionDelayCurrent[interactionFunc] = functionDelayCurrent[interactionFunc] - functionDelay[interactionFunc]
end
nextStep = cycle.counter + (functionDelayCurrent[interactionFunc]*INV_MIN_INTERVAL + 1) // 1
else
nextStep = cycle.counter + (functionDelay[interactionFunc]*INV_MIN_INTERVAL + 1) // 1
end
else
nextStep = cycle.counter + 1
end
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = thisPair
thisPair[0x5] = nextStep
thisPair[0x6] = numPairs[nextStep]
end
end
elseif not pairingExcluded[actorA][actorB] then
aFunc = GetInteractionFunc(actorA, actorB)
if aFunc then
if actorA.priority < actorB.priority then
bFunc = GetInteractionFunc(actorB, actorA)
if bFunc then
CreatePair(actorB, actorA, bFunc)
else
CreatePair(actorA, actorB, aFunc)
end
else
CreatePair(actorA, actorB, aFunc)
end
else
bFunc = GetInteractionFunc(actorB, actorA)
if bFunc then
CreatePair(actorB, actorA, bFunc)
end
end
end
end
actorB = actorB.nextInCell[self]
end
self.numActors = self.numActors + 1
end
RemoveCell = function(self, actorA)
if self.first == actorA then
self.first = actorA.nextInCell[self]
else
actorA.previousInCell[self].nextInCell[self] = actorA.nextInCell[self]
end
if self.last == actorA then
self.last = actorA.previousInCell[self]
else
actorA.nextInCell[self].previousInCell[self] = actorA.previousInCell[self]
end
actorA.isInCell[self] = nil
self.numActors = self.numActors - 1
end
LeaveCell = function(self, actorA, wasLoaded)
RemoveCell(self, actorA)
if actorA.hasInfiniteRange then
return
end
local DO_NOT_EVALUATE = DO_NOT_EVALUATE
local actorB = self.first
for __ = 1, self.numActors do
if not actorAlreadyChecked[actorB] then
actorAlreadyChecked[actorB] = true
local thisPair = pairList[actorA][actorB] or pairList[actorB][actorA]
if thisPair then
if thisPair[0x7] then
if thisPair[0x6] and (((actorA.maxX < actorB.minX or actorA.minX > actorB.maxX or actorA.maxY < actorB.minY or actorA.minY > actorB.maxY) and not functionIsUnbreakable[thisPair[0x8]]) or wasLoaded) and actorB.usesCells then
RemovePairFromEveryStepList(thisPair)
if thisPair.hadContact then
if functionOnReset[thisPair[0x8]] and not cycle.isCrash then
local tempPair = currentPair
currentPair = thisPair
functionOnReset[thisPair[0x8]](thisPair[0x3], thisPair[0x4], thisPair.userData, false)
currentPair = tempPair
end
thisPair.hadContact = nil
end
if functionOnBreak[thisPair[0x8]] then
local tempPair = currentPair
currentPair = thisPair
functionOnBreak[thisPair[0x8]](thisPair[0x3], thisPair[0x4], thisPair.userData, false)
currentPair = tempPair
end
end
elseif thisPair[0x5] ~= DO_NOT_EVALUATE and (actorA.maxX < actorB.minX or actorA.minX > actorB.maxX or actorA.maxY < actorB.minY or actorA.minY > actorB.maxY) and not functionIsUnbreakable[thisPair[0x8]] and actorB.usesCells then
whichPairs[thisPair[0x5]][thisPair[0x6]] = DUMMY_PAIR
local nextStep = DO_NOT_EVALUATE
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = thisPair
thisPair[0x5] = nextStep
thisPair[0x6] = numPairs[nextStep]
if thisPair.hadContact then
if functionOnReset[thisPair[0x8]] and not cycle.isCrash then
local tempPair = currentPair
currentPair = thisPair
functionOnReset[thisPair[0x8]](thisPair[0x3], thisPair[0x4], thisPair.userData, false)
currentPair = tempPair
end
thisPair.hadContact = nil
end
if functionOnBreak[thisPair[0x8]] then
local tempPair = currentPair
currentPair = thisPair
functionOnBreak[thisPair[0x8]](thisPair[0x3], thisPair[0x4], thisPair.userData, false)
currentPair = tempPair
end
end
end
end
actorB = actorB.nextInCell[self]
end
end
--#endregion
--===========================================================================================================================================================
--Repair
--===========================================================================================================================================================
--#region Repair
local function RepairCycle(firstPosition)
local numSteps
local nextStep
--Variable Step Cycle
local returnValue
local pairsThisStep = whichPairs[cycle.counter]
for i = firstPosition, numPairs[cycle.counter] do
currentPair = pairsThisStep[i]
if currentPair.destructionQueued then
if currentPair ~= DUMMY_PAIR then
nextStep = cycle.counter + MAX_STEPS
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[0x5] = nextStep
currentPair[0x6] = numPairs[nextStep]
end
else
returnValue = currentPair[0x8](currentPair[0x3], currentPair[0x4])
if returnValue then
numSteps = (returnValue*INV_MIN_INTERVAL + 1) // 1 --convert seconds to steps, then ceil.
if numSteps < 1 then
numSteps = 1
elseif numSteps > MAX_STEPS then
numSteps = MAX_STEPS
end
nextStep = cycle.counter + numSteps
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[0x5] = nextStep
currentPair[0x6] = numPairs[nextStep]
else
AddPairToEveryStepList(currentPair)
functionIsEveryStep[currentPair[0x8]] = true
currentPair[0x7] = true
end
end
end
numPairs[cycle.counter] = 0
currentPair = OUTSIDE_OF_CYCLE
end
local function PrintCrashMessage(crashingPair, A, B)
local warning
if B == SELF_INTERACTION_ACTOR then
warning = "\n|cffff0000Error:|r ALICE Cycle crashed during last execution. The identifier of the actor responsible is "
.. "|cffffcc00" .. Identifier2String(A.identifier) .. "|r. Unique number: " .. A.unique .. ". The crash occured during self-interaction with function |cffaaaaff" .. Function2String(crashingPair[0x8]) .. "|r. The interaction has been disabled."
else
warning = "\n|cffff0000Error:|r ALICE Cycle crashed during last execution. The identifiers of the actors responsible are "
.. "|cffffcc00" .. Identifier2String(A.identifier) .. "|r and |cffaaaaff" .. Identifier2String(B.identifier) .. "|r. Unique numbers: " .. A.unique .. ", " .. B.unique .. ". The pair has been removed from the cycle."
end
if type(A.host) == "table" then
local requiredFieldString = GetMissingRequiredFieldsString(A, crashingPair[0x8], true, false)
if requiredFieldString ~= "" then
warning = warning .. "\n\nThere are one or more |cffff0000required fields missing|r for the interaction function in the host table of actor " .. A.unique .. ":\n|cffaaaaff" .. requiredFieldString .. "|r"
end
end
if type(B.host) == "table" then
local requiredFieldString = GetMissingRequiredFieldsString(B, crashingPair[0x8], false, true)
if requiredFieldString ~= "" then
warning = warning .. "\n\nThere are one or more |cffff0000required fields missing|r for the interaction function in the host table of actor " .. B.unique .. ":\n|cffaaaaff" .. requiredFieldString .. "|r"
end
end
Warning(warning)
end
local function OnCrash()
local crashingPair = currentPair
--Remove pair and continue with cycle after the crashing pair.
local A = crashingPair[0x1]
local B = crashingPair[0x2]
pairingExcluded[A][B] = true
pairingExcluded[B][A] = true
PrintCrashMessage(crashingPair, A, B)
if not crashingPair[0x7] then
local nextPosition = crashingPair[0x6] + 1
numPairs[DO_NOT_EVALUATE] = numPairs[DO_NOT_EVALUATE] + 1
whichPairs[DO_NOT_EVALUATE][numPairs[DO_NOT_EVALUATE]] = crashingPair
crashingPair[0x5] = DO_NOT_EVALUATE
crashingPair[0x6] = numPairs[DO_NOT_EVALUATE]
cycle.isCrash = true
DestroyPair(crashingPair)
RepairCycle(nextPosition)
else
cycle.isCrash = true
DestroyPair(crashingPair)
end
--If this is the second time the same actor caused a crash, isolate it to prevent it from causing further crashes.
if A.causedCrash then
Warning("\nActor with identifier " .. Identifier2String(A.identifier) .. ", unique number: " .. A.unique .. " is repeatedly causing crashes. Isolating...")
Suspend(A)
elseif B.causedCrash and B ~= SELF_INTERACTION_ACTOR then
Warning("\nActor with identifier " .. Identifier2String(B.identifier) .. ", unique number: " .. B.unique .. " is repeatedly causing crashes. Isolating...")
Suspend(B)
end
A.causedCrash = true
B.causedCrash = true
cycle.isCrash = false
end
--#endregion
--===========================================================================================================================================================
--Main Functions
--===========================================================================================================================================================
--#region Main Functions
local function ResetCoordinateLookupTables()
local classX, classY = coord.classX, coord.classY
for key, __ in pairs(classX) do
classX[key], classY[key] = nil, nil
end
local classZ = coord.classZ
for key, __ in pairs(classZ) do
classZ[key] = nil
end
local unitX, unitY = coord.unitX, coord.unitY
for key, __ in pairs(unitX) do
unitX[key], unitY[key] = nil, nil
end
local unitZ = coord.unitZ
for key, __ in pairs(unitZ) do
unitZ[key] = nil
end
if not config.ITEMS_ARE_STATIONARY then
local itemX, itemY = coord.itemX, coord.itemY
for key, __ in pairs(itemX) do
itemX[key], itemY[key] = nil, nil
end
local itemZ = coord.itemZ
for key, __ in pairs(itemZ) do
itemZ[key] = nil
end
end
local terrainZ = coord.terrainZ
for key, __ in pairs(terrainZ) do
terrainZ[key] = nil
end
end
local function BindChecks()
for i = #widgets.bindChecks, 1, -1 do
local actor = widgets.bindChecks[i]
if actor.bindToBuff then
if actor.waitingForBuff then
if GetUnitAbilityLevel(actor.unit, FourCC(actor.bindToBuff)) > 0 then
actor.waitingForBuff = nil
end
elseif GetUnitAbilityLevel(actor.unit, FourCC(actor.bindToBuff)) == 0 then
Destroy(actor)
widgets.bindChecks[i] = widgets.bindChecks[#widgets.bindChecks]
widgets.bindChecks[#widgets.bindChecks] = nil
end
elseif actor.bindToOrder then
if GetUnitCurrentOrder(actor.unit) ~= actor.bindToOrder then
Destroy(actor)
widgets.bindChecks[i] = widgets.bindChecks[#widgets.bindChecks]
widgets.bindChecks[#widgets.bindChecks] = nil
end
end
end
end
---All destroyed pairs are only flagged and not destroyed until main cycle completes. This function destroys all pairs in one go.
local function RemovePairsFromCycle()
for i = #destroyedActors, 1, -1 do
local actor = destroyedActors[i]
if actor then
local firstPair = actor.firstPair
local thisPair = actor.lastPair
while thisPair ~= firstPair do
DestroyPair(thisPair)
thisPair = actor.lastPair
end
Release(actor)
end
destroyedActors[i] = nil
end
end
local function CellCheck()
local x, y
local minx, miny, maxx, maxy
local changedCells
local newMinX, newMinY, newMaxX, newMaxY
local oldMinX, oldMinY, oldMaxX, oldMaxY
local halfWidth, halfHeight
local actor
local currentCounter = cycle.counter
local actorsThisStep = cellCheckedActors[currentCounter]
local nextStep
local CYCLE_LENGTH = CYCLE_LENGTH
for i = 1, numCellChecks[currentCounter] do
actor = actorsThisStep[i]
x = actor.x[actor.anchor]
y = actor.y[actor.anchor]
halfWidth = actor.halfWidth
halfHeight = actor.halfHeight
minx = x - halfWidth
miny = y - halfHeight
maxx = x + halfWidth
maxy = y + halfHeight
newMinX = actor.minX
newMinY = actor.minY
newMaxX = actor.maxX
newMaxY = actor.maxY
if x > actor.lastX then
while minx > CELL_MAX_X[newMinX] and newMinX < NUM_CELLS_X do
changedCells = true
newMinX = newMinX + 1
end
while maxx > CELL_MAX_X[newMaxX] and newMaxX < NUM_CELLS_X do
changedCells = true
newMaxX = newMaxX + 1
end
else
while minx < CELL_MIN_X[newMinX] and newMinX > 1 do
changedCells = true
newMinX = newMinX - 1
end
while maxx < CELL_MIN_X[newMaxX] and newMaxX > 1 do
changedCells = true
newMaxX = newMaxX - 1
end
end
if y > actor.lastY then
while miny > CELL_MAX_Y[newMinY] and newMinY < NUM_CELLS_Y do
changedCells = true
newMinY = newMinY + 1
end
while maxy > CELL_MAX_Y[newMaxY] and newMaxY < NUM_CELLS_Y do
changedCells = true
newMaxY = newMaxY + 1
end
else
while miny < CELL_MIN_Y[newMinY] and newMinY > 1 do
changedCells = true
newMinY = newMinY - 1
end
while maxy < CELL_MIN_Y[newMaxY] and newMaxY > 1 do
changedCells = true
newMaxY = newMaxY - 1
end
end
if changedCells then
oldMinX = actor.minX
oldMinY = actor.minY
oldMaxX = actor.maxX
oldMaxY = actor.maxY
actor.minY = newMinY
actor.maxX = newMaxX
actor.maxY = newMaxY
for key, __ in pairs(actorAlreadyChecked) do
actorAlreadyChecked[key] = nil
end
actorAlreadyChecked[actor] = true
if newMinX > oldMinX then
actor.minX = newMinX
for X = oldMinX, newMinX - 1 < oldMaxX and newMinX - 1 or oldMaxX do
for Y = oldMinY, oldMaxY do
LeaveCell(CELL_LIST[X][Y], actor)
end
end
elseif newMinX < oldMinX then
actor.minX = newMinX
for X = newMinX, newMaxX < oldMinX - 1 and newMaxX or oldMinX - 1 do
for Y = newMinY, newMaxY do
EnterCell(CELL_LIST[X][Y], actor)
end
end
end
if newMaxX > oldMaxX then
for X = oldMaxX + 1 > newMinX and oldMaxX + 1 or newMinX, newMaxX do
for Y = newMinY, newMaxY do
EnterCell(CELL_LIST[X][Y], actor)
end
end
elseif newMaxX < oldMaxX then
for X = newMaxX + 1 > oldMinX and newMaxX + 1 or oldMinX , oldMaxX do
for Y = oldMinY, oldMaxY do
LeaveCell(CELL_LIST[X][Y], actor)
end
end
end
if newMinY > oldMinY then
for Y = oldMinY, newMinY - 1 < oldMaxY and newMinY - 1 or oldMaxY do
for X = oldMinX > newMinX and oldMinX or newMinX, oldMaxX < newMaxX and oldMaxX or newMaxX do
LeaveCell(CELL_LIST[X][Y], actor)
end
end
elseif newMinY < oldMinY then
for Y = newMinY, newMaxY < oldMinY - 1 and newMaxY or oldMinY - 1 do
for X = oldMinX > newMinX and oldMinX or newMinX, oldMaxX < newMaxX and oldMaxX or newMaxX do
EnterCell(CELL_LIST[X][Y], actor)
end
end
end
if newMaxY > oldMaxY then
for Y = oldMaxY + 1 > newMinY and oldMaxY + 1 or newMinY, newMaxY do
for X = oldMinX > newMinX and oldMinX or newMinX, oldMaxX < newMaxX and oldMaxX or newMaxX do
EnterCell(CELL_LIST[X][Y], actor)
end
end
elseif newMaxY < oldMaxY then
for Y = newMaxY + 1 > oldMinY and newMaxY + 1 or oldMinY , oldMaxY do
for X = oldMinX > newMinX and oldMinX or newMinX, oldMaxX < newMaxX and oldMaxX or newMaxX do
LeaveCell(CELL_LIST[X][Y], actor)
end
end
end
if actor.cellsVisualized then
RedrawCellVisualizers(actor)
end
changedCells = false
end
actor.lastX, actor.lastY = x, y
nextStep = currentCounter + actor.cellCheckInterval
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numCellChecks[nextStep] = numCellChecks[nextStep] + 1
cellCheckedActors[nextStep][numCellChecks[nextStep]] = actor
actor.nextCellCheck = nextStep
actor.positionInCellCheck = numCellChecks[nextStep]
end
if debug.visualizeAllActors then
for i = 1, numCellChecks[currentCounter] do
actor = actorsThisStep[i]
BlzSetSpecialEffectPosition(actor.visualizer, actor.x[actor.anchor], actor.y[actor.anchor], actor.z[actor] + 75)
end
end
numCellChecks[currentCounter] = 0
end
local function Interpolate()
interpolationCounter = interpolationCounter + 1
if interpolationCounter == 1 then
return
end
local actor, anchor
isInterpolated = true
RemovePairsFromCycle()
for i = 1, #interpolatedPairs do
currentPair = interpolatedPairs[i]
if not currentPair.destructionQueued then
actor = currentPair[0x1]
if actor.x then
anchor = actor.anchor
actor.x[anchor] = nil
actor.y[anchor] = nil
actor.z[actor] = nil
end
actor = currentPair[0x2]
if actor.x then
anchor = actor.anchor
actor.x[anchor] = nil
actor.y[anchor] = nil
actor.z[actor] = nil
end
currentPair[0x8](currentPair[0x3], currentPair[0x4], true)
end
end
isInterpolated = false
currentPair = OUTSIDE_OF_CYCLE
end
--#endregion
--===========================================================================================================================================================
--Main
--===========================================================================================================================================================
--#region Main
local function Main()
local INV_MIN_INTERVAL = INV_MIN_INTERVAL
local CYCLE_LENGTH = CYCLE_LENGTH
local MAX_STEPS = MAX_STEPS
local evalCounter = cycle.unboundCounter - (cycle.unboundCounter // 10)*10 + 1
local startTime = os.clock()
interpolationCounter = 0
for i = 1, #interpolatedPairs do
interpolatedPairs[i] = nil
end
if currentPair ~= OUTSIDE_OF_CYCLE then
if config.HALT_ON_FIRST_CRASH then
local A = currentPair[0x1]
local B = currentPair[0x2]
PrintCrashMessage(currentPair, A, B)
ALICE_Halt()
if not debug.enabled then
EnableDebugMode()
end
return
else
OnCrash()
end
end
--First-in first-out.
local k = 1
while delayedCallbackFunctions[k] do
delayedCallbackFunctions[k](unpack(delayedCallbackArgs[k]))
k = k + 1
end
for i = 1, #delayedCallbackFunctions do
delayedCallbackFunctions[i] = nil
end
BindChecks()
RemovePairsFromCycle()
cycle.counter = cycle.counter + 1
if cycle.counter > CYCLE_LENGTH then
cycle.counter = 1
end
local currentCounter = cycle.counter
cycle.unboundCounter = cycle.unboundCounter + 1
ALICE_TimeElapsed = cycle.unboundCounter*config.MIN_INTERVAL
while userCallbacks.first and userCallbacks.first.callCounter == cycle.unboundCounter do
ExecuteUserCallback(userCallbacks.first)
end
for i = 1, #debug.visualizationLightnings do
local lightning = debug.visualizationLightnings[i]
TimerStart(CreateTimer(), 0.02, false, function()
DestroyTimer(GetExpiredTimer())
DestroyLightning(lightning)
end)
debug.visualizationLightnings[i] = nil
end
if debug.benchmark then
local averageEvalTime = 0
for i = 1, 10 do
averageEvalTime = averageEvalTime + (debug.evaluationTime[i] or 0)/10
end
Warning("eval time: |cffffcc00" .. string.format("\x25.2f", 1000*averageEvalTime) .. "ms|r, actors: " .. #actorList .. ", pairs: " .. numPairs[currentCounter] + numEveryStepPairs .. ", cell checks: " .. numCellChecks[currentCounter])
end
if debug.enabled then
UpdateSelectedActor()
end
local numSteps, nextStep
--Every Step Cycle
currentPair = firstEveryStepPair
for __ = 1, numEveryStepPairs do
currentPair = currentPair[0x5]
if not currentPair.destructionQueued then
currentPair[0x8](currentPair[0x3], currentPair[0x4])
end
end
ResetCoordinateLookupTables()
CellCheck()
--Variable Step Cycle
local returnValue
local pairsThisStep = whichPairs[currentCounter]
for i = 1, numPairs[currentCounter] do
currentPair = pairsThisStep[i]
if currentPair.destructionQueued then
if currentPair ~= DUMMY_PAIR then
nextStep = currentCounter + MAX_STEPS
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[0x5] = nextStep
currentPair[0x6] = numPairs[nextStep]
end
else
returnValue = currentPair[0x8](currentPair[0x3], currentPair[0x4])
if returnValue then
numSteps = (returnValue*INV_MIN_INTERVAL + 1) // 1 --convert seconds to steps, then ceil.
if numSteps < 1 then
numSteps = 1
elseif numSteps > MAX_STEPS then
numSteps = MAX_STEPS
end
nextStep = currentCounter + numSteps
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[0x5] = nextStep
currentPair[0x6] = numPairs[nextStep]
else
AddPairToEveryStepList(currentPair)
if currentPair[0x8] ~= PeriodicWrapper and currentPair[0x8] ~= RepeatedWrapper then
functionIsEveryStep[currentPair[0x8]] = true
end
currentPair[0x7] = true
end
end
end
numPairs[currentCounter] = 0
currentPair = OUTSIDE_OF_CYCLE
k = 1
while delayedCallbackFunctions[k] do
delayedCallbackFunctions[k](unpack(delayedCallbackArgs[k]))
k = k + 1
end
for i = 1, #delayedCallbackFunctions do
delayedCallbackFunctions[i] = nil
end
local endTime = os.clock()
debug.evaluationTime[evalCounter] = endTime - startTime
ALICE_CPULoad = (endTime - startTime)/config.MIN_INTERVAL
end
--#endregion
--===========================================================================================================================================================
--Debug Mode
--===========================================================================================================================================================
---@param whichPair Pair
---@param lightningType string
VisualizationLightning = function(whichPair, lightningType)
local A = whichPair[0x1]
local B = whichPair[0x2]
if A.alreadyDestroyed or B.alreadyDestroyed or A.isGlobal or B.isGlobal then
return
end
local xa = A.x[A.anchor]
local ya = A.y[A.anchor]
local za = A.z[A]
local xb = B.x[B.anchor]
local yb = B.y[B.anchor]
local zb = B.z[B]
if za and zb then
insert(debug.visualizationLightnings, AddLightningEx(lightningType, true, xa, ya, za, xb, yb, zb))
else
insert(debug.visualizationLightnings, AddLightning(lightningType, true, xa, ya, xb, yb))
end
end
UpdateSelectedActor = function()
if debug.selectedActor then
if not debug.selectedActor.isGlobal then
local x = debug.selectedActor.x[debug.selectedActor.anchor]
local y = debug.selectedActor.y[debug.selectedActor.anchor]
BlzSetSpecialEffectPosition(debug.selectedActor.visualizer, x, y, debug.selectedActor.z[debug.selectedActor] + 75)
SetCameraQuickPosition(x, y)
end
local description, title = GetDescription(debug.selectedActor)
BlzFrameSetText(debug.tooltipText, description)
BlzFrameSetText(debug.tooltipTitle, title )
BlzFrameSetSize(debug.tooltipText, 0.28, 0.0)
BlzFrameSetSize(debug.tooltip, 0.29, BlzFrameGetHeight(debug.tooltipText) + 0.0315)
local funcs = {}
local next = debug.selectedActor.nextPair
local pair = next[debug.selectedActor.firstPair]
while pair do
if (pair[0x7] and pair[0x6] ~= nil) or (not pair[0x7] and pair[0x5] == cycle.counter) then
VisualizationLightning(pair, "DRAL")
if debug.printFunctionNames then
funcs[pair[0x8]] = (funcs[pair[0x8]] or 0) + 1
end
end
pair = next[pair]
end
if debug.printFunctionNames then
local first = true
local message
for func, amount in pairs(funcs) do
if first then
message = "\n|cffffcc00Step " .. cycle.unboundCounter .. ":|r"
first = false
end
if amount > 1 then
message = message .. "\n" .. Function2String(func) .. " |cffaaaaffx" .. amount .. "|r"
else
message = message .. "\n" .. Function2String(func)
end
end
if message then
Warning(message)
end
end
end
end
---@param x number
---@param y number
---@param z number
---@return number, number
local function World2Screen(eyeX, eyeY, eyeZ, angleOfAttack, x, y, z)
local cosAngle = math.cos(angleOfAttack)
local sinAngle = math.sin(angleOfAttack)
local dx = x - eyeX
local dy = y - eyeY
local dz = (z or 0) - eyeZ
local yPrime = cosAngle*dy - sinAngle*dz
local zPrime = sinAngle*dy + cosAngle*dz
return 0.4 + 0.7425*dx/yPrime, 0.355 + 0.7425*zPrime/yPrime
end
--#region Debug Mode
local function OnMouseClick()
if debug.selectionLocked or BlzGetTriggerPlayerMouseButton() ~= MOUSE_BUTTON_TYPE_LEFT then
return
end
local previousSelectedActor = debug.selectedActor
if debug.selectedActor then
Deselect(debug.selectedActor)
end
local mouseX = BlzGetTriggerPlayerMouseX()
local mouseY = BlzGetTriggerPlayerMouseY()
local objects = ALICE_EnumObjectsInRange(mouseX, mouseY, 500, {MATCHING_TYPE_ALL}, nil)
local closestDist = 0.04
local closestObject = nil
local eyeX = GetCameraEyePositionX()
local eyeY = GetCameraEyePositionY()
local eyeZ = GetCameraEyePositionZ()
local angleOfAttack = -GetCameraField(CAMERA_FIELD_ANGLE_OF_ATTACK)
local mouseScreenX, mouseScreenY = World2Screen(eyeX, eyeY, eyeZ, angleOfAttack, mouseX, mouseY, GetTerrainZ(mouseX, mouseY))
local x, y, dx, dy
for __, object in ipairs(objects) do
local actor = GetActor(object)
--Find the actor that is closest to the mouse-cursor.
if not actor.isUnselectable and (previousSelectedActor == nil or ALICE_GetAnchor(object) ~= previousSelectedActor.anchor) then
x, y = World2Screen(eyeX, eyeY, eyeZ, angleOfAttack, ALICE_GetCoordinates3D(actor))
dx, dy = x - mouseScreenX, y - mouseScreenY
local dist = sqrt(dx*dx + dy*dy)
if dist < closestDist then
closestDist = dist
closestObject = actor.anchor
end
end
end
if closestObject then
if actorOf[closestObject].isActor then
Select(actorOf[closestObject])
else
Warning("Multiple actors are anchored to this object. Press |cffffcc00Ctrl + Q|r to cycle through.")
Select(actorOf[closestObject][1])
end
end
end
local function OnCtrlR()
Warning("Going to step " .. cycle.unboundCounter + 1 .. " |cffaaaaaa(" .. string.format("\x25.2f", config.MIN_INTERVAL*(cycle.unboundCounter + 1)) .. "s)|r.")
Main()
if debug.gameIsPaused then
ALICE_ForAllObjectsDo(function(unit) PauseUnit(unit, true) end, "unit")
end
end
local function OnCtrlG()
if debug.printFunctionNames then
Warning("\nPrinting function names disabled.")
else
Warning("\nPrinting function names enabled.")
end
debug.printFunctionNames = not debug.printFunctionNames
end
local function OnCtrlW()
if debug.selectionLocked then
Warning("\nSelection unlocked.")
else
Warning("\nSelection locked. To unlock, press |cffffcc00Ctrl + W|r.")
end
debug.selectionLocked = not debug.selectionLocked
end
---Cycle through actors anchored to the same object.
local function OnCtrlQ()
if debug.selectedActor == nil then
return
end
local selectedObject = debug.selectedActor.anchor
if actorOf[selectedObject].isActor then
return
end
for index, actor in ipairs(actorOf[selectedObject]) do
if debug.selectedActor == actor then
Deselect(debug.selectedActor)
if actorOf[selectedObject][index + 1] then
Select(actorOf[selectedObject][index + 1])
return
else
Select(actorOf[selectedObject][1])
return
end
end
end
end
local function OnCtrlT()
if cycle.isHalted then
ALICE_Resume()
Warning("\nALICE Cycle resumed.")
else
ALICE_Halt(BlzGetTriggerPlayerMetaKey() == 3)
Warning("\nALICE Cycle halted. To go to the next step, press |cffffcc00Ctrl + R|r. To resume, press |cffffcc00Ctrl + T|r.")
end
end
local function DownTheRabbitHole()
EnableDebugMode()
if debug.enabled then
Warning("\nDebug mode enabled. Left-click near an actor to display attributes and enable visualization.")
else
Warning("\nDebug mode has been disabled.")
end
end
EnableDebugMode = function()
local playerName = GetPlayerName(GetTriggerPlayer())
local nameFound = false
for __, name in ipairs(config.MAP_CREATORS) do
if string.find(playerName, name) then
nameFound = true
break
end
end
if not nameFound then
if GetLocalPlayer() == GetTriggerPlayer() then
print("|cffff0000Warning:|r You need to set yourself as a map creator in the ALICE config to use debug mode.")
end
return
end
if not debug.enabled then
debug.enabled = true
BlzLoadTOCFile("CustomTooltip.toc")
debug.tooltip = BlzCreateFrame("CustomTooltip", BlzGetOriginFrame(ORIGIN_FRAME_WORLD_FRAME, 0), 0, 0)
BlzFrameSetAbsPoint(debug.tooltip, FRAMEPOINT_BOTTOMRIGHT, 0.8, 0.165)
BlzFrameSetSize(debug.tooltip, 0.32, 0.0)
debug.tooltipTitle = BlzGetFrameByName("CustomTooltipTitle", 0)
debug.tooltipText = BlzGetFrameByName("CustomTooltipValue", 0)
debug.nextStepTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.nextStepTrigger, GetTriggerPlayer() or Player(0), OSKEY_R, 2, true)
TriggerAddAction(debug.nextStepTrigger, OnCtrlR)
debug.mouseClickTrigger = CreateTrigger()
TriggerRegisterPlayerEvent(debug.mouseClickTrigger, GetTriggerPlayer() or Player(0), EVENT_PLAYER_MOUSE_DOWN)
TriggerAddAction(debug.mouseClickTrigger, OnMouseClick)
debug.lockSelectionTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.lockSelectionTrigger, GetTriggerPlayer() or Player(0), OSKEY_W, 2, true)
TriggerAddAction(debug.lockSelectionTrigger, OnCtrlW)
debug.cycleSelectTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.cycleSelectTrigger, GetTriggerPlayer() or Player(0), OSKEY_Q, 2, true)
TriggerAddAction(debug.cycleSelectTrigger, OnCtrlQ)
debug.haltTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.haltTrigger, GetTriggerPlayer() or Player(0), OSKEY_T, 2, true)
BlzTriggerRegisterPlayerKeyEvent(debug.haltTrigger, GetTriggerPlayer() or Player(0), OSKEY_T, 3, true)
TriggerAddAction(debug.haltTrigger, OnCtrlT)
debug.printFunctionsTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.printFunctionsTrigger, GetTriggerPlayer() or Player(0), OSKEY_G, 2, true)
TriggerAddAction(debug.printFunctionsTrigger, OnCtrlG)
else
if debug.selectedActor then
Deselect(debug.selectedActor)
end
debug.enabled = false
DestroyTrigger(debug.nextStepTrigger)
DestroyTrigger(debug.lockSelectionTrigger)
DestroyTrigger(debug.mouseClickTrigger)
DestroyTrigger(debug.cycleSelectTrigger)
DestroyTrigger(debug.haltTrigger)
DestroyTrigger(debug.printFunctionsTrigger)
BlzDestroyFrame(debug.tooltip)
end
end
--#endregion
--===========================================================================================================================================================
--Widget Actors
--===========================================================================================================================================================
--#region WidgetActors
local actorFlags = {}
local identifiers = {}
local function Kill(object)
if type(object) == "table" then
if object.destroy then
object:destroy()
elseif object.visual then
if HandleType[object.visual] == "effect" then
DestroyEffect(object.visual)
elseif HandleType[object.visual] == "unit" then
KillUnit(object.visual)
elseif HandleType[object.visual] == "image" then
DestroyImage(object.visual)
elseif HandleType[object.visual] == "lightning" then
DestroyLightning(object.visual)
end
end
elseif IsHandle[object] then
if HandleType[object] == "unit" then
KillUnit(object)
elseif HandleType[object] == "destructable" then
KillDestructable(object)
elseif HandleType[object] == "item" then
RemoveItem(object)
end
end
end
local function Clear(object, wasUnitDeath)
local actor = actorOf[object]
if actor then
if not actor.isActor then
for i = #actor, 1, -1 do
if not wasUnitDeath or not actor[i].persistOnDeath then
if actor[i].host ~= object then
Kill(actor[i].host)
end
Destroy(actor[i])
end
end
elseif not wasUnitDeath or not actor.persistOnDeath then
Destroy(actor)
end
end
end
local function OnLoad(widget, transport)
if actorOf[widget] == nil then
return
end
if actorOf[widget].isActor then
actorOf[widget].anchor = transport
SetCoordinateFuncs(actorOf[widget])
Suspend(actorOf[widget], true)
else
for __, actor in ipairs(actorOf[widget]) do
actor.anchor = transport
SetCoordinateFuncs(actor)
Suspend(actor, true)
end
end
end
local function OnUnload(widget)
if actorOf[widget].isActor then
local actor = actorOf[widget]
actor.anchor = actor.originalAnchor
actor.x[actor.anchor] = nil
actor.y[actor.anchor] = nil
actor.z[actor] = nil
SetCoordinateFuncs(actor)
Suspend(actorOf[widget], false)
else
for __, actor in ipairs(actorOf[widget]) do
actor.anchor = actor.originalAnchor
actor.x[actor.anchor] = nil
actor.y[actor.anchor] = nil
actor.z[actor] = nil
SetCoordinateFuncs(actor)
Suspend(actor, false)
end
end
end
--===========================================================================================================================================================
--Unit Actors
--===========================================================================================================================================================
local function CorpseCleanUp(u)
if GetUnitTypeId(u) == 0 then
DestroyTrigger(widgets.reviveTriggers[u])
widgets.reviveTriggers[u] = nil
for __, func in ipairs(eventHooks.onUnitRemove) do
func(u)
end
Clear(u)
end
return 1.0
end
---@param u unit
---@return boolean
local function CreateUnitActor(u)
local id = GetUnitTypeId(u)
if GetUnitAbilityLevel(u, 1097625443) > 0 then --FourCC "Aloc" (Locust)
return false
end
if not widgets.idInclusions[id] and (config.NO_UNIT_ACTOR or widgets.idExclusions[id]) then
return false
end
if id == 0 then
return false
end
for key, __ in pairs(identifiers) do
identifiers[key] = nil
end
local interactions
if GetUnitState(u, UNIT_STATE_LIFE) > 0.405 then
identifiers[#identifiers + 1] = "unit"
actorFlags.isStationary = IsUnitType(u, UNIT_TYPE_STRUCTURE)
elseif config.UNITS_LEAVE_BEHIND_CORPSES then
identifiers[#identifiers + 1] = "corpse"
interactions = {self = CorpseCleanUp}
actorFlags.isStationary = config.UNIT_CORPSES_ARE_STATIONARY
else
return false
end
if config.ADD_WIDGET_NAMES then
identifiers[#identifiers + 1] = toCamelCase[GetUnitName(u)]
if IsUnitType(u, UNIT_TYPE_HERO) then
identifiers[#identifiers + 1] = toCamelCase[GetHeroProperName(u)]
end
end
for __, unittype in ipairs(config.UNIT_ADDED_CLASSIFICATIONS) do
if IsUnitType(u, unittype) then
identifiers[#identifiers + 1] = UNIT_CLASSIFICATION_NAMES[unittype]
else
identifiers[#identifiers + 1] = "non" .. UNIT_CLASSIFICATION_NAMES[unittype]
end
end
identifiers[#identifiers + 1] = string.pack(">I4", id)
actorFlags.radius = config.DEFAULT_UNIT_RADIUS
actorFlags.persistOnDeath = config.UNITS_LEAVE_BEHIND_CORPSES
Create(u, identifiers, interactions, actorFlags)
return true
end
local function OnRevive()
local u = GetTriggerUnit()
ALICE_RemoveSelfInteraction(u, CorpseCleanUp, "corpse")
ALICE_SwapIdentifier(u, "corpse", "unit", "corpse")
if config.UNIT_CORPSES_ARE_STATIONARY and not IsUnitType(u, UNIT_TYPE_STRUCTURE) then
ALICE_SetStationary(u, false)
end
DestroyTrigger(widgets.reviveTriggers[u])
widgets.reviveTriggers[u] = nil
for __, func in ipairs(eventHooks.onUnitRevive) do
func(u)
end
end
local function OnUnitDeath()
local u = GetTriggerUnit()
local actor = actorOf[u]
if actor == nil then
return
end
if config.UNITS_LEAVE_BEHIND_CORPSES then
ALICE_AddSelfInteraction(u, CorpseCleanUp, "unit")
ALICE_SwapIdentifier(u, "unit", "corpse", "unit")
if config.UNIT_CORPSES_ARE_STATIONARY then
ALICE_SetStationary(u, true)
end
widgets.reviveTriggers[u] = CreateTrigger()
TriggerAddAction(widgets.reviveTriggers[u], OnRevive)
TriggerRegisterUnitStateEvent(widgets.reviveTriggers[u], u, UNIT_STATE_LIFE, GREATER_THAN_OR_EQUAL, 0.405)
for __, func in ipairs(eventHooks.onUnitDeath) do
func(u)
end
Clear(u, true)
else
for __, func in ipairs(eventHooks.onUnitRemove) do
func(u)
end
Clear(u)
end
end
local function OnUnitEnter()
local u = GetTrainedUnit() or GetTriggerUnit()
if GetActor(u, "unit") then
return
end
if CreateUnitActor(u) then
for __, func in ipairs(eventHooks.onUnitEnter) do
func(u)
end
end
end
local function OnUnitLoaded()
local u = GetLoadedUnit()
OnLoad(u, GetTransportUnit())
ALICE_CallPeriodic(function(unit)
if not IsUnitLoaded(unit) then
ALICE_DisableCallback()
if actorOf[unit] then
OnUnload(unit)
end
end
end, 0, u)
end
--===========================================================================================================================================================
--Destructable Actors
--===========================================================================================================================================================
---@param d destructable
local function CreateDestructableActor(d)
local id = GetDestructableTypeId(d)
if not widgets.idInclusions[id] and (config.NO_DESTRUCTABLE_ACTOR or widgets.idExclusions[id]) then
return
end
if id == 0 then
return
end
for key, __ in pairs(identifiers) do
identifiers[key] = nil
end
identifiers[#identifiers + 1] = "destructable"
local name = GetDestructableName(d)
if config.ADD_WIDGET_NAMES then
identifiers[#identifiers + 1] = toCamelCase[name]
end
identifiers[#identifiers + 1] = string.pack(">I4", id)
actorFlags.radius = config.DEFAULT_DESTRUCTABLE_RADIUS
actorFlags.isStationary = true
actorFlags.persistOnDeath = nil
Create(d, identifiers, nil, actorFlags)
end
OnDestructableDeath = function()
local whichObject = GetTriggerDestructable()
DestroyTrigger(widgets.deathTriggers[whichObject])
widgets.deathTriggers[whichObject] = nil
for __, func in ipairs(eventHooks.onDestructableDestroy) do
func(whichObject)
end
Clear(whichObject)
end
--===========================================================================================================================================================
--Item Actors
--===========================================================================================================================================================
---@param i item
local function CreateItemActor(i)
local id = GetItemTypeId(i)
if not widgets.idInclusions[id] and (config.NO_ITEM_ACTOR or widgets.idExclusions[id]) then
return
end
if id == 0 then
return
end
for key, __ in pairs(identifiers) do
identifiers[key] = nil
end
identifiers[#identifiers + 1] = "item"
if config.ADD_WIDGET_NAMES then
identifiers[#identifiers + 1] = toCamelCase[GetItemName(i)]
end
identifiers[#identifiers + 1] = string.pack(">I4", id)
actorFlags.radius = config.DEFAULT_ITEM_RADIUS
actorFlags.isStationary = config.ITEMS_ARE_STATIONARY
actorFlags.persistOnDeath = nil
Create(i, identifiers, nil, actorFlags)
end
local function OnItemPickup()
local item = GetManipulatedItem()
OnLoad(item, GetTriggerUnit())
if config.ITEMS_ARE_STATIONARY then
ALICE_SetStationary(item, false)
end
end
local function OnItemDrop()
local item = GetManipulatedItem()
if actorOf[item] then
OnUnload(item)
if config.ITEMS_ARE_STATIONARY then
ALICE_SetStationary(item, true)
end
else
AddDelayedCallback(function(whichItem)
if GetItemTypeId(whichItem) == 0 then
return
end
CreateItemActor(whichItem)
for __, func in ipairs(eventHooks.onItemEnter) do
func(whichItem)
end
end, item)
end
end
local function OnItemSold()
Clear(GetManipulatedItem())
end
OnItemDeath = function()
SaveWidgetHandle(widgets.hash, 0, 0, GetTriggerWidget())
local whichObject = LoadItemHandle(widgets.hash, 0, 0)
DestroyTrigger(widgets.deathTriggers[whichObject])
widgets.deathTriggers[whichObject] = nil
for __, func in ipairs(eventHooks.onItemDestroy) do
func(whichObject)
end
Clear(whichObject)
end
--#endregion
--===========================================================================================================================================================
--Init
--===========================================================================================================================================================
--#region Init
local function Init()
Require "HandleType"
Require "Hook"
timers.MASTER = CreateTimer()
timers.INTERPOLATION = CreateTimer()
MAX_STEPS = (config.MAX_INTERVAL/config.MIN_INTERVAL) // 1
CYCLE_LENGTH = MAX_STEPS + 1
DO_NOT_EVALUATE = CYCLE_LENGTH + 1
for i = 1, DO_NOT_EVALUATE do
numPairs[i] = 0
whichPairs[i] = {}
end
for i = 1, CYCLE_LENGTH do
numCellChecks[i] = 0
cellCheckedActors[i] = {}
end
local worldBounds = GetWorldBounds()
MAP_MIN_X = GetRectMinX(worldBounds)
MAP_MAX_X = GetRectMaxX(worldBounds)
MAP_MIN_Y = GetRectMinY(worldBounds)
MAP_MAX_Y = GetRectMaxY(worldBounds)
MAP_SIZE_X = MAP_MAX_X - MAP_MIN_X
MAP_SIZE_Y = MAP_MAX_Y - MAP_MIN_Y
NUM_CELLS_X = MAP_SIZE_X // config.CELL_SIZE
NUM_CELLS_Y = MAP_SIZE_Y // config.CELL_SIZE
for X = 1, NUM_CELLS_X do
CELL_LIST[X] = {}
for Y = 1, NUM_CELLS_Y do
CELL_LIST[X][Y] = {numActors = 0}
end
end
for x = 1, NUM_CELLS_X do
CELL_MIN_X[x] = MAP_MIN_X + (x-1)/NUM_CELLS_X*MAP_SIZE_X
CELL_MAX_X[x] = MAP_MIN_X + x/NUM_CELLS_X*MAP_SIZE_X
end
for y = 1, NUM_CELLS_Y do
CELL_MIN_Y[y] = MAP_MIN_Y + (y-1)/NUM_CELLS_Y*MAP_SIZE_Y
CELL_MAX_Y[y] = MAP_MIN_Y + y/NUM_CELLS_Y*MAP_SIZE_Y
end
GetTable = config.TABLE_RECYCLER_GET or function()
local numUnusedTables = #unusedTables
if numUnusedTables == 0 then
return {}
else
local returnTable = unusedTables[numUnusedTables]
unusedTables[numUnusedTables] = nil
return returnTable
end
end
ReturnTable = config.TABLE_RECYCLER_RETURN or function(whichTable)
for key, __ in pairs(whichTable) do
whichTable[key] = nil
end
unusedTables[#unusedTables + 1] = whichTable
setmetatable(whichTable, nil)
end
local trig = CreateTrigger()
for i = 0, 23 do
TriggerRegisterPlayerChatEvent(trig, Player(i), "downtherabbithole", true)
TriggerRegisterPlayerChatEvent(trig, Player(i), "-downtherabbithole", true)
end
TriggerAddAction(trig, DownTheRabbitHole)
SELF_INTERACTION_ACTOR = Create({}, "selfInteraction", nil, EMPTY_TABLE)
actorList[#actorList] = nil
celllessActorList[#celllessActorList] = nil
totalActors = totalActors - 1
SELF_INTERACTION_ACTOR.unique = 0
debug.functionName[CorpseCleanUp] = "CorpseCleanUp"
TimerStart(timers.MASTER, config.MIN_INTERVAL, true, Main)
if config.INTERPOLATION_INTERVAL then
TimerStart(timers.INTERPOLATION, config.INTERPOLATION_INTERVAL, true, Interpolate)
end
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetTerrainZ = _G.GetTerrainZ
else
moveableLoc = Location(0, 0)
GetTerrainZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
widgets.hash = InitHashtable()
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_HERO_REVIVE_FINISH)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_SUMMON)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_TRAIN_FINISH)
TriggerAddAction(trig, OnUnitEnter)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_DEATH)
TriggerAddAction(trig, OnUnitDeath)
local G = CreateGroup()
GroupEnumUnitsInRect(G, GetPlayableMapRect(), nil)
ForGroup(G, function()
local u = GetEnumUnit()
if CreateUnitActor(u) then
for __, func in ipairs(eventHooks.onUnitEnter) do
func(u)
end
end
end)
DestroyGroup(G)
EnumDestructablesInRect(worldBounds, nil, function() CreateDestructableActor(GetEnumDestructable()) end)
EnumItemsInRect(worldBounds, nil, function() CreateItemActor(GetEnumItem()) end)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_DROP_ITEM)
TriggerAddAction(trig, OnItemDrop)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_PICKUP_ITEM)
TriggerAddAction(trig, OnItemPickup)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_PAWN_ITEM)
TriggerAddAction(trig, OnItemSold)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_CHANGE_OWNER)
TriggerAddAction(trig, OnUnitChangeOwner)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_LOADED)
TriggerAddAction(trig, OnUnitLoaded)
local function CreateUnitHookFunc(self, ...)
local newUnit = self.old(...)
CreateUnitActor(newUnit)
for __, func in ipairs(eventHooks.onUnitEnter) do
func(newUnit)
end
return newUnit
end
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateUnit = CreateUnitHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateUnitByName = CreateUnitHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateUnitAtLoc = CreateUnitHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateUnitAtLocByName = CreateUnitHookFunc
if config.UNITS_LEAVE_BEHIND_CORPSES then
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateCorpse = CreateUnitHookFunc
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:RemoveUnit(whichUnit)
local item
for i = 0, UnitInventorySize(whichUnit) - 1 do
item = UnitItemInSlot(whichUnit, i)
for __, func in ipairs(eventHooks.onItemDestroy) do
func(item)
end
Clear(item)
end
for __, func in ipairs(eventHooks.onUnitRemove) do
func(whichUnit)
end
Clear(whichUnit)
self.old(whichUnit)
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:ShowUnit(whichUnit, enable)
self.old(whichUnit, enable)
if actorOf[whichUnit] == nil then
return
end
if actorOf[whichUnit].isActor then
Suspend(actorOf[whichUnit], not enable)
else
for __, actor in ipairs(actorOf[whichUnit]) do
Suspend(actor, not enable)
end
end
end
local function CreateDestructableHookFunc(self, ...)
local newDestructable = self.old(...)
CreateDestructableActor(newDestructable)
for __, func in ipairs(eventHooks.onDestructableEnter) do
func(newDestructable)
end
return newDestructable
end
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateDestructable = CreateDestructableHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateDestructableZ = CreateDestructableHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.BlzCreateDestructableWithSkin = CreateDestructableHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.BlzCreateDestructableZWithSkin = CreateDestructableHookFunc
---@diagnostic disable-next-line: duplicate-set-field
function Hook:RemoveDestructable(whichDestructable)
for __, func in ipairs(eventHooks.onDestructableDestroy) do
func(whichDestructable)
end
Clear(whichDestructable)
if widgets.deathTriggers[whichDestructable] then
DestroyTrigger(widgets.deathTriggers[whichDestructable])
widgets.deathTriggers[whichDestructable] = nil
end
self.old(whichDestructable)
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:DestructableRestoreLife(whichDestructable, life, birth)
self.old(whichDestructable, life, birth)
if GetDestructableLife(whichDestructable) > 0 and GetActor(whichDestructable, "destructable") == nil then
CreateDestructableActor(whichDestructable)
for __, func in ipairs(eventHooks.onDestructableEnter) do
func(whichDestructable)
end
end
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:CreateItem(...)
local newItem
newItem = self.old(...)
CreateItemActor(newItem)
for __, func in ipairs(eventHooks.onItemEnter) do
func(newItem)
end
return newItem
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:RemoveItem(whichItem)
for __, func in ipairs(eventHooks.onItemDestroy) do
func(whichItem)
end
Clear(whichItem)
if widgets.deathTriggers[whichItem] then
DestroyTrigger(widgets.deathTriggers[whichItem])
widgets.deathTriggers[whichItem] = nil
end
self.old(whichItem)
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:SetItemVisible(whichItem, enable)
self.old(whichItem, enable)
if actorOf[whichItem] == nil then
return
end
if actorOf[whichItem].isActor then
Suspend(actorOf[whichItem], not enable)
else
for __, actor in ipairs(actorOf[whichItem]) do
Suspend(actor, not enable)
end
end
end
end
OnInit.final("ALICE", Init)
--#endregion
--===========================================================================================================================================================
--API
--===========================================================================================================================================================
--#region API
--Core API
--===========================================================================================================================================================
---Create an actor for the object host and add it to the cycle. If the host is a table and is provided as the only input argument, all other arguments will be retrieved directly from that table.
---@param host any
---@param identifier? string | string[]
---@param interactions? table
---@param flags? table
function ALICE_Create(host, identifier, interactions, flags)
if host == nil then
error("Host is nil.")
end
if identifier then
Create(host, identifier, interactions, flags or EMPTY_TABLE)
else
Create(host, host.identifier, host.interactions, host)
end
end
---Destroy the actor of the specified object. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param keyword? string
function ALICE_Destroy(object, keyword)
local actor = GetActor(object, keyword)
if actor then
Destroy(actor)
end
end
---Calls the appropriate function to destroy the object, then destroys all actors attached to it. If the object is a table, the object:destroy() method will be called. If no destroy function exists, it will try to destroy the table's visual, which can be an effect, a unit, or an image.
---@param object Object
function ALICE_Kill(object)
if object == nil then
return
end
Kill(object)
Clear(object)
end
--Math API
--===========================================================================================================================================================
---Returns the distance between the objects of the pair currently being evaluated in two dimensions. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number
function ALICE_PairGetDistance2D()
local actorA = currentPair[0x1]
local actorB = currentPair[0x2]
if actorA and actorB == SELF_INTERACTION_ACTOR then
return 0
end
local anchorA = actorA.anchor
local anchorB = actorB.anchor
local dx = actorA.x[anchorA] - actorB.x[anchorB]
local dy = actorA.y[anchorA] - actorB.y[anchorB]
return sqrt(dx*dx + dy*dy)
end
---Returns the distance between the objects of the pair currently being evaluated in three dimensions. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number
function ALICE_PairGetDistance3D()
local actorA = currentPair[0x1]
local actorB = currentPair[0x2]
if actorA and actorB == SELF_INTERACTION_ACTOR then
return 0
end
local anchorA = actorA.anchor
local anchorB = actorB.anchor
local dx = actorA.x[anchorA] - actorB.x[anchorB]
local dy = actorA.y[anchorA] - actorB.y[anchorB]
local dz = actorA.z[actorA] - actorB.z[actorB]
return sqrt(dx*dx + dy*dy + dz*dz)
end
---Returns the angle from object A to object B of the pair currently being evaluated. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number
function ALICE_PairGetAngle2D()
local actorA = currentPair[0x1]
local actorB = currentPair[0x2]
if actorA and actorB == SELF_INTERACTION_ACTOR then
return 0
end
local anchorA = actorA.anchor
local anchorB = actorB.anchor
local dx = actorB.x[anchorB] - actorA.x[anchorA]
local dy = actorB.y[anchorB] - actorA.y[anchorA]
return atan(dy, dx)
end
---Returns the horizontal and vertical angles from object A to object B of the pair currently being evaluated. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number, number
function ALICE_PairGetAngle3D()
local actorA = currentPair[0x1]
local actorB = currentPair[0x2]
if actorA and actorB == SELF_INTERACTION_ACTOR then
return 0, 0
end
local anchorA = actorA.anchor
local anchorB = actorB.anchor
local dx = actorB.x[anchorB] - actorA.x[anchorA]
local dy = actorB.y[anchorB] - actorA.y[anchorA]
local dz = actorB.z[actorB] - actorA.z[actorA]
return atan(dy, dx), atan(dz, sqrt(dx*dx + dy*dy))
end
---Returns the coordinates of the objects in the pair currently being evaluated in the order x1, y1, x2, y2. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number, number, number, number
function ALICE_PairGetCoordinates2D()
local actorA = currentPair[0x1]
local actorB = currentPair[0x2]
local anchorA = actorA.anchor
local anchorB = actorB.anchor
return actorA.x[anchorA], actorA.y[anchorA], actorB.x[anchorB], actorB.y[anchorB]
end
---Returns the coordinates of the objects in the pair currently being evaluated in the order x1, y1, z1, x2, y2, z2. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number, number, number, number, number, number
function ALICE_PairGetCoordinates3D()
local actorA = currentPair[0x1]
local actorB = currentPair[0x2]
local anchorA = actorA.anchor
local anchorB = actorB.anchor
return actorA.x[anchorA], actorA.y[anchorA], actorA.z[actorA], actorB.x[anchorB], actorB.y[anchorB], actorB.z[actorB]
end
---Returns the coordinates x, y of an object. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@param object Object
---@param keyword? string
---@return number, number
function ALICE_GetCoordinates2D(object, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return 0, 0
end
local anchor = actor.anchor
return actor.x[anchor], actor.y[anchor]
end
---Returns the coordinates x, y, z of an object. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@param object Object
---@param keyword? string
---@return number, number, number
function ALICE_GetCoordinates3D(object, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return 0, 0, 0
end
local anchor = actor.anchor
return actor.x[anchor], actor.y[anchor], actor.z[actor]
end
--Callback API
--===========================================================================================================================================================
---Invokes the callback function after the specified delay, passing additional arguments into the callback function.
---@param callback function
---@param delay? number
---@vararg any
---@return table
function ALICE_CallDelayed(callback, delay, ...)
local new = GetTable()
new.callCounter = cycle.unboundCounter + ((delay or 0)*INV_MIN_INTERVAL + 1) // 1
new.callback = callback
local numArgs = select("#", ...)
if numArgs == 1 then
new.args = select(1, ...)
elseif numArgs > 1 then
new.args = pack(...)
new.unpack = true
end
AddUserCallback(new)
return new
end
---Invokes the callback function after the specified delay, passing the hosts of the current pair as arguments. A third parameter is passed into the callback, specifying whether you have access to the ALICE_Pair functions. You will not if the current pair has been destroyed after the callback was queued up.
---@param callback function
---@param delay? number
---@return table
function ALICE_PairCallDelayed(callback, delay)
local new = GetTable()
new.callCounter = cycle.unboundCounter + ((delay or 0)*INV_MIN_INTERVAL + 1) // 1
new.callback = callback
new.hostA = currentPair[0x3]
new.hostB = currentPair[0x4]
new.pair = currentPair
AddUserCallback(new)
return new
end
---Periodically invokes the callback function. Optional delay parameter to delay the first execution. Additional arguments are passed into the callback function. The return value of the callback function specifies the interval until next execution.
---@param callback function
---@param delay? number
---@vararg any
---@return table
function ALICE_CallPeriodic(callback, delay, ...)
local host = pack(...)
host.callback = callback
host.excess = delay or 0
host.isPeriodic = true
local actor = CreateStub(host)
actor.periodicPair = CreatePair(actor, SELF_INTERACTION_ACTOR, PeriodicWrapper)
return host
end
---Periodically invokes the callback function up to howOften times. Optional delay parameter to delay the first execution. The arguments passed into the callback function are the current iteration, followed by any additional arguments. The return value of the callback function specifies the interval until next execution.
---@param callback function
---@param howOften integer
---@param delay? number
---@vararg any
---@return table
function ALICE_CallRepeated(callback, howOften, delay, ...)
local host = pack(...)
host.callback = callback
host.howOften = howOften
host.currentExecution = 0
host.excess = delay or 0
host.isPeriodic = true
local actor = CreateStub(host)
if howOften > 0 then
actor.periodicPair = CreatePair(actor, SELF_INTERACTION_ACTOR, RepeatedWrapper)
end
return host
end
---Disables a callback returned by ALICE_CallDelayed, ALICE_CallPeriodic, or ALICE_CallRepeated. If called from within a periodic callback function itself, the parameter can be omitted. Returns whether the callback was interrupted.
---@param callback? table
---@return boolean
function ALICE_DisableCallback(callback)
local actor
if callback then
if callback.isPeriodic then
actor = GetActor(callback)
if actor == nil or actor.alreadyDestroyed then
return false
end
AddDelayedCallback(DestroyPair, actor.periodicPair)
actor.periodicPair.destructionQueued = true
if functionOnDestroy[callback.callback] then
functionOnDestroy[callback.callback](unpack(callback))
end
DestroyStub(actor)
for key, __ in pairs(callback) do
callback[key] = nil
end
return true
else
if callback.callCounter == nil or callback.callCounter <= cycle.unboundCounter then
return false
end
if functionOnDestroy[callback.callback] then
if callback.pair then
if callback.pair[0x3] == callback.hostA and callback.pair[0x4] == callback.hostB then
currentPair = callback.pair
functionOnDestroy[callback.callback](callback.hostA, callback.hostB, true)
currentPair = OUTSIDE_OF_CYCLE
else
functionOnDestroy[callback.callback](callback.hostA, callback.hostB, false)
end
elseif callback.args then
if callback.unpack then
functionOnDestroy[callback.callback](unpack(callback.args))
else
functionOnDestroy[callback.callback](callback.args)
end
else
functionOnDestroy[callback.callback]()
end
end
if not callback.isPaused then
RemoveUserCallbackFromList(callback)
end
for key, __ in pairs(callback) do
callback[key] = nil
end
return true
end
elseif currentPair ~= OUTSIDE_OF_CYCLE then
actor = currentPair[0x1]
if actor == nil or actor.alreadyDestroyed or actor.periodicPair == nil then
return false
end
AddDelayedCallback(DestroyPair, actor.periodicPair)
actor.periodicPair.destructionQueued = true
callback = actor.host
if functionOnDestroy[callback.callback] then
functionOnDestroy[callback.callback](unpack(callback))
end
DestroyStub(actor)
for key, __ in pairs(callback) do
callback[key] = nil
end
return true
end
return false
end
---Pauses or unpauses a callback returned by ALICE_CallDelayed, ALICE_CallPeriodic, or ALICE_CallRepeated. If a periodic callback is unpaused this way, the next iteration will be executed immediately. Otherwise, the remaining time will be waited. If called from within a periodic callback function itself, the callback parameter can be omitted.
---@param callback? table
---@param enable? boolean
function ALICE_PauseCallback(callback, enable)
enable = enable ~= false
local actor
if callback then
if callback.isPeriodic then
if callback.isPaused == enable then
return
end
callback.isPaused = enable
actor = GetActor(callback)
if enable then
PausePair(actor.periodicPair)
else
UnpausePair(actor.periodicPair)
end
else
if callback.callCounter == nil then
return
end
if callback.isPaused == enable then
return
end
callback.isPaused = enable
if enable then
if callback.callCounter <= cycle.unboundCounter then
return
end
callback.stepsRemaining = callback.callCounter - cycle.unboundCounter
RemoveUserCallbackFromList(callback)
else
callback.callCounter = cycle.unboundCounter + callback.stepsRemaining
AddUserCallback(callback)
end
return
end
elseif currentPair ~= OUTSIDE_OF_CYCLE then
if callback.isPaused == enable then
return
end
callback.isPaused = enable
actor = currentPair[0x1]
if enable then
PausePair(actor.periodicPair)
else
UnpausePair(actor.periodicPair)
end
else
end
end
--Enum API
--===========================================================================================================================================================
---Enum functions return a table with all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param identifier string | table
---@param condition? function
---@vararg any
---@return table
function ALICE_EnumObjects(identifier, condition, ...)
local returnTable = GetTable()
if type(identifier) == "string" then
for __, actor in ipairs(actorList) do
if actor.identifier[identifier] and (condition == nil or condition(actor.host, ...)) then
if not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
end
end
else
for __, actor in ipairs(actorList) do
if HasIdentifierFromTable(actor, identifier) and (condition == nil or condition(actor.host, ...)) then
if not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
end
end
end
return returnTable
end
---Performs the action on all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into both the filter and the action function.
---@param action function
---@param identifier string | table
---@param condition function | nil
---@vararg any
function ALICE_ForAllObjectsDo(action, identifier, condition, ...)
local list = ALICE_EnumObjects(identifier, condition, ...)
for __, object in ipairs(list) do
action(object, ...)
end
ReturnTable(list)
end
---Enum functions return a table with all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param x number
---@param y number
---@param range number
---@param identifier string | table
---@param condition? function
---@vararg any
---@return table
function ALICE_EnumObjectsInRange(x, y, range, identifier, condition, ...)
local returnTable = GetTable()
ResetCoordinateLookupTables()
local minX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x - range - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local minY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y - range - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local maxX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x + range - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local maxY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y + range - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local dx
local dy
local rangeSquared = range*range
local identifierIsString = type(identifier) == "string"
local actor, cell
for X = minX, maxX do
for Y = minY, maxY do
cell = CELL_LIST[X][Y]
actor = cell.first
if actor then
if identifierIsString then
for __ = 1, cell.numActors do
if actor.identifier[identifier] and not alreadyEnumerated[actor] and (condition == nil or condition(actor.host, ...)) then
alreadyEnumerated[actor] = true
dx = actor.x[actor.anchor] - x
dy = actor.y[actor.anchor] - y
if dx*dx + dy*dy < rangeSquared then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
else
for __ = 1, cell.numActors do
if HasIdentifierFromTable(actor, identifier) and not alreadyEnumerated[actor] and (condition == nil or condition(actor.host, ...)) then
alreadyEnumerated[actor] = true
dx = actor.x[actor.anchor] - x
dy = actor.y[actor.anchor] - y
if dx*dx + dy*dy < rangeSquared then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
end
end
end
end
for key, __ in pairs(alreadyEnumerated) do
alreadyEnumerated[key] = nil
end
return returnTable
end
---Performs the action on all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into both the filter and the action function.
---@param action function
---@param x number
---@param y number
---@param range number
---@param identifier string | table
---@param condition? function
---@vararg any
function ALICE_ForAllObjectsInRangeDo(action, x, y, range, identifier, condition, ...)
local list = ALICE_EnumObjectsInRange(x, y, range, identifier, condition, ...)
for __, object in ipairs(list) do
action(object, ...)
end
ReturnTable(list)
end
---Enum functions return a table with all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param minx number
---@param miny number
---@param maxx number
---@param maxy number
---@param identifier string | table
---@param condition? function
---@vararg any
---@return table
function ALICE_EnumObjectsInRect(minx, miny, maxx, maxy, identifier, condition, ...)
local returnTable = GetTable()
ResetCoordinateLookupTables()
local minX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(minx - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local minY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(miny - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local maxX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(maxx - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local maxY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(maxy - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local x
local y
local identifierIsString = type(identifier) == "string"
local actor, cell
for X = minX, maxX do
for Y = minY, maxY do
cell = CELL_LIST[X][Y]
actor = cell.first
if actor then
if identifierIsString then
for __ = 1, cell.numActors do
if actor.identifier[identifier] and not alreadyEnumerated[actor] and (condition == nil or condition(actor.host, ...)) then
alreadyEnumerated[actor] = true
x = actor.x[actor.anchor]
y = actor.y[actor.anchor]
if x > minx and x < maxx and y > miny and y < maxy then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
else
for __ = 1, cell.numActors do
if HasIdentifierFromTable(actor, identifier) and not alreadyEnumerated[actor] and (condition == nil or condition(actor.host, ...)) then
alreadyEnumerated[actor] = true
x = actor.x[actor.anchor]
y = actor.y[actor.anchor]
if x > minx and x < maxx and y > miny and y < maxy then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
end
end
end
end
for key, __ in pairs(alreadyEnumerated) do
alreadyEnumerated[key] = nil
end
return returnTable
end
---Performs the action on all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into both the filter and the action function.
---@param action function
---@param minx number
---@param miny number
---@param maxx number
---@param maxy number
---@param identifier string | table
---@param condition? function
---@vararg any
function ALICE_ForAllObjectsInRectDo(action, minx, miny, maxx, maxy, identifier, condition, ...)
local list = ALICE_EnumObjectsInRect(minx, miny, maxx, maxy, identifier, condition, ...)
for __, object in ipairs(list) do
action(object, ...)
end
ReturnTable(list)
end
---Enum functions return a table with all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param x1 number
---@param y1 number
---@param x2 number
---@param y2 number
---@param halfWidth number
---@param identifier string | table
---@param condition? function
---@vararg any
---@return table
function ALICE_EnumObjectsInLineSegment(x1, y1, x2, y2, halfWidth, identifier, condition, ...)
if x2 == x1 then
return ALICE_EnumObjectsInRect(x1 - halfWidth, min(y1, y2), x1 + halfWidth, max(y1, y2), identifier, condition, ...)
end
ResetCoordinateLookupTables()
local returnTable = GetTable()
local cells = GetTable()
local angle = atan(y2 - y1, x2 - x1)
local cosAngle = math.cos(angle)
local sinAngle = math.sin(angle)
local Xmin, Xmax, Ymin, Ymax, cRight, cLeft, slope
local XminRight = (NUM_CELLS_X*(x1 + halfWidth*sinAngle - MAP_MIN_X)/MAP_SIZE_X)
local XmaxRight = (NUM_CELLS_X*(x2 + halfWidth*sinAngle - MAP_MIN_X)/MAP_SIZE_X)
local YminRight = (NUM_CELLS_Y*(y1 - halfWidth*cosAngle - MAP_MIN_Y)/MAP_SIZE_Y)
local YmaxRight = (NUM_CELLS_Y*(y2 - halfWidth*cosAngle - MAP_MIN_Y)/MAP_SIZE_Y)
local XminLeft = (NUM_CELLS_X*(x1 - halfWidth*sinAngle - MAP_MIN_X)/MAP_SIZE_X)
local XmaxLeft = (NUM_CELLS_X*(x2 - halfWidth*sinAngle - MAP_MIN_X)/MAP_SIZE_X)
local YminLeft = (NUM_CELLS_Y*(y1 + halfWidth*cosAngle - MAP_MIN_Y)/MAP_SIZE_Y)
local YmaxLeft = (NUM_CELLS_Y*(y2 + halfWidth*cosAngle - MAP_MIN_Y)/MAP_SIZE_Y)
slope = (y2 - y1)/(x2 - x1)
cRight = YminRight - XminRight*slope
cLeft = YminLeft - XminLeft*slope
if x2 > x1 then
if y2 > y1 then
Ymin = min(NUM_CELLS_Y, max(1, YminRight // 1)) + 1
Ymax = min(NUM_CELLS_Y, max(1, YmaxLeft // 1)) + 1
for j = Ymin, Ymax do
Xmin = min(NUM_CELLS_X, max(1, max((j - 1 - cLeft)/slope, XminLeft) // 1 + 1))
Xmax = min(NUM_CELLS_X, max(1, min((j - cRight)/slope, XmaxRight) // 1 + 1))
for i = Xmin, Xmax do
cells[#cells + 1] = CELL_LIST[i][j]
end
end
else
Ymin = min(NUM_CELLS_Y, max(1, YmaxRight // 1)) + 1
Ymax = min(NUM_CELLS_Y, max(1, YminLeft // 1)) + 1
for j = Ymin, Ymax do
Xmin = min(NUM_CELLS_X, max(1, max((j - cRight)/slope, XminRight) // 1 + 1))
Xmax = min(NUM_CELLS_X, max(1, min((j - 1 - cLeft)/slope, XmaxLeft) // 1 + 1))
for i = Xmin, Xmax do
cells[#cells + 1] = CELL_LIST[i][j]
end
end
end
else
if y2 > y1 then
Ymin = min(NUM_CELLS_Y, max(1, YminLeft // 1)) + 1
Ymax = min(NUM_CELLS_Y, max(1, YmaxRight // 1)) + 1
for j = Ymin, Ymax do
Xmin = min(NUM_CELLS_X, max(1, max((j - cLeft)/slope, XmaxLeft) // 1 + 1))
Xmax = min(NUM_CELLS_X, max(1, min((j - 1 - cRight)/slope, XminRight) // 1 + 1))
for i = Xmin, Xmax do
cells[#cells + 1] = CELL_LIST[i][j]
end
end
else
Ymin = min(NUM_CELLS_Y, max(1, YmaxLeft // 1)) + 1
Ymax = min(NUM_CELLS_Y, max(1, YminRight // 1)) + 1
for j = Ymin, Ymax do
Xmin = min(NUM_CELLS_X, max(1, max((j - 1 - cRight)/slope, XmaxRight) // 1 + 1))
Xmax = min(NUM_CELLS_X, max(1, min((j - cLeft)/slope, XminLeft) // 1 + 1))
for i = Xmin, Xmax do
cells[#cells + 1] = CELL_LIST[i][j]
end
end
end
end
local identifierIsString = type(identifier) == "string"
local actor
local maxDist = sqrt((x2 - x1)^2 + (y2 - y1)^2)
local dx, dy, xPrime, yPrime
for __, cell in ipairs(cells) do
actor = cell.first
if actor then
if identifierIsString then
for __ = 1, cell.numActors do
if actor.identifier[identifier] and not alreadyEnumerated[actor] and (condition == nil or condition(actor.host, ...)) then
alreadyEnumerated[actor] = true
dx = actor.x[actor.anchor] - x1
dy = actor.y[actor.anchor] - y1
xPrime = cosAngle*dx + sinAngle*dy
yPrime = -sinAngle*dx + cosAngle*dy
if yPrime < halfWidth and yPrime > -halfWidth and xPrime > 0 and xPrime < maxDist then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
else
for __ = 1, cell.numActors do
if HasIdentifierFromTable(actor, identifier) and not alreadyEnumerated[actor] and (condition == nil or condition(actor.host, ...)) then
alreadyEnumerated[actor] = true
dx = actor.x[actor.anchor] - x1
dy = actor.y[actor.anchor] - y1
xPrime = cosAngle*dx + sinAngle*dy
yPrime = -sinAngle*dx + cosAngle*dy
if yPrime < halfWidth and yPrime > -halfWidth and xPrime > 0 and xPrime < maxDist then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
end
end
end
ReturnTable(cells)
for key, __ in pairs(alreadyEnumerated) do
alreadyEnumerated[key] = nil
end
return returnTable
end
---Performs the action on all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into both the filter and the action function.
---@param action function
---@param x1 number
---@param y1 number
---@param x2 number
---@param y2 number
---@param halfWidth number
---@param identifier string | table
---@param condition? function
---@vararg any
function ALICE_ForAllObjectsInLineSegmentDo(action, x1, y1, x2, y2, halfWidth, identifier, condition, ...)
local list = ALICE_EnumObjectsInLineSegment(x1, y1, x2, y2, halfWidth, identifier, condition, ...)
for __, object in ipairs(list) do
action(object, ...)
end
ReturnTable(list)
end
---Returns the closest object to a point from among objects with the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param x number
---@param y number
---@param identifier string | table
---@param cutOffDistance? number
---@param condition? function
---@vararg any
---@return Object | nil
function ALICE_GetClosestObject(x, y, identifier, cutOffDistance, condition, ...)
ResetCoordinateLookupTables()
cutOffDistance = cutOffDistance or 99999
local minX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x - cutOffDistance - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local minY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y - cutOffDistance - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local maxX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x + cutOffDistance - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local maxY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y + cutOffDistance - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local dx, dy
local closestDistSquared = cutOffDistance*cutOffDistance
local closestObject, thisDistSquared
local identifierIsString = type(identifier) == "string"
local actor, cell
for X = minX, maxX do
for Y = minY, maxY do
cell = CELL_LIST[X][Y]
actor = cell.first
if actor then
if identifierIsString then
for __ = 1, cell.numActors do
dx = actor.x[actor.anchor] - x
dy = actor.y[actor.anchor] - y
thisDistSquared = dx*dx + dy*dy
if thisDistSquared < closestDistSquared and actor.identifier[identifier] and (condition == nil or condition(actor.host, ...)) and not actor.isSuspended then
closestDistSquared = thisDistSquared
closestObject = actor.host
end
actor = actor.nextInCell[cell]
end
else
for __ = 1, cell.numActors do
dx = actor.x[actor.anchor] - x
dy = actor.y[actor.anchor] - y
thisDistSquared = dx*dx + dy*dy
if thisDistSquared < closestDistSquared and HasIdentifierFromTable(actor, identifier) and (condition == nil or condition(actor.host, ...)) and not actor.isSuspended then
closestDistSquared = thisDistSquared
closestObject = actor.host
end
actor = actor.nextInCell[cell]
end
end
end
end
end
return closestObject
end
--Debug API
--===========================================================================================================================================================
---Display warnings in the actor tooltips and crash messages of actors interacting with the specified function or list of functions if the listed fields are not present in the host table. requiredOnMale and requiredOnFemale control whether the field is expected to exist in the host table of the initiating (male) or receiving (female) actor of the interaction. Strings or string sequences specify fields that always need to be present. A table entry {optionalField = requiredField} denotes that requiredField must be present only if optionalField is also present in the table. requiredField can be a string or string sequence.
---@param whichFunc function | function[]
---@param requiredOnMale boolean
---@param requiredOnFemale boolean
---@vararg string | string[] | table<string,string|table>
function ALICE_FuncRequireFields(whichFunc, requiredOnMale, requiredOnFemale, ...)
local entry
whichFunc = type(whichFunc) == "function" and {whichFunc} or whichFunc
local actors = {
male = requiredOnMale or nil,
female = requiredOnFemale or nil
}
for actorType, __ in pairs(actors) do
for __, func in pairs(whichFunc) do
functionRequiredFields[func] = functionRequiredFields[func] or {}
if requiredOnMale then
functionRequiredFields[func][actorType] = functionRequiredFields[func][actorType] or {}
for i = 1, select("#", ...) do
entry = select(i, ...)
entry = type(entry) == "string" and {entry} or entry
for key, value in pairs(entry) do
if type(key) == "string" then
if type(value) == "table" then
for __, subvalue in ipairs(value) do
functionRequiredFields[func][actorType][subvalue] = key
end
else
functionRequiredFields[func][actorType][value] = key
end
else
functionRequiredFields[func][actorType][value] = true
end
end
end
end
end
end
end
---Sets the name of a function when displayed in debug mode.
---@param whichFunc function
---@param name string
function ALICE_FuncSetName(whichFunc, name)
debug.functionName[whichFunc] = name
end
---Enable or disable debug mode.
---@param enable? boolean
function ALICE_Debug(enable)
if enable == nil or (not debug.enabled and enable == true) or (debug.enabled and enable == false) then
EnableDebugMode()
end
end
---List all global actors.
function ALICE_ListGlobals()
local message = "List of all global actors:"
for __, actor in ipairs(celllessActorList) do
if actor.isGlobal then
message = message .. "\n" .. Identifier2String(actor.identifier) .. ", Unique: " .. actor.unique
end
end
Warning(message)
end
---Select the actor of the specified object if qualifier is an object, the first actor encountered with the specified identifier if qualifier is a string, or the actor with the specified unique number if qualifier is an integer. Requires debug mode.
---@param qualifier Object | integer | string
function ALICE_Select(qualifier)
if not debug.enabled then
Warning("|cffff0000Error:|r ALICE_Select is only available in debug mode.")
return
end
if type(qualifier) == "number" then
for __, actor in ipairs(actorList) do
if actor.unique == qualifier then
Select(actor)
SetCameraPosition(ALICE_GetCoordinates2D(actor))
return
end
end
Warning("\nNo actor exists with the specified unique number.")
elseif type(qualifier) == "string" then
for __, actor in ipairs(actorList) do
if actor.identifier[qualifier] then
Select(actor)
SetCameraPosition(ALICE_GetCoordinates2D(actor))
return
end
end
Warning("\nNo actor exists with the specified identifier.")
else
local actor = GetActor(qualifier)
if actor then
Select(qualifier)
SetCameraPosition(ALICE_GetCoordinates2D(actor))
else
Warning("\nNo actor exists for the specified object.")
end
end
end
---Returns true if one of the actors in the current pair is selected.
---@return boolean
function ALICE_PairIsSelected()
return debug.selectedActor == currentPair[0x1] or debug.selectedActor == currentPair[0x2]
end
---Create a lightning effect between the objects of the current pair. Optional lightning type argument.
---@param lightningType? string
function ALICE_PairVisualize(lightningType)
VisualizationLightning(currentPair, lightningType or "DRAL")
end
---Pause the entire cycle. Optional pauseGame parameter to pause all units on the map.
---@param pauseGame? boolean
function ALICE_Halt(pauseGame)
cycle.isHalted = true
PauseTimer(timers.MASTER)
if config.INTERPOLATION_INTERVAL then
PauseTimer(timers.INTERPOLATION)
end
if pauseGame then
ALICE_ForAllObjectsDo(PauseUnit, "unit", nil, true)
end
debug.gameIsPaused = pauseGame
end
---Resume the entire cycle.
function ALICE_Resume()
cycle.isHalted = false
TimerStart(timers.MASTER, config.MIN_INTERVAL, true, Main)
if config.INTERPOLATION_INTERVAL then
TimerStart(timers.INTERPOLATION, config.INTERPOLATION_INTERVAL, true, Interpolate)
end
if debug.gameIsPaused then
ALICE_ForAllObjectsDo(PauseUnit, "unit", nil, false)
debug.gameIsPaused = false
end
end
---Prints out statistics showing which functions are occupying which percentage of the calculations.
function ALICE_Statistics()
local countActivePairs = 0
local functionCount = {}
--Every Step Cycle
local thisPair = firstEveryStepPair
for __ = 1, numEveryStepPairs do
thisPair = thisPair[0x5]
if not thisPair.destructionQueued then
functionCount[thisPair[0x8]] = (functionCount[thisPair[0x8]] or 0) + 1
countActivePairs = countActivePairs + 1
end
end
local currentCounter = cycle.counter + 1
--Variable Step Cycle
local pairsThisStep = whichPairs[currentCounter]
for i = 1, numPairs[currentCounter] do
thisPair = pairsThisStep[i]
if not thisPair.destructionQueued then
functionCount[thisPair[0x8]] = (functionCount[thisPair[0x8]] or 0) + 1
countActivePairs = countActivePairs + 1
end
end
if countActivePairs == 0 then
return "\nThere are no functions currently being evaluated."
end
local statistic = "Here is a breakdown of the functions currently being evaluated:"
local sortedKeys = {}
local count = 0
for key, __ in pairs(functionCount) do
count = count + 1
sortedKeys[count] = key
end
sort(sortedKeys, function(a, b) return functionCount[a] > functionCount[b] end)
for __, functionType in ipairs(sortedKeys) do
if (100*functionCount[functionType]/countActivePairs) > 0.1 then
statistic = statistic .. "\n" .. string.format("\x25.2f", 100*functionCount[functionType]/countActivePairs) .. "\x25 |cffffcc00" .. Function2String(functionType) .. "|r |cffaaaaaa(" .. functionCount[functionType] .. ")|r"
end
end
print(statistic)
end
---Continuously prints the cycle evaluation time and the number of actors, pair interactions, and cell checks until disabled.
function ALICE_Benchmark()
debug.benchmark = not debug.benchmark
end
---Prints the values of _G.whichVar[host], if _G.whichVar exists, as well as host.whichVar, if the host is a table, in the actor tooltips in debug mode. You can list multiple variables.
---@vararg ... string
function ALICE_TrackVariables(...)
for i = 1, select("#", ...) do
debug.trackedVariables[select(i, ...)] = true
end
end
---Attempts to find the pair of the specified objects and prints the state of that pair. Pass integers to select by unique numbers. Possible return values are "active", "outofrange", "paused", "disabled", and "uninitialized". Optional keyword parameters to specify actor with the keyword in its identifier for objects with multiple actors.
---@param objectA Object | integer
---@param objectB Object | integer
---@param keywordA? string
---@param keywordB? string
---@return string
function ALICE_GetPairState(objectA, objectB, keywordA, keywordB)
local actorA, actorB
if type(objectA) == "number" then
for __, actor in ipairs(actorList) do
if actor.unique == objectA then
actorA = actor
break
end
end
if actorA == nil then
Warning("\nNo actor exists with unique number " .. objectA .. ".")
end
else
actorA = GetActor(objectA, keywordA)
if actorA == nil then
Warning("\nNo actor exists for the specified object.")
end
end
if type(objectB) == "number" then
for __, actor in ipairs(actorList) do
if actor.unique == objectB then
actorB = actor
break
end
end
if actorB == nil then
Warning("\nNo actor exists with unique number " .. objectB .. ".")
end
else
actorB = GetActor(objectB, keywordB)
if actorB == nil then
Warning("\nNo actor exists for the specified object.")
end
end
local thisPair = pairList[actorA][actorB] or pairList[actorB][actorA]
if thisPair then
if thisPair.paused then
return "paused"
elseif (thisPair[0x7] and thisPair[0x6]) or (not thisPair[0x7] and thisPair[0x5] ~= DO_NOT_EVALUATE) then
return "active"
else
return "outofrange"
end
elseif pairingExcluded[actorA][actorB] then
return "disabled"
else
return "uninitialized"
end
end
---Create lightning effects around all cells.
function ALICE_VisualizeAllCells()
debug.visualizeAllCells = not debug.visualizeAllCells
if debug.visualizeAllCells then
for X = 1, NUM_CELLS_X do
for Y = 1, NUM_CELLS_Y do
local minx = MAP_MIN_X + (X-1)/NUM_CELLS_X*MAP_SIZE_X
local miny = MAP_MIN_Y + (Y-1)/NUM_CELLS_Y*MAP_SIZE_Y
local maxx = MAP_MIN_X + X/NUM_CELLS_X*MAP_SIZE_X
local maxy = MAP_MIN_Y + Y/NUM_CELLS_Y*MAP_SIZE_Y
CELL_LIST[X][Y].horizontalLightning = AddLightning("DRAM", false, minx, miny, maxx, miny)
SetLightningColor(CELL_LIST[X][Y].horizontalLightning, 1, 1, 1, 0.35)
CELL_LIST[X][Y].verticalLightning = AddLightning("DRAM", false, maxx, miny, maxx, maxy)
SetLightningColor(CELL_LIST[X][Y].verticalLightning, 1, 1, 1, 0.35)
end
end
else
for X = 1, NUM_CELLS_X do
for Y = 1, NUM_CELLS_Y do
DestroyLightning(CELL_LIST[X][Y].horizontalLightning)
DestroyLightning(CELL_LIST[X][Y].verticalLightning)
end
end
end
end
---Creates arrows above all non-global actors.
function ALICE_VisualizeAllActors()
debug.visualizeAllActors = not debug.visualizeAllActors
if debug.visualizeAllActors then
for __, actor in ipairs(actorList) do
if not actor.isGlobal and actor ~= debug.selectedActor then
CreateVisualizer(actor)
end
end
else
for __, actor in ipairs(actorList) do
if not actor.isGlobal and actor ~= debug.selectedActor then
DestroyEffect(actor.visualizer)
end
end
end
end
--Pair Utility API
--===========================================================================================================================================================
---Returns true if the owners of the objects in the current pair are allies.
---@return boolean
function ALICE_PairIsFriend()
local actorA = currentPair[0x1]
local actorB = currentPair[0x2]
local ownerA = actorA.getOwner(actorA.host)
local ownerB = actorB.getOwner(actorB.host)
return IsPlayerAlly(ownerA, ownerB)
end
---Returns true if the owners of the objects in the current pair are enemies.
---@return boolean
function ALICE_PairIsEnemy()
local actorA = currentPair[0x1]
local actorB = currentPair[0x2]
local ownerA = actorA.getOwner(actorA.host)
local ownerB = actorB.getOwner(actorB.host)
return IsPlayerEnemy(ownerA, ownerB)
end
---Changes the interactionFunc of the pair currently being evaluated. You cannot replace a function without a return value with one that has a return value.
---@param whichFunc function
function ALICE_PairSetInteractionFunc(whichFunc)
if currentPair[0x2] == SELF_INTERACTION_ACTOR then
currentPair[0x1].selfInteractions[currentPair[0x8]] = nil
currentPair[0x1].selfInteractions[whichFunc] = currentPair
end
currentPair[0x8] = whichFunc
end
---Disables interactions between the actors of the current pair after this one.
function ALICE_PairDisable()
if not functionIsUnbreakable[currentPair[0x8]] and currentPair[0x2] ~= SELF_INTERACTION_ACTOR then
pairingExcluded[currentPair[0x1]][currentPair[0x2]] = true
pairingExcluded[currentPair[0x2]][currentPair[0x1]] = true
end
if currentPair.destructionQueued then
return
end
if currentPair[0x2] == SELF_INTERACTION_ACTOR then
currentPair[0x1].selfInteractions[currentPair[0x8]] = nil
end
currentPair.destructionQueued = true
AddDelayedCallback(DestroyPair, currentPair)
end
---Modifies the return value of an interactionFunc so that, on average, the interval is the specified value, even if it isn't an integer multiple of the minimum interval.
---@param value number
---@return number
function ALICE_PairPreciseInterval(value)
local ALICE_MIN_INTERVAL = config.MIN_INTERVAL
local data = ALICE_PairLoadData()
local numSteps = (value*INV_MIN_INTERVAL + 1) // 1
local newDelta = (data.returnDelta or 0) + value - ALICE_MIN_INTERVAL*numSteps
if newDelta > 0.5*ALICE_MIN_INTERVAL then
newDelta = newDelta - ALICE_MIN_INTERVAL
numSteps = numSteps + 1
data.returnDelta = newDelta
elseif newDelta < -0.5*ALICE_MIN_INTERVAL then
newDelta = newDelta + ALICE_MIN_INTERVAL
numSteps = numSteps - 1
data.returnDelta = newDelta
if numSteps == 0 and not currentPair.destructionQueued then
currentPair[0x8](currentPair[0x3], currentPair[0x4])
end
else
data.returnDelta = newDelta
end
return ALICE_MIN_INTERVAL*numSteps
end
---Returns false if this function was invoked for another pair that has the same interactionFunc and the same receiving actor. Otherwise, returns true. In other words, only one pair can execute the code within an ALICE_PairIsUnoccupied() block.
function ALICE_PairIsUnoccupied()
if currentPair[0x2][currentPair[0x8]] and currentPair[0x2][currentPair[0x8]] ~= currentPair then
return false
else
--Store for the female actor at the key of the interaction func the current pair as occupying that slot, blocking other pairs.
currentPair[0x2][currentPair[0x8]] = currentPair
return true
end
end
---Returns the remaining cooldown for this pair, then invokes a cooldown of the specified duration. Optional cooldownType parameter to create and differentiate between multiple separate cooldowns.
---@param duration number
---@param cooldownType? string
---@return number
function ALICE_PairCooldown(duration, cooldownType)
currentPair.cooldown = currentPair.cooldown or GetTable()
local key = cooldownType or "default"
local cooldownExpiresStep = currentPair.cooldown[key]
if cooldownExpiresStep == nil or cooldownExpiresStep <= cycle.unboundCounter then
currentPair.cooldown[key] = cycle.unboundCounter + (duration*INV_MIN_INTERVAL + 1) // 1
return 0
else
return (cooldownExpiresStep - cycle.unboundCounter)*config.MIN_INTERVAL
end
end
---Returns a table unique to the pair currently being evaluated, which can be used to read and write data. Optional argument to set a metatable for the data table.
---@param whichMetatable? table
---@return table
function ALICE_PairLoadData(whichMetatable)
if currentPair.userData == nil then
currentPair.userData = GetTable()
setmetatable(currentPair.userData, whichMetatable)
end
return currentPair.userData
end
---Returns true if this is the first time this function was invoked for the current pair, otherwise false. Resets when the objects in the pair leave the interaction range.
---@return boolean
function ALICE_PairIsFirstContact()
if currentPair.hadContact == nil then
currentPair.hadContact = true
return true
else
return false
end
end
---Calls the initFunc with the hosts as arguments whenever a pair is created with the specified interactions.
---@param whichFunc function
---@param initFunc function
function ALICE_FuncSetInit(whichFunc, initFunc)
functionInitializer[whichFunc] = initFunc
end
---Executes the function onDestroyFunc(objectA, objectB, pairData) when a pair using the specified function is destroyed or a callback using that function expires or is disabled. Only one callback per function.
---@param whichFunc function
---@param onDestroyFunc function
function ALICE_FuncSetOnDestroy(whichFunc, onDestroyFunc)
functionOnDestroy[whichFunc] = onDestroyFunc
end
---Executes the function onBreakFunc(objectA, objectB, pairData, wasDestroyed) when a pair using the specified function is destroyed or the actors leave interaction range. Only one callback per function.
---@param whichFunc function
---@param onBreakFunc function
function ALICE_FuncSetOnBreak(whichFunc, onBreakFunc)
functionOnBreak[whichFunc] = onBreakFunc
end
---Executes the function onResetFunc(objectA, objectB, pairData, wasDestroyed) when a pair using the specified function is destroyed, the actors leave interaction range, or the ALICE_PairReset function is called, but only if ALICE_PairIsFirstContact has been called previously. Only one callback per function.
---@param whichFunc function
---@param onResetFunc function
function ALICE_FuncSetOnReset(whichFunc, onResetFunc)
functionOnReset[whichFunc] = onResetFunc
end
---Purge pair data, call onDestroy method and reset ALICE_PairIsFirstContact and ALICE_PairIsUnoccupied functions.
function ALICE_PairReset()
if currentPair.hadContact then
if functionOnReset[currentPair[0x8]] and not cycle.isCrash then
functionOnReset[currentPair[0x8]](currentPair[0x3], currentPair[0x4], currentPair.userData, false)
end
currentPair.hadContact = nil
end
if currentPair[0x2][currentPair[0x8]] == currentPair then
currentPair[0x2][currentPair[0x8]] = nil
end
end
--Repeatedly calls the interaction function of the current pair at a rate of the ALICE_Config.INTERPOLATION_INTERVAL until the next main step. A true is passed into the interaction function as the third parameter if it is called from within the interpolation loop.
function ALICE_PairInterpolate()
if not isInterpolated then
interpolatedPairs[#interpolatedPairs + 1] = currentPair
end
end
--Widget API
--===========================================================================================================================================================
---Widgets with the specified fourCC codes will always receive actors, indepedent of the config.
---@vararg string | integer
function ALICE_IncludeTypes(...)
for i = 1, select("#", ...) do
local whichType = select(i, ...)
if type(whichType) == "string" then
widgets.idInclusions[FourCC(whichType)] = true
else
widgets.idInclusions[whichType] = true
end
end
end
---Widgets with the specified fourCC codes will not receive actors, indepedent of the config.
---@vararg string | integer
function ALICE_ExcludeTypes(...)
for i = 1, select("#", ...) do
local whichType = select(i, ...)
if type(whichType) == "string" then
widgets.idExclusions[FourCC(whichType)] = true
else
widgets.idExclusions[whichType] = true
end
end
end
---Injects the functions listed in the hookTable into the hooks created by ALICE. The hookTable can have the keys: onUnitEnter - The listed function is called for all preplaced units and whenever a unit enters the map or a hero is revived. onUnitDeath - The listed function is called when a unit dies. onUnitRevive - The listed function is called when a nonhero unit is revived. onUnitRemove - The listed function is called when a unit is removed from the game or its corpse decays fully. onUnitChangeOwner - The listed function is called when a unit changes owner. onDestructableEnter - The listed function is called for all preplaced destructables and whenever a destructable is created. onDestructableDestroy - The listed function is called when a destructable dies or is removed. onItemEnter - The listed function is called for all preplaced items and whenever an item is dropped or created. onItemDestroy - The listed function is called when an item is destroyed, removed, or picked up.
---@param hookTable table
function ALICE_OnWidgetEvent(hookTable)
insert(eventHooks.onUnitEnter, hookTable.onUnitEnter)
insert(eventHooks.onUnitDeath, hookTable.onUnitDeath)
insert(eventHooks.onUnitRevive, hookTable.onUnitRevive)
insert(eventHooks.onUnitRemove, hookTable.onUnitRemove)
insert(eventHooks.onUnitChangeOwner, hookTable.onUnitChangeOwner)
insert(eventHooks.onDestructableEnter, hookTable.onDestructableEnter)
insert(eventHooks.onDestructableDestroy, hookTable.onDestructableDestroy)
insert(eventHooks.onItemEnter, hookTable.onItemEnter)
insert(eventHooks.onItemDestroy, hookTable.onItemDestroy)
for key, __ in pairs(hookTable) do
if not eventHooks[key] then
Warning("|cffff0000Warning:|r Unrecognized key " .. key .. " in hookTable passed to ALICE_OnWidgetEvent.")
end
end
if hookTable.onDeath and not config.UNITS_LEAVE_BEHIND_CORPSES then
Warning("|cffff0000Warning:|r Attempted to create onDeath unit event hook, but ALICE_UNITS_LEAVE_BEHIND_CORPSES is not enabled. Use onRemove instead.")
end
end
--Identifier API
--===========================================================================================================================================================
---Add identifier(s) to an object and pair it with all other objects it is now eligible to be paired with. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param newIdentifier string | string[]
---@param keyword? string
function ALICE_AddIdentifier(object, newIdentifier, keyword)
local actor = GetActor(object, keyword)
if actor == nil or newIdentifier == nil then
return
end
if type(newIdentifier) == "string" then
actor.identifier[newIdentifier] = true
else
for __, word in ipairs(newIdentifier) do
actor.identifier[word] = true
end
end
AssignActorClass(actor, true, false)
AddDelayedCallback(DestroyObsoletePairs, actor)
AddDelayedCallback(Flicker, actor)
end
---Remove identifier(s) from an object and remove all pairings with objects it is no longer eligible to be paired with. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param toRemove string | string[]
---@param keyword? string
function ALICE_RemoveIdentifier(object, toRemove, keyword)
local actor = GetActor(object, keyword)
if actor == nil or toRemove == nil then
return
end
if type(toRemove) == "string" then
if actor.identifier[toRemove] == nil then
return
end
actor.identifier[toRemove] = nil
else
local removedSomething = false
for __, word in ipairs(toRemove) do
if actor.identifier[word] then
removedSomething = true
actor.identifier[word] = nil
end
end
if not removedSomething then
return
end
end
AssignActorClass(actor, true, false)
AddDelayedCallback(DestroyObsoletePairs, actor)
AddDelayedCallback(Flicker, actor)
end
---Exchanges one of the object's identifier with another. If the old identifier is not found, the new one won't be added. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param oldIdentifier string
---@param newIdentifier string
---@param keyword? string
function ALICE_SwapIdentifier(object, oldIdentifier, newIdentifier, keyword)
local actor = GetActor(object, keyword)
if actor == nil or oldIdentifier == nil or newIdentifier == nil then
return
end
if actor.identifier[oldIdentifier] == nil then
return
end
actor.identifier[oldIdentifier] = nil
actor.identifier[newIdentifier] = true
AssignActorClass(actor, true, false)
AddDelayedCallback(DestroyObsoletePairs, actor)
AddDelayedCallback(Flicker, actor)
end
---Sets the object's identifier to a string or string sequence.
---@param object Object
---@param newIdentifier string | string[]
---@param keyword? string
function ALICE_SetIdentifier(object, newIdentifier, keyword)
local actor = GetActor(object, keyword)
if actor == nil or newIdentifier == nil then
return
end
for word, __ in pairs(actor.identifier) do
actor.identifier[word] = nil
end
if type(newIdentifier) == "string" then
actor.identifier[newIdentifier] = true
else
for __, word in ipairs(newIdentifier) do
actor.identifier[word] = true
end
end
AssignActorClass(actor, true, false)
AddDelayedCallback(DestroyObsoletePairs, actor)
AddDelayedCallback(Flicker, actor)
end
---Checks if the object has the specified identifiers. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param identifier string | table
---@param keyword? string
---@return boolean
function ALICE_HasIdentifier(object, identifier, keyword)
local actor = GetActor(object, keyword)
if actor == nil or identifier == nil then
return false
end
if type(identifier) == "string" then
return actor.identifier[identifier] == true
else
return HasIdentifierFromTable(actor, identifier)
end
end
---Compiles the identifiers of an object into the provided table or a new table. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param keyword? string
---@param table? table
function ALICE_GetIdentifier(object, keyword, table)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
local returnTable = table or {}
for key, __ in pairs(actor.identifier) do
insert(returnTable, key)
end
sort(returnTable)
return returnTable
end
---Returns the first entry in the given list of identifiers for which an actor exists for the specified object.
---@param object Object
---@vararg ... string
---@return string | nil
function ALICE_FindIdentifier(object, ...)
local identifier
for i = 1, select("#", ...) do
identifier = select(i, ...)
if identifier and GetActor(object, identifier) then
return identifier
end
end
return nil
end
---If table is a table with identifier keys, returns the field that matches with the specified object's identifier. If no match is found, returns table.other. If table is not a table, returns the variable itself. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param table any
---@param object Object
---@param keyword? string
---@return any
function ALICE_FindField(table, object, keyword)
if type(table) ~= "table" then
return table
end
local actor = GetActor(object, keyword)
if actor == nil then
return nil
end
local identifier = actor.identifier
local entry
local level = 0
local conflict = false
for key, value in pairs(table) do
if type(key) == "string" then
if identifier[key] then
if level < 1 then
entry = value
level = 1
elseif level == 1 then
conflict = true
end
end
else
local match = true
for __, tableKey in ipairs(key) do
if not identifier[tableKey] then
match = false
break
end
end
if match then
if #key > level then
entry = value
level = #key
conflict = false
elseif #key == level then
conflict = true
end
end
end
end
if entry == nil and table.other then
return table.other
end
if conflict then
Warning("Return value ambiguous in ALICE_FindField for " .. Identifier2String(object.identifier) .. ".")
return nil
end
return entry
end
--Interaction API
--===========================================================================================================================================================
---Changes the interaction function of the specified object towards the target identifier to the specified function or removes it. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param target string | string[]
---@param newFunc function | nil
---@param keyword? string
function ALICE_SetInteractionFunc(object, target, newFunc, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
local oldFunc = actor.interactions[target]
if oldFunc ~= newFunc then
actor.interactions[target] = newFunc
AssignActorClass(actor, false, true)
if newFunc == nil then
AddDelayedCallback(DestroyObsoletePairs, actor)
elseif oldFunc == nil then
AddDelayedCallback(Flicker, actor)
else
local next = actor.nextPair
local pair = next[actor.firstPair]
while pair do
if pair[0x8] == oldFunc then
pair[0x8] = newFunc
end
pair = next[pair]
end
end
end
end
---Adds a self-interaction with the specified function to the object. If a self-interaction with that function already exists, nothing happens. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors. Optional data parameter to initialize a data table that can be accessed with ALICE_PairLoadData.
---@param object Object
---@param whichFunc function
---@param keyword? string
---@param data? table
function ALICE_AddSelfInteraction(object, whichFunc, keyword, data)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
if actor.selfInteractions[whichFunc] then
return
end
actor.selfInteractions[whichFunc] = CreatePair(actor, SELF_INTERACTION_ACTOR, whichFunc)
if data then
local pairData = GetTable()
for key, value in pairs(data) do
pairData[key] = value
end
actor.selfInteractions[whichFunc].userData = pairData
end
end
---Removes the self-interaction with the specified function from the object. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFunc function
---@param keyword? string
function ALICE_RemoveSelfInteraction(object, whichFunc, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
if actor.selfInteractions[whichFunc] == nil then
return
end
local pair = actor.selfInteractions[whichFunc]
actor.selfInteractions[whichFunc] = nil
AddDelayedCallback(DestroyPair, pair)
end
---Checks if the object has a self-interaction with the specified function. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFunc function
---@param keyword? string
---@return boolean
function ALICE_HasSelfInteraction(object, whichFunc, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return false
end
return actor.selfInteractions[whichFunc] ~= nil
end
--Misc API
--===========================================================================================================================================================
---The first interaction of all pairs using this function will be delayed by the specified number.
---@param whichFunc function
---@param delay number
function ALICE_FuncSetDelay(whichFunc, delay)
if delay > config.MAX_INTERVAL then
Warning("|cffff0000Warning:|r Delay specified in ALICE_FuncSetDelay is greater than ALICE_MAX_INTERVAL.")
end
functionDelay[whichFunc] = min(config.MAX_INTERVAL, delay)
end
---Changes the behavior of pairs using the specified function so that the interactions continue to be evaluated when the two objects leave their interaction range. Also changes the behavior of ALICE_PairDisable to not prevent the two object from pairing again.
---@param whichFunc function
function ALICE_FuncSetUnbreakable(whichFunc)
functionIsUnbreakable[whichFunc] = true
end
---Changes the behavior of the specified function such that pairs using this function will persist if a unit is loaded into a transport or an item is picked up by a unit.
---@param whichFunc function
function ALICE_FuncSetUnsuspendable(whichFunc)
functionIsUnsuspendable[whichFunc] = true
end
---Automatically pauses and unpauses all pairs using the specified function whenever the initiating (male) actor is set to stationary/not stationary.
---@param whichFunc function
function ALICE_FuncPauseOnStationary(whichFunc)
functionPauseOnStationary[whichFunc] = true
end
---Checks if an actor exists with the specified identifier for the specified object. Optional strict flag to exclude actors that are anchored to that object.
---@param object Object
---@param identifier string
---@param strict? boolean
---@return boolean
function ALICE_HasActor(object, identifier, strict)
local actor = GetActor(object, identifier)
if actor == nil then
return false
end
return not strict or actor.host == object
end
---Returns the object the specified object is anchored to or itself if there is no anchor.
---@param object Object
---@return Object | nil
function ALICE_GetAnchor(object)
local actor = GetActor(object)
if actor == nil then
return object
end
return actor.originalAnchor
end
---Accesses all objects anchored to the specified object and returns the one with the specified identifier.
---@param object Object
---@param identifier string
---@return Object | nil
function ALICE_GetAnchoredObject(object, identifier)
local actor = GetActor(object, identifier)
if actor == nil then
return nil
end
return actor.host
end
---Sets the value of a flag for the actor of an object to the specified value. To change the isStationary flag, use ALICE_SetStationary instead. Cannot change hasInfiniteRange flag. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFlag string
---@param value any
---@param keyword? string
function ALICE_SetFlag(object, whichFlag, value, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
assert(RECOGNIZED_FLAGS[whichFlag], "Flag " .. whichFlag .. " is not recognized.")
assert(SetFlag[whichFlag], "Flag " .. whichFlag .. " cannot be changed with ALICE_SetFlag.")
SetFlag[whichFlag](actor, value)
end
---Returns the value stored for the specified flag of the specified actor. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFlag string
---@param keyword? string
---@return any
function ALICE_GetFlag(object, whichFlag, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
assert(RECOGNIZED_FLAGS[whichFlag], "Flag " .. whichFlag .. " is not recognized.")
if whichFlag == "radius" then
return actor.halfWidth
elseif whichFlag == "width" then
return 2*actor.halfWidth
elseif whichFlag == "height" then
return 2*actor.halfHeight
elseif whichFlag == "cellCheckInterval" then
return actor.cellCheckInterval*config.MIN_INTERVAL
elseif whichFlag == "anchor" then
return actor.originalAnchor
else
return actor[whichFlag]
end
end
---Returns the owner of the specified object. Faster than GetOwningPlayer. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param keyword? string
---@return player | nil
function ALICE_GetOwner(object, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return HandleType[object] == "unit" and GetOwningPlayer(object) or nil
end
return actor.getOwner(actor.host)
end
--Pair Access API
--===========================================================================================================================================================
---Restore a pair that has been previously destroyed with ALICE_PairDisable. Returns two booleans. The first denotes whether a pair now exists and the second if it was just created.
---@param objectA Object
---@param objectB Object
---@param keywordA? string
---@param keywordB? string
---@return boolean, boolean
function ALICE_Enable(objectA, objectB, keywordA, keywordB)
local actorA = GetActor(objectA, keywordA)
local actorB = GetActor(objectB, keywordB)
if actorA == nil or actorB == nil then
return false, false
end
if pairingExcluded[actorA][actorB] == nil then
if pairList[actorA][actorB] or pairList[actorB][actorA] then
return true, false
else
return false, false
end
end
pairingExcluded[actorA][actorB] = nil
pairingExcluded[actorB][actorA] = nil
if (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
local actorAFunc = GetInteractionFunc(actorA, actorB)
local actorBFunc = GetInteractionFunc(actorB, actorA)
if actorAFunc and actorBFunc then
if actorA.priority < actorB.priority then
CreatePair(actorB, actorA, actorBFunc)
return true, true
else
CreatePair(actorA, actorB, actorAFunc)
return true, true
end
elseif actorAFunc then
CreatePair(actorA, actorB, actorAFunc)
return true, true
elseif actorBFunc then
CreatePair(actorB, actorA, actorBFunc)
return true, true
end
end
return false, false
end
---Access the pair for objects A and B and, if it exists, return the data table stored for that pair. If objectB is a function, returns the data of the self-interaction of objectA using the specified function.
---@param objectA Object
---@param objectB Object | function
---@param keywordA? string
---@param keywordB? string
---@return table | nil
function ALICE_AccessData(objectA, objectB, keywordA, keywordB)
local actorA = GetActor(objectA, keywordA)
local actorB
local whichPair
if type(objectB) == "function" then
whichPair = actorA.selfInteractions[objectB]
else
actorB = GetActor(objectB, keywordB)
if actorA == nil or actorB == nil then
return nil
end
whichPair = pairList[actorA][actorB] or pairList[actorB][actorA]
end
if whichPair then
if whichPair.userData then
return whichPair.userData
else
whichPair.userData = GetTable()
return whichPair.userData
end
end
return nil
end
---Access the pair for objects A and B and, if it is paused, unpause it. If objectB is a function, unpauses the self-interaction of objectA using the specified function.
---@param objectA Object
---@param objectB Object | function
---@param keywordA? string
---@param keywordB? string
function ALICE_UnpausePair(objectA, objectB, keywordA, keywordB)
local actorA = GetActor(objectA, keywordA)
local actorB
local whichPair
if type(objectB) == "function" then
whichPair = actorA.selfInteractions[objectB]
else
actorB = GetActor(objectB, keywordB)
if actorA == nil or actorB == nil then
return nil
end
whichPair = pairList[actorA][actorB] or pairList[actorB][actorA]
end
if whichPair then
AddDelayedCallback(UnpausePair, whichPair)
end
end
---Access the pair for objects A and B and, if it exists, perform the specified action. Returns the return value of the action function. The hosts of the pair as well as any additional parameters are passed into the action function. If objectB is a function, access the pair of the self-inteaction of objectA using the specified function.
---@param action function
---@param objectA Object
---@param objectB Object | function
---@param keywordA? string
---@param keywordB? string
---@vararg any
---@return any
function ALICE_GetPairAndDo(action, objectA, objectB, keywordA, keywordB, ...)
local actorA = GetActor(objectA, keywordA)
local actorB
local whichPair
if type(objectB) == "function" then
whichPair = actorA.selfInteractions[objectB]
else
actorB = GetActor(objectB, keywordB)
if actorA == nil or actorB == nil then
return nil
end
whichPair = pairList[actorA][actorB] or pairList[actorB][actorA]
end
if whichPair then
local tempPair = currentPair
currentPair = whichPair
local returnValue = action(whichPair[0x3], whichPair[0x4], ...)
currentPair = tempPair
return returnValue
end
end
---Access all pairs for the object using the specified interactionFunc and perform the specified action. The hosts of the pairs as well as any additional parameters are passed into the action function. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param action function
---@param object Object
---@param whichFunc function
---@param includeInactive? boolean
---@param keyword? string
---@vararg any
function ALICE_ForAllPairsDo(action, object, whichFunc, includeInactive, keyword, ...)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
local DO_NOT_EVALUATE = DO_NOT_EVALUATE
local next = actor.nextPair
local thisPair = next[actor.firstPair]
local tempPair = currentPair
while thisPair do
if thisPair[0x8] == whichFunc and (includeInactive or (thisPair[0x7] and thisPair[0x6] ~= nil) or (not thisPair[0x7] and thisPair[0x5] ~= DO_NOT_EVALUATE)) then
currentPair = thisPair
action(thisPair[0x3], thisPair[0x4], ...)
end
thisPair = next[thisPair]
end
currentPair = tempPair
end
--Optimization API
--===========================================================================================================================================================
---Pauses interactions of the current pair after this one. Resume with an unpause function.
function ALICE_PairPause()
AddDelayedCallback(PausePair, currentPair)
end
---Unpauses all paused interactions of the object. Optional whichFunctions argument, which can be a function or a function sequence, to limit unpausing to pairs using those functions. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFunctions? function | table
---@param keyword? string
function ALICE_Unpause(object, whichFunctions, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
if type(whichFunctions) == "table" then
for key, value in ipairs(whichFunctions) do
whichFunctions[value] = true
whichFunctions[key] = nil
end
elseif whichFunctions then
local functionsTable = GetTable()
functionsTable[whichFunctions] = true
whichFunctions = functionsTable
end
AddDelayedCallback(Unpause, actor, whichFunctions)
end
---Sets an object to stationary/not stationary. Will affect all actors attached to the object.
---@param object Object
---@param enable? boolean
function ALICE_SetStationary(object, enable)
objectIsStationary[object] = enable ~= false
if actorOf[object] == nil then
return
end
if actorOf[object].isActor then
SetStationary(actorOf[object], enable ~= false)
else
for __, actor in ipairs(actorOf[object]) do
SetStationary(actor, enable ~= false)
end
end
end
---Returns whether the specified object is set to stationary.
---@param object Object
function ALICE_IsStationary(object)
return objectIsStationary[object]
end
---The first interaction of all pairs using this function will be delayed by up to the specified number, distributing individual calls over the interval to prevent computation spikes.
---@param whichFunc function
---@param interval number
function ALICE_FuncDistribute(whichFunc, interval)
if interval > config.MAX_INTERVAL then
Warning("|cffff0000Warning:|r Delay specified in ALICE_FuncDistribute is greater than ALICE_MAX_INTERVAL.")
end
functionDelay[whichFunc] = interval
functionDelayIsDistributed[whichFunc] = true
functionDelayCurrent[whichFunc] = 0
end
--Modular API
--===========================================================================================================================================================
---Executes the specified function before an object with the specified identifier is created. The function is called with the host as the parameter.
---@param matchingIdentifier string
---@param whichFunc function
function ALICE_OnCreation(matchingIdentifier, whichFunc)
onCreation.funcs[matchingIdentifier] = onCreation.funcs[matchingIdentifier] or {}
insert(onCreation.funcs[matchingIdentifier], whichFunc)
end
---Add a flag with the specified value to objects with matchingIdentifier when they are created. If a function is provided for value, the returned value of the function will be added.
---@param matchingIdentifier string
---@param flag string
---@param value any
function ALICE_OnCreationAddFlag(matchingIdentifier, flag, value)
if not OVERWRITEABLE_FLAGS[flag] then
error("Flag " .. flag .. " cannot be overwritten with ALICE_OnCreationAddFlag.")
end
onCreation.flags[matchingIdentifier] = onCreation.flags[matchingIdentifier] or {}
onCreation.flags[matchingIdentifier][flag] = value
end
---Adds an additional identifier to objects with matchingIdentifier when they are created. If a function is provided for value, the returned string of the function will be added.
---@param matchingIdentifier string
---@param value string | function
function ALICE_OnCreationAddIdentifier(matchingIdentifier, value)
onCreation.identifiers[matchingIdentifier] = onCreation.identifiers[matchingIdentifier] or {}
insert(onCreation.identifiers[matchingIdentifier], value)
end
---Adds an interaction to all objects with matchingIdentifier when they are created towards objects with the specified keyword in their identifier. To add a self-interaction, use ALICE_OnCreationAddSelfInteraction instead.
---@param matchingIdentifier string
---@param keyword string | string[]
---@param interactionFunc function
function ALICE_OnCreationAddInteraction(matchingIdentifier, keyword, interactionFunc)
onCreation.interactions[matchingIdentifier] = onCreation.interactions[matchingIdentifier] or {}
if onCreation.interactions[matchingIdentifier][keyword] then
Warning("|cffff0000Warning:|r Multiple interactionsFuncs added on creation to " .. matchingIdentifier .. " and " .. keyword .. ". Previous entry was overwritten.")
end
onCreation.interactions[matchingIdentifier][keyword] = interactionFunc
end
---Adds a self-interaction to all objects with matchingIdentifier when they are created.
---@param matchingIdentifier string
---@param selfinteractions function
function ALICE_OnCreationAddSelfInteraction(matchingIdentifier, selfinteractions)
onCreation.selfInteractions[matchingIdentifier] = onCreation.selfInteractions[matchingIdentifier] or {}
insert(onCreation.selfInteractions[matchingIdentifier], selfinteractions)
end
--#endregion
end
if Debug then Debug.beginFile "CAT Camera" end
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
=============================================================================================================================================================
C A M E R A S
=============================================================================================================================================================
This template creates an actor for each player's camera, which can be used for visibility detection. The camera gets the identifier "camera".
The camera actor is fully asynchronous and must not engage in any interactions that require synchronicity (see under Tutorial & Documentation -> Advanced ->
Asynchronous Code).
The following fields can be read:
CAT_Camera.x The camera's target position.
CAT_Camera.y
CAT_Camera.z
CAT_Camera.eyeX The camera's eye position.
CAT_Camera.eyeY
CAT_Camera.eyeZ
CAT_Camera.angleOfAttack The camera's angle of attack.
CAT_Camera.rotation The camera's rotation.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local MAX_CAMERA_RADIUS = 3000 ---@type number
--Caps the maximum radius of the camera field when the camera is at a low angle.
--===========================================================================================================================================================
CAT_Camera = nil ---@type Camera
--InteractionFunc
function UpdateCameraParameters(camera)
camera.angleOfAttack = GetCameraField(CAMERA_FIELD_ANGLE_OF_ATTACK)
camera.rotation = GetCameraField(CAMERA_FIELD_ROTATION)
camera.eyeX = GetCameraEyePositionX()
camera.eyeY = GetCameraEyePositionY()
camera.eyeZ = GetCameraEyePositionZ()
camera.x = GetCameraTargetPositionX()
camera.y = GetCameraTargetPositionY()
camera.z = GetCameraTargetPositionZ()
--Approximation of camera viewing distance.
local newCameraRadius = math.min(MAX_CAMERA_RADIUS, 0.5*GetCameraField(CAMERA_FIELD_TARGET_DISTANCE)/(5.88 - camera.angleOfAttack))
if math.abs(ALICE_GetFlag(camera, "radius") - newCameraRadius) > 100 then
ALICE_SetFlag(camera, "radius", newCameraRadius)
end
end
---@class Camera
local Camera = {
eyeX = nil,
eyeY = nil,
eyeZ = nil,
angleOfAttack = nil,
rotation = nil,
--ALICE
x = nil,
y = nil,
z = nil,
identifier = nil,
interactions = nil,
cellCheckInterval = nil,
}
Camera.__index = Camera
OnInit.final("CAT_Camera", function()
Require "ALICE"
CAT_Camera = {
eyeX = GetCameraEyePositionX(),
eyeY = GetCameraEyePositionY(),
eyeZ = GetCameraEyePositionZ(),
angleOfAttack = 0,
rotation = 0,
--ALICE
x = GetCameraTargetPositionX(),
y = GetCameraTargetPositionY(),
z = GetCameraTargetPositionZ(),
identifier = "camera",
interactions = {
self = UpdateCameraParameters,
},
cellCheckInterval = ALICE_Config.MIN_INTERVAL,
}
ALICE_Create(CAT_Camera)
end)
end
if Debug then Debug.beginFile "CAT Rects" end
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
=============================================================================================================================================================
R E C T S
=============================================================================================================================================================
This template contains function to help with the creation of actors representing rects, which can be built from the native rect type or from tables with the
minX, minY, maxX, and maxY fields.
=============================================================================================================================================================
L I S T O F F U N C T I O N S
=============================================================================================================================================================
CAT_CreateFromRect(rect, flags) Creates a stationary actor with the extents of the specified rect. Rect can be a native rect type or a table with the minX,
minY, maxX, and maxY fields. All fields added with the fields parameter are passed into ALICE, including identifier and
interactions. This parameter can be omitted and all fields directly put into the rect if a table is used to represent it. This
function returns the table that it created for the host.
CAT_RectCheck An interaction function. Checks if the object is inside the rect, invokes the .onEnter(object, rect) function when it enters,
the .onPeriodic(object, rect) function while it is inside the rect, and the .onLeave(object, rect) function when it leaves the
rect. The .interval field determines the interaction interval. The rect must be the female actor for this interaction function.
CAT_IsPointInRect(x, y, rect)
CAT_DoRectsIntersect(rect1, rect2)
CAT_IsRectInRect(smallerRect, largerRect)
=============================================================================================================================================================
]]
---Creates a stationary actor with the extents of the specified rect. All fields added with the fields parameter are passed into ALICE, including identifier and interactions. This parameter can be omitted and all fields directly put into the rect if a table is used to represent it. This function returns the table that it created for the host.
---@param rect rect | table
---@param fields? table
---@return table
function CAT_CreateFromRect(rect, fields)
local self
if IsHandle[rect] then
self = {
x = GetRectCenterX(rect),
y = GetRectCenterY(rect),
minX = GetRectMinX(rect),
minY = GetRectMinY(rect),
maxX = GetRectMaxX(rect),
maxY = GetRectMaxY(rect),
}
self.width = self.maxX - self.minX
self.height = self.maxY - self.minY
else
self = rect
self.x = (rect.maxX + rect.minX)/2
self.y = (rect.maxY + rect.minY)/2
self.width = rect.maxX - rect.minX
self.height = rect.maxY - rect.minY
end
if fields then
for key, value in pairs(fields) do
self[key] = value
end
end
self.identifier = self.identifier or "rect"
self.isStationary = true
ALICE_Create(self)
return self
end
local function RectOnLeave(object, rect)
if rect.onLeave then
rect.onLeave(object, rect)
end
end
function CAT_RectCheck(object, rect)
local x, y = ALICE_GetCoordinates2D(object)
if CAT_IsPointInRect(x, y, rect) then
if ALICE_PairIsFirstContact() then
if rect.onEnter then
rect.onEnter(object, rect)
end
end
if rect.onPeriodic then
rect.onPeriodic(object, rect)
end
else
ALICE_PairReset()
end
return rect.interval or 0
end
---@param x number
---@param y number
---@param rect table
function CAT_IsPointInRect(x, y, rect)
return x > rect.minX and x < rect.maxX and y > rect.minY and y < rect.maxY
end
---@param rect1 table
---@param rect2 table
function CAT_DoRectsIntersect(rect1, rect2)
return rect1.maxX > rect2.minX and rect1.minX < rect2.maxX and rect1.maxY > rect2.minY and rect1.minY < rect2.maxY
end
---@param smallerRect table
---@param largerRect table
function CAT_IsRectInRect(smallerRect, largerRect)
return smallerRect.minX >= largerRect.minX and smallerRect.maxX <= largerRect.maxX and smallerRect.minY >= largerRect.minY and smallerRect.maxY <= largerRect.maxY
end
local function InitRectsCAT()
ALICE_FuncSetOnReset(CAT_RectCheck, RectOnLeave)
end
OnInit.global("CAT_Rects", InitRectsCAT)
end
do
PLAYER_COLORS_RGB = {
[1] = {255, 4, 2}, --Red
[2] = {16, 82, 255}, --Blue
[3] = {27, 230, 186}, --Teal
[4] = {133, 48, 177}, --Purple
[5] = {255, 252, 0}, --Yellow
[6] = {255, 138, 13}, --Orange
[7] = {32, 191, 0}, --Green
[8] = {227, 91, 175}, --Pink
[9] = {148, 150, 151}, --Light Gray
[10] = {126, 191, 241}, --Light Blue
[11] = {16, 98, 71}, --Aqua
[12] = {79, 43, 5}, --Brown
[13] = {156, 0, 0}, --Maroon
[14] = {0, 0, 194}, --Navy
[15] = {0, 235, 235}, --Turquoise
[16] = {190, 0, 255}, --Violet
[17] = {236, 204, 134}, --Wheat
[18] = {247, 164, 139}, --Peach
[19] = {191, 255, 128}, --Mint
[20] = {219, 184, 236}, --Lavender
[21] = {79, 79, 85}, --Coal
[22] = {236, 240, 255}, --Snow
[23] = {0, 120, 30}, --Emerald
[24] = {164, 111, 52} --Peanut
}
PLAYER_COLORS_HEX = {
[1] = "|cffff0402", --Red
[2] = "|cff1052ff", --Blue
[3] = "|cff1BE6BA", --Teal
[4] = "|cff8530b1", --Purple
[5] = "|cfffffc00", --Yellow
[6] = "|cffff8a0d", --Orange
[7] = "|cff20bf00", --Green
[8] = "|cffE35BAF", --Pink
[9] = "|cff949697", --Light Gray
[10] = "|cff7EBFF1", --Light Blue
[11] = "|cff106247", --Aqua
[12] = "|cff4F2B05", --Brown
[13] = "|cff9C0000", --Maroon
[14] = "|cff0000C2", --Navy
[15] = "|cff00EBEB", --Turquoise
[16] = "|cffBE00FF", --Violet
[17] = "|cffECCC86", --Wheat
[18] = "|cffF7A48B", --Peach
[19] = "|cffBFFF80", --Mint
[20] = "|cffDBB8EC", --Lavender
[21] = "|cff4F4F55", --Coal
[22] = "|cffECF0FF", --Snow
[23] = "|cff00781E", --Emerald
[24] = "|cffA46F34" --Peanut
}
end
do
--[[
Adrt = "TerrainArt\\Ashenvale\\Ashen_Dirt",
Adrg = "TerrainArt\\Ashenvale\\Ashen_DirtGrass",
Adrd = "TerrainArt\\Ashenvale\\Ashen_DirtRough",
Agrs = "TerrainArt\\Ashenvale\\Ashen_Grass",
Agrd = "TerrainArt\\Ashenvale\\Ashen_GrassLumpy",
Alvd = "TerrainArt\\Ashenvale\\Ashen_Leaves",
Arck = "TerrainArt\\Ashenvale\\Ashen_Rock",
Avin = "TerrainArt\\Ashenvale\\Ashen_Vines",
Bdsr = "TerrainArt\\Barrens\\Barrens_Desert",
Bdsd = "TerrainArt\\Barrens\\Barrens_DesertDark",
Bdrt = "TerrainArt\\Barrens\\Barrens_Dirt",
Bdrg = "TerrainArt\\Barrens\\Barrens_DirtGrass",
Bdrh = "TerrainArt\\Barrens\\Barrens_DirtRough",
Bgrr = "TerrainArt\\Barrens\\Barrens_Grass",
Bdrr = "TerrainArt\\Barrens\\Barrens_Pebbles",
Bflr = "TerrainArt\\Barrens\\Barrens_Rock",
Yblm = "TerrainArt\\Cityscape\\City_BlackMarble",
Ybtl = "TerrainArt\\Cityscape\\City_BrickTiles",
Ydrt = "TerrainArt\\Cityscape\\City_Dirt",
Ydtr = "TerrainArt\\Cityscape\\City_DirtRough",
Ygsb = "TerrainArt\\Cityscape\\City_Grass",
Yhdg = "TerrainArt\\Cityscape\\City_GrassTrim",
Yrtl = "TerrainArt\\Cityscape\\City_RoundTiles",
Ysqd = "TerrainArt\\Cityscape\\City_SquareTiles",
Ywmb = "TerrainArt\\Cityscape\\City_WhiteMarble",
Xblm = "TerrainArt\\Dalaran\\Dalaran_BlackMarble",
Xbtl = "TerrainArt\\Dalaran\\Dalaran_BrickTiles",
Xdrt = "TerrainArt\\Dalaran\\Dalaran_Dirt",
Xdtr = "TerrainArt\\Dalaran\\Dalaran_DirtRough",
Xgsb = "TerrainArt\\Dalaran\\Dalaran_Grass",
Xhdg = "TerrainArt\\Dalaran\\Dalaran_GrassTrim",
Xrtl = "TerrainArt\\Dalaran\\Dalaran_RoundTiles",
Xsqd = "TerrainArt\\Dalaran\\Dalaran_SquareTiles",
Xwmb = "TerrainArt\\Dalaran\\Dalaran_WhiteMarble",
Dbrk = "TerrainArt\\Dungeon\\Cave_Brick",
Ddkr = "TerrainArt\\Dungeon\\Cave_DarkRocks",
Ddrt = "TerrainArt\\Dungeon\\Cave_Dirt",
Dgrs = "TerrainArt\\Dungeon\\Cave_GreyStones",
Dlav = "TerrainArt\\Dungeon\\Cave_Lava",
Dlvc = "TerrainArt\\Dungeon\\Cave_LavaCracks",
Drds = "TerrainArt\\Dungeon\\Cave_RedStones",
Dsqd = "TerrainArt\\Dungeon\\Cave_SquareTiles",
Gbrk = "TerrainArt\\Dungeon2\\GBrick",
Gdkr = "TerrainArt\\Dungeon2\\GDarkRocks",
Gdrt = "TerrainArt\\Dungeon2\\Dirt",
Ggrs = "TerrainArt\\Dungeon2\\GGreyStones",
Glav = "TerrainArt\\Dungeon2\\GLava",
Glvc = "TerrainArt\\Dungeon2\\GLavaCracks",
Grds = "TerrainArt\\Dungeon2\\GRedStones",
Gsqd = "TerrainArt\\Dungeon2\\GSquareTiles",
Cdrt = "TerrainArt\\Felwood\\Felwood_Dirt",
Cdrd = "TerrainArt\\Felwood\\Felwood_DirtRough",
Cgrs = "TerrainArt\\Felwood\\Felwood_Grass",
Clvg = "TerrainArt\\Felwood\\Felwood_Leaves",
Cpos = "TerrainArt\\Felwood\\Felwood_Poison",
Crck = "TerrainArt\\Felwood\\Felwood_Rock",
Cvin = "TerrainArt\\Felwood\\Felwood_Vines",
Fdrt = "TerrainArt\\LordaeronFall\\Lordf_Dirt",
Fdrg = "TerrainArt\\LordaeronFall\\Lordf_DirtGrass",
Fdro = "TerrainArt\\LordaeronFall\\Lordf_DirtRough",
Fgrs = "TerrainArt\\LordaeronFall\\Lordf_Grass",
Fgrd = "TerrainArt\\LordaeronFall\\Lordf_GrassDark",
Frok = "TerrainArt\\LordaeronFall\\Lordf_Rock",
Ldrt = "TerrainArt\\LordaeronSummer\\Lords_Dirt",
Ldrg = "TerrainArt\\LordaeronSummer\\Lords_DirtGrass",
Ldro = "TerrainArt\\LordaeronSummer\\Lords_DirtRough",
Lgrs = "TerrainArt\\LordaeronSummer\\Lords_Grass",
Lgrd = "TerrainArt\\LordaeronSummer\\Lords_GrassDark",
Lrok = "TerrainArt\\LordaeronSummer\\Lords_Rock",
Wdrt = "TerrainArt\\LordaeronWinter\\Lordw_Dirt",
Wdro = "TerrainArt\\LordaeronWinter\\Lordw_DirtRough",
Wgrs = "TerrainArt\\LordaeronWinter\\Lordw_Grass",
Wrok = "TerrainArt\\LordaeronWinter\\Lordw_Rock",
Wsnw = "TerrainArt\\LordaeronWinter\\Lordw_Snow",
Wsng = "TerrainArt\\LordaeronWinter\\Lordw_SnowGrass",
Ndrt = "TerrainArt\\Northrend\\North_Dirt",
Ndrd = "TerrainArt\\Northrend\\North_DirtDark",
Ngrs = "TerrainArt\\Northrend\\North_Grass",
Nice = "TerrainArt\\Northrend\\North_Ice",
Nrck = "TerrainArt\\Northrend\\North_Rock",
Nsnw = "TerrainArt\\Northrend\\North_Snow",
Nsnr = "TerrainArt\\Northrend\\North_SnowRock",
Vcbp = "TerrainArt\\Village\\Village_CobblePath",
Vcrp = "TerrainArt\\Village\\Village_Crops",
Vdrt = "TerrainArt\\Village\\Village_Dirt",
Vdrr = "TerrainArt\\Village\\Village_DirtRough",
Vgrs = "TerrainArt\\Village\\Village_GrassShort",
Vgrt = "TerrainArt\\Village\\Village_GrassThick",
Vrck = "TerrainArt\\Village\\Village_Rocks",
Vstp = "TerrainArt\\Village\\Village_StonePath",
Qcbp = "Terrain\\VillageFall\\VillageFall_CobblePath",
Qcrp = "Terrain\\VillageFall\\VillageFall_Crops",
Qdrt = "Terrain\\VillageFall\\VillageFall_Dirt",
Qdrr = "Terrain\\VillageFall\\VillageFall_DirtRough",
Qgrs = "Terrain\\VillageFall\\VillageFall_GrassShort",
Qgrt = "Terrain\\VillageFall\\VillageFall_GrassThick",
Qrck = "Terrain\\VillageFall\\VillageFall_Rocks",
Qstp = "Terrain\\VillageFall\\VillageFall_StonePath",
Kdkt = "Terrain\\BlackCitadel\\Citadel_DarkTiles",
Kdrt = "Terrain\\BlackCitadel\\Citadel_Dirt",
Kfsl = "Terrain\\BlackCitadel\\Citadel_DirtLight",
Kfst = "Terrain\\BlackCitadel\\Citadel_FlatStones",
Klgb = "Terrain\\BlackCitadel\\Citadel_LargeBricks",
Kdtr = "Terrain\\BlackCitadel\\Citadel_RoughDirt",
Ksmb = "Terrain\\BlackCitadel\\Citadel_SmallBricks",
Ksqt = "Terrain\\BlackCitadel\\Citadel_SquareTiles",
Jblm = "TerrainArt\\DalaranRuins\\DRuins_BlackMarble",
Jbtl = "TerrainArt\\DalaranRuins\\DRuins_BrickTiles",
Jdrt = "TerrainArt\\DalaranRuins\\DRuins_Dirt",
Jdtr = "TerrainArt\\DalaranRuins\\DRuins_DirtRough",
Jgsb = "TerrainArt\\DalaranRuins\\DRuins_Grass",
Jhdg = "TerrainArt\\DalaranRuins\\DRuins_GrassTrim",
Jrtl = "TerrainArt\\DalaranRuins\\DRuins_RoundTiles",
Jsgd = "TerrainArt\\DalaranRuins\\DRuins_SquareTiles",
Jwmb = "TerrainArt\\DalaranRuins\\DRuins_WhiteMarble",
Ibkb = "TerrainArt\\Icecrown\\Ice_BlackBricks",
Ibsq = "TerrainArt\\Icecrown\\Ice_BlackSquares",
Idki = "TerrainArt\\Icecrown\\Ice_DarkIce",
Idrt = "TerrainArt\\Icecrown\\Ice_Dirt",
Idtr = "TerrainArt\\Icecrown\\Ice_DirtRough",
Iice = "TerrainArt\\Icecrown\\Ice_Ice",
Irbk = "TerrainArt\\Icecrown\\Ice_RuneBricks",
Isnw = "TerrainArt\\Icecrown\\Ice_Snow",
Itbk = "TerrainArt\\Icecrown\\Ice_TileBricks",
Oaby = "TerrainArt\\Outland\\Outland_Abyss",
Odrt = "TerrainArt\\Outland\\Outland_Dirt",
Ofst = "TerrainArt\\Outland\\Outland_DirtCracked",
Odtr = "TerrainArt\\Outland\\Outland_DirtLight",
Olgb = "TerrainArt\\Outland\\Outland_FlatStones",
Ofsl = "TerrainArt\\Outland\\Outland_FlatStonesLight",
Orok = "TerrainArt\\Outland\\Outland_Rock",
Osmb = "TerrainArt\\Outland\\Outland_RoughDirt",
Zdrt = "TerrainArt\\Ruins\\Ruins_Dirt",
Zdrg = "TerrainArt\\Ruins\\Ruins_DirtGrass",
Zdtr = "TerrainArt\\Ruins\\Ruins_DirtRough",
Zgrs = "TerrainArt\\Ruins\\Ruins_Grass",
Zvin = "TerrainArt\\Ruins\\Ruins_GrassDark",
Zbkl = "TerrainArt\\Ruins\\Ruins_LargeBricks",
Ztil = "TerrainArt\\Ruins\\Ruins_RoundTiles",
Zsan = "TerrainArt\\Ruins\\Ruins_Sand",
Zbks = "TerrainArt\\Ruins\\Ruins_SmallBricks",
]]
OnInit.global("TerrainTextureColors", function()
local colors = {
Adrt = {66,64,23},
Adrg = {48,70,12},
Adrd = {49,58,20},
Agrs = {42,84,15},
Agrd = {40,66,20},
Alvd = {32,51,23},
Arck = {114,119,74},
Avin = {29,68,24},
Bdsr = {133,87,50},
Bdsd = {102,61,28},
Bdrt = {83,53,32},
Bdrg = {75,43,15},
Bdrh = {56,34,18},
Bgrr = {119,70,10},
Bdrr = {88,47,32},
Bflr = {80,39,27},
Yblm = {40,32,20},
Ybtl = {149,136,117},
Ydrt = {77,73,38},
Ydtr = {61,61,29},
Ygsb = {20,71,18},
Yhdg = {7,44,5},
Yrtl = {91,83,72},
Ysqd = {132,112,82},
Ywmb = {173,165,157},
Xblm = {49,26,33},
Xbtl = {154,138,138},
Xdrt = {71,67,45},
Xdtr = {56,55,34},
Xgsb = {28,70,16},
Xhdg = {8,44,5},
Xrtl = {126,114,108},
Xsqd = {92,62,85},
Xwmb = {167,167,167},
Dbrk = {54,18,19},
Ddkr = {62,20,16},
Ddrt = {56,25,21},
Dgrs = {42,14,12},
Dlav = {200,40,4},
Dlvc = {133,14,2},
Drds = {91,23,16},
Dsqd = {75,49,46},
Gbrk = {27,42,39},
Gdkr = {14,30,16},
Gdrt = {18,34,31},
Ggrs = {20,21,19},
Glav = {52,155,166},
Glvc = {26,97,100},
Grds = {28,40,33},
Gsqd = {47,53,41},
Cdrt = {39,54,49},
Cdrd = {27,42,33},
Cgrs = {19,56,27},
Clvg = {20,48,33},
Cpos = {20,87,5},
Crck = {5,46,28},
Cvin = {24,58,37},
Fdrt = {111,86,49},
Fdrg = {102,76,25},
Fdro = {108,80,45},
Fgrs = {114,79,19},
Fgrd = {92,61,11},
Frok = {139,108,96},
Ldrt = {145,101,54},
Ldrg = {107,98,36},
Ldro = {141,98,51},
Lgrs = {36,117,25},
Lgrd = {11,87,12},
Lrok = {139,108,96},
Wdrt = {76,77,60},
Wdro = {72,76,61},
Wgrs = {35,68,61},
Wrok = {92,77,63},
Wsnw = {189,208,228},
Wsng = {66,75,59},
Ndrt = {34,61,53},
Ndrd = {20,42,37},
Ngrs = {17,80,74},
Nice = {89,160,184},
Nrck = {18,53,58},
Nsnw = {189,208,228},
Nsnr = {124,159,176},
Vcbp = {62,53,33},
Vcrp = {54,66,30},
Vdrt = {77,73,38},
Vdrr = {61,61,29},
Vgrs = {68,79,28},
Vgrt = {20,71,18},
Vrck = {100,101,69},
Vstp = {106,92,60},
Qcbp = {59,48,29},
Qcrp = {64,64,22},
Qdrt = {74,70,41},
Qdrr = {58,58,32},
Qgrs = {73,55,19},
Qgrt = {94,58,9},
Qrck = {106,90,72},
Qstp = {97,87,67},
Kdkt = {40,14,14},
Kdrt = {101,26,9},
Kfsl = {105,46,18},
Kfst = {45,8,1},
Klgb = {51,9,9},
Kdtr = {54,18,3},
Ksmb = {75,23,11},
Ksqt = {18,3,2},
Jblm = {29,16,19},
Jbtl = {59,50,48},
Jdrt = {55,52,38},
Jdtr = {36,36,21},
Jgsb = {34,42,22},
Jhdg = {17,26,13},
Jrtl = {35,30,28},
Jsgd = {45,27,40},
Jwmb = {73,73,73},
Ibkb = {3,21,26},
Ibsq = {2,24,26},
Idki = {16,115,122},
Idrt = {30,49,53},
Idtr = {15,25,27},
Iice = {95,189,207},
Irbk = {15,43,49},
Isnw = {152,209,230},
Itbk = {6,60,67},
Oaby = {0,0,0},
Odrt = {101,26,9},
Ofst = {99,30,11},
Odtr = {105,46,18},
Olgb = {45,8,1},
Ofsl = {118,55,25},
Orok = {36,3,1},
Osmb = {54,18,3},
Zdrt = {107,106,55},
Zdrg = {73,98,32},
Zdtr = {82,81,33},
Zgrs = {11,87,12},
Zvin = {0,46,0},
Zbkl = {142,133,75},
Ztil = {39,83,34},
Zsan = {121,120,69},
Zbks = {58,69,27},
}
TERRAIN_TEXTURE_COLORS = {}
for key, value in pairs(colors) do
TERRAIN_TEXTURE_COLORS[FourCC(key)] = value
end
end)
end
if Debug then Debug.beginFile "RPGMinimap" end
do
--[[
=============================================================================================================================================================
RPG Minimap
by Antares
v1.5.2
A scrolling, highly customizable minimap for RPGs with a locked camera.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
ALICE https://www.hiveworkshop.com/threads/.353126/
Camera CAT Included in ALICE.
Rects CAT Included in ALICE.
RPGMinimap Assets.zip Included in Test Map.
Pathing Wizard (optional) https://www.hiveworkshop.com/threads/.355027/
For installation guide, tutorials & documentation, see here:
https://www.hiveworkshop.com/threads/.355230/
=============================================================================================================================================================
A P I
=============================================================================================================================================================
RPGMinimap
.AddIconTarget(whichObject, texture, size, level, flags) Creates a minimap icon attached to the specified object.
.AddIconLoc(x, y, texture, size, level, flags) Creates a minimap icon at the specified coordinates.
.RemoveIcon(whichObject) Removes a minimap icon.
.CreateTranslocatorZone(originRect, targetRect, exit, parent) Creates a translocator zone that clones all objects inside originRect to also appear
inside targetRect.
.OverwriteTerrainColor(rect, color, trumpsFogOfWar) Overwrites the terrain color in the specified rect to the specified color. Optional
trumpsFogOfWar parameter to overwrite the fog of war color.
.AddWaypointMarker(whichObject, texture, color) Creates a waypoint marker attached to the specified object. Optional color parameter to
specify the tinting color of the waypoint marker.
.RemoveWaypointMarker(whichObject) Removes the waypoint marker that is attached to the specified object.
.SetObjectTexture(whichObject, texture) Sets the texture of the minimap icon attached to the specified object. If no texture is
provided, resets it to the default value.
.SetObjectSize(whichObject, size) Sets the size of the minimap icon attached to the specified object. If no value is
provided, resets it to the default value.
.SetObjectVisibilityRadius(whichObject, radius) Sets the visibility radius of the minimap icon attached to the specified object. If no
value is provided, resets it to the default value.
.SetObjectLevel(whichObject, level) Sets the frame level of the minimap icon attached to the specified object. If no value
is provided, resets it to the default value.
.SetObjectName(whichObject, name) Sets the tooltip name of the minimap icon attached to the specified object. If no name
is provided, resets it to the default value. Set to an empty string to remove name.
.RevealRect(minX, minY, maxX, maxY) Reveal the map in a rectangular area. Can be called asynchronously.
.RevealCircle(x, y, radius) Reveal the map in a circular area. Can be called asynchronously.
.RedrawRect(minX, minY, maxX, maxY) Updates the minimap textures in the specified rect.
.ModifyWidgetType(fourCC, propertyTable) Writes into the config tables for widgets with the specified code the properties in the
provided table. The possible keys of the property table are texture, size, level,
visibiltiyRadius, color, and exception (which can be true or false). Will only have an
effect if the tables are referenced in the getter functions.
.SetExplorer(whichObject) Causes an object to continuously reveal the minimap around its position. This function
can be used to share exploration between players. It can be called asynchronously to
share exploration only between specific players.
.SaveExploration() Encodes the exploration map of the local player in a string. If exploration is not
synced, the generated code will be asynchronous.
.LoadExploration(code, whichPlayer) Loads the exploration map from a code for the specified player or for all players if
it is not specified.
.Init() Initializes the terrain map. Only necessary if AUTO_RUN is disabled.
.Show(enable) Shows or hides the RPG minimap.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--These constants control the general behavior of the minimap.
--A static minimap does not scroll and always displays the entirety of the specified area.
local STATIC_MINIMAP = false ---@type boolean
--Specify the world bounds for the static minimap. Set a parameter to nil to automatically use map bounds.
local STATIC_MIN_X = -2400 ---@type number|nil
local STATIC_MIN_Y = nil ---@type number|nil
local STATIC_MAX_X = nil ---@type number|nil
local STATIC_MAX_Y = nil ---@type number|nil
--The extent of the minimap if static minimap is disabled. The number of terrain tiles (128x128) that are drawn on the minimap from edge to edge.
local MINIMAP_NUMBER_OF_TILES = 40 ---@constant integer
--(Requires PathingWizard). Inaccessible terrain becomes black.
local HIDE_INACCESSIBLE_TERRAIN = true ---@constant boolean
--The size required for an inaccessible section of the map (in 64x64 tiles) to be hidden. This ensure that not every tree creates a hole in the minimap.
local HIDE_INACCESSIBLE_TERRAIN_MIN_SIZE = 30 ---@constant integer
--The minimap is veiled until it is explored. Sharing exploration between players is currently not supported.
local MINIMAP_MUST_BE_EXPLORED = true ---@constant boolean
--The radius of the area around the camera in which the minimap is revealed.
local MINIMAP_REVELATION_RADIUS = 1000 ---@constant number
--If enabled, the minimap is only revealed in areas the player has vision of.
local CHECK_FOG_OF_WAR_BEFORE_REVEALING = false ---@constant boolean
--If enabled, the minimap will automatically be revealed around the camera position. Otherwise, one or more explorers must be added with RPGMinimap.SetExplorer.
local CAMERA_IS_EXPLORER = true ---@constant boolean
--If enabled, the general shape of the terrain will be visible even through fog of war.
local INACCESSIBLE_TRUMPS_FOG_OF_WAR = false ---@constant boolean
--If enabled, the minimap uses the fog of war color instead of black at the map edge.
local MAP_EDGE_IS_FOG_OF_WAR = true ---@constant boolean
--Create mouse-over tooltips for objects on the minimap (requires NeatTextMessage.fdf).
local CREATE_TOOLTIPS = true ---@constant boolean
--Use hero proper name instead of unit name in mouse-over tooltips of heroes.
local USE_HERO_PROPER_NAME = true ---@constant boolean
--If enabled, automatically create the terrain map on map initialization. If disabled, you have to initialize it with RPGMinimap.Init()
local AUTO_RUN = true ---@constant boolean
--(Ignore for single-player maps). Because frames cannot be created asynchronously as an object appears on the minimap for one player, the system preallocates
--and recycles frames that are used to represent objects on the minimap. Preallocate a number of frames that is higher than the amount of objects that could
--reasonably be expected to be on the screen at the same time.
local NUMBER_OF_PREALLOCATED_FRAMES = 100 ---@constant integer
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--These constants control which units are drawn on the minimap.
--Disable drawing units on the minimap based on ownership. These filters are overwritten if a unit type is added to the exception list.
local DO_NOT_DRAW_ALLIES = false ---@constant boolean
local DO_NOT_DRAW_NEUTRALS = true ---@constant boolean
local DO_NOT_DRAW_ENEMIES = true ---@constant boolean
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--These constants control the appearance of waypoint markers.
--The size of waypoint markers.
local WAYPOINT_MARKER_SIZE = 0.018 ---@constant number
--How many textures are imported for different angles of the waypoint marker.
local WAYPOINT_MARKER_ANGLE_SPACING = 6 ---@constant integer
--The level of the waypoint marker frame.
local WAYPOINT_MARKER_LEVEL = 6 ---@constant integer
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--These constants control the colors of various terrain types.
--The color of water (red, green, blue).
local WATER_COLOR = {20, 30, 85} ---@constant integer[]
--How much the terrain color shimmers through. At a value of 0, the water is invisible. At a value of 1, the terrain is invisible.
local DEEP_WATER_OPACITY = 0.8 ---@constant number
local SHALLOW_WATER_OPACITY = 0.4 ---@constant number
--Replace terrain tiles with blight on affected areas. Blighted areas will not be updated automatically. You need to use RPGMinimap.RedrawRect.
local USE_BLIGHT = true ---@constant boolean
--The color of blight (red, green, blue).
local BLIGHT_COLOR = {55, 52, 37} ---@constant integer[]
--The color of unexplored terrain (red, green, blue).
local FOG_OF_WAR_COLOR = {32, 32, 32} ---@constant integer[]
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--These constants control the position of the minimap.
--Screen positions of the minimap.
local MINIMAP_SCREEN_MIN_X = 0.010 ---@constant number
local MINIMAP_SCREEN_MIN_Y = 0.007 ---@constant number
local MINIMAP_SCREEN_DIAMETER = 0.1385 ---@constant number
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Define any preset texture constants for minimap icons.
MINIMAP_TEXTURE_WAYPOINT_MARKER = "MinimapTextures\\MinimapMarker"
MINIMAP_TEXTURE_INVISIBLE = "MinimapTextures\\Invisible"
MINIMAP_TEXTURE_QUEST_AVAILABLE = "MinimapTextures\\ExclamationMark"
MINIMAP_TEXTURE_QUEST_COMPLETED = "MinimapTextures\\Questionmark"
MINIMAP_HERO_GLOW = "MinimapTextures\\HeroGlow"
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--These tables are global so you can add entries anywhere. Alternatively, you can use the RPGMinimap.ModifyWidgetType function to add entries.
--You can add widget types (fourCC) codes to this table to exclude them from the filters that control which objects are drawn. Adding an exception will overwrite
--the ownership filters (DO_NOT_DRAW_ALLIES, DO_NOT_DRAW_NEUTRALS, and DO_NOT_DRAW_ENEMIES).
MINIMAP_WIDGET_TYPE_EXCEPTIONS = {
"phea" --Potion of Healing
}
--[[
Set the values for size, texture, visibilityRadius and level for the minimap icons of different widget types (fourCC codes). You can use these tables in the
getter functions below.
Size The size of the minimap icon in screen coordinates.
Texture The path to the texture for the minimap icon.
VisibilityRadius If set, the minimap icon will only be visible up to the specified distance from the camera. Set to -1 for no visibility radius.
Level The level of the created frame. Frames with a higher level occlude frames with a lower level. Setting the level to a negative number
or to a value greater than 9 will crash the game.
Color A table with {red, green, blue}-integer values (0-255).
]]
MINIMAP_WIDGET_TYPE_TEXTURE = {
Etyr = "TyrandeMinimap.blp",
phea = "HealingPotionMinimap.blp"
}
MINIMAP_WIDGET_TYPE_SIZE = {
}
MINIMAP_WIDGET_TYPE_VISIBILITY_RADIUS = {
}
MINIMAP_WIDGET_TYPE_LEVEL = {
}
MINIMAP_WIDGET_TYPE_COLOR = {
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--These functions are called to retrieve the parameters for widgets. You can reference the tables you set above. Any fourCC code you entered will be converted
--into an id, so you can reference them without calling FourCC. The exception list is converted into a boolean table with id keys.
--This is a static filter. Do not put changing conditions in here.
local function ShouldUnitBeDrawn(unit)
return IsUnitType(unit, UNIT_TYPE_HERO) or MINIMAP_WIDGET_TYPE_EXCEPTIONS[GetUnitTypeId(unit)] == true
end
local function GetUnitTexture(unit)
return MINIMAP_WIDGET_TYPE_TEXTURE[GetUnitTypeId(unit)]
end
local function GetUnitSize(unit)
return IsUnitType(unit, UNIT_TYPE_HERO) and 0.01 or 0.007
end
local function GetUnitVisibilityRadius(unit)
return nil
end
local function GetUnitLevel(unit)
return IsUnitType(unit, UNIT_TYPE_HERO) and 7 or 4
end
local function GetUnitColor(unit)
if IsUnitType(unit, UNIT_TYPE_HERO) then
return nil
else
return PLAYER_COLORS_RGB[GetConvertedPlayerId(GetOwningPlayer(unit))]
end
end
--An invisible unit will not appear on the minimap.
local function IsUnitInvisible(unit)
return false
end
-------------------------------------------------------------------------------------------------------------------------------------------------------------
local function ShouldDestructableBeDrawn(destructable)
return MINIMAP_WIDGET_TYPE_EXCEPTIONS[GetDestructableTypeId(destructable)] == true
end
local function GetDestructableTexture(destructable)
return MINIMAP_WIDGET_TYPE_TEXTURE[GetDestructableTypeId(destructable)]
end
local function GetDestructableSize(destructable)
return MINIMAP_WIDGET_TYPE_SIZE[GetDestructableTypeId(destructable)]
end
local function GetDestructableVisibilityRadius(destructable)
return nil
end
local function GetDestructableLevel(destructable)
return 4
end
local function GetDestructableColor(destructable)
return nil
end
-------------------------------------------------------------------------------------------------------------------------------------------------------------
local function ShouldItemBeDrawn(item)
return MINIMAP_WIDGET_TYPE_EXCEPTIONS[GetItemTypeId(item)] == true
end
local function GetItemTexture(item)
return MINIMAP_WIDGET_TYPE_TEXTURE[GetItemTypeId(item)]
end
local function GetItemSize(item)
return 0.007
end
local function GetItemVisibilityRadius(item)
return 1500
end
local function GetItemLevel(item)
return 5
end
local function GetItemColor(item)
return nil
end
---------------------------------------------------------------------------------------------------------------------------------------------------------------
--Customize the UI adjustments made to accomodate the minimap. If you're using a custom UI texture, you might need to tweak some of the numbers. If you're using
--a fully altered UI, you might need to rewrite this function completely.
local function AdjustUI()
--Hide the default minimap
BlzFrameSetVisible(BlzGetOriginFrame(ORIGIN_FRAME_MINIMAP, 0), false)
--Increase the level of the console UI so that the minimap frames are drawn under it.
BlzFrameSetLevel(BlzGetFrameByName("ConsoleBottomBar", 0), 4)
--The UI elements such as command buttons and gold/lumber are now hidden by the console UI. So, we import modified console UI textures that are transparent
--at the necessary spots. Finally, because the UI is now transparent and you can see the world frame behind it, we add black backdrops that are drawn below
--the UI elements that were hidden by the console UI before the adjustments.
local UI_BACKDROPS = {}
for i = 1, 3 do
UI_BACKDROPS[i] = BlzCreateSimpleFrame("MinimapTextureFrame", BlzGetFrameByName("ConsoleUIBackdrop", 0), 0)
BlzFrameSetTexture(BlzGetFrameByName("MinimapTexture", 0), "MinimapTextures\\Black.blp", 0, true)
end
BlzFrameSetAbsPoint(UI_BACKDROPS[1], FRAMEPOINT_BOTTOMLEFT, 0.15, 0.125)
BlzFrameSetAbsPoint(UI_BACKDROPS[1], FRAMEPOINT_TOPRIGHT, 0.18, 0.15)
BlzFrameSetAbsPoint(UI_BACKDROPS[2], FRAMEPOINT_BOTTOMLEFT, 0.6, 0.125)
BlzFrameSetAbsPoint(UI_BACKDROPS[2], FRAMEPOINT_TOPRIGHT, 0.8, 0.15)
BlzFrameSetAbsPoint(UI_BACKDROPS[3], FRAMEPOINT_BOTTOMLEFT, 0, 0.58)
BlzFrameSetAbsPoint(UI_BACKDROPS[3], FRAMEPOINT_TOPRIGHT, 0.8, 0.6)
end
--[[
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
local abs = math.abs
local cos = math.cos
local sin = math.sin
local tan = math.tan
local min = math.min
local max = math.max
local sqrt = math.sqrt
local sign = function(v) if v >= 0 then return 1 else return -1 end end
local unpack = table.unpack
local sort = table.sort
local NATIVE_FLAGS = {
name = true,
visibilityRadius = true,
onFirstReveal = true,
owner = true,
color = true,
identifier = true
}
local MINIMAP_WORLD_DIAMETER
local MINIMAP_NUM_FRAMES
local TERRAIN_FRAME_SIZE
local WORLD_MIN_X ---@type number
local WORLD_MIN_Y ---@type number
local WORLD_MAX_X ---@type number
local WORLD_MAX_Y ---@type number
local MINIMAP_CENTER_X = MINIMAP_SCREEN_MIN_X + MINIMAP_SCREEN_DIAMETER/2
local MINIMAP_CENTER_Y = MINIMAP_SCREEN_MIN_Y + MINIMAP_SCREEN_DIAMETER/2
local MINIMAP_SCREEN_MAX_X = MINIMAP_SCREEN_MIN_X + MINIMAP_SCREEN_DIAMETER
local MINIMAP_SCREEN_MAX_Y = MINIMAP_SCREEN_MIN_Y + MINIMAP_SCREEN_DIAMETER
local BLACK_CONVERTED_COLOR ---@type integer
local BLIGHT_CONVERTED_COLOR ---@type integer
local FOG_OF_WAR_CONVERTED_COLOR ---@type integer
local TINTING_COLOR_WHITE = {255, 255, 255}
local terrainVertexColors = {} ---@type integer[][]
local terrainTileColors = {} ---@type integer[][][]
local terrainConnectionTypes = {} ---@type integer[][][]
local terrainIsExplored = {} ---@type boolean[][]
local overwriteTerrainColor = {} ---@type integer[][]
local overwriteTrumpsFogOfWar = {} ---@type boolean[][]
local minimapParentFrames = {} ---@type framehandle[][][]
local minimapTextureFrames = {} ---@type framehandle[][][]
local anchorColumn ---@type integer
local anchorRow ---@type integer
local firstColumn ---@type integer
local firstRow ---@type integer
local lastColumn ---@type integer
local lastRow ---@type integer
local anchorFrame ---@type framehandle
local minWorldTileI ---@type integer
local minWorldTileJ ---@type integer
local worldMaxI ---@type integer
local worldMaxJ ---@type integer
local minimapPreInit = false ---@type boolean
local minimapInitialized = false ---@type boolean
local minimapShown = false ---@type boolean
local cameraTranslocationZone ---@type Translocator | nil
local MinimapArtist ---@type table
local wt = {__mode = "k"}
local translocationZoneOf = setmetatable({}, wt) ---@type Translocator[]
local translocatedCloneOf = setmetatable({}, wt) ---@type table[]
local waypointMarkerOf = setmetatable({}, wt) ---@type WaypointMarker[]
local isVisible = setmetatable({}, wt) ---@type boolean[]
local unusedFrames = {} ---@type table
local localPlayer ---@type player
local playerNeutralPassive ---@type player
local colors = {} ---@type integer[]
local waterColor = {} ---@type integer[]
local indices = {} ---@type integer[]
local sortedColors = {} ---@type integer[]
local occurrences = {} ---@type integer[]
local chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
local NUMBER_OF_CHARS = 56 ---@constant number
--===========================================================================================================================================================
--Lookup Tables
--===========================================================================================================================================================
--Default values are to prevent stack overflows.
local textureCache = setmetatable({},
{
__mode = "k",
__index = function(self, object)
if IsHandle[object] then
if HandleType[object] == "unit" then
self[object] = GetUnitTexture(object) or ""
elseif HandleType[object] == "destructable" then
self[object] = GetDestructableTexture(object) or ""
elseif HandleType[object] == "item" then
self[object] = GetItemTexture(object) or ""
end
else
self[object] = object.texture or ""
end
return self[object]
end
}
)
local sizeCache = setmetatable({},
{
__mode = "k",
__index = function(self, object)
if IsHandle[object] then
if HandleType[object] == "unit" then
self[object] = GetUnitSize(object) or 0
elseif HandleType[object] == "destructable" then
self[object] = GetDestructableSize(object) or 0
elseif HandleType[object] == "item" then
self[object] = GetItemSize(object) or 0
end
else
self[object] = object.size or 0
end
return self[object]
end
}
)
local visibilityRadiusCache = setmetatable({},
{
__mode = "k",
__index = function(self, object)
if IsHandle[object] then
if HandleType[object] == "unit" then
self[object] = GetUnitVisibilityRadius(object) or -1
elseif HandleType[object] == "destructable" then
self[object] = GetDestructableVisibilityRadius(object) or -1
elseif HandleType[object] == "item" then
self[object] = GetItemVisibilityRadius(object) or -1
end
else
self[object] = object.visibilityRadius or -1
end
return self[object]
end
}
)
local levelCache = setmetatable({},
{
__mode = "k",
__index = function(self, object)
if IsHandle[object] then
if HandleType[object] == "unit" then
self[object] = GetUnitLevel(object) or 4
elseif HandleType[object] == "destructable" then
self[object] = GetDestructableLevel(object) or 4
elseif HandleType[object] == "item" then
self[object] = GetItemLevel(object) or 4
end
else
self[object] = object.level or 4
end
return self[object]
end
}
)
local nameCache = setmetatable({},
{
__mode = "k",
__index = function(self, object)
if IsHandle[object] then
if HandleType[object] == "unit" then
self[object] = USE_HERO_PROPER_NAME and IsUnitType(object, UNIT_TYPE_HERO) and GetHeroProperName(object) or GetUnitName(object) or ""
elseif HandleType[object] == "destructable" then
self[object] = GetDestructableName(object) or ""
else
self[object] = GetItemName(object) or ""
end
else
self[object] = object.name or ""
end
return self[object]
end
}
)
local colorCache = setmetatable({},
{
__mode = "k",
__index = function(self, object)
if IsHandle[object] then
if HandleType[object] == "unit" then
self[object] = GetUnitColor(object) or TINTING_COLOR_WHITE
elseif HandleType[object] == "destructable" then
self[object] = GetDestructableColor(object) or TINTING_COLOR_WHITE
else
self[object] = GetItemColor(object) or TINTING_COLOR_WHITE
end
else
self[object] = object.color or TINTING_COLOR_WHITE
end
return self[object]
end
}
)
local function ClearAllCaches(object)
textureCache[object] = nil
sizeCache[object] = nil
levelCache[object] = nil
visibilityRadiusCache[object] = nil
colorCache[object] = nil
ALICE_GetPairAndDo(ALICE_PairReset, object, MinimapArtist, "drawable", "minimapArtist")
end
--===========================================================================================================================================================
--Class Definitions
--===========================================================================================================================================================
---@class Translocator
local Translocator = {
--originRect
minX = nil, ---@type number
minY = nil, ---@type number
maxX = nil, ---@type number
maxY = nil, ---@type number
width = nil, ---@type number
height = nil, ---@type number
--targetRect
targetMinX = nil, ---@type number
targetMinY = nil, ---@type number
targetMaxX = nil, ---@type number
targetMaxY = nil, ---@type number
targetWidth = nil, ---@type number
targetHeight = nil, ---@type number
--exit
hasExit = nil, ---@type boolean
exitX = nil, ---@type number
exitY = nil, ---@type number
parent = nil, ---@type Translocator
children = nil, ---@type Translocator[]
--ALICE
x = nil, ---@type number
y = nil, ---@type number
identifier = nil, ---@type string
interactions = nil, ---@type table
radius = nil, ---@type number
isStationary = nil ---@type boolean
}
---@class WaypointMarker
local WaypointMarker = {
color = nil, ---@type integer[]
frames = nil, ---@type table
texture = nil, ---@type string
anchorSize = nil, ---@type number
--ALICE
identifier = nil, ---@type string | string[]
anchor = nil, ---@type Object
hasInfiniteRange = nil, ---@type boolean
}
---@class MinimapIcon
local MinimapIcon = {
x = nil, ---@type number
y = nil, ---@type number
identifier = nil, ---@type string | string[]
anchor = nil, ---@type Object
radius = nil, ---@type number
texture = nil, ---@type string
size = nil, ---@type number
level = nil, ---@type integer
visibilityRadius = nil, ---@type number | nil
name = nil ---@type string | nil
}
--===========================================================================================================================================================
--Utility
--===========================================================================================================================================================
local function OnExceptionAdded(object)
if HandleType[object] == "unit" then
if ALICE_HasIdentifier(object, "drawable", "unit") then
ALICE_UnpausePair(object, MinimapArtist, "drawable", "minimapArtist")
elseif ShouldUnitBeDrawn(object) then
ALICE_AddIdentifier(object, "drawable", "unit")
end
elseif HandleType[object] == "destructable" then
if ALICE_HasIdentifier(object, "drawable", "destructable") then
ALICE_UnpausePair(object, MinimapArtist, "drawable", "minimapArtist")
elseif ShouldDestructableBeDrawn(object) then
ALICE_AddIdentifier(object, "drawable", "destructable")
end
elseif HandleType[object] == "item" then
if ALICE_HasIdentifier(object, "drawable", "item") then
ALICE_UnpausePair(object, MinimapArtist, "drawable", "minimapArtist")
elseif ShouldItemBeDrawn(object) then
ALICE_AddIdentifier(object, "drawable", "item")
end
end
end
local function OnExceptionRemoved(object)
if HandleType[object] == "unit" then
if not ShouldUnitBeDrawn(object) then
ALICE_RemoveIdentifier(object, "drawable", "unit")
end
elseif HandleType[object] == "destructable" then
if not ShouldDestructableBeDrawn(object) then
ALICE_RemoveIdentifier(object, "drawable", "destructable")
end
elseif HandleType[object] == "item" then
if not ShouldItemBeDrawn(object) then
ALICE_RemoveIdentifier(object, "drawable", "item")
end
end
end
local function SetTooltipText(frames, text, dx, dy)
if text == nil then
return
end
BlzFrameSetText(frames.text, text)
BlzFrameSetPoint(frames.tooltip, FRAMEPOINT_BOTTOMLEFT, frames.parent, FRAMEPOINT_TOPRIGHT, dx or 0, dy or 0)
BlzFrameSetSize(frames.text, 0, 0)
BlzFrameSetSize(frames.tooltip, BlzFrameGetWidth(frames.text) + 0.009, BlzFrameGetHeight(frames.text) + 0.009)
BlzFrameSetPoint(frames.box, FRAMEPOINT_BOTTOMLEFT, frames.tooltip, FRAMEPOINT_BOTTOMLEFT, 0, 0)
BlzFrameSetPoint(frames.box, FRAMEPOINT_TOPRIGHT, frames.tooltip, FRAMEPOINT_TOPRIGHT, 0, 0)
BlzFrameSetLevel(frames.tooltip, 0)
BlzFrameSetLevel(frames.text, 1)
BlzFrameSetAlpha(frames.box, text ~= "" and 255 or 0)
BlzFrameSetAlpha(frames.text, text ~= "" and 255 or 0)
end
local function World2MinimapCoordinates(x, y, size, artistX, artistY)
local screenX = MINIMAP_CENTER_X + MINIMAP_SCREEN_DIAMETER*(x - artistX)/MINIMAP_WORLD_DIAMETER
local screenY = MINIMAP_CENTER_Y + MINIMAP_SCREEN_DIAMETER*(y - artistY)/MINIMAP_WORLD_DIAMETER
local halfSize = 0.5*size
if screenX > MINIMAP_SCREEN_MAX_X - halfSize or screenX < MINIMAP_SCREEN_MIN_X + halfSize or screenY > MINIMAP_SCREEN_MAX_Y - halfSize or screenY < MINIMAP_SCREEN_MIN_Y + halfSize then
return screenX, screenY, false
else
return screenX, screenY, true
end
end
local function IsZoneChild(toCheck, toMatch)
for __, child in ipairs(toCheck.children) do
if child == toMatch then
return true
end
end
return false
end
local function SquareCos(angle)
if abs(cos(angle)) > abs(sin(angle)) then
return sign(cos(angle))
else
return sign(cos(angle))/abs(tan(angle))
end
end
local function SquareSin(angle)
if abs(sin(angle)) > abs(cos(angle)) then
return sign(sin(angle))
else
return sign(sin(angle))*abs(tan(angle))
end
end
local function ModFrames(i)
if i > MINIMAP_NUM_FRAMES then
return i - MINIMAP_NUM_FRAMES
elseif i < 1 then
return i + MINIMAP_NUM_FRAMES
else
return i
end
end
local function FrameOfRow(j)
j = j + firstRow - 1
if j > MINIMAP_NUM_FRAMES then
return j - MINIMAP_NUM_FRAMES
elseif j < 1 then
return j + MINIMAP_NUM_FRAMES
else
return j
end
end
local function FrameOfColumn(i)
i = i + firstColumn - 1
if i > MINIMAP_NUM_FRAMES then
return i - MINIMAP_NUM_FRAMES
elseif i < 1 then
return i + MINIMAP_NUM_FRAMES
else
return i
end
end
local function ColumnOfTile(worldI)
if worldI >= minWorldTileI and worldI <= minWorldTileI + MINIMAP_NUMBER_OF_TILES then
return worldI - minWorldTileI
end
return nil
end
local function RowOfTile(worldJ)
if worldJ >= minWorldTileJ and worldJ <= minWorldTileJ + MINIMAP_NUMBER_OF_TILES then
return worldJ - minWorldTileJ
end
return nil
end
local function SortByOccurrence(a, b)
if occurrences[colors[a]] == occurrences[colors[b]] then
return colors[a] > colors[b]
else
return occurrences[colors[a]] > occurrences[colors[b]]
end
end
--===========================================================================================================================================================
--Render Minimap
--===========================================================================================================================================================
local function DrawFrame(frames, textures, i, j)
if i >= 1 and i <= worldMaxI and j >= 1 and j <= worldMaxJ then
for k = 1, 4 do
if k <= #terrainTileColors[i][j] then
BlzFrameSetTexture(textures[k], "MinimapTextures\\MinimapTerrainTexture" .. terrainConnectionTypes[i][j][k], 0, true)
BlzFrameSetVertexColor(textures[k], terrainTileColors[i][j][k])
BlzFrameSetVisible(frames[k], true)
BlzFrameSetLevel(frames[k], k - 1)
else
BlzFrameSetVisible(frames[k], false)
end
end
else
BlzFrameSetTexture(textures[1], "MinimapTextures\\MinimapTerrainTexture0", 0, true)
if MAP_EDGE_IS_FOG_OF_WAR then
BlzFrameSetVertexColor(textures[1], FOG_OF_WAR_CONVERTED_COLOR)
else
BlzFrameSetVertexColor(textures[1], BLACK_CONVERTED_COLOR)
end
BlzFrameSetVisible(frames[1], true)
BlzFrameSetLevel(frames[1], 0)
BlzFrameSetVisible(frames[2], false)
BlzFrameSetVisible(frames[3], false)
BlzFrameSetVisible(frames[4], false)
end
end
local function SetTerrainVertexColor(i, j, x, y)
local terrainType
if overwriteTerrainColor[i][j] then
if not MINIMAP_MUST_BE_EXPLORED or overwriteTrumpsFogOfWar[i][j] or terrainIsExplored[i][j] then
terrainVertexColors[i][j] = overwriteTerrainColor[i][j]
else
terrainVertexColors[i][j] = FOG_OF_WAR_CONVERTED_COLOR
end
elseif INACCESSIBLE_TRUMPS_FOG_OF_WAR and HIDE_INACCESSIBLE_TERRAIN and not IsPointAccessible(x, y) and GetSectionSize(x, y) > HIDE_INACCESSIBLE_TERRAIN_MIN_SIZE then
terrainVertexColors[i][j] = BLACK_CONVERTED_COLOR
elseif MINIMAP_MUST_BE_EXPLORED and not terrainIsExplored[i][j] then
terrainVertexColors[i][j] = FOG_OF_WAR_CONVERTED_COLOR
elseif not INACCESSIBLE_TRUMPS_FOG_OF_WAR and HIDE_INACCESSIBLE_TERRAIN and not IsPointAccessible(x, y) and GetSectionSize(x, y) > HIDE_INACCESSIBLE_TERRAIN_MIN_SIZE then
terrainVertexColors[i][j] = BLACK_CONVERTED_COLOR
else
terrainType = GetTerrainType(x, y)
if TERRAIN_TEXTURE_COLORS[terrainType] == nil then
print("|cffff0000Warning:|r Color missing for terrain type " .. string.pack(">I4", terrainType) .. ".")
TERRAIN_TEXTURE_COLORS[terrainType] = BLACK_CONVERTED_COLOR
end
--IsTerrainPathable native returns opposite of what it should.
if not IsTerrainPathable(x, y, PATHING_TYPE_FLOATABILITY) then --Is Water
if IsTerrainPathable(x, y, PATHING_TYPE_WALKABILITY) then --Is Deep Water
for k = 1, 3 do
waterColor[k] = (DEEP_WATER_OPACITY*WATER_COLOR[k] + (1 - DEEP_WATER_OPACITY)*TERRAIN_TEXTURE_COLORS[terrainType][k]) // 1
end
terrainVertexColors[i][j] = BlzConvertColor(255, unpack(waterColor))
else --Is Shallow Water
for k = 1, 3 do
waterColor[k] = (SHALLOW_WATER_OPACITY*WATER_COLOR[k] + (1 - SHALLOW_WATER_OPACITY)*TERRAIN_TEXTURE_COLORS[terrainType][k]) // 1
end
terrainVertexColors[i][j] = BlzConvertColor(255, unpack(waterColor))
end
else
terrainVertexColors[i][j] = USE_BLIGHT and IsPointBlighted(x, y) and BLIGHT_CONVERTED_COLOR or BlzConvertColor(255, unpack(TERRAIN_TEXTURE_COLORS[terrainType]))
end
end
end
local function SetTerrainTileTexture(i, j)
local level
local numLevels
local terrainColor, terrainOccurrence
if i < worldMaxI and j < worldMaxJ then
for key, __ in pairs(occurrences) do
occurrences[key] = nil
end
colors[1] = terrainVertexColors[i+1][j]
colors[2] = terrainVertexColors[i+1][j+1]
colors[3] = terrainVertexColors[i][j+1]
colors[4] = terrainVertexColors[i][j]
for k = 1, 4 do
indices[k] = k
occurrences[colors[k]] = (occurrences[colors[k]] or 0) + 1
end
sort(indices, SortByOccurrence)
numLevels = 4
for k = 1, 4 do
sortedColors[k] = colors[indices[k]]
if sortedColors[k] == sortedColors[k-1] then
numLevels = numLevels - 1
end
end
level = numLevels
for k = 1, 4 do
terrainColor = sortedColors[k]
terrainOccurrence = occurrences[terrainColor]
if terrainColor ~= sortedColors[k-1] then
terrainTileColors[i][j][level] = terrainColor
terrainConnectionTypes[i][j][level] = ((occurrences[colors[1]] > terrainOccurrence or (occurrences[colors[1]] == terrainOccurrence and colors[1] >= terrainColor)) and 0 or 1)
+ ((occurrences[colors[2]] > terrainOccurrence or (occurrences[colors[2]] == terrainOccurrence and colors[2] >= terrainColor)) and 0 or 2)
+ ((occurrences[colors[3]] > terrainOccurrence or (occurrences[colors[3]] == terrainOccurrence and colors[3] >= terrainColor)) and 0 or 4)
+ ((occurrences[colors[4]] > terrainOccurrence or (occurrences[colors[4]] == terrainOccurrence and colors[4] >= terrainColor)) and 0 or 8)
level = level - 1
end
end
elseif i == worldMaxI then
if j == worldMaxJ then
terrainTileColors[i][j][1] = terrainVertexColors[i][j]
terrainConnectionTypes[i][j][1] = 0
else
colors[1] = terrainVertexColors[i][j+1]
colors[2] = terrainVertexColors[i][j]
if colors[1] == colors[2] then
terrainTileColors[i][j][1] = colors[1]
terrainConnectionTypes[i][j][1] = 0
else
terrainTileColors[i][j][1] = colors[1]
terrainTileColors[i][j][2] = colors[2]
terrainConnectionTypes[i][j][2] = 6
terrainConnectionTypes[i][j][1] = 0
end
end
else
colors[1] = terrainVertexColors[i][j]
colors[2] = terrainVertexColors[i+1][j]
if colors[1] == colors[2] then
terrainTileColors[i][j][1] = colors[1]
terrainConnectionTypes[i][j][1] = 0
else
terrainTileColors[i][j][1] = colors[1]
terrainTileColors[i][j][2] = colors[2]
terrainConnectionTypes[i][j][2] = 12
terrainConnectionTypes[i][j][1] = 0
end
end
end
local function UpdateTerrainTileTexture(i, j)
for k = 1, #terrainTileColors[i][j] do
terrainTileColors[i][j][k] = nil
terrainConnectionTypes[i][j][k] = nil
end
SetTerrainTileTexture(i, j)
local screenI, screenJ = ColumnOfTile(i), RowOfTile(j)
if screenI and screenJ then
local frameI, frameJ = FrameOfColumn(screenI), FrameOfRow(screenJ)
DrawFrame(minimapParentFrames[frameI][frameJ], minimapTextureFrames[frameI][frameJ], i, j)
end
end
local function UpdateTerrainVertexColor(i, j)
SetTerrainVertexColor(i, j, (i - 1)*128 + WORLD_MIN_X, (j - 1)*128 + WORLD_MIN_Y)
for I = max(1, i - 1), min(i + 1, worldMaxI) do
for J = max(1, j - 1), min(j + 1, worldMaxJ) do
UpdateTerrainTileTexture(I, J)
end
end
end
local function CreateTerrainMap()
local xMin = (WORLD_MIN_X // 128)*128
local yMin = (WORLD_MIN_Y // 128)*128
local xMax = (WORLD_MAX_X // 128)*128 + 1
local yMax = (WORLD_MAX_Y // 128)*128 + 1
local x = xMin
local y
local i = 1
local j
while x <= xMax do
terrainVertexColors[i] = {}
terrainTileColors[i] = {}
terrainConnectionTypes[i] = {}
if MINIMAP_MUST_BE_EXPLORED then
terrainIsExplored[i] = {}
end
overwriteTerrainColor[i] = {}
overwriteTrumpsFogOfWar[i] = {}
y = yMin
j = 1
while y <= yMax do
SetTerrainVertexColor(i, j, x, y)
terrainTileColors[i][j] = {}
terrainConnectionTypes[i][j] = {}
j = j + 1
y = y + 128
end
i = i + 1
x = x + 128
end
worldMaxI = i - 2
worldMaxJ = j - 2
for i = 1, worldMaxI do
for j = 1, worldMaxJ do
SetTerrainTileTexture(i, j)
end
end
end
local function CreateTerrainFrames()
local parentFrame = BlzGetOriginFrame(ORIGIN_FRAME_WORLD_FRAME, 0)
local newFrame
anchorColumn = 1
anchorRow = 1
firstColumn = 1
firstRow = 1
lastColumn = MINIMAP_NUM_FRAMES
lastRow = MINIMAP_NUM_FRAMES
for i = 1, MINIMAP_NUM_FRAMES do
minimapParentFrames[i] = {}
minimapTextureFrames[i] = {}
for j = 1, MINIMAP_NUM_FRAMES do
minimapParentFrames[i][j] = {}
minimapTextureFrames[i][j] = {}
for k = 1, 4 do
newFrame = BlzCreateSimpleFrame("MinimapTextureFrame", parentFrame, 0)
if k == 1 then
if i == 1 and j == 1 then
anchorFrame = newFrame
BlzFrameSetAbsPoint(newFrame, FRAMEPOINT_BOTTOMLEFT, MINIMAP_SCREEN_MIN_X, MINIMAP_SCREEN_MIN_Y)
else
BlzFrameSetPoint(newFrame, FRAMEPOINT_BOTTOMLEFT, anchorFrame, FRAMEPOINT_BOTTOMLEFT, (i - anchorColumn)*TERRAIN_FRAME_SIZE, (j - anchorRow)*TERRAIN_FRAME_SIZE)
end
else
BlzFrameSetPoint(newFrame, FRAMEPOINT_BOTTOMLEFT, minimapParentFrames[i][j][k-1], FRAMEPOINT_BOTTOMLEFT, 0, 0)
end
BlzFrameSetVisible(newFrame, false)
minimapParentFrames[i][j][k] = newFrame
minimapTextureFrames[i][j][k] = BlzGetFrameByName("MinimapTexture", 0)
end
end
end
end
local function ReanchorAllFrames()
local I
for i = 1, MINIMAP_NUM_FRAMES do
I = FrameOfColumn(i)
for j = 1, MINIMAP_NUM_FRAMES do
if i ~= anchorColumn or j ~= anchorRow then
BlzFrameSetPoint(minimapParentFrames[I][FrameOfRow(j)][1], FRAMEPOINT_BOTTOMLEFT, anchorFrame, FRAMEPOINT_BOTTOMLEFT, (i - anchorColumn)*TERRAIN_FRAME_SIZE, (j - anchorRow)*TERRAIN_FRAME_SIZE)
end
end
end
end
local function MinimapMoveLeft()
minWorldTileI = minWorldTileI - 1
anchorColumn = ModFrames(anchorColumn + 1)
firstColumn = lastColumn
lastColumn = ModFrames(lastColumn - 1)
if anchorColumn == 1 then
ReanchorAllFrames()
else
for j = 1, MINIMAP_NUM_FRAMES do
--Anchor new first column to anchorFrame.
if j ~= anchorRow or firstColumn ~= 1 then
BlzFrameSetPoint(minimapParentFrames[firstColumn][FrameOfRow(j)][1], FRAMEPOINT_BOTTOMLEFT, anchorFrame, FRAMEPOINT_BOTTOMLEFT, (1 - anchorColumn)*TERRAIN_FRAME_SIZE, (j - anchorRow)*TERRAIN_FRAME_SIZE)
end
end
end
local worldI = minWorldTileI + 1
local worldJ
local framesi = minimapParentFrames[firstColumn]
local framesij
local texturesi = minimapTextureFrames[firstColumn]
local texturesij
--Redraw new first column.
for j = 1, MINIMAP_NUM_FRAMES do
worldJ = minWorldTileJ + j
texturesij = texturesi[FrameOfRow(j)]
framesij = framesi[FrameOfRow(j)]
DrawFrame(framesij, texturesij, worldI, worldJ)
end
end
local function MinimapMoveRight()
minWorldTileI = minWorldTileI + 1
anchorColumn = ModFrames(anchorColumn - 1)
lastColumn = firstColumn
firstColumn = ModFrames(firstColumn + 1)
if anchorColumn == MINIMAP_NUM_FRAMES then
ReanchorAllFrames()
else
for j = 1, MINIMAP_NUM_FRAMES do
--Anchor new last column to anchorFrame.
if j ~= anchorRow or lastColumn ~= 1 then
BlzFrameSetPoint(minimapParentFrames[lastColumn][FrameOfRow(j)][1], FRAMEPOINT_BOTTOMLEFT, anchorFrame, FRAMEPOINT_BOTTOMLEFT, (MINIMAP_NUM_FRAMES - anchorColumn)*TERRAIN_FRAME_SIZE, (j - anchorRow)*TERRAIN_FRAME_SIZE)
end
end
end
local worldI = minWorldTileI + MINIMAP_NUM_FRAMES
local worldJ
local framesi = minimapParentFrames[lastColumn]
local framesij
local texturesi = minimapTextureFrames[lastColumn]
local texturesij
--Redraw new last column.
for j = 1, MINIMAP_NUM_FRAMES do
worldJ = minWorldTileJ + j
texturesij = texturesi[FrameOfRow(j)]
framesij = framesi[FrameOfRow(j)]
DrawFrame(framesij, texturesij, worldI, worldJ)
end
end
local function MinimapMoveDown()
minWorldTileJ = minWorldTileJ - 1
anchorRow = ModFrames(anchorRow + 1)
firstRow = lastRow
lastRow = ModFrames(lastRow - 1)
if anchorRow == 1 then
ReanchorAllFrames()
else
for i = 1, MINIMAP_NUM_FRAMES do
--Anchor new first row to anchorFrame.
if i ~= anchorColumn or firstRow ~= 1 then
BlzFrameSetPoint(minimapParentFrames[FrameOfColumn(i)][firstRow][1], FRAMEPOINT_BOTTOMLEFT, anchorFrame, FRAMEPOINT_BOTTOMLEFT, (i - anchorColumn)*TERRAIN_FRAME_SIZE, (1 - anchorRow)*TERRAIN_FRAME_SIZE)
end
end
end
local worldI
local worldJ = minWorldTileJ + 1
local framesij
local texturesij
--Redraw new first row.
for i = 1, MINIMAP_NUM_FRAMES do
worldI = minWorldTileI + i
texturesij = minimapTextureFrames[FrameOfColumn(i)][firstRow]
framesij = minimapParentFrames[FrameOfColumn(i)][firstRow]
DrawFrame(framesij, texturesij, worldI, worldJ)
end
end
local function MinimapMoveUp()
minWorldTileJ = minWorldTileJ + 1
anchorRow = ModFrames(anchorRow - 1)
lastRow = firstRow
firstRow = ModFrames(firstRow + 1)
if anchorRow == MINIMAP_NUM_FRAMES then
ReanchorAllFrames()
else
for i = 1, MINIMAP_NUM_FRAMES do
--Anchor new last row to anchorFrame.
if i ~= anchorColumn or lastRow ~= 1 then
BlzFrameSetPoint(minimapParentFrames[FrameOfColumn(i)][lastRow][1], FRAMEPOINT_BOTTOMLEFT, anchorFrame, FRAMEPOINT_BOTTOMLEFT, (i - anchorColumn)*TERRAIN_FRAME_SIZE, (MINIMAP_NUM_FRAMES - anchorRow)*TERRAIN_FRAME_SIZE)
end
end
end
local worldI
local worldJ = minWorldTileJ + MINIMAP_NUM_FRAMES
local framesij
local texturesij
--Redraw new last row.
for i = 1, MINIMAP_NUM_FRAMES do
worldI = minWorldTileI + i
texturesij = minimapTextureFrames[FrameOfColumn(i)][lastRow]
framesij = minimapParentFrames[FrameOfColumn(i)][lastRow]
DrawFrame(framesij, texturesij, worldI, worldJ)
end
end
---@param minimapArtist table
local function InitRenderMinimap(minimapArtist)
local x, y = ALICE_GetCoordinates2D(minimapArtist)
local minx = x - MINIMAP_WORLD_DIAMETER/2
local miny = y - MINIMAP_WORLD_DIAMETER/2
local miniReal = (minx - WORLD_MIN_X) / 128
local minjReal = (miny - WORLD_MIN_Y) / 128
local mini = miniReal // 1
local minj = minjReal // 1
minWorldTileI = mini
minWorldTileJ = minj
local framesi, framesij
local texturesi, texturesij
ALICE_CallDelayed(function()
local worldI, worldJ
for i = 1, MINIMAP_NUM_FRAMES do
worldI = mini + i
framesi = minimapParentFrames[i]
texturesi = minimapTextureFrames[i]
for j = 1, MINIMAP_NUM_FRAMES do
worldJ = minj + j
framesij = framesi[j]
texturesij = texturesi[j]
DrawFrame(framesij, texturesij, worldI, worldJ)
end
end
end, 0)
if STATIC_MINIMAP then
ALICE_PairDisable()
end
end
---@param minimapArtist table
local function RenderMinimap(minimapArtist)
if not minimapShown then
return
end
local x, y = ALICE_GetCoordinates2D(minimapArtist)
local minx = x - MINIMAP_WORLD_DIAMETER/2
local miny = y - MINIMAP_WORLD_DIAMETER/2
local miniReal = (minx - WORLD_MIN_X) / 128
local minjReal = (miny - WORLD_MIN_Y) / 128
local mini = miniReal // 1
local minj = minjReal // 1
local fractionX = miniReal - mini
local fractionY = minjReal - minj
while minWorldTileI > mini do
MinimapMoveLeft()
end
while minWorldTileI < mini do
MinimapMoveRight()
end
while minWorldTileJ > minj do
MinimapMoveDown()
end
while minWorldTileJ < minj do
MinimapMoveUp()
end
BlzFrameSetAbsPoint(anchorFrame, FRAMEPOINT_BOTTOMLEFT, MINIMAP_SCREEN_MIN_X + (anchorColumn - 1 - fractionX)*TERRAIN_FRAME_SIZE, MINIMAP_SCREEN_MIN_Y + (anchorRow - 1 - fractionY)*TERRAIN_FRAME_SIZE)
end
---@param whichObject Object
local function ExploreMinimap(whichObject)
if minimapInitialized then
local x, y = ALICE_GetCoordinates2D(whichObject)
RPGMinimap.RevealCircle(x, y, MINIMAP_REVELATION_RADIUS, CHECK_FOG_OF_WAR_BEFORE_REVEALING)
end
return 0.25
end
--===========================================================================================================================================================
--Frame Recycler
--===========================================================================================================================================================
local function RequestFrame(parent, texture, size, level, color, name, dx, dy)
if #unusedFrames == 0 then
if bj_isSinglePlayer then
parent.frames = {}
parent.frames.parent = BlzCreateSimpleFrame("MinimapTextureFrame", BlzGetOriginFrame(ORIGIN_FRAME_GAME_UI, 0), 0)
parent.frames.texture = BlzGetFrameByName("MinimapTexture", 0)
if CREATE_TOOLTIPS then
parent.frames.hover = BlzCreateFrameByType("FRAME" , "drawableHover" , BlzGetOriginFrame(ORIGIN_FRAME_GAME_UI, 0) , "" , 0)
BlzFrameSetAllPoints(parent.frames.hover, parent.frames.parent)
parent.frames.tooltip = BlzCreateFrame("TextMessage", parent.frames.hover, 0, 0)
parent.frames.text = BlzFrameGetChild(parent.frames.tooltip, 0)
parent.frames.box = BlzFrameGetChild(parent.frames.tooltip, 1)
BlzFrameSetTooltip(parent.frames.hover, parent.frames.tooltip)
end
else
print("|cffff0000Warning:|r Not enough frames allocated for RPG Minimap. Increase NUMBER_OF_PREALLOCATED_FRAMES.")
return false
end
else
parent.frames = unusedFrames[#unusedFrames]
unusedFrames[#unusedFrames] = nil
end
BlzFrameSetVisible(parent.frames.parent, true)
BlzFrameSetVisible(parent.frames.hover, true)
BlzFrameSetSize(parent.frames.parent, size, size)
BlzFrameSetLevel(parent.frames.parent, level)
BlzFrameSetLevel(parent.frames.hover, level)
BlzFrameSetTexture(parent.frames.texture, texture, 0, true)
BlzFrameSetVertexColor(parent.frames.texture, BlzConvertColor(255, unpack(color)))
if CREATE_TOOLTIPS and name then
SetTooltipText(parent.frames, name, dx, dy)
end
return true
end
local function ReturnFrame(parent)
unusedFrames[#unusedFrames + 1] = parent.frames
BlzFrameSetVisible(parent.frames.parent, false)
BlzFrameSetVisible(parent.frames.hover, false)
end
--===========================================================================================================================================================
--Minimap Icon
--===========================================================================================================================================================
---@param minimapArtist table
---@param drawable any
local function DrawMinimapIcon(minimapArtist, drawable)
if not minimapShown then
ALICE_PairReset()
ALICE_PairPause()
return
end
local owner = ALICE_GetOwner(drawable)
local isDrawn = not (owner and not (HandleType[drawable] == "unit" and MINIMAP_WIDGET_TYPE_EXCEPTIONS[GetUnitTypeId(drawable)]) and ((DO_NOT_DRAW_ALLIES and owner ~= localPlayer and IsPlayerAlly(owner, localPlayer)) or (DO_NOT_DRAW_ENEMIES and IsPlayerEnemy(owner, localPlayer)) or (DO_NOT_DRAW_NEUTRALS and owner == playerNeutralPassive)))
if not isDrawn then
ALICE_PairPause()
return
end
local x, y = ALICE_GetCoordinates2D(drawable)
local screenX, screenY, visible = World2MinimapCoordinates(x, y, sizeCache[drawable], ALICE_GetCoordinates2D(minimapArtist))
isVisible[drawable] = visible and (visibilityRadiusCache[drawable] == -1 or ALICE_PairGetDistance2D() < visibilityRadiusCache[drawable]) and (waypointMarkerOf[drawable] ~= nil or (not MINIMAP_MUST_BE_EXPLORED or terrainIsExplored[(x - WORLD_MIN_X) // 128 + 1][(y - WORLD_MIN_Y) // 128 + 1])) and (HandleType[drawable] ~= "unit" or not IsUnitInvisible(drawable))
if isVisible[drawable] then
local data = ALICE_PairLoadData()
if ALICE_PairIsFirstContact() then
if not RequestFrame(data, textureCache[drawable], sizeCache[drawable], levelCache[drawable], colorCache[drawable], nameCache[drawable], 0, 0) then
ALICE_PairDisable()
return
end
if type(drawable) == "table" and drawable.onFirstReveal then
drawable.onFirstReveal(drawable)
drawable.onFirstReveal = nil
end
end
BlzFrameSetAbsPoint(data.frames.parent, FRAMEPOINT_CENTER, screenX, screenY)
else
ALICE_PairReset()
end
end
---@param minimapArtist table
---@param drawable any
---@param data table
local function DrawMinimapIconOnReset(minimapArtist, drawable, data)
isVisible[drawable] = false
ReturnFrame(data)
end
--===========================================================================================================================================================
--Minimap Marker
--===========================================================================================================================================================
---@param minimapArtist table
---@param waypointMarker WaypointMarker
local function InitDrawWaypointMarker(minimapArtist, waypointMarker)
if not RequestFrame(waypointMarker, waypointMarker.texture .. "0.blp", WAYPOINT_MARKER_SIZE, WAYPOINT_MARKER_LEVEL, waypointMarker.color or TINTING_COLOR_WHITE, nameCache[waypointMarker.anchor], -0.2*WAYPOINT_MARKER_SIZE, -0.2*WAYPOINT_MARKER_SIZE) then
ALICE_PairDisable()
end
end
local function AdjustWaypointMarker(waypointMarker, x, y, angle)
if angle < 0 then
angle = angle + 2*bj_PI
end
local index = (math.floor((bj_RADTODEG*angle) / WAYPOINT_MARKER_ANGLE_SPACING + 0.5))*WAYPOINT_MARKER_ANGLE_SPACING
if index == 360 then
index = 0
end
BlzFrameSetVisible(waypointMarker.frames.parent, true)
if CREATE_TOOLTIPS then
BlzFrameSetVisible(waypointMarker.frames.hover, true)
end
BlzFrameSetTexture(waypointMarker.frames.texture, waypointMarker.texture .. index .. ".blp", 0, true)
BlzFrameSetAbsPoint(waypointMarker.frames.parent, FRAMEPOINT_CENTER, x, y)
end
---@param minimapArtist table
---@param waypointMarker WaypointMarker
local function DrawWaypointMarker(minimapArtist, waypointMarker)
if not minimapShown then
ALICE_PairPause()
BlzFrameSetVisible(waypointMarker.frames.parent, false)
if CREATE_TOOLTIPS then
BlzFrameSetVisible(waypointMarker.frames.hover, false)
end
return
end
local angle
local drawable = waypointMarker.anchor
local owner = ALICE_GetOwner(drawable)
local isDrawn = not (owner and not (IsWidget[drawable] and MINIMAP_WIDGET_TYPE_EXCEPTIONS[drawable]) and ((DO_NOT_DRAW_ALLIES and IsPlayerAlly(owner, localPlayer)) or (DO_NOT_DRAW_ENEMIES and IsPlayerEnemy(owner, localPlayer)) or (DO_NOT_DRAW_NEUTRALS and owner == playerNeutralPassive)))
if isDrawn and not isVisible[drawable] and cameraTranslocationZone == translocationZoneOf[drawable] then
angle = ALICE_PairGetAngle2D()
local screenX = MINIMAP_CENTER_X + (MINIMAP_SCREEN_DIAMETER/2 - WAYPOINT_MARKER_SIZE/2)*SquareCos(angle)
local screenY = MINIMAP_CENTER_Y + (MINIMAP_SCREEN_DIAMETER/2 - WAYPOINT_MARKER_SIZE/2)*SquareSin(angle)
AdjustWaypointMarker(waypointMarker, screenX, screenY, angle)
elseif cameraTranslocationZone and cameraTranslocationZone.hasExit and not ALICE_HasIdentifier(drawable, "translocatedClone", "drawable") and cameraTranslocationZone ~= translocationZoneOf[drawable] and not IsZoneChild(cameraTranslocationZone, translocationZoneOf[drawable]) then
local x, y = ALICE_GetCoordinates2D(minimapArtist)
local screenX, screenY, visible = World2MinimapCoordinates(cameraTranslocationZone.exitX, cameraTranslocationZone.exitY, 0, x, y)
angle = math.atan(cameraTranslocationZone.exitY - y, cameraTranslocationZone.exitX - x)
screenX = MINIMAP_CENTER_X + (MINIMAP_SCREEN_DIAMETER/2 - WAYPOINT_MARKER_SIZE/2)*SquareCos(angle)
screenY = MINIMAP_CENTER_Y + (MINIMAP_SCREEN_DIAMETER/2 - WAYPOINT_MARKER_SIZE/2)*SquareSin(angle)
AdjustWaypointMarker(waypointMarker, screenX, screenY, angle)
else
BlzFrameSetVisible(waypointMarker.frames.parent, false)
if CREATE_TOOLTIPS then
BlzFrameSetVisible(waypointMarker.frames.hover, false)
end
end
end
---@param minimapArtist table
---@param waypointMarker WaypointMarker
local function DrawWaypointMarkerOnDestroy(minimapArtist, waypointMarker)
ReturnFrame(waypointMarker)
end
--===========================================================================================================================================================
--Translocation
--===========================================================================================================================================================
---@param translocator Translocator
---@param minimapArtist table
local function SetCameraTranslocationZone(translocator, minimapArtist)
cameraTranslocationZone = translocator
return ALICE_Config.MAX_INTERVAL
end
---@param translocator Translocator
---@param minimapArtist table
local function SetCameraTranslocationZoneOnBreak(translocator, minimapArtist)
if cameraTranslocationZone == translocator then
cameraTranslocationZone = nil
end
end
-------------------------------------------------------------------------------------------------------------------------------------------------------------
---@param translocator Translocator
---@param drawable any
local function TranslocateMinimapIcon(translocator, drawable)
local x, y = ALICE_GetCoordinates2D(drawable)
if CAT_IsPointInRect(x, y, translocator) then
local xTarget = translocator.targetMinX + translocator.targetWidth*(1 - (translocator.maxX - x)/translocator.width)
local yTarget = translocator.targetMinY + translocator.targetHeight*(1 - (translocator.maxY - y)/translocator.height)
if ALICE_PairIsFirstContact() then
translocationZoneOf[drawable] = translocator
local clone = {}
clone.x = xTarget
clone.y = yTarget
clone.identifier = {
"drawable",
"translocatedClone"
}
clone.owner = ALICE_GetOwner(drawable, "drawable")
textureCache[clone] = textureCache[drawable]
sizeCache[clone] = sizeCache[drawable]
levelCache[clone] = levelCache[drawable]
visibilityRadiusCache[clone] = visibilityRadiusCache[drawable]
nameCache[clone] = nameCache[drawable]
colorCache[clone] = colorCache[drawable]
ALICE_Create(clone)
local data = ALICE_PairLoadData()
data.clone = clone
translocatedCloneOf[drawable] = clone
if waypointMarkerOf[drawable] then
RPGMinimap.AddWaypointMarker(clone, waypointMarkerOf[drawable].texture, waypointMarkerOf[drawable].color)
end
else
local data = ALICE_PairLoadData()
data.clone.x = xTarget
data.clone.y = yTarget
end
else
ALICE_PairReset()
end
end
---@param translocator Translocator
---@param drawable any
---@param data table
local function TranslocateMinimapIconOnReset(translocator, drawable, data)
if translocationZoneOf[drawable] == translocator then
translocationZoneOf[drawable] = nil
translocatedCloneOf[drawable] = nil
end
ALICE_Kill(data.clone)
data.clone = nil
end
--===========================================================================================================================================================
--Init
--===========================================================================================================================================================
local function OnCreationUnitAddIdentifier(unit)
return ShouldUnitBeDrawn(unit) and "drawable" or nil
end
local function OnCreationDestructableAddIdentifier(destructable)
return ShouldDestructableBeDrawn(destructable) and "drawable" or nil
end
local function OnCreationItemAddIdentifier(item)
return ShouldItemBeDrawn(item) and "drawable" or nil
end
local function BeforeAliceInit()
Require "TerrainTextureColors"
if not BlzLoadTOCFile("RPGMinimapFrames.toc") then
print("|cffff0000Warning:|r TOC file RPGMinimapFrames.toc failed to load. Did you remove the war3mapImported subpath? Does the .toc file have an empty line at the bottom?")
return
end
if STATIC_MINIMAP then
WORLD_MIN_X = STATIC_MIN_X and (STATIC_MIN_X // 128)*128 or GetRectMinX(bj_mapInitialPlayableArea)
WORLD_MIN_Y = STATIC_MIN_Y and (STATIC_MIN_Y // 128)*128 or GetRectMinY(bj_mapInitialPlayableArea)
WORLD_MAX_X = STATIC_MAX_X and (STATIC_MAX_X // 128)*128 or GetRectMaxX(bj_mapInitialPlayableArea)
WORLD_MAX_Y = STATIC_MAX_Y and (STATIC_MAX_Y // 128)*128 or GetRectMaxY(bj_mapInitialPlayableArea)
MINIMAP_NUMBER_OF_TILES = max(WORLD_MAX_X - WORLD_MIN_X, WORLD_MAX_Y - WORLD_MIN_Y) // 128
MINIMAP_WORLD_DIAMETER = 128*MINIMAP_NUMBER_OF_TILES
MINIMAP_NUM_FRAMES = MINIMAP_NUMBER_OF_TILES + 1
TERRAIN_FRAME_SIZE = MINIMAP_SCREEN_DIAMETER/MINIMAP_NUMBER_OF_TILES
else
WORLD_MIN_X = GetRectMinX(bj_mapInitialPlayableArea)
WORLD_MIN_Y = GetRectMinY(bj_mapInitialPlayableArea)
WORLD_MAX_X = GetRectMaxX(bj_mapInitialPlayableArea)
WORLD_MAX_Y = GetRectMaxY(bj_mapInitialPlayableArea)
MINIMAP_WORLD_DIAMETER = 128*MINIMAP_NUMBER_OF_TILES
MINIMAP_NUM_FRAMES = MINIMAP_NUMBER_OF_TILES + 1
TERRAIN_FRAME_SIZE = MINIMAP_SCREEN_DIAMETER/MINIMAP_NUMBER_OF_TILES
end
if HIDE_INACCESSIBLE_TERRAIN then
if OnPathabilityUpdate then
OnPathabilityUpdate(function(x, y, __)
UpdateTerrainVertexColor((x - WORLD_MIN_X) // 128 + 1, (y - WORLD_MIN_Y) // 128 + 1)
end)
else
print("|cffff0000Warning:|r HIDE_INACCESSIBLE_TERRAIN requires PathingWizard.")
HIDE_INACCESSIBLE_TERRAIN = false
end
end
BLACK_CONVERTED_COLOR = BlzConvertColor(255, 0, 0, 0)
BLIGHT_CONVERTED_COLOR = BlzConvertColor(255, unpack(BLIGHT_COLOR))
FOG_OF_WAR_CONVERTED_COLOR = BlzConvertColor(255, unpack(FOG_OF_WAR_COLOR))
playerNeutralPassive = Player(PLAYER_NEUTRAL_PASSIVE)
localPlayer = GetLocalPlayer()
local keys = {}
for __, fourCC in ipairs(MINIMAP_WIDGET_TYPE_EXCEPTIONS) do
---@diagnostic disable-next-line: assign-type-mismatch
MINIMAP_WIDGET_TYPE_EXCEPTIONS[FourCC(fourCC)] = true
end
for fourCC, texture in pairs(MINIMAP_WIDGET_TYPE_TEXTURE) do
keys[fourCC] = texture
end
for fourCC, texture in pairs(keys) do
MINIMAP_WIDGET_TYPE_TEXTURE[FourCC(fourCC)] = texture
keys[fourCC] = nil
end
for fourCC, size in pairs(MINIMAP_WIDGET_TYPE_SIZE) do
keys[fourCC] = size
end
for fourCC, size in pairs(keys) do
MINIMAP_WIDGET_TYPE_SIZE[FourCC(fourCC)] = size
keys[fourCC] = nil
end
for fourCC, visibilityRadius in pairs(MINIMAP_WIDGET_TYPE_VISIBILITY_RADIUS) do
keys[fourCC] = visibilityRadius
end
for fourCC, visibilityRadius in pairs(keys) do
MINIMAP_WIDGET_TYPE_VISIBILITY_RADIUS[FourCC(fourCC)] = visibilityRadius
keys[fourCC] = nil
end
for fourCC, level in pairs(MINIMAP_WIDGET_TYPE_LEVEL) do
keys[fourCC] = level
end
for fourCC, level in pairs(keys) do
MINIMAP_WIDGET_TYPE_LEVEL[FourCC(fourCC)] = level
keys[fourCC] = nil
end
for fourCC, color in pairs(MINIMAP_WIDGET_TYPE_COLOR) do
keys[fourCC] = color
end
for fourCC, color in pairs(keys) do
MINIMAP_WIDGET_TYPE_COLOR[FourCC(fourCC)] = color
keys[fourCC] = nil
end
if not bj_isSinglePlayer then
for i = 1, NUMBER_OF_PREALLOCATED_FRAMES do
unusedFrames[i] = {}
unusedFrames[i].parent = BlzCreateSimpleFrame("MinimapTextureFrame", BlzGetOriginFrame(ORIGIN_FRAME_GAME_UI, 0), 0)
unusedFrames[i].texture = BlzGetFrameByName("MinimapTexture", 0)
BlzFrameSetVisible(unusedFrames[i].parent, false)
if CREATE_TOOLTIPS then
unusedFrames[i].hover = BlzCreateFrameByType("FRAME" , "drawableHover" , unusedFrames[i].parent, "", 0)
BlzFrameSetAllPoints(unusedFrames[i].hover, unusedFrames[i].parent)
unusedFrames[i].tooltip = BlzCreateFrame("TextMessage", unusedFrames[i].parent, 0, 0)
unusedFrames[i].text = BlzFrameGetChild(unusedFrames[i].tooltip, 0)
unusedFrames[i].box = BlzFrameGetChild(unusedFrames[i].tooltip, 1)
BlzFrameSetVisible(unusedFrames[i].tooltip, false)
end
end
end
ALICE_OnCreationAddIdentifier("unit", OnCreationUnitAddIdentifier)
ALICE_OnCreationAddIdentifier("destructable", OnCreationDestructableAddIdentifier)
ALICE_OnCreationAddIdentifier("item", OnCreationItemAddIdentifier)
if ALICE_Config.UNITS_LEAVE_BEHIND_CORPSES then
ALICE_OnWidgetEvent({
onUnitDeath = function(unit)
ALICE_SwapIdentifier(unit, "drawable", "deadDrawable", "corpse")
end,
onUnitRevive = function(unit)
ALICE_SwapIdentifier(unit, "deadDrawable", "drawable", "unit")
end,
})
end
ALICE_OnWidgetEvent({
onUnitChangeOwner = function(unit)
ClearAllCaches(unit)
ALICE_UnpausePair(unit, MinimapArtist, "drawable", "minimapArtist")
if translocatedCloneOf[unit] then
ALICE_GetPairAndDo(ALICE_PairReset, translocatedCloneOf[unit], translocationZoneOf[unit], "drawable", "translocator")
end
end
})
ALICE_FuncSetOnReset(DrawMinimapIcon, DrawMinimapIconOnReset)
ALICE_FuncSetInit(RenderMinimap, InitRenderMinimap)
ALICE_FuncSetOnReset(TranslocateMinimapIcon, TranslocateMinimapIconOnReset)
ALICE_FuncSetOnBreak(SetCameraTranslocationZone, SetCameraTranslocationZoneOnBreak)
ALICE_FuncSetInit(DrawWaypointMarker, InitDrawWaypointMarker)
ALICE_FuncSetOnDestroy(DrawWaypointMarker, DrawWaypointMarkerOnDestroy)
ALICE_FuncSetUnsuspendable(DrawWaypointMarker)
ALICE_FuncDistribute(ExploreMinimap, 0.25)
ALICE_FuncSetName(RenderMinimap, "RenderMinimap")
ALICE_FuncSetName(DrawMinimapIcon, "DrawMinimapIcon")
ALICE_FuncSetName(SetCameraTranslocationZone, "SetCameraTranslocationZone")
ALICE_FuncSetName(TranslocateMinimapIcon, "TranslocateMinimapIcon")
ALICE_FuncSetName(DrawWaypointMarker, "DrawWaypointMarker")
ALICE_FuncSetName(ExploreMinimap, "ExploreMinimap")
if CAMERA_IS_EXPLORER then
ALICE_OnCreationAddSelfInteraction("camera", ExploreMinimap)
end
minimapPreInit = true
if AUTO_RUN then
if HIDE_INACCESSIBLE_TERRAIN then
Require "PathingWizard"
end
CreateTerrainMap()
end
end
local function AfterAliceInit()
if not AUTO_RUN then
return
end
Require "ALICE"
Require "CAT_Camera"
Require "CAT_Rects"
RPGMinimap.Init()
end
OnInit.global(BeforeAliceInit)
OnInit.final("RPGMinimap", AfterAliceInit)
--===========================================================================================================================================================
--API
--===========================================================================================================================================================
RPGMinimap = {
---Creates a minimap icon attached to the specified object.
---@param whichObject Object
---@param texture string
---@param size number
---@param level integer
---@param flags? table
---@return MinimapIcon
AddIconTarget = function(whichObject, texture, size, level, flags)
local self = {
identifier = {"drawable", "minimapIcon"},
anchor = whichObject,
radius = 0,
texture = texture,
size = size,
level = level,
name = nameCache[whichObject],
}
if flags then
self.visibilityRadius = flags.visibilityRadius
self.name = flags.name or self.name
self.color = flags.color
self.owner = flags.owner
self.onFirstReveal = flags.onFirstReveal
table.insert(self.identifier, flags.identifier)
for flag, value in pairs(flags) do
if not NATIVE_FLAGS[flag] then
self[flag] = value
end
end
end
ALICE_Create(self)
return self
end,
---Creates a minimap icon at the specified coordinates.
---@param x number
---@param y number
---@param texture string
---@param size number
---@param level integer
---@param flags? table
---@return MinimapIcon
AddIconLoc = function(x, y, texture, size, level, flags)
local self = {
identifier = {"drawable", "minimapIcon"},
x = x,
y = y,
radius = 0,
isStationary = true,
texture = texture,
size = size,
level = level,
}
if flags then
self.visibilityRadius = flags.visibilityRadius
self.name = flags.name
self.color = flags.color
self.owner = flags.owner
self.onFirstReveal = flags.onFirstReveal
table.insert(self.identifier, flags.identifier)
for flag, value in pairs(flags) do
if not NATIVE_FLAGS[flag] then
self[flag] = value
end
end
end
ALICE_Create(self)
return self
end,
---Removes a minimap icon.
---@param whichObject MinimapIcon | unit | destructable | item | table
RemoveIcon = function(whichObject)
if ALICE_HasIdentifier(whichObject, "minimapIcon", "drawable") then
ALICE_Kill(whichObject)
else
ALICE_RemoveIdentifier(whichObject, "drawable", "drawable")
end
end,
---Creates a translocator zone that clones all objects inside originRect to also appear inside targetRect. If one of the rects is a table, it must have the minX, minY, maxX, and maxY fields set. Optional exit parameter to define a location where waypoint markers of objects in a parent zone are pointing to. If exit is a table, it must contain a pair of coordinates. Optional parent parameter to define the zone entered through the exit if it not the overworld.
---@param originRect rect | table
---@param targetRect rect | table
---@param exit? rect | table
---@param parent? Translocator
---@return Translocator
CreateTranslocatorZone = function(originRect, targetRect, exit, parent)
local self = {} ---@type Translocator
if IsHandle[targetRect] then
self.targetMinX = GetRectMinX(targetRect)
self.targetMinY = GetRectMinY(targetRect)
self.targetMaxX = GetRectMaxX(targetRect)
self.targetMaxY = GetRectMaxY(targetRect)
else
self.targetMinX = targetRect.minX
self.targetMinY = targetRect.minY
self.targetMaxX = targetRect.maxX
self.targetMaxY = targetRect.maxY
end
if exit then
self.hasExit = true
if IsHandle[exit] then
self.exitX = GetRectCenterX(exit)
self.exitY = GetRectCenterY(exit)
else
self.exitX = exit[1]
self.exitY = exit[2]
end
if parent then
self.parent = parent
repeat
table.insert(parent.children, self)
parent = parent.parent
until parent == nil
end
end
self.targetWidth = self.targetMaxX - self.targetMinX
self.targetHeight = self.targetMaxY - self.targetMinY
self.identifier = "translocator"
self.interactions = {
minimapArtist = SetCameraTranslocationZone,
drawable = TranslocateMinimapIcon,
}
self.children = {}
if IsHandle[originRect] then
CAT_CreateFromRect(originRect, self)
else
self.minX = originRect.minX
self.minY = originRect.minY
self.maxX = originRect.maxX
self.maxY = originRect.maxY
CAT_CreateFromRect(self)
end
return self
end,
---Overwrites the terrain color in the specified rect to the specified color, a table containing three integers for red, green, and blue (0-255). If rect is a table, it must have the minX, minY, maxX, and maxY fields set. Optional trumpsFogOfWar parameter to overwrite the fog of war color.
---@param rect rect | table
---@param color table
---@param trumpsFogOfWar? boolean
OverwriteTerrainColor = function(rect, color, trumpsFogOfWar)
local minI, minJ, maxI, maxJ
if IsHandle[rect] then
minI = max(1, min(worldMaxI, (GetRectMinX(rect) - WORLD_MIN_X) // 128 + 1))
minJ = max(1, min(worldMaxJ, (GetRectMinY(rect) - WORLD_MIN_Y) // 128 + 1))
maxI = max(1, min(worldMaxI, (GetRectMaxX(rect) - WORLD_MIN_X) // 128 + 1))
maxJ = max(1, min(worldMaxJ, (GetRectMaxY(rect) - WORLD_MIN_Y) // 128 + 1))
else
minI = max(1, min(worldMaxI, (rect.minX - WORLD_MIN_X) // 128 + 1))
minJ = max(1, min(worldMaxJ, (rect.minY - WORLD_MIN_Y) // 128 + 1))
maxI = max(1, min(worldMaxI, (rect.maxX - WORLD_MIN_X) // 128 + 1))
maxJ = max(1, min(worldMaxJ, (rect.maxY - WORLD_MIN_Y) // 128 + 1))
end
local convertedColor = BlzConvertColor(255, unpack(color))
for i = minI, maxI do
for j = minJ, maxJ do
overwriteTerrainColor[i][j] = convertedColor
if trumpsFogOfWar then
overwriteTrumpsFogOfWar[i][j] = true
end
UpdateTerrainVertexColor(i, j)
end
end
end,
---Creates a waypoint marker attached to the specified object. Optional color parameter to specify the tinting color of the waypoint marker. It must be a table containing three integers for red, green, and blue (0-255).
---@param whichObject unit | destructable | item | table
---@param texture string
---@param color? table
AddWaypointMarker = function(whichObject, texture, color)
--Safety delay because unit actors are not available immediately as they are created with unit enters map trigger.
if waypointMarkerOf[whichObject] then
return
end
if not ALICE_HasActor(whichObject, "drawable", true) then
print("|cffff0000Warning:|r Attempted to add minimap marker to object, but that object is not being drawn on the minimap.")
return
end
local self = { ---@type WaypointMarker
identifier = "waypointMarker",
anchor = whichObject,
hasInfiniteRange = true,
texture = texture,
color = color
}
waypointMarkerOf[whichObject] = self
ALICE_Create(self)
if translocatedCloneOf[whichObject] then
RPGMinimap.AddWaypointMarker(translocatedCloneOf[whichObject], texture, color)
end
end,
---Removes the waypoint marker that is attached to the specified object.
---@param whichObject unit | destructable | item | table
RemoveWaypointMarker = function(whichObject)
if waypointMarkerOf[whichObject] == nil then
return
end
ALICE_Kill(waypointMarkerOf[whichObject])
waypointMarkerOf[whichObject] = nil
if translocatedCloneOf[whichObject] then
RPGMinimap.RemoveWaypointMarker(translocatedCloneOf[whichObject])
end
end,
---Sets the texture of the minimap icon attached to the specified object. If no texture is provided, resets it to the default value.
---@param whichObject MinimapIcon | unit | destructable | item | table
---@param texture? string
SetObjectTexture = function(whichObject, texture)
if texture == nil then
textureCache[whichObject] = nil
texture = textureCache[whichObject]
else
textureCache[whichObject] = texture
end
local data = ALICE_AccessData(whichObject, MinimapArtist, "drawable", "minimapArtist")
if data then
BlzFrameSetTexture(data.frames.texture, texture, 0, true)
else
print("|cffff0000Warning:|r Attempted to change the texture of an object that is not being drawn on the minimap.")
end
if translocatedCloneOf[whichObject] then
textureCache[translocatedCloneOf[whichObject]] = texture
data = ALICE_AccessData(translocatedCloneOf[whichObject], MinimapArtist, "drawable", "minimapArtist")
if data then
BlzFrameSetTexture(data.frames.texture, texture, 0, true)
end
end
end,
---Sets the size of the minimap icon attached to the specified object. If no value is provided, resets it to the default value.
---@param whichObject MinimapIcon | unit | destructable | item | table
---@param size? number
SetObjectSize = function(whichObject, size)
if size == nil then
sizeCache[whichObject] = nil
size = sizeCache[whichObject]
else
sizeCache[whichObject] = size
end
local data = ALICE_AccessData(whichObject, MinimapArtist, "drawable", "minimapArtist")
if data then
BlzFrameSetSize(data.frames.parent, size, size)
else
print("|cffff0000Warning:|r Attempted to change the size of an object that is not being drawn on the minimap.")
end
if translocatedCloneOf[whichObject] then
sizeCache[translocatedCloneOf[whichObject]] = size
data = ALICE_AccessData(translocatedCloneOf[whichObject], MinimapArtist, "drawable", "minimapArtist")
if data then
BlzFrameSetSize(data.frames.parent, size, size)
end
end
end,
---Sets the visibility radius of the minimap icon attached to the specified object. If no value is provided, resets it to the default value.
---@param whichObject MinimapIcon | unit | destructable | item | table
---@param radius? number
SetObjectVisibilityRadius = function(whichObject, radius)
if radius == nil then
visibilityRadiusCache[whichObject] = nil
radius = visibilityRadiusCache[whichObject]
else
visibilityRadiusCache[whichObject] = radius
end
local data = ALICE_AccessData(whichObject, MinimapArtist, "drawable", "minimapArtist")
if data then
BlzFrameSetSize(data.frames.parent, radius, radius)
else
print("|cffff0000Warning:|r Attempted to change the visibility radius of an object that is not being drawn on the minimap.")
end
if translocatedCloneOf[whichObject] then
visibilityRadiusCache[translocatedCloneOf[whichObject]] = radius
data = ALICE_AccessData(translocatedCloneOf[whichObject], MinimapArtist, "drawable", "minimapArtist")
if data then
BlzFrameSetSize(data.frames.parent, radius, radius)
end
end
end,
---Sets the frame level of the minimap icon attached to the specified object. If no value is provided, resets it to the default value.
---@param whichObject MinimapIcon | unit | destructable | item | table
---@param level? integer
SetObjectLevel = function(whichObject, level)
if level == nil then
levelCache[whichObject] = nil
level = levelCache[whichObject]
else
levelCache[whichObject] = level
end
local data = ALICE_AccessData(whichObject, MinimapArtist, "drawable", "minimapArtist")
if data then
BlzFrameSetLevel(data.frames.parent, level)
else
print("|cffff0000Warning:|r Attempted to change the level of an object that is not being drawn on the minimap.")
end
if translocatedCloneOf[whichObject] then
levelCache[translocatedCloneOf[whichObject]] = level
data = ALICE_AccessData(translocatedCloneOf[whichObject], MinimapArtist, "drawable", "minimapArtist")
if data then
BlzFrameSetLevel(data.frames.parent, level)
end
end
end,
---Sets the tooltip name of the minimap icon attached to the specified object. If no name is provided, resets it to the default value. Set to an empty string to remove name.
---@param whichObject MinimapIcon | unit | destructable | item | table
---@param name? string
SetObjectName = function(whichObject, name)
if name == nil then
nameCache[whichObject] = nil
name = nameCache[whichObject]
else
nameCache[whichObject] = name
end
local data = ALICE_AccessData(whichObject, MinimapArtist, "drawable", "minimapArtist")
if data then
SetTooltipText(data.frames, name)
else
print("|cffff0000Warning:|r Attempted to change the name of an object that is not being drawn on the minimap.")
end
if translocatedCloneOf[whichObject] then
nameCache[translocatedCloneOf[whichObject]] = name
data = ALICE_AccessData(translocatedCloneOf[whichObject], MinimapArtist, "drawable", "minimapArtist")
if data then
SetTooltipText(data.frames, name)
end
end
end,
---Reveal the map in a rectangular area. Can be called asynchronously.
---@param minX number
---@param minY number
---@param maxX number
---@param maxY number
---@param checkFogOfWar? boolean
RevealRect = function(minX, minY, maxX, maxY, checkFogOfWar)
local iMin = (minX - WORLD_MIN_X) // 128 + 1
local jMin = (minY - WORLD_MIN_Y) // 128 + 1
local iMax = (maxX - WORLD_MIN_X) // 128 + 1
local jMax = (maxY - WORLD_MIN_Y) // 128 + 1
for worldI = iMin, iMax do
for worldJ = jMin, jMax do
if not terrainIsExplored[worldI][worldJ] and (not checkFogOfWar or IsVisibleToPlayer(WORLD_MIN_X + (worldI - 1)*128, WORLD_MIN_Y + (worldJ - 1)*128, localPlayer)) then
terrainIsExplored[worldI][worldJ] = true
UpdateTerrainVertexColor(worldI, worldJ)
end
end
end
end,
---Reveal the map in a circular area. Can be called asynchronously.
---@param x number
---@param y number
---@param radius number
---@param checkFogOfWar? boolean
RevealCircle = function(x, y, radius, checkFogOfWar)
local tileI = (x - WORLD_MIN_X) // 128 + 1
local tileJ = (y - WORLD_MIN_Y) // 128 + 1
local numTiles = radius // 128
local deltaJ
for worldI = max(tileI - numTiles, 1), min(tileI + numTiles, worldMaxI) do
deltaJ = sqrt(radius^2/16384 - (worldI - tileI)^2) // 1
for worldJ = max(tileJ - deltaJ, 1), min(tileJ + deltaJ, worldMaxJ) do
if not terrainIsExplored[worldI][worldJ] and (not checkFogOfWar or IsVisibleToPlayer(WORLD_MIN_X + (worldI - 1)*128, WORLD_MIN_Y + (worldJ - 1)*128, localPlayer)) then
terrainIsExplored[worldI][worldJ] = true
UpdateTerrainVertexColor(worldI, worldJ)
end
end
end
end,
---Updates the minimap textures in the specified rect.
---@param minX number
---@param minY number
---@param maxX number
---@param maxY number
RedrawRect = function(minX, minY, maxX, maxY)
local minI = max(1, min(worldMaxI, (minX - WORLD_MIN_X) // 128))
local minJ = max(1, min(worldMaxJ, (minY - WORLD_MIN_Y) // 128))
local maxI = max(1, min(worldMaxI, (maxX - WORLD_MIN_X) // 128 + 1))
local maxJ = max(1, min(worldMaxJ, (maxY - WORLD_MIN_Y) // 128 + 1))
for i = minI, maxI do
for j = minJ, maxJ do
UpdateTerrainVertexColor(i, j)
end
end
end,
---Writes into the config tables for widgets with the specified code the properties in the provided table. The possible keys of the property table are texture, size, level, visibiltiyRadius, color, and exception (which can be true or false). Will only have an effect if the tables are referenced in the getter functions.
---@param fourCC string | integer
---@param propertyTable table
ModifyWidgetType = function(fourCC, propertyTable)
fourCC = type(fourCC) == "string" and fourCC or string.pack(">I4", fourCC)
local key = minimapPreInit and FourCC(fourCC) or fourCC
if propertyTable.texture then
MINIMAP_WIDGET_TYPE_TEXTURE[key] = propertyTable.texture
end
if propertyTable.size then
MINIMAP_WIDGET_TYPE_SIZE[key] = propertyTable.size
end
if propertyTable.level then
MINIMAP_WIDGET_TYPE_LEVEL[key] = propertyTable.level
end
if propertyTable.visibilityRadius then
MINIMAP_WIDGET_TYPE_VISIBILITY_RADIUS[key] = propertyTable.visibilityRadius
end
if propertyTable.color then
MINIMAP_WIDGET_TYPE_COLOR[key] = propertyTable.color
end
if propertyTable.exception then
---@diagnostic disable-next-line: assign-type-mismatch
MINIMAP_WIDGET_TYPE_EXCEPTIONS[key] = propertyTable.exception
end
if minimapInitialized then
ALICE_ForAllObjectsDo(ClearAllCaches, fourCC)
if propertyTable.exception == true then
ALICE_ForAllObjectsDo(OnExceptionAdded, fourCC)
elseif propertyTable.exception == false then
ALICE_ForAllObjectsDo(OnExceptionRemoved, fourCC)
end
end
end,
---Causes an object to continuously reveal the minimap around its position. This function can be used to share exploration between players. It can be called asynchronously to share exploration only between specific players.
---@param whichObject Object
---@param enable? boolean
SetExplorer = function(whichObject, enable)
if enable ~= false then
ALICE_AddSelfInteraction(whichObject, ExploreMinimap, HandleType[whichObject] == "" and "drawable" or HandleType[whichObject])
else
ALICE_RemoveSelfInteraction(whichObject, ExploreMinimap, HandleType[whichObject] == "" and "drawable" or HandleType[whichObject])
end
end,
---Initializes the terrain map. Only necessary if AUTO_RUN is disabled.
Init = function()
if not AUTO_RUN then
CreateTerrainMap()
end
AdjustUI()
CreateTerrainFrames()
MinimapArtist = {
identifier = "minimapArtist",
interactions = {
drawable = DrawMinimapIcon,
waypointMarker = DrawWaypointMarker,
self = RenderMinimap
},
cellCheckInterval = ALICE_Config.MIN_INTERVAL,
radius = 128*MINIMAP_NUMBER_OF_TILES/2
}
if STATIC_MINIMAP then
MinimapArtist.x = (WORLD_MAX_X + WORLD_MIN_X)/2
MinimapArtist.y = (WORLD_MAX_Y + WORLD_MIN_Y)/2
MinimapArtist.isStationary = true
else
MinimapArtist.anchor = CAT_Camera
end
ALICE_Create(MinimapArtist)
minimapInitialized = true
end,
---Shows or hides the RPG minimap.
---@param enable? boolean
Show = function(enable)
if not minimapInitialized then
print("|cffff0000Warning:|r Attempted to show minimap before it was initialized.")
return
end
enable = enable ~= false
if enable == minimapShown then
return
end
if enable then
ALICE_Unpause(MinimapArtist, {DrawMinimapIcon, DrawWaypointMarker}, "minimapArtist")
end
minimapShown = true
for i = 1, MINIMAP_NUM_FRAMES do
for j = 1, MINIMAP_NUM_FRAMES do
for k = 1, 4 do
BlzFrameSetVisible(minimapParentFrames[i][j][k], enable)
end
end
end
end,
---Encodes the exploration map of the local player in a string. If exploration is not synced, the generated code will be asynchronous.
---@return string
SaveExploration = function()
local code = ""
local currentIsExplored = false
local numRepetitions = 0
local accumulatedRepetitions
local numColumnRepetitions = 0
local stars
for i = 1, worldMaxI do
accumulatedRepetitions = 0
for j = 1, worldMaxJ do
if (terrainIsExplored[i][j] == true) ~= currentIsExplored then
currentIsExplored = not currentIsExplored
if numColumnRepetitions > 0 then
stars = ""
while numColumnRepetitions > NUMBER_OF_CHARS do
stars = stars .. "*"
numColumnRepetitions = numColumnRepetitions - NUMBER_OF_CHARS
end
code = code .. stars .. "|" .. chars:sub(numColumnRepetitions + 1, numColumnRepetitions + 1)
numColumnRepetitions = 0
end
stars = ""
while numRepetitions > NUMBER_OF_CHARS do
stars = stars .. "*"
numRepetitions = numRepetitions - NUMBER_OF_CHARS
end
code = code .. stars .. chars:sub(numRepetitions + 1, numRepetitions + 1)
numRepetitions = 1
accumulatedRepetitions = 1
else
numRepetitions = numRepetitions + 1
accumulatedRepetitions = accumulatedRepetitions + 1
if accumulatedRepetitions == worldMaxJ then
numColumnRepetitions = numColumnRepetitions + 1
numRepetitions = 0
end
end
end
end
if numColumnRepetitions > 0 then
code = code .. "|" .. chars:sub(numColumnRepetitions + 1, numColumnRepetitions + 1)
end
return code
end,
---Loads the exploration map from a code for the specified player or for all players if it is not specified.
---@param code string
---@param whichPlayer? player
LoadExploration = function(code, whichPlayer)
if whichPlayer ~= nil and localPlayer ~= whichPlayer then
return
end
local iCurrent = 1
local jCurrent = 1
local currentPos = 1
local currentIsExplored = false
local length = code:len()
local numRepetitions = 0
local char
local charValues = {}
for k = 1, NUMBER_OF_CHARS do
charValues[chars:sub(k, k)] = k - 1
end
while currentPos <= length do
char = code:sub(currentPos, currentPos)
if char == "|" then
currentPos = currentPos + 1
if iCurrent ~= 1 and jCurrent ~= 1 then
for j = jCurrent, worldMaxJ do
terrainIsExplored[iCurrent][j] = currentIsExplored or nil
end
iCurrent = iCurrent + 1
jCurrent = 1
end
char = code:sub(currentPos, currentPos)
while char == "*" do
numRepetitions = numRepetitions + NUMBER_OF_CHARS
currentPos = currentPos + 1
char = code:sub(currentPos, currentPos)
end
if char ~= "|" then
numRepetitions = numRepetitions + charValues[char]
else
currentPos = currentPos - 1
end
for i = iCurrent, iCurrent + numRepetitions - 1 do
for j = 1, worldMaxJ do
terrainIsExplored[i][j] = currentIsExplored or nil
end
end
iCurrent = iCurrent + numRepetitions
numRepetitions = 0
else
while char == "*" do
numRepetitions = numRepetitions + NUMBER_OF_CHARS
currentPos = currentPos + 1
char = code:sub(currentPos, currentPos)
end
if char ~= "|" then
numRepetitions = numRepetitions + charValues[char]
else
currentPos = currentPos - 1
end
for j = 1, numRepetitions do
terrainIsExplored[iCurrent][jCurrent] = currentIsExplored or nil
jCurrent = jCurrent + 1
if jCurrent > worldMaxJ then
iCurrent = iCurrent + 1
jCurrent = 1
end
end
currentIsExplored = not currentIsExplored
numRepetitions = 0
end
currentPos = currentPos + 1
end
for worldI = 1, worldMaxI do
for worldJ = 1, worldMaxJ do
UpdateTerrainVertexColor(worldI, worldJ)
end
end
end
}
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "TestMap" end
do
local questIcon = {}
local questMark = {}
local fizzleSnoutQuestActive = false
local function PlaySoundLocal(soundPath, localPlayerCanHearSound)
local volume ---@type number
local s = CreateSound( soundPath , FALSE, FALSE, FALSE, 10, 10, "DefaultEAXON") ---@type sound
SetSoundChannel(s, 0)
if localPlayerCanHearSound then
volume = 100
else
volume = 0
end
SetSoundVolumeBJ( s , volume )
StartSound(s)
KillSoundWhenDone(s)
end
function PlayTavernMusic(zoneName)
ClearMapMusic()
PlayMusic("war3mapImported\\TavernAlliance.mp3")
end
function ResetMusic(zoneName)
ClearMapMusic()
PlayMusic("Sound\\Music\\mp3Music\\NightElf3.flac")
end
local function CreateQuestActor(anchor, quest)
local self = {
identifier = "quest",
interactions = {Etyr = quest},
radius = 250,
anchor = anchor
}
ALICE_Create(self)
end
function GiveGoldReward(quest, Etyr)
if ALICE_PairGetDistance2D() < 250 then
DisplayTimedTextToForce(GetPlayersAll(), 10, [[
|cffffcc00Marshal Hagris:|r
Thank you, priestess. The kingdom is now safer thanks to you. Here is your gold, as promised.]])
SetPlayerState(GetOwningPlayer(Etyr), PLAYER_STATE_RESOURCE_GOLD, GetPlayerState(GetOwningPlayer(Etyr), PLAYER_STATE_RESOURCE_GOLD) + 100)
ALICE_Destroy(quest)
RPGMinimap.RemoveIcon(questIcon[Hagris])
DestroyEffect(questMark[Hagris])
PlaySoundLocal("Sound\\Interface\\QuestCompleted.flac", true)
end
end
function FizzlesnoutQuest(quest, Etyr)
if ALICE_PairGetDistance2D() < 250 then
DisplayTimedTextToForce(GetPlayersAll(), 12, [[
|cffffcc00Marshal Hagris:|r
There is a gnoll out there in the forest who has been terrorizing the local farmers since fall.
A hundred gold coins to anyone who can put an end to that wretched creature!
You will find him hiding in the woods near the Veiled Path. Fizzlesnout is his name.]])
RPGMinimap.RemoveIcon(questIcon[Hagris])
DestroyEffect(questMark[Hagris])
ALICE_Destroy(quest)
PlaySoundLocal("Sound\\Interface\\QuestNew.flac", true)
fizzleSnoutQuestActive = true
end
end
function AcceptSupplies(quest, Etyr)
if ALICE_PairGetDistance2D() < 250 and UnitHasItemOfTypeBJ(Etyr, FourCC "I001") then
DisplayTimedTextToForce(GetPlayersAll(), 8, [[
|cffffcc00Innkeeper Barnes:|r
Thank you for bringing these to me. Here's some booze.]])
ALICE_Destroy(quest)
RPGMinimap.RemoveIcon(questIcon[Barnes])
DestroyEffect(questMark[Barnes])
PlaySoundLocal("Sound\\Interface\\QuestCompleted.flac", true)
RemoveItem(UnitItemInSlot(Etyr, GetInventoryIndexOfItemTypeBJ(Etyr, FourCC "I001") - 1))
UnitAddItemById(Tyrande, FourCC "I000")
end
end
function GiveQuest(quest, Etyr)
if ALICE_PairGetDistance2D() < 250 then
DisplayTimedTextToForce(GetPlayersAll(), 12, [[
|cffffcc00Alice Ferguson:|r
Well met, priestess. Could you be so kind and bring these supplies to our local inn? You find it on the King's Plaza to the south. I'm sure Innkeeper Barnes will treat you with a bowl of his best moonberry wine for your troubles.]])
UnitAddItemById(Tyrande, FourCC "I001")
RPGMinimap.RemoveIcon(questIcon[Alice])
DestroyEffect(questMark[Alice])
questIcon[Barnes] = RPGMinimap.AddIconTarget(Barnes, MINIMAP_TEXTURE_QUEST_COMPLETED, 0.01, 5)
questMark[Barnes] = AddSpecialEffectTarget("CompletedQuest.mdx", Barnes, "overhead")
RPGMinimap.AddWaypointMarker(questIcon[Barnes], MINIMAP_TEXTURE_WAYPOINT_MARKER, {255, 200, 0})
ALICE_Destroy(quest)
CreateQuestActor(Barnes, AcceptSupplies)
PlaySoundLocal("Sound\\Interface\\QuestNew.flac", true)
end
end
local function Drunk()
local u = GetOrderedUnit()
if GetUnitAbilityLevel(u, FourCC "Bdef") > 0 then
local trig = GetTriggeringTrigger()
local xt, yt = GetOrderPointX(), GetOrderPointY()
local xo, yo = GetUnitX(u), GetUnitY(u)
ALICE_CallDelayed(function()
DisableTrigger(trig)
IssuePointOrder(u, "smart", 2*xo - xt, 2*yo - yt)
EnableTrigger(trig)
end,
0)
end
end
OnInit.final(function()
Require "RPGMinimap"
Require "FixedCameraLock"
Require "PreplacedWidgetIndexer"
--Tints the minimap terrain inside the tavern in a woody brown.
RPGMinimap.OverwriteTerrainColor(gg_rct_theDrunkenMurloc, {58, 41, 38}, false)
Tyrande = GetPreplacedWidget("Etyr")
FCL_Lock(Tyrande)
--Projects all quest icons in the tavern to its location in the overworld.
RPGMinimap.CreateTranslocatorZone(gg_rct_theDrunkenMurloc, gg_rct_theDrunkenMurlocTarget, {-5650, -10000})
RPGMinimap.Show()
EnableRegionTitles()
SelectUnitForPlayerSingle(Tyrande, Player(0))
Barnes = GetPreplacedWidget("Innkeeper Barnes")
Alice = GetPreplacedWidget("Alice Ferguson")
questIcon[Alice] = RPGMinimap.AddIconTarget(Alice, MINIMAP_TEXTURE_QUEST_AVAILABLE, 0.01, 5)
questMark[Alice] = AddSpecialEffectTarget("AvailableQuest.mdl", Alice, "overhead")
CreateQuestActor(Alice, GiveQuest)
Hagris = GetPreplacedWidget("Marshal Hagris")
questIcon[Hagris] = RPGMinimap.AddIconTarget(Hagris, MINIMAP_TEXTURE_QUEST_AVAILABLE, 0.01, 5)
questMark[Hagris] = AddSpecialEffectTarget("AvailableQuest.mdl", Hagris, "overhead")
CreateQuestActor(Hagris, FizzlesnoutQuest)
local potion = GetPreplacedWidget("Potion of Healing")
RPGMinimap.AddIconTarget(potion, MINIMAP_TEXTURE_INVISIBLE, 0, 1, {
visibilityRadius = 1500,
onFirstReveal = function()
print([[|cffffcc00Tyrande:|r
A healing potion! That will come in handy.]])
end
})
local trig = CreateTrigger()
TriggerRegisterUnitEvent(trig, GetPreplacedWidget("Fizzlesnout"), EVENT_UNIT_DEATH)
TriggerAddAction(trig, function()
if fizzleSnoutQuestActive then
ALICE_Enable(Tyrande, Hagris, "unit", "unit")
CreateQuestActor(Hagris, GiveGoldReward)
questIcon[Hagris] = RPGMinimap.AddIconTarget(Hagris, MINIMAP_TEXTURE_QUEST_COMPLETED, 0.01, 5)
questMark[Hagris] = AddSpecialEffectTarget("CompletedQuest.mdx", Hagris, "overhead")
RPGMinimap.AddWaypointMarker(questIcon[Hagris], MINIMAP_TEXTURE_WAYPOINT_MARKER, {255, 200, 0})
PlaySoundLocal("Sound\\Interface\\QuestLog.flac", true)
end
end)
trig = CreateTrigger()
TriggerRegisterUnitEvent(trig, Tyrande, EVENT_UNIT_ISSUED_POINT_ORDER)
TriggerAddAction(trig, Drunk)
end)
OnInit.global(function()
--Prevents ALICE from creating actors for pathing blockers.
ALICE_ExcludeTypes("YTpb", "YTpc", "YTlb", "Ytlc", "B00F", "B009", "B00E")
end)
end
do
OnInit.global(function()
ALICE_OnCreation("hero", function(object)
RPGMinimap.AddIconTarget(object, MINIMAP_HERO_GLOW, 0.014, 6, {
color = PLAYER_COLORS_RGB[GetConvertedPlayerId(GetOwningPlayer(object))],
owner = GetOwningPlayer(object),
name = "",
identifier = "heroGlow"
})
end)
end)
end
do
local TELEPORTER_MAX_DISTANCE = 75
local steppedThroughTeleporter = setmetatable({}, {__mode = "k"})
local function Teleport(teleporter, unit)
local dist = ALICE_PairGetDistance2D()
if dist > TELEPORTER_MAX_DISTANCE then
if steppedThroughTeleporter[unit] == teleporter.target then
steppedThroughTeleporter[unit] = nil
end
elseif steppedThroughTeleporter[unit] ~= teleporter.target and dist < TELEPORTER_MAX_DISTANCE then
SetUnitPosition(unit, teleporter.target.x, teleporter.target.y)
steppedThroughTeleporter[unit] = teleporter
if teleporter.onTeleport then
teleporter.onTeleport(unit)
end
end
end
local function TeleportOnBreak(teleporter, unit)
if steppedThroughTeleporter[unit] == teleporter.target then
steppedThroughTeleporter[unit] = nil
end
end
---@class Teleporter
local Teleporter = {
x = nil,
y = nil,
identifier = "teleporter",
interactions = {[{"unit", "hero"}] = Teleport},
isStationary = true,
__name = "Teleporter",
target = nil,
onTeleport = nil
}
Teleporter.__index = Teleporter
---@param x1 number
---@param y1 number
---@param x2 number
---@param y2 number
---@param onTeleport? function
---@param onBackTeleport? function
function CreateTeleporters(x1, y1, x2, y2, onTeleport, onBackTeleport)
local teleporter = {
x = x1,
y = y1,
onTeleport = onTeleport
}
setmetatable(teleporter, Teleporter)
ALICE_Create(teleporter)
local backTeleporter = {
x = x2,
y = y2,
onTeleport = onBackTeleport
}
setmetatable(backTeleporter, Teleporter)
ALICE_Create(backTeleporter)
backTeleporter.target = teleporter
teleporter.target = backTeleporter
end
OnInit.final(function()
ALICE_FuncSetOnBreak(Teleport, TeleportOnBreak)
ALICE_FuncSetName(Teleport, "Teleport")
end)
OnInit.final(function()
CreateTeleporters(220, -11960, -5590, -8950)
end)
end
if Debug then Debug.beginFile "PreplacedWidgetIndexer" end
do
--[[
=============================================================================================================================================================
Preplaced Widget Indexer
by Antares
Compiles all preplaced units, destructables, and/or items into easy-to-use lists.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
HandleType https://www.hiveworkshop.com/threads/.354436/
ALICE (optional) https://www.hiveworkshop.com/threads/.353126/
=============================================================================================================================================================
A P I
=============================================================================================================================================================
GetPreplacedWidget(widgetType, index?) Returns a preplaced widget identified by widgetType, which can be an id, fourCC code, name, or hero proper
name. Optional index parameter for widget types for which more than one preplaced instance exists.
GetAllPreplacedWidgets(widgetType) Returns all preplaced widgets identified by widgetType, which can be an id, fourCC code, name, or hero
proper name.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--Specify which preplaced widgets are added to the lists.
local DO_UNITS = true
local DO_DESTRUCTABLES = true
local DO_ITEMS = true
--(Requires ALICE) If debug mode is enabled, ALICE debug mode will be enabled immediately on map initialization and the indices of all widgets are written
--into their actor tooltips. To show the tooltip, simply click on the widget.
local DEBUG_MODE = false
--If enabled, widgets are sorted based on their position on the map, with the lowest index being assigned to those in the bottom-left corner of the map.
local SORT_BY_POSITION = true
--If enabled, you can control the indices of preplaced units and destructables by setting their forcedIndex percentage to the desired index in the World Editor.
--The forcedIndex will then be set to max forcedIndex after the system initializes.
local INDEX_BY_HEALTH_PERCENT = false
--List fourCC codes of widget types that should be ignored by the indexing by forcedIndex method.
local INDEX_BY_HEALTH_IGNORE_TYPES = { ---@constant string[]
}
--[[
You can set rects with the World Editor to force an index for units standing in those rects. To do that, simply give those rects a name containing "forceIndexN",
where N is an integer. Each rect should have only one widget of the same type in it.
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
local widgetsOfId = {}
local nameOfId = {}
local idOfName = {}
local forceIndexRects = {}
local weakKeys = {__mode = "k"}
local insert = table.insert
local sort = table.sort
PreplacedIndex = setmetatable({}, weakKeys)
local GetWidgetId = {
unit = GetUnitTypeId,
destructable = GetDestructableTypeId,
item = GetItemTypeId
}
local GetWidgetMaxLife = {
unit = BlzGetUnitMaxHP,
destructable = GetDestructableMaxLife,
}
local GetWidgetName = {
unit = GetUnitName,
destructable = GetDestructableName,
item = GetItemName
}
local function GetIndexFromRect(x, y)
for __, rect in ipairs(forceIndexRects) do
if x > rect.minX and x < rect.maxX and y > rect.minY and y < rect.maxY then
return rect.index
end
end
return nil
end
local function BeforeAliceInit()
local preplacedWidgets = {}
for __, value in ipairs(INDEX_BY_HEALTH_IGNORE_TYPES) do
---@diagnostic disable-next-line: assign-type-mismatch
INDEX_BY_HEALTH_IGNORE_TYPES[FourCC(value)] = true
end
--Process forceIndexRects
for name, rect in pairs(_G) do
if name:find("gg_rct_forceIndex") then
insert(forceIndexRects, {
minX = GetRectMinX(rect),
minY = GetRectMinY(rect),
maxX = GetRectMaxX(rect),
maxY = GetRectMaxY(rect),
index = tonumber(name:match("gg_rct_forceIndex(\x25d+)"))
})
end
end
local x = setmetatable({}, {__index = function(self, key) self[key] = GetWidgetX(key) return self[key] end})
local y = setmetatable({}, {__index = function(self, key) self[key] = GetWidgetY(key) return self[key] end})
if DO_UNITS then
local units = CreateGroup()
GroupEnumUnitsInRect(units, bj_mapInitialPlayableArea)
local u = FirstOfGroup(units)
while u do
GroupRemoveUnit(units, u)
preplacedWidgets[#preplacedWidgets + 1] = u
u = FirstOfGroup(units)
end
end
if DO_DESTRUCTABLES then
EnumDestructablesInRect(bj_mapInitialPlayableArea, nil, function()
preplacedWidgets[#preplacedWidgets + 1] = GetEnumDestructable()
end)
end
if DO_ITEMS then
EnumItemsInRect(bj_mapInitialPlayableArea, nil, function()
preplacedWidgets[#preplacedWidgets + 1] = GetEnumItem()
end)
end
local id, name
for __, widget in ipairs(preplacedWidgets) do
id = GetWidgetId[HandleType[widget]](widget)
if widgetsOfId[id] then
insert(widgetsOfId[id], widget)
else
widgetsOfId[id] = setmetatable({widget}, weakKeys)
name = GetWidgetName[HandleType[widget]](widget)
idOfName[name] = id
nameOfId[id] = name
if HandleType[widget] == "unit" and IsUnitType(widget, UNIT_TYPE_HERO) then
idOfName[GetHeroProperName(widget)] = id
end
end
end
if SORT_BY_POSITION then
for __, widgets in pairs(widgetsOfId) do
if #widgets > 1 then
sort(widgets, function(widgetA, widgetB)
return x[widgetA] + y[widgetA] < x[widgetB] + y[widgetB]
end)
end
end
end
if INDEX_BY_HEALTH_PERCENT then
local indexFromRect, forcedIndex, tempWidget, healthPercent, indexFromHealth
local toHeal = {}
for id, widgets in pairs(widgetsOfId) do
local indices = {}
for index, widget in pairs(widgets) do
::begin::
indexFromRect = GetIndexFromRect(x[widget], y[widget])
healthPercent = HandleType[widget] ~= "item" and (100*GetWidgetLife(widget) + 0.5) // GetWidgetMaxLife[HandleType[widget]](widget) or 100
indexFromHealth = not INDEX_BY_HEALTH_IGNORE_TYPES[id] and healthPercent < 100 and healthPercent or nil
forcedIndex = indexFromRect or indexFromHealth
if forcedIndex then
if indexFromHealth then
insert(toHeal, widget)
end
if index ~= forcedIndex then
if widgets[forcedIndex] then
if indices[forcedIndex] then
print("|cffff0000Warning:|r Two or more widgets of type |cffffcc00" .. nameOfId[id] .. "|r have the same forced index " .. forcedIndex .. ".")
break
end
tempWidget = widgets[forcedIndex]
widgets[forcedIndex] = widget
widgets[index] = tempWidget
widget = tempWidget
indices[forcedIndex] = true
goto begin
else
widgets[forcedIndex] = widget
widgets[index] = nil
end
end
end
end
end
for __, widget in ipairs(toHeal) do
SetWidgetLife(widget, GetWidgetMaxLife[HandleType[widget]](widget))
end
end
for __, widgets in pairs(widgetsOfId) do
for index, widget in pairs(widgets) do
PreplacedIndex[widget] = index
end
end
end
local function AfterAliceInit()
Require "ALICE"
ALICE_TrackVariables("PreplacedIndex")
ALICE_Debug()
end
OnInit.global("PreplacedWidgetIndexer", BeforeAliceInit)
if DEBUG_MODE then
OnInit.final(AfterAliceInit)
end
---Returns a preplaced widget identified by widgetType, which can be an id, fourCC code, name, or hero proper name. Optional index parameter for widget types for which more than one preplaced instance exists.
---@param widgetType string | integer
---@param index? integer
---@return unit | destructable | item
function GetPreplacedWidget(widgetType, index)
if type(widgetType) == "number" then
assert(widgetsOfId[widgetType], "Preplaced widgets with fourCC code " .. string.pack(">I4", widgetType) .. " do not exist.")
return widgetsOfId[widgetType][index or 1]
elseif widgetType:len() == 4 then
local fourCC = FourCC(widgetType)
assert(widgetsOfId[fourCC], "Preplaced widgets with fourCC code " .. fourCC .. " do not exist.")
return widgetsOfId[fourCC][index or 1]
else
assert(idOfName[widgetType], "Preplaced widgets with name " .. widgetType .. " do not exist.")
return widgetsOfId[idOfName[widgetType]][index or 1]
end
end
---Returns all preplaced widgets identified by widgetType, which can be an id, fourCC code, name, or hero proper name.
---@param widgetType string | integer
---@return table
function GetAllPreplacedWidgets(widgetType)
if type(widgetType) == "number" then
return widgetsOfId[widgetType]
elseif widgetType:len() == 4 then
return widgetsOfId[FourCC(widgetType)]
else
assert(idOfName[widgetType], "Preplaced widgets with name " .. widgetType .. " do not exist.")
return widgetsOfId[idOfName[widgetType]]
end
end
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "RegionTitles" end
do
--[[
=============================================================================================================================================================
Region Titles
by Antares
Shows the names of map regions in a WoW-like style as the player enters them. Suited for an rpg map with a locked camera.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
ALICE https://www.hiveworkshop.com/threads/.353126/
Camera CAT Included in ALICE.
Rects CAT Included in ALICE.
RegionTitle.fdf Included in Test Map.
RegionTitle.toc Included in Test Map.
=============================================================================================================================================================
To import, copy this script and its requirements. Import the RegionTitle.fdf and RegionTitle.toc without a subpath.
To create titled regions, add their names to the REGIONS table. Then, create rects with the World Editor that determine the extents of those regions. Creating
rects with code before RegionTitles initializes also works. Another option are tables with the minX, minY, maxX, and maxY fields. The variables must be globals
with names equal to the regions' names, but with all special characters and color codes removed, and formatting converted to camelCase. Example:
King's Plaza -> kingsPlaza
|cffff0000Throne of Ash-Gazhur|r -> throneOfAshGazhur
The name is followed by an integer if there are multiple rects for one titled region (kingsPlaza1, kingsPlaza2 etc.).
Titled regions have priorities. Within the REGIONS table, you add regions in ascending order of priority. If two regions are intersecting, the one with the
higher priority overshadows the other. This means that you can create a region that encompasses the entire map, call it, for example, "Kalimdor", and put it
at the first position in the table. Now, whenever the player is in no other region, "Kalimdor" will pop up.
This system is DISABLED BY DEFAULT. Enable it with EnableRegionTitles(). If necessary, disable it for cinematics with EnableRegionTitles(false).
To change font size, edit the FrameFont field in the RegionTitle.fdf file.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local TITLE_Y = 0.45 ---@constant number
local TITLE_FADE_IN_TIME = 1.2 ---@constant number
local TITLE_DURATION = 1.5 ---@constant number
local TITLE_FADE_OUT_TIME = 3.0 ---@constant number
local REGIONS = { ---@constant string[]
"|cff00ff00King's Plaza|r",
"|cffffcc00Deren's Crossing|r",
"|cffffcc00North Road|r",
"|cffff0000The Veiled Path|r",
"|cffffcc00East Road|r",
"|cff00ff00The Drunken Murloc"
}
local ON_REGION_ENTER
local ON_REGION_LEAVE
local function InitZoneTriggers()
--RUNS ASYNCHRONOUSLY!!! Functions that are executed when a player enters a titled region. The keys are the converted region names. You can use the other keyword
--to denote a function that is executed for each region that isn't specifically listed. In multiplayer maps, only run async-safe code within the functions (such as
--playing music, showing frames etc.)
ON_REGION_ENTER = { ---@constant table<string,function>
theDrunkenMurloc = PlayTavernMusic,
other = nil
}
--RUNS ASYNCHRONOUSLY!!! Same as ON_REGION_ENTER, but is executed when a player leaves a titled region.
ON_REGION_LEAVE = { ---@constant table<string,function>
theDrunkenMurloc = ResetMusic,
other = nil
}
end
--[[
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
local REGION_PRIORITY = {} ---@type table<string,integer>
local currentRegion ---@type string | nil
local numRectsOfRegion = {} ---@type table<string,integer>
local titleFrame ---@type framehandle
local titleFrameChildren = {} ---@type framehandle[]
local titleTime ---@type number
local isFirstRegion = true ---@type boolean
local regionTitlesEnabled = false ---@type boolean
local lastPopup = nil ---@type string
local fadeActive = nil ---@type boolean
local function ToUpperCase(__, letter)
return letter:upper()
end
local function ToCamelCase(whichString)
whichString = whichString:gsub("|[cC]\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x", "")
whichString = whichString:gsub("|[rR]", "")
whichString = whichString:gsub("[^\x25w]", "")
whichString = whichString:gsub("\x25s(\x25d)", "\x251")
whichString = whichString:gsub("(\x25s)(\x25a)", ToUpperCase)
return string.lower(whichString:sub(1,1)) .. string.sub(whichString,2)
end
local function FadeTitle()
titleTime = titleTime + ALICE_Config.MIN_INTERVAL
if titleTime < TITLE_FADE_IN_TIME then
BlzFrameSetAlpha(titleFrame, (255*(titleTime/TITLE_FADE_IN_TIME)^2) // 1)
elseif titleTime < TITLE_FADE_IN_TIME + TITLE_DURATION then
BlzFrameSetAlpha(titleFrame, 255)
elseif titleTime < TITLE_FADE_IN_TIME + TITLE_DURATION + TITLE_FADE_OUT_TIME then
BlzFrameSetAlpha(titleFrame, (255*(1 - (titleTime - TITLE_FADE_IN_TIME - TITLE_DURATION)/TITLE_FADE_OUT_TIME)^2) // 1)
else
BlzFrameSetVisible(titleFrame, false)
ALICE_DisableCallback()
fadeActive = false
end
end
local function TitledRegionOnEnter(regionChecker, titledRegion)
numRectsOfRegion[titledRegion.name] = (numRectsOfRegion[titledRegion.name] or 0) + 1
end
local function TitledRegionPeriodic(regionChecker, titledRegion)
if currentRegion == nil or REGION_PRIORITY[titledRegion.name] > REGION_PRIORITY[currentRegion] then
currentRegion = titledRegion.name
if isFirstRegion then
isFirstRegion = false
return
end
if not regionTitlesEnabled then
return
end
local func = ON_REGION_ENTER[ToCamelCase(currentRegion)] or ON_REGION_ENTER.other
if func then
func(currentRegion)
end
if lastPopup == currentRegion then
return
end
titleTime = 0
for __, frame in ipairs(titleFrameChildren) do
BlzFrameSetText(frame, currentRegion)
end
BlzFrameSetVisible(titleFrame, true)
BlzFrameSetAlpha(titleFrame, 0)
if not fadeActive then
ALICE_CallPeriodic(FadeTitle)
fadeActive = true
end
lastPopup = currentRegion
end
end
local function TitledRegionOnLeave(regionChecker, titledRegion)
numRectsOfRegion[titledRegion.name] = (numRectsOfRegion[titledRegion.name] or 0) - 1
if numRectsOfRegion[titledRegion.name] == 0 and currentRegion == titledRegion.name then
currentRegion = nil
local func = ON_REGION_LEAVE[ToCamelCase(titledRegion.name)] or ON_REGION_LEAVE.other
if func then
func(titledRegion.name)
end
end
end
local function AfterAliceInit()
Require "ALICE"
Require "CAT_Camera"
if not BlzLoadTOCFile("RegionTitle.toc") then
error("|cffff0000Warning:|r RegionTitle.toc failed to load.")
return
end
InitZoneTriggers()
titleFrame = BlzCreateFrame("RegionTitle", BlzGetOriginFrame(ORIGIN_FRAME_WORLD_FRAME, 0), 0, 0)
BlzFrameSetAbsPoint(titleFrame, FRAMEPOINT_CENTER, 0.4, TITLE_Y)
BlzFrameSetEnable(titleFrame, false)
BlzFrameSetSize(titleFrame, 0.4, 0.1)
for i = 1, 4 do
titleFrameChildren[i] = BlzFrameGetChild(titleFrame, i - 1)
BlzFrameSetTextAlignment(titleFrameChildren[i], TEXT_JUSTIFY_MIDDLE, TEXT_JUSTIFY_CENTER)
BlzFrameSetEnable(titleFrameChildren[i], false)
end
local i, rect, rectName
for index, region in ipairs(REGIONS) do
REGION_PRIORITY[region] = index
rectName = ToCamelCase(region)
rect = _G["gg_rct_" .. rectName .. 1] or _G["gg_rct_" .. rectName] or _G[rectName .. 1] or _G[rectName]
if not rect then
print("|cffff0000Warning:|r No rects found for " .. region .. ". Expected rect name is " .. rectName .. ".")
end
local titledRegion = {
identifier = "titledRegion",
onEnter = TitledRegionOnEnter,
onLeave = TitledRegionOnLeave,
onPeriodic = TitledRegionPeriodic,
interval = 0.2,
name = region
}
i = 1
while rect do
CAT_CreateFromRect(rect, titledRegion)
i = i + 1
rect = _G["gg_rct_" .. rectName .. i] or _G[rectName .. i]
end
end
local regionChecker = {
identifier = "regionChecker",
interactions = {titledRegion = CAT_RectCheck},
anchor = CAT_Camera,
radius = 0
}
ALICE_Create(regionChecker)
end
OnInit.final("RegionTitles", AfterAliceInit)
--===========================================================================================================================================================
--API
--===========================================================================================================================================================
---@param enable? boolean
function EnableRegionTitles(enable)
regionTitlesEnabled = enable ~= false
end
end
if Debug then Debug.beginFile "FixedCameraLock" end
do
--[[
=============================================================================================================================================================
Fixed Camera Lock
by Antares
Locks the camera to a unit while dynamically adjusting the z-offset to disable awfulness.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-height-map.353477/
=============================================================================================================================================================
A P I
=============================================================================================================================================================
FCL_Lock(whichUnit, whichPlayer) Locks the camera of the specified player to the specified unit or the camera of the owning player of that unit,
if player is not specified.
FCL_Release(whichPlayer) Releases the camera of the specified player or for all players if no player is specified.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local ADJUSTMENT_INTERVAL = 0.1 ---@constant number
--The adjustment strength when the camera target is below the unit. This type of camera shift is always awful and I recommend a value of 1.
local ADJUSTMENT_STRENGTH_UP = 1.0 ---@constant number
--The adjustment strength when the camera target is above the unit. This camera shift is sometimes actually useful, so you can disable it if you want to.
local ADJUSTMENT_STRENGTH_DOWN = 1.0 ---@constant number
--===========================================================================================================================================================
FCL_Anchor = {} ---@type table<player,unit>
local MASTER_TIMER ---@type timer
local lockEnabled = false ---@type boolean
local moveableLoc ---@type location
local GetLocZ ---@type function
local localPlayer ---@type player
---@param whichUnit unit
---@param whichPlayer? player
function FCL_Lock(whichUnit, whichPlayer)
whichPlayer = whichPlayer or GetOwningPlayer(whichUnit)
if GetLocalPlayer() == whichPlayer then
SetCameraTargetController(whichUnit, 0, 0, false)
lockEnabled = true
end
FCL_Anchor[whichPlayer] = whichUnit
end
---@param whichPlayer? player
function FCL_Release(whichPlayer)
if whichPlayer == nil or GetLocalPlayer() == whichPlayer then
ResetToGameCamera(0)
lockEnabled = false
end
if whichPlayer then
FCL_Anchor[whichPlayer] = nil
else
for i = 0, bj_MAX_PLAYER_SLOTS - 1 do
FCL_Anchor[Player(i)] = nil
end
end
end
local function AdjustCameraHeight()
if lockEnabled then
local dz = GetLocZ(GetUnitX(FCL_Anchor[localPlayer]), GetUnitY(FCL_Anchor[localPlayer])) - (GetCameraTargetPositionZ() - GetCameraField(CAMERA_FIELD_ZOFFSET))
if dz > 0 then
SetCameraField(CAMERA_FIELD_ZOFFSET, ADJUSTMENT_STRENGTH_UP*dz, ADJUSTMENT_INTERVAL)
else
SetCameraField(CAMERA_FIELD_ZOFFSET, ADJUSTMENT_STRENGTH_DOWN*dz, ADJUSTMENT_INTERVAL)
end
end
end
OnInit.final("FixedCameraLock", function()
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetLocZ = _G.GetLocZ
else
moveableLoc = Location(0, 0)
GetLocZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
localPlayer = GetLocalPlayer()
MASTER_TIMER = CreateTimer()
TimerStart(MASTER_TIMER, ADJUSTMENT_INTERVAL, true, AdjustCameraHeight)
end)
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "RPG Control" end
do
--[[
=============================================================================================================================================================
RPG Controls
by Antares
A movement system for RPGs and other single-hero maps that includes click-and-hold movement and auto-walk.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
Fixed Camera Lock (optional) https://www.hiveworkshop.com/threads/.354970/
World2Screen Transform Synced (optional) https://www.hiveworkshop.com/threads/.354017/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/.353477/
Synced Camera (optional) Included in World2Screen Transform.
PathingWizard (optional) https://www.hiveworkshop.com/threads/.355027/
=============================================================================================================================================================
A P I
=============================================================================================================================================================
EnableRPGControls(enable, whichPlayer) Enables or disables the system for a player or for all players if not specified.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--Disables the click-and-hold trigger for this many seconds when a hero casts a spell. This enables the user to cast a spell without releasing the right
--mouse-button.
local IGNORE_MOUSE_SPELL_DURATION = 0.5 ---@constant number
--Disables the click-and-hold trigger for this many seconds right after the right mouse-button is pressed. This prevents the trigger from firing on a simple
--right-click.
local IGNORE_MOUSE_CLICK_DURATION = 0.25 ---@constant number
--How often the check of the mouse-position is performed.
local CHECK_INTERVAL = 0.1 ---@constant number
--The minimum angle difference in degrees between the current movement direction of the hero and the angle from the hero to the mouse cursor before a new
--command is given. If too many commands are given, the hero will slow down.
local MIN_ANGLE_DELTA = 5 ---@constant number
--When the hero comes closer to the last ordered point than this value, a new command will be given.
local MIN_DISTANCE = 100 ---@constant number
--The hotkey to toggle auto-walk. Set nil to disable.
local AUTO_WALK_HOTKEY = OSKEY_TAB ---@constant oskeytype
--If you're using the Fixed Camera Lock system, enable this option to make RPG Controls compatible. Requires World2ScreenSynced and SyncedCameras.
local USE_FIXED_CAMERA_LOCK = true ---@constant boolean
--If enabled, the hero will ignore obstacles and walk in a straight line in the direction of the mouse-cursor until it can no longer go any further.
--Requires PathingWizard.
local NO_PATHING = true ---@constant boolean
--If you have NO_PATHING enabled, you can additionally enable this to also apply the same behavior to normal mouse right-clicks.
local NO_PATHING_ON_NORMAL_CLICK = true ---@constant boolean
--Without this set, the hero would constantly get stuck on corners when NO_PATHING is enabled. Increase if the hero still gets stuck.
local OBSTACLE_BYPASS_DISTANCE = 100 ---@constant number
--If enabled, the system will be on sleep as long as the hero of the player is not selected.
local CHECK_SELECTION = false ---@constant boolean
--Spells added to this list won't disable click-and-hold movement or auto-walk.
local SPELL_EXCEPTIONS = { ---@constant string[]
"Absk"
}
--This function should return the unit that should get ordered.
local function GetHeroOfPlayer(whichPlayer)
return FCL_Anchor[whichPlayer]
end
--===========================================================================================================================================================
local zeroTable = {__index = function(self, key) self[key] = 0 return 0 end}
local mouseX = setmetatable({}, zeroTable)
local mouseY = setmetatable({}, zeroTable)
local currentOrderX = setmetatable({}, zeroTable)
local currentOrderY = setmetatable({}, zeroTable)
local rightClickOn = {}
local autoWalkEnabled = {}
local mouseIgnore = {}
local loopTimerOfPlayer = {}
local ignoreToggleTimerOfPlayer = {}
local playerOfTimer = {}
local SMART = 851971
local spellKeyList = {}
local commandTrigger
local acos, sqrt, atan, cos, sin, pi = math.acos, math.sqrt, math.atan, math.cos, math.sin, math.pi
local function UpdateOrder(whichPlayer, whichHero, desiredX, desiredY)
if AUTO_WALK_HOTKEY then
DisableTrigger(commandTrigger)
end
currentOrderX[whichPlayer] = desiredX
currentOrderY[whichPlayer] = desiredY
IssuePointOrderById(whichHero, SMART, desiredX, desiredY)
if AUTO_WALK_HOTKEY then
EnableTrigger(commandTrigger)
end
end
local function GetAdjustedPoint(xHero, yHero, orderX, orderY)
local desiredX, desiredY, endPointReached = GetFurthestAccessiblePoint(xHero, yHero, orderX, orderY)
if not endPointReached then
local dist = sqrt((xHero - desiredX)^2 + (yHero - desiredY)^2)
if dist < MIN_DISTANCE then
local angle = atan(orderY - yHero, orderX - xHero)
local newStartX, newStartY = xHero + OBSTACLE_BYPASS_DISTANCE*cos(angle + pi/2), yHero + OBSTACLE_BYPASS_DISTANCE*sin(angle + pi/2)
local testX, testY = GetFurthestAccessiblePoint(newStartX, newStartY, orderX, orderY)
dist = sqrt((newStartX - testX)^2 + (newStartY - testY)^2)
if dist > MIN_DISTANCE then
desiredX, desiredY = testX, testY
else
newStartX, newStartY = xHero - OBSTACLE_BYPASS_DISTANCE*cos(angle + pi/2), yHero - OBSTACLE_BYPASS_DISTANCE*sin(angle + pi/2)
testX, testY = GetFurthestAccessiblePoint(newStartX, newStartY, orderX, orderY)
dist = sqrt((newStartX - testX)^2 + (newStartY - testY)^2)
if dist > MIN_DISTANCE then
desiredX, desiredY = testX, testY
end
end
end
end
return desiredX, desiredY, endPointReached
end
local function GetDesiredPoint(whichPlayer)
if USE_FIXED_CAMERA_LOCK then
return Screen2WorldSynced(mouseX[whichPlayer], mouseY[whichPlayer], whichPlayer)
else
local desiredX, desiredY = mouseX[whichPlayer], mouseY[whichPlayer]
return desiredX, desiredY, desiredX ~= 0 or desiredY ~= 0
end
end
local function Loop()
local whichPlayer = playerOfTimer[GetExpiredTimer()]
if (not rightClickOn[whichPlayer] or mouseIgnore[whichPlayer]) and not autoWalkEnabled[whichPlayer] then
return
end
local desiredX, desiredY, validMousePosition = GetDesiredPoint(whichPlayer)
if not validMousePosition then
return
end
local whichHero = GetHeroOfPlayer(whichPlayer)
if whichHero == nil then
return
end
if CHECK_SELECTION and not IsUnitSelected(whichHero, whichPlayer) then
return
end
local xHero, yHero = GetUnitX(whichHero), GetUnitY(whichHero)
if NO_PATHING then
desiredX, desiredY = GetAdjustedPoint(xHero, yHero, desiredX, desiredY)
end
local dxOld, dyOld = currentOrderX[whichPlayer] - xHero, currentOrderY[whichPlayer] - yHero
local dxNew, dyNew = desiredX - xHero, desiredY - yHero
local distOld = sqrt(dxOld*dxOld + dyOld*dyOld)
if distOld < MIN_DISTANCE then
UpdateOrder(whichPlayer, whichHero, desiredX, desiredY)
else
local distNew = sqrt(dxNew*dxNew + dyNew*dyNew)
local angleDelta = acos((dxOld*dxNew + dyOld*dyNew)/(distOld*distNew))
if angleDelta > bj_DEGTORAD*MIN_ANGLE_DELTA then
UpdateOrder(whichPlayer, whichHero, desiredX, desiredY)
end
end
end
local function OnPointOrder()
local whichUnit = GetTriggerUnit()
local whichPlayer = GetOwningPlayer(whichUnit)
if whichUnit ~= GetHeroOfPlayer(whichPlayer) then
return
end
autoWalkEnabled[whichPlayer] = false
if NO_PATHING and NO_PATHING_ON_NORMAL_CLICK and (not rightClickOn[whichPlayer] or mouseIgnore[whichPlayer]) and GetIssuedOrderId() == SMART then
local xHero, yHero = GetUnitX(whichUnit), GetUnitY(whichUnit)
local orderX, orderY = GetOrderPointX(), GetOrderPointY()
local desiredX, desiredY, endPointReached = GetAdjustedPoint(xHero, yHero, orderX, orderY)
if not endPointReached then
DisableTrigger(commandTrigger)
currentOrderX[whichPlayer] = desiredX
currentOrderY[whichPlayer] = desiredY
IssuePointOrderById(whichUnit, SMART, desiredX, desiredY)
EnableTrigger(commandTrigger)
end
end
end
local function ToggleAutoWalk()
local whichPlayer = GetTriggerPlayer()
autoWalkEnabled[whichPlayer] = not autoWalkEnabled[whichPlayer]
if not rightClickOn[whichPlayer] then
if autoWalkEnabled[whichPlayer] then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
else
IssueImmediateOrder(GetHeroOfPlayer(whichPlayer), "stop")
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
end
end
local function DisableIgnore()
mouseIgnore[playerOfTimer[GetExpiredTimer()]] = false
end
local function MouseSpellIgnore()
if spellKeyList[GetSpellAbilityId()] then
return
end
local whichUnit = GetSpellAbilityUnit()
local whichPlayer = GetOwningPlayer(whichUnit)
if whichUnit == GetHeroOfPlayer(whichPlayer) then
mouseIgnore[whichPlayer] = true
autoWalkEnabled[whichPlayer] = false
TimerStart(ignoreToggleTimerOfPlayer[whichPlayer], IGNORE_MOUSE_SPELL_DURATION, false, DisableIgnore)
end
end
local function MouseMove()
local whichPlayer = GetTriggerPlayer()
if USE_FIXED_CAMERA_LOCK then
mouseX[whichPlayer], mouseY[whichPlayer] = GetTriggerPlayerMouseScreenCoordinates()
else
mouseX[whichPlayer], mouseY[whichPlayer] = BlzGetTriggerPlayerMouseX(), BlzGetTriggerPlayerMouseY()
end
end
local function MouseRightClick()
if BlzGetTriggerPlayerMouseButton() == MOUSE_BUTTON_TYPE_RIGHT then
local whichPlayer = GetTriggerPlayer()
rightClickOn[whichPlayer] = true
mouseIgnore[whichPlayer] = true
TimerStart(ignoreToggleTimerOfPlayer[whichPlayer], IGNORE_MOUSE_CLICK_DURATION, false, DisableIgnore)
if not autoWalkEnabled[whichPlayer] then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
end
end
end
local function MouseRightRelease()
if BlzGetTriggerPlayerMouseButton() == MOUSE_BUTTON_TYPE_RIGHT then
local whichPlayer = GetTriggerPlayer()
if rightClickOn[whichPlayer] then
rightClickOn[whichPlayer] = false
if not mouseIgnore[whichPlayer] then
local desiredX, desiredY, validMousePosition = GetDesiredPoint(whichPlayer)
if validMousePosition then
local whichHero = GetHeroOfPlayer(whichPlayer)
if whichHero == nil then
return
end
if NO_PATHING then
local xHero, yHero = GetUnitX(whichHero), GetUnitY(whichHero)
desiredX, desiredY = GetAdjustedPoint(xHero, yHero, desiredX, desiredY)
end
IssuePointOrderById(GetHeroOfPlayer(whichPlayer), SMART, desiredX, desiredY)
end
end
if not autoWalkEnabled[whichPlayer] then
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
end
end
end
OnInit.final("RPGControls", function()
if USE_FIXED_CAMERA_LOCK then
local fixedCameraLock = Require.optionally "FixedCameraLock"
local world2ScreenSynced = Require.optionally "World2ScreenSynced"
if not fixedCameraLock then
USE_FIXED_CAMERA_LOCK = false
elseif not world2ScreenSynced then
USE_FIXED_CAMERA_LOCK = false
print("|cffff0000Warning:|r USE_FIXED_CAMERA_LOCK requires World2ScreenSynced.")
end
end
if (NO_PATHING or NO_PATHING_ON_NORMAL_CLICK) and not GetFurthestAccessiblePoint then
NO_PATHING = false
NO_PATHING_ON_NORMAL_CLICK = false
print("|cffff0000Warning:|r NO_PATHING requires PathingWizard.")
end
local whichPlayer
local trigDown = CreateTrigger()
local trigUp = CreateTrigger()
local trigIgnore = CreateTrigger()
local trigMove = CreateTrigger()
local trigAutoWalk
if AUTO_WALK_HOTKEY then
trigAutoWalk = CreateTrigger()
TriggerAddAction(trigAutoWalk, ToggleAutoWalk)
commandTrigger = CreateTrigger()
TriggerAddAction(commandTrigger, OnPointOrder)
end
for i = 0, 23 do
whichPlayer = Player(i)
if GetPlayerSlotState(whichPlayer) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(whichPlayer) == MAP_CONTROL_USER then
TriggerRegisterPlayerEvent(trigDown, whichPlayer, EVENT_PLAYER_MOUSE_DOWN)
TriggerRegisterPlayerEvent(trigUp, whichPlayer, EVENT_PLAYER_MOUSE_UP)
TriggerRegisterPlayerEvent(trigMove, whichPlayer, EVENT_PLAYER_MOUSE_MOVE)
TriggerRegisterPlayerUnitEvent(commandTrigger, whichPlayer, EVENT_PLAYER_UNIT_ISSUED_POINT_ORDER)
BlzTriggerRegisterPlayerKeyEvent(trigAutoWalk, whichPlayer, AUTO_WALK_HOTKEY, 0, true)
loopTimerOfPlayer[whichPlayer] = CreateTimer()
ignoreToggleTimerOfPlayer[whichPlayer] = CreateTimer()
playerOfTimer[loopTimerOfPlayer[whichPlayer]] = whichPlayer
playerOfTimer[ignoreToggleTimerOfPlayer[whichPlayer]] = whichPlayer
end
i = i + 1
end
TriggerAddAction(trigMove, MouseMove)
TriggerAddAction(trigDown, MouseRightClick)
TriggerAddAction(trigUp, MouseRightRelease)
TriggerRegisterAnyUnitEventBJ(trigIgnore, EVENT_PLAYER_UNIT_SPELL_CAST)
TriggerAddAction(trigIgnore, MouseSpellIgnore)
for __, fourCC in ipairs(SPELL_EXCEPTIONS) do
spellKeyList[FourCC(fourCC)] = true
end
end)
---@param enable? boolean
---@param whichPlayer? player
function EnableRPGControls(enable, whichPlayer)
enable = enable ~= false
if whichPlayer then
if enable then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
else
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
else
for i = 0, 23 do
whichPlayer = Player(i)
if enable then
if GetPlayerSlotState(whichPlayer) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(whichPlayer) == MAP_CONTROL_USER then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
end
elseif GetPlayerSlotState(whichPlayer) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(whichPlayer) == MAP_CONTROL_USER then
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
i = i + 1
end
end
end
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "FastWorld2ScreenTransformSynced" end
do
--[[
=============================================================================================================================================================
Fast World2Screen Transform (Synced)
by Antares
Transform from world to screen coordinates and back.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/.353477/
SyncedCamera Included in Test Map.
=============================================================================================================================================================
A P I
=============================================================================================================================================================
World2ScreenSynced(x, y, z, player) Takes the world coordinates x, y, and z and returns the screen positions x and y of that point on the
specified player's screen. The third return value specifies if the point is on the screen.
Screen2WorldSynced(x, y, player) Takes the screen coordinates x and y and the player for which the calculation should be performed and
returns the x, y, and z world coordinates. The fourth return value specifies whether or not the search for
the world intersection point converged. This function may fail when a ray pointing from the camera to the
world intersects at multiple points with the terrain.
GetTriggerPlayerMouseScreenCoordinates() Returns the screen coordinates of the player's mouse on a mouse move or mouse click event.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--The interval between updates of each player's camera parameters.
local TIME_STEP = 0.02 ---@constant number
--If enabled and camera lock target is set in FixedCameraLock for a player, the camera parameters are calculated differently to return a more accurate result.
--The ADJUSTMENT_STRENGTH_UP and ADJUSTMENT_STRENGTH_DOWN in FixedCameraLock should be set to 1 and the ADJUSTMENT_INTERVAL set very low to get the most
--accurate result.
local USE_FIXED_CAMERA_LOCK = false ---@constant boolean
--[[
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
local cos = math.cos
local sin = math.sin
local sqrt = math.sqrt
local preCalc = {} ---@type table<player,boolean>
local eyeX = {} ---@type table<player,number>
local eyeY = {} ---@type table<player,number>
local eyeZ = {} ---@type table<player,number>
local cosRot = {} ---@type table<player,number>
local sinRot = {} ---@type table<player,number>
local cosAttack = {} ---@type table<player,number>
local sinAttack = {} ---@type table<player,number>
local cosAttackCosRot = {} ---@type table<player,number>
local cosAttackSinRot = {} ---@type table<player,number>
local sinAttackCosRot = {} ---@type table<player,number>
local sinAttackSinRot = {} ---@type table<player,number>
local yCenterScreenShift = {} ---@type table<player,number>
local scaleFactor = {} ---@type table<player,number>
local GetTerrainZ ---@type function
local moveableLoc ---@type location
local function CameraPrecalc(player)
local angleOfAttack = SyncedCamera.AngleOfAttack[player]
local rotation = SyncedCamera.Rotation[player]
local fieldOfView = SyncedCamera.FieldOfView[player]
cosAttack[player] = cos(angleOfAttack)
sinAttack[player] = sin(angleOfAttack)
cosRot[player] = cos(rotation)
sinRot[player] = sin(rotation)
if USE_FIXED_CAMERA_LOCK and FCL_Anchor[player] then
local x, y = GetUnitX(FCL_Anchor[player]), GetUnitY(FCL_Anchor[player])
eyeX[player] = x + SyncedCamera.TargetDistance[player]*cosAttack[player]*cosRot[player]
eyeY[player] = y - SyncedCamera.TargetDistance[player]*cosAttack[player]*sinRot[player]
eyeZ[player] = GetLocZ(x, y) - SyncedCamera.TargetDistance[player]*sinAttack[player]
else
eyeX[player] = SyncedCamera.EyeX[player]
eyeY[player] = SyncedCamera.EyeY[player]
eyeZ[player] = SyncedCamera.EyeZ[player]
end
yCenterScreenShift[player] = 0.1284*cosAttack[player]
cosAttackCosRot[player] = cosAttack[player]*cosRot[player]
cosAttackSinRot[player] = cosAttack[player]*sinRot[player]
sinAttackCosRot[player] = sinAttack[player]*cosRot[player]
sinAttackSinRot[player] = sinAttack[player]*sinRot[player]
scaleFactor[player] = 0.0524*fieldOfView^3 - 0.0283*fieldOfView^2 + 1.061*fieldOfView
preCalc[player] = true
end
---Takes the world coordinates x, y, and z and returns the screen positions x and y of that point on the specified player's screen. The third return value specifies if the point is on the screen.
---@param x number
---@param y number
---@param z number
---@param player player
---@return number, number, boolean
function World2ScreenSynced(x, y, z, player)
if not preCalc[player] then
CameraPrecalc(player)
end
local dx = x - eyeX[player]
local dy = y - eyeY[player]
local dz = z - eyeZ[player]
local xPrime = scaleFactor[player]*(-cosAttackCosRot[player]*dx - cosAttackSinRot[player]*dy - sinAttack[player]*dz)
local xs = 0.4 + (cosRot[player]*dy - sinRot[player]*dx)/xPrime
local ys = 0.42625 - yCenterScreenShift[player] + (sinAttackCosRot[player]*dx + sinAttackSinRot[player]*dy - cosAttack[player]*dz)/xPrime
return xs, ys, xPrime < 0 and xs > -0.1333 and xs < 0.9333 and ys > 0 and ys < 0.6
end
---Takes the screen coordinates x and y and the player for which the calculation should be performed and returns the x, y, and z world coordinates. The fourth return value specifies whether or not the search for the world intersection point converged. This function may fail when a ray pointing from the camera to the world intersects at multiple points with the terrain.
---@param x number
---@param y number
---@param player player
---@return number, number, number, boolean
function Screen2WorldSynced(x, y, player)
if not preCalc[player] then
CameraPrecalc(player)
end
local a = (x - 0.4)*scaleFactor[player]
local b = (0.42625 - yCenterScreenShift[player] - y)*scaleFactor[player]
--This is the unit vector pointing towards the mouse cursor in the camera's coordinate system.
local nx = 1/sqrt(1 + a*a + b*b)
local ny = sqrt(1 - (1 + b*b)*nx*nx)
local nz = sqrt(1 - nx*nx - ny*ny)
if a > 0 then
ny = -ny
end
if b < 0 then
nz = -nz
end
--Constructs the unit vector pointing from the camera eye position to the mouse cursor.
local nxPrime = cosAttackCosRot[player]*nx - sinRot[player]*ny + sinAttackCosRot[player]*nz
local nyPrime = cosAttackSinRot[player]*nx + cosRot[player]*ny + sinAttackSinRot[player]*nz
local nzPrime = -sinAttack[player]*nx + cosAttack[player]*nz
local eyeX, eyeY, eyeZ = eyeX[player], eyeY[player], eyeZ[player]
--Try to find intersection point of vector with terrain.
local zGuess = GetTerrainZ(eyeX, eyeY)
local xGuess = eyeX + nxPrime*(eyeZ - zGuess)/nzPrime
local yGuess = eyeY + nyPrime*(eyeZ - zGuess)/nzPrime
local zWorld = GetTerrainZ(xGuess, yGuess)
local deltaZ = zWorld - zGuess
zGuess = zWorld
local zWorldOld, deltaZOld
local i = 0
while (deltaZ > 1 or deltaZ < -1) and i < 50 do
zWorldOld = zWorld
deltaZOld = deltaZ
xGuess = eyeX + nxPrime*(eyeZ - zGuess)/nzPrime
yGuess = eyeY + nyPrime*(eyeZ - zGuess)/nzPrime
zWorld = GetTerrainZ(xGuess, yGuess)
deltaZ = zWorld - zGuess
zGuess = (deltaZOld*zWorld - deltaZ*zWorldOld)/(deltaZOld - deltaZ)
i = i + 1
end
return xGuess, yGuess, zWorld, i < 50
end
---@return number, number
function GetTriggerPlayerMouseScreenCoordinates()
local x, y = BlzGetTriggerPlayerMouseX(), BlzGetTriggerPlayerMouseY()
local xs, ys = World2ScreenSynced(x, y, GetTerrainZ(x, y), GetTriggerPlayer())
return xs, ys
end
OnInit.final("World2ScreenSynced", function()
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetTerrainZ = _G.GetTerrainZ
else
moveableLoc = Location(0, 0)
GetTerrainZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
TimerStart(CreateTimer(), TIME_STEP, true, function()
for key, __ in pairs(preCalc) do
preCalc[key] = nil
end
end)
end)
end
if Debug then Debug.endFile() end
do
--[[
=============================================================================================================================================================
Synced Camera
by Antares
Continuously syncs player camera parameters and writes them into a table.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
=============================================================================================================================================================
]]
local TIME_STEP = 0.02
local zeroTable = {__index = function(self, key) return 0 end}
SyncedCamera = {
EyeX = setmetatable({}, zeroTable),
EyeY = setmetatable({}, zeroTable),
EyeZ = setmetatable({}, zeroTable),
AngleOfAttack = setmetatable({}, zeroTable),
Rotation = setmetatable({}, zeroTable),
FieldOfView = setmetatable({}, zeroTable),
TargetDistance = setmetatable({}, zeroTable)
}
--===========================================================================================================================================================
local EPSILON = 0.001
local localPlayer
local syncReady = {}
local abs = math.abs
OnInit.final(function()
localPlayer = GetLocalPlayer()
local trig = CreateTrigger()
for i = 0, bj_MAX_PLAYER_SLOTS - 1 do
syncReady[Player(i)] = true
BlzTriggerRegisterPlayerSyncEvent(trig, Player(i), "SyncCamera", false)
end
TriggerAddAction(trig, function()
local data = BlzGetTriggerSyncData()
local nextComma = data:find(",")
local player = Player(tonumber(data:sub(1, nextComma - 1)) - 1)
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.EyeX[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.EyeY[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.EyeZ[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.AngleOfAttack[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.Rotation[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.FieldOfView[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
SyncedCamera.TargetDistance[player] = tonumber(data)
syncReady[player] = true
end)
TimerStart(CreateTimer(), TIME_STEP, true, function()
if syncReady[localPlayer] then
local eyeX = GetCameraEyePositionX()
local eyeY = GetCameraEyePositionY()
local eyeZ = GetCameraEyePositionZ()
local angleOfAttack = GetCameraField(CAMERA_FIELD_ANGLE_OF_ATTACK)
local rotation = GetCameraField(CAMERA_FIELD_ROTATION)
local fieldOfView = GetCameraField(CAMERA_FIELD_FIELD_OF_VIEW)
local targetDistance = GetCameraField(CAMERA_FIELD_TARGET_DISTANCE)
if abs(eyeX - SyncedCamera.EyeX[localPlayer]) > EPSILON or
abs(eyeY - SyncedCamera.EyeY[localPlayer]) > EPSILON or
abs(eyeZ - SyncedCamera.EyeZ[localPlayer]) > EPSILON or
abs(angleOfAttack - SyncedCamera.AngleOfAttack[localPlayer]) > EPSILON or
abs(rotation - SyncedCamera.Rotation[localPlayer]) > EPSILON or
abs(fieldOfView - SyncedCamera.FieldOfView[localPlayer]) > EPSILON or
abs(targetDistance - SyncedCamera.TargetDistance[localPlayer]) > EPSILON then
syncReady[localPlayer] = false
BlzSendSyncData("SyncCamera",
GetPlayerId(localPlayer) + 1 .. ","
.. tostring(eyeX) .. ","
.. tostring(eyeY) .. ","
.. tostring(eyeZ) .. ","
.. tostring(angleOfAttack) .. ","
.. tostring(rotation) .. ","
.. tostring(fieldOfView) .. ","
.. tostring(targetDistance)
)
end
end
end)
end)
end