1
0

Merge branch 'master' of github.com:mc-server/MCServer

This commit is contained in:
Alexander Harkness 2015-05-19 18:43:19 +01:00
commit cbb425f027
191 changed files with 4066 additions and 2983 deletions

3
.gitmodules vendored
View File

@ -28,3 +28,6 @@
[submodule "lib/libevent"]
path = lib/libevent
url = https://github.com/mc-server/libevent.git
[submodule "lib/TCLAP"]
path = lib/TCLAP
url = https://github.com/mc-server/TCLAP.git

View File

@ -2,7 +2,7 @@ language: cpp
compiler: clang
before_install:
- if [ "$TRAVIS_MCSERVER_BUILD_TYPE" == "COVERAGE" ]; then sudo pip install cpp_coveralls; fi
# - if [ "$TRAVIS_MCSERVER_BUILD_TYPE" == "COVERAGE" ]; then sudo pip install cpp_coveralls; fi
# g++4.8
- sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
@ -21,17 +21,17 @@ install:
# Build MCServer
script: ./CIbuild.sh
after_success:
- ./uploadCoverage.sh
#after_success:
# - ./uploadCoverage.sh
env:
- TRAVIS_MCSERVER_BUILD_TYPE=RELEASE MCSERVER_PATH=./MCServer
- TRAVIS_MCSERVER_BUILD_TYPE=DEBUG MCSERVER_PATH=./MCServer_debug
matrix:
include:
- compiler: gcc
env: TRAVIS_MCSERVER_BUILD_TYPE=COVERAGE MCSERVER_PATH=./MCServer
#matrix:
# include:
# - compiler: gcc
# env: TRAVIS_MCSERVER_BUILD_TYPE=COVERAGE MCSERVER_PATH=./MCServer
# Notification Settings
notifications:

View File

@ -7,9 +7,13 @@ export MCSERVER_BUILD_ID=$TRAVIS_JOB_NUMBER
export MCSERVER_BUILD_DATETIME=`date`
cmake . -DBUILD_TOOLS=1 -DSELF_TEST=1;
echo "Checking basic style..."
cd src
lua CheckBasicStyle.lua
cd ..
echo "Building..."
make -j 2;
make -j 2 test ARGS="-V";
cd MCServer/;

View File

@ -78,6 +78,9 @@ endif()
# The Expat library is linked in statically, make the source files aware of that:
add_definitions(-DXML_STATIC)
# Let Lua use additional checks on its C API. This is only compiled into Debug builds:
add_definitions(-DLUA_USE_APICHECK)
# Self Test Mode enables extra checks at startup
if(${SELF_TEST})
add_definitions(-DSELF_TEST)

View File

@ -1,7 +1,27 @@
Code Stuff
Code Conventions
----------
When contributing, you must follow our code conventions. Otherwise, the CI builds will automatically fail and your PR will not be merged until the non-conforming code is fixed. Due to this, we strongly advise you to run `src/CheckBasicStyle.lua` before commiting, it will perform various code style checks and warn you if your code does not conform to our conventions. `CheckBasicStyle.lua` can be configured to run automatically before every commit via a pre-commit hook, **this is highly recommended**. The way to do it is listed at the bottom of this file.
Here are the conventions:
* We use the subset of C++11 supported by MSVC 2013 (ask if you think that something would be useful)
* All new public functions in all classes need documenting comments on what they do and what behavior they follow, use doxy-comments formatted as `/** Description */`. Do not use asterisks on additional lines in multi-line comments.
* Use spaces after the comment markers: `// Comment` instead of `//Comment`. A comment must be prefixed with two spaces if it's on the same line with code:
- `SomeFunction()<Space><Space>//<Space>Note the two spaces prefixed to me and the space after the slashes.`
* All variable names and function names use CamelCase style, with the exception of single letter variables.
- `ThisIsAProperFunction()` `This_is_bad()` `this_is_bad` `GoodVariableName` `badVariableName`.
* All member variables start with `m_`, all function parameters start with `a_`, all class names start with `c`.
- `class cMonster { int m_Health; int DecreaseHealth(int a_Amount); }`
* Put spaces after commas. `Vector3d(1, 2, 3)` instead of `Vector3d(1,2,3)`
* Put spaces before and after every operator.
- `a = b + c;`
- `if (a == b)`
* Keep individual functions spaced out by 5 empty lines, this enhances readability and makes navigation in the source file easier.
* Add those extra parentheses to conditions, especially in C++:
- `if ((a == 1) && ((b == 2) || (c == 3)))` instead of ambiguous `if (a == 1 && b == 2 || c == 3)`
- This helps prevent mistakes such as `if (a & 1 == 0)`
*
* Use the provided wrappers for OS stuff:
- Threading is done by inheriting from `cIsThread`, thread synchronization through `cCriticalSection`, `cSemaphore` and `cEvent`, file access and filesystem operations through the `cFile` class, high-precision timers through `cTimer`, high-precision sleep through `cSleep`
* No magic numbers, use named constants:
@ -16,10 +36,6 @@ Code Stuff
- `cPlayer:IsGameModeCreative()` instead of` (cPlayer:GetGameMode() == gmCreative)` (the player can also inherit the gamemode from the world, which the value-d condition doesn't catch)
* Please use **tabs for indentation and spaces for alignment**. This means that if it's at line start, it's a tab; if it's in the middle of a line, it's a space
* Alpha-sort stuff that makes sense alpha-sorting - long lists of similar items etc.
* Keep individual functions spaced out by 5 empty lines, this enhances readability and makes navigation in the source file easier.
* Add those extra parentheses to conditions, especially in C++
- `if ((a == 1) && ((b == 2) || (c == 3)))` instead of ambiguous `if (a == 1 && b == 2 || c == 3)`
- This helps prevent mistakes such as `if (a & 1 == 0)`
* White space is free, so use it freely
- "freely" as in "plentifully", not "arbitrarily"
* All `case` statements inside a `switch` need an extra indent.
@ -27,9 +43,22 @@ Code Stuff
- The only exception: a `switch` statement with all `case` statements being a single short statement is allowed to use the short brace-less form.
- These two rules really mean that indent is governed by braces
* Add an empty last line in all source files (GCC and GIT can complain otherwise)
* All new public functions in all classes need documenting comments on what they do and what behavior they follow, use doxy-comments formatted as `/** Description */`. Do not use asterisks on additional lines in multi-line comments.
* Use spaces after the comment markers: `// Comment` instead of `//Comment`
Pre-commit hook
---------
When contributing, the code conventions above *must* be followed. Otherwise, the CI builds will automatically fail and your PR will not be merged until the non-conforming code is fixed. It is highly recommended to set up a pre-commit hook which will check your code style before every commit. Here is how to do that:
* Clone the repository as usual.
* Go to your `<clone location>/.git/hooks` folder, create a text file named "pre-commit" there with the following contents:
```
#!/usr/sh
src/CheckBasicStyle.lua 1>&2 -g
```
* If on Linux/Unix, you need to give the newly created file an execute permission: `chmod +x .git/hooks/pre-commit`
* Lua must be installed.
* You're done. Now, `src/CheckBasicStyle.lua` will check the changed files before every commit. If a problem is found, it will point you to that problem and will cancel the commit.
Note that the check script is not smart enough to catch everything, so not having any warnings does not necessarily imply that you followed the conventions fully. The other humans working on this will perform more checks before merging.
Copyright
---------

View File

@ -7,6 +7,7 @@ Diusrex
Duralex
FakeTruth (founder)
Howaner
jasperarmstrong
keyboard
Lapayo
Luksor

View File

@ -8,7 +8,8 @@
g_APIDesc =
{
Classes =
F --[[
{
--[[
-- What the APIDump plugin understands / how to document stuff:
ExampleClassName =
{
@ -2046,7 +2047,7 @@ a_Player:OpenWindow(Window);
BroadcastChatSuccess = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtSuccess. Use for success messages." },
BroadcastChatWarning = { Params = "MessageText", Return = "", Notes = "Broadcasts the specified message to all players, with its message type set to mtWarning. Use for concerning events, such as plugin reload etc." },
CreateAndInitializeWorld = { Params = "WorldName", Return = "{{cWorld|cWorld}}", Notes = "Creates a new world and initializes it. If there is a world whith the same name it returns nil.<br><br><b>NOTE</b>This function is currently unsafe, do not use!" },
FindAndDoWithPlayer = { Params = "PlayerName, CallbackFunction", Return = "", Notes = "Calls the given callback function for all players with names partially (or fully) matching the name string provided.<br>This function is not case-sensitive." },
FindAndDoWithPlayer = { Params = "PlayerName, CallbackFunction", Return = "bool", Notes = "Calls the given callback function for the player with the name best matching the name string provided.<br>This function is case-insensitive and will match partial names.<br>Returns false if player not found or there is ambiguity, true otherwise. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre>" },
DoWithPlayerByUUID = { Params = "PlayerUUID, CallbackFunction", Return = "bool", Notes = "If there is the player with the uuid, calls the CallbackFunction with the {{cPlayer}} parameter representing the player. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre> The function returns false if the player was not found, or whatever bool value the callback returned if the player was found." },
ForEachPlayer = { Params = "CallbackFunction", Return = "", Notes = "Calls the given callback function for each player. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|cPlayer}})</pre>" },
ForEachWorld = { Params = "CallbackFunction", Return = "", Notes = "Calls the given callback function for each world. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cWorld|cWorld}})</pre>" },
@ -2330,7 +2331,7 @@ local CompressedString = cStringCompression.CompressStringGZIP("DataToCompress")
{ Params = "BlockX, BlockY, BlockZ, BlockType, BlockMeta", Return = "", Notes = "Sets the block at the specified coords, without waking up the simulators or replacing the block entities for the previous block type. Do not use if the block being replaced has a block entity tied to it!" },
{ Params = "{{Vector3i|BlockCoords}}, BlockType, BlockMeta", Return = "", Notes = "Sets the block at the specified coords, without waking up the simulators or replacing the block entities for the previous block type. Do not use if the block being replaced has a block entity tied to it!" },
},
FindAndDoWithPlayer = { Params = "PlayerNameHint, CallbackFunction", Return = "bool", Notes = "If there is a player of a name similar to the specified name (weighted-match), calls the CallbackFunction with the {{cPlayer}} parameter representing the player. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre> The function returns false if the player was not found, or whatever bool value the callback returned if the player was found. Note that the name matching is very loose, so it is a good idea to check the player name in the callback function." },
FindAndDoWithPlayer = { Params = "PlayerName, CallbackFunction", Return = "bool", Notes = "Calls the given callback function for the player with the name best matching the name string provided.<br>This function is case-insensitive and will match partial names.<br>Returns false if player not found or there is ambiguity, true otherwise. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cPlayer|Player}})</pre>" },
ForEachBlockEntityInChunk = { Params = "ChunkX, ChunkZ, CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each block entity in the chunk. Returns true if all block entities in the chunk have been processed (including when there are zero block entities), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cBlockEntity|BlockEntity}})</pre> The callback should return false or no value to continue with the next block entity, or true to abort the enumeration. Use {{tolua}}.cast() to cast the Callback's BlockEntity parameter to the correct {{cBlockEntity}} descendant." },
ForEachChestInChunk = { Params = "ChunkX, ChunkZ, CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each chest in the chunk. Returns true if all chests in the chunk have been processed (including when there are zero chests), or false if the callback has aborted the enumeration by returning true. The CallbackFunction has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cChestEntity|ChestEntity}})</pre> The callback should return false or no value to continue with the next chest, or true to abort the enumeration." },
ForEachEntity = { Params = "CallbackFunction", Return = "bool", Notes = "Calls the specified callback for each entity in the loaded world. Returns true if all the entities have been processed (including when there are zero entities), or false if the callback function has aborted the enumeration by returning true. The callback function has the following signature: <pre class=\"prettyprint lang-lua\">function Callback({{cEntity|Entity}})</pre> The callback should return false or no value to continue with the next entity, or true to abort the enumeration." },

View File

@ -68,6 +68,7 @@ cPluginManager.AddHook(cPluginManager.HOOK_CHAT, OnChatMessage);
CallPlugin = { Params = "PluginName, FunctionName, [FunctionArgs...]", Return = "[FunctionRets]", Notes = "(STATIC) Calls the specified function in the specified plugin, passing all the given arguments to it. If it succeeds, it returns all the values returned by that function. If it fails, returns no value at all. Note that only strings, numbers, bools, nils and classes can be used for parameters and return values; tables and functions cannot be copied across plugins." },
DoWithPlugin = { Params = "PluginName, CallbackFn", Return = "bool", Notes = "(STATIC) Calls the CallbackFn for the specified plugin, if found. A plugin can be found even if it is currently unloaded, disabled or errored, the callback should check the plugin status. If the plugin is not found, this function returns false, otherwise it returns the bool value that the callback has returned. The CallbackFn has the following signature: <pre class=\"prettyprint lang-lua\">function ({{cPlugin|Plugin}})</pre>" },
ExecuteCommand = { Params = "{{cPlayer|Player}}, CommandStr", Return = "{{cPluginManager#CommandResult|CommandResult}}", Notes = "Executes the command as if given by the specified Player. Checks permissions." },
ExecuteConsoleCommand = { Params = "CommandStr", Return = "bool, string", Notes = "Executes the console command as if given by the admin on the console. If the command is successfully executed, returns true and the text that would be output to the console normally. On error it returns false and an error message." },
FindPlugins = { Params = "", Return = "", Notes = "<b>OBSOLETE</b>, use RefreshPluginList() instead"},
ForceExecuteCommand = { Params = "{{cPlayer|Player}}, CommandStr", Return = "{{cPluginManager#CommandResult|CommandResult}}", Notes = "Same as ExecuteCommand, but doesn't check permissions" },
ForEachCommand = { Params = "CallbackFn", Return = "bool", Notes = "Calls the CallbackFn function for each command that has been bound using BindCommand(). The CallbackFn has the following signature: <pre class=\"prettyprint lang-lua\">function(Command, Permission, HelpString)</pre> If the callback returns true, the enumeration is aborted and this API function returns false; if it returns false or no value, the enumeration continues with the next command, and the API function returns true." },

View File

@ -7,7 +7,8 @@ return
Desc = [[
A plugin may implement an OnChat() function and register it as a Hook to process chat messages from
the players. The function is then called for every in-game message sent from any player. Note that
commands are handled separately using a command framework API.
registered in-game commands are not sent through this hook. Use the
{{OnExecuteCommand|HOOK_EXECUTE_COMMAND}} to intercept registered in-game commands.
]],
Params = {
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who sent the message" },

View File

@ -0,0 +1,29 @@
return
{
HOOK_ENTITY_CHANGE_WORLD =
{
CalledWhen = "Before a entity is changing the world.",
DefaultFnName = "OnEntityChangeWorld", -- also used as pagename
Desc = [[
This hook is called before the server moves the {{cEntity|entity}} to the given world. Plugins may
refuse the changing of the entity to the new world.<p>
See also the {{OnEntityChangedWorld|HOOK_ENTITY_CHANGED_WORLD}} hook for a similar hook is called after the
entity has been moved to the world.
]],
Params =
{
{ Name = "Entity", Type = "{{cEntity}}", Notes = "The entity that wants to change the world" },
{ Name = "World", Type = "{{cWorld}}", Notes = "The world to which the entity wants to change" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called. If the function
returns true, no other callback is called for this event and the change of the entity to the world is
cancelled.
]],
}, -- HOOK_ENTITY_CHANGE_WORLD
}

View File

@ -0,0 +1,28 @@
return
{
HOOK_ENTITY_CHANGED_WORLD =
{
CalledWhen = "After a entity has changed the world.",
DefaultFnName = "OnEntityChangedWorld", -- also used as pagename
Desc = [[
This hook is called after the server has moved the {{cEntity|entity}} to the given world. This is an information-only
callback, the entity is already in the new world.<p>
See also the {{OnEntityChangeWorld|HOOK_ENTITY_CHANGE_WORLD}} hook for a similar hook called before the
entity is moved to the new world.
]],
Params =
{
{ Name = "Entity", Type = "{{cEntity}}", Notes = "The entity that has changed the world" },
{ Name = "World", Type = "{{cWorld}}", Notes = "The world from which the entity has come" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called. If the function
returns true, no other callback is called for this event.
]],
}, -- HOOK_ENTITY_CHANGED_WORLD
}

View File

@ -2,7 +2,10 @@ return
{
HOOK_EXECUTE_COMMAND =
{
CalledWhen = "A player executes an in-game command, or the admin issues a console command. Note that built-in console commands are exempt to this hook - they are always performed and the hook is not called.",
CalledWhen = [[
A player executes an in-game command, or the admin issues a console command. Note that built-in
console commands are exempt to this hook - they are always performed and the hook is not called.
]],
DefaultFnName = "OnExecuteCommand", -- also used as pagename
Desc = [[
A plugin may implement a callback for this hook to intercept both in-game commands executed by the
@ -11,17 +14,24 @@ return
server.</p>
<p>
If the command is in-game, the first parameter to the hook function is the {{cPlayer|player}} who's
executing the command. If the command comes from the server console, the first parameter is nil.
executing the command. If the command comes from the server console, the first parameter is nil.</p>
<p>
The server calls this hook even for unregistered (unknown) console commands. It also calls the hook
for unknown in-game commands, as long as they begin with a slash ('/'). If a plugin needs to intercept
in-game chat messages not beginning with a slash, it should use the {{OnChat|HOOK_CHAT}} hook.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "For in-game commands, the player who has sent the message. For console commands, nil" },
{ Name = "Command", Type = "table of strings", Notes = "The command and its parameters, broken into a table by spaces" },
{ Name = "CommandSplit", Type = "array-table of strings", Notes = "The command and its parameters, broken into a table by spaces" },
{ Name = "EntireCommand", Type = "string", Notes = "The entire command as a single string" },
},
Returns = [[
If the plugin returns true, the command will be blocked and none of the remaining hook handlers will
be called. If the plugin returns false, MCServer calls all the remaining hook handlers and finally
the command will be executed.
If the plugin returns false, MCServer calls all the remaining hook handlers and finally the command
will be executed. If the plugin returns true, the none of the remaining hook handlers will be called.
In this case the plugin can return a second value, specifying whether what the command result should
be set to, one of the {{cPluginManager#CommandResult|CommandResult}} constants. If not
provided, the value defaults to crBlocked.
]],
}, -- HOOK_EXECUTE_COMMAND
}

View File

@ -285,7 +285,7 @@ local function WriteHtmlHook(a_Hook, a_HookNav)
for _, param in ipairs(a_Hook.Params) do
f:write("<tr><td>", param.Name, "</td><td>", LinkifyString(param.Type, HookName), "</td><td>", LinkifyString(param.Notes, HookName), "</td></tr>\n");
end
f:write("</table>\n<p>" .. (a_Hook.Returns or "") .. "</p>\n\n");
f:write("</table>\n<p>" .. LinkifyString(a_Hook.Returns or "", HookName) .. "</p>\n\n");
f:write([[<hr /><h1>Code examples</h1><h2>Registering the callback</h2>]]);
f:write("<pre class=\"prettyprint lang-lua\">\n");
f:write([[cPluginManager:AddHook(cPluginManager.]] .. a_Hook.Name .. ", My" .. a_Hook.DefaultFnName .. [[);]]);
@ -971,7 +971,7 @@ end
--- Writes a list of undocumented objects into a file
local function ListUndocumentedObjects(API, UndocumentedHooks)
f = io.open("API/_undocumented.lua", "w");
local f = io.open("API/_undocumented.lua", "w");
if (f ~= nil) then
f:write("\n-- This is the list of undocumented API objects, automatically generated by APIDump\n\n");
f:write("g_APIDesc =\n{\n\tClasses =\n\t{\n");

View File

@ -54,7 +54,7 @@ function Initialize(a_Plugin)
-- TestBlockAreas()
-- TestSQLiteBindings()
-- TestExpatBindings()
-- TestPluginCalls()
TestPluginCalls()
TestBlockAreasString()
TestStringBase64()
@ -157,26 +157,18 @@ function TestPluginCalls()
-- The Split parameter should be a table, but it is not used in that function anyway,
-- so we can get away with passing nil to it.
-- Use the old, deprecated and unsafe method:
local Core = cPluginManager:Get():GetPlugin("Core")
if (Core ~= nil) then
LOGINFO("Calling Core::ReturnColorFromChar() the old-fashioned way...")
local Gray = Core:Call("ReturnColorFromChar", nil, "8")
LOG("Debuggers: Calling NoSuchPlugin.FnName()...")
cPluginManager:CallPlugin("NoSuchPlugin", "FnName", "SomeParam")
LOG("Debuggers: Calling Core.NoSuchFunction()...")
cPluginManager:CallPlugin("Core", "NoSuchFunction", "SomeParam")
LOG("Debuggers: Calling Core.ReturnColorFromChar(..., \"8\")...")
local Gray = cPluginManager:CallPlugin("Core", "ReturnColorFromChar", "split", "8")
if (Gray ~= cChatColor.Gray) then
LOGWARNING("Call failed, exp " .. cChatColor.Gray .. ", got " .. (Gray or "<nil>"))
LOGWARNING("Debuggers: Call failed, exp " .. cChatColor.Gray .. ", got " .. (Gray or "<nil>"))
else
LOGINFO("Call succeeded")
end
end
-- Use the new method:
LOGINFO("Calling Core::ReturnColorFromChar() the recommended way...")
local Gray = cPluginManager:CallPlugin("Core", "ReturnColorFromChar", nil, "8")
if (Gray ~= cChatColor.Gray) then
LOGWARNING("Call failed, exp " .. cChatColor.Gray .. ", got " .. (Gray or "<nil>"))
else
LOGINFO("Call succeeded")
LOG("Debuggers: Call succeeded")
end
LOG("Debuggers: Inter-plugin calls done.")
end

View File

@ -65,8 +65,12 @@ local function ForumizeString(a_Str)
a_Str = a_Str:gsub("{%%p}", "\n\n")
a_Str = a_Str:gsub("{%%b}", "[b]"):gsub("{%%/b}", "[/b]")
a_Str = a_Str:gsub("{%%i}", "[i]"):gsub("{%%/i}", "[/i]")
a_Str = a_Str:gsub("{%%list}", "[list]"):gsub("{%%/list}", "[/list]")
a_Str = a_Str:gsub("{%%li}", "[*]"):gsub("{%%/li}", "")
a_Str = a_Str:gsub("{%%list}", "\n[list]"):gsub("{%%/list}", "[/list]")
a_Str = a_Str:gsub("{%%li}", "\n[*]"):gsub("{%%/li}", "\n")
-- Process links: {%a LinkDestination}LinkText{%/a}
a_Str = a_Str:gsub("{%%a%s([^}]*)}([^{]*){%%/a}", "[url=%1]%2[/url]")
-- TODO: Other formatting
return a_Str
@ -106,8 +110,12 @@ local function GithubizeString(a_Str)
a_Str = a_Str:gsub("{%%p}", "\n\n")
a_Str = a_Str:gsub("{%%b}", "**"):gsub("{%%/b}", "**")
a_Str = a_Str:gsub("{%%i}", "*"):gsub("{%%/i}", "*")
a_Str = a_Str:gsub("{%%list}", ""):gsub("{%%/list}", "")
a_Str = a_Str:gsub("{%%li}", " - "):gsub("{%%/li}", "")
a_Str = a_Str:gsub("{%%list}", "\n"):gsub("{%%/list}", "\n")
a_Str = a_Str:gsub("{%%li}", "\n - "):gsub("{%%/li}", "")
-- Process links: {%a LinkDestination}LinkText{%/a}
a_Str = a_Str:gsub("{%%a%s([^}]*)}([^{]*){%%/a}", "[%2](%1)")
-- TODO: Other formatting
return a_Str
@ -592,7 +600,10 @@ local function DumpPluginInfoForum(a_PluginFolder, a_PluginInfo)
DumpCommandsForum(a_PluginInfo, f)
DumpPermissionsForum(a_PluginInfo, f)
if (a_PluginInfo.SourceLocation ~= nil) then
f:write("[b][color=blue]Source:[/color] [url=", a_PluginInfo.SourceLocation, "]Link[/url][/b]")
f:write("\n[b]Source[/b]: ", a_PluginInfo.SourceLocation, "\n")
end
if (a_PluginInfo.DownloadLocation ~= nil) then
f:write("[b]Download[/b]: ", a_PluginInfo.DownloadLocation)
end
f:close()
return true

View File

@ -43,21 +43,21 @@ end
--- This is a generic command callback used for handling multicommands' parent commands
-- For example, if there are "/gal save" and "/gal load" commands, this callback handles the "/gal" command
-- It is used for both console and in-game commands; the console version has a_Player set to nil
local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_Level)
local Verb = a_Split[a_Level + 1];
local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_Level, a_EntireCommand)
local Verb = a_Split[a_Level + 1]
if (Verb == nil) then
-- No verb was specified. If there is a handler for the upper level command, call it:
if (a_CmdInfo.Handler ~= nil) then
return a_CmdInfo.Handler(a_Split, a_Player);
return a_CmdInfo.Handler(a_Split, a_Player, a_EntireCommand)
end
-- Let the player know they need to give a subcommand:
assert(type(a_CmdInfo.Subcommands) == "table", "Info.lua error: There is no handler for command \"" .. a_CmdString .. "\" and there are no subcommands defined at level " .. a_Level)
ListSubcommands(a_Player, a_CmdInfo.Subcommands, a_CmdString);
return true;
ListSubcommands(a_Player, a_CmdInfo.Subcommands, a_CmdString)
return true
end
-- A verb was specified, look it up in the subcommands table:
local Subcommand = a_CmdInfo.Subcommands[Verb];
local Subcommand = a_CmdInfo.Subcommands[Verb]
if (Subcommand == nil) then
if (a_Level > 1) then
-- This is a true subcommand, display the message and make MCS think the command was handled
@ -67,7 +67,7 @@ local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_
else
a_Player:SendMessage("The " .. a_CmdString .. " command doesn't support verb " .. Verb)
end
return true;
return true
end
-- This is a top-level command, let MCS handle the unknown message
return false;
@ -76,22 +76,22 @@ local function MultiCommandHandler(a_Split, a_Player, a_CmdString, a_CmdInfo, a_
-- Check the permission:
if (a_Player ~= nil) then
if not(a_Player:HasPermission(Subcommand.Permission or "")) then
a_Player:SendMessage("You don't have permission to execute this command");
return true;
a_Player:SendMessage("You don't have permission to execute this command")
return true
end
end
-- If the handler is not valid, check the next sublevel:
if (Subcommand.Handler == nil) then
if (Subcommand.Subcommands == nil) then
LOG("Cannot find handler for command " .. a_CmdString .. " " .. Verb);
return false;
LOG("Cannot find handler for command " .. a_CmdString .. " " .. Verb)
return false
end
return MultiCommandHandler(a_Split, a_Player, a_CmdString .. " " .. Verb, Subcommand, a_Level + 1);
return MultiCommandHandler(a_Split, a_Player, a_CmdString .. " " .. Verb, Subcommand, a_Level + 1, a_EntireCommand)
end
-- Execute:
return Subcommand.Handler(a_Split, a_Player);
return Subcommand.Handler(a_Split, a_Player, a_EntireCommand)
end
@ -104,39 +104,39 @@ function RegisterPluginInfoCommands()
-- The a_Prefix param already contains the space after the previous command
-- a_Level is the depth of the subcommands being registered, with 1 being the top level command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil);
assert(a_Subcommands ~= nil)
-- A table that will hold aliases to subcommands temporarily, during subcommand iteration
local AliasTable = {}
-- Iterate through the subcommands, register them, and accumulate aliases:
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd;
local Handler = info.Handler;
local CmdName = a_Prefix .. cmd
local Handler = info.Handler
-- Provide a special handler for multicommands:
if (info.Subcommands ~= nil) then
Handler = function(a_Split, a_Player)
return MultiCommandHandler(a_Split, a_Player, CmdName, info, a_Level);
Handler = function(a_Split, a_Player, a_EntireCommand)
return MultiCommandHandler(a_Split, a_Player, CmdName, info, a_Level, a_EntireCommand)
end
end
if (Handler == nil) then
LOGWARNING(g_PluginInfo.Name .. ": Invalid handler for command " .. CmdName .. ", command will not be registered.");
LOGWARNING(g_PluginInfo.Name .. ": Invalid handler for command " .. CmdName .. ", command will not be registered.")
else
local HelpString;
local HelpString
if (info.HelpString ~= nil) then
HelpString = " - " .. info.HelpString;
HelpString = " - " .. info.HelpString
else
HelpString = "";
HelpString = ""
end
cPluginManager.BindCommand(CmdName, info.Permission or "", Handler, HelpString);
cPluginManager.BindCommand(CmdName, info.Permission or "", Handler, HelpString)
-- Register all aliases for the command:
if (info.Alias ~= nil) then
if (type(info.Alias) == "string") then
info.Alias = {info.Alias};
info.Alias = {info.Alias}
end
for idx, alias in ipairs(info.Alias) do
cPluginManager.BindCommand(a_Prefix .. alias, info.Permission or "", Handler, HelpString);
cPluginManager.BindCommand(a_Prefix .. alias, info.Permission or "", Handler, HelpString)
-- Also copy the alias's info table as a separate subcommand,
-- so that MultiCommandHandler() handles it properly. Need to off-load into a separate table
-- than the one we're currently iterating and join after the iterating.
@ -147,7 +147,7 @@ function RegisterPluginInfoCommands()
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1);
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1)
end
end -- for cmd, info - a_Subcommands[]
@ -159,7 +159,7 @@ function RegisterPluginInfoCommands()
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.Commands, 1);
RegisterSubcommands("", g_PluginInfo.Commands, 1)
end
@ -171,26 +171,26 @@ function RegisterPluginInfoConsoleCommands()
-- A sub-function that registers all subcommands of a single command, using the command's Subcommands table
-- The a_Prefix param already contains the space after the previous command
local function RegisterSubcommands(a_Prefix, a_Subcommands, a_Level)
assert(a_Subcommands ~= nil);
assert(a_Subcommands ~= nil)
for cmd, info in pairs(a_Subcommands) do
local CmdName = a_Prefix .. cmd;
local CmdName = a_Prefix .. cmd
local Handler = info.Handler
if (Handler == nil) then
Handler = function(a_Split)
return MultiCommandHandler(a_Split, nil, CmdName, info, a_Level);
Handler = function(a_Split, a_EntireCommand)
return MultiCommandHandler(a_Split, nil, CmdName, info, a_Level, a_EntireCommand)
end
end
cPluginManager.BindConsoleCommand(CmdName, Handler, info.HelpString or "");
cPluginManager.BindConsoleCommand(CmdName, Handler, info.HelpString or "")
-- Recursively register any subcommands:
if (info.Subcommands ~= nil) then
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1);
RegisterSubcommands(a_Prefix .. cmd .. " ", info.Subcommands, a_Level + 1)
end
end
end
-- Loop through all commands in the plugin info, register each:
RegisterSubcommands("", g_PluginInfo.ConsoleCommands, 1);
RegisterSubcommands("", g_PluginInfo.ConsoleCommands, 1)
end

View File

@ -304,7 +304,7 @@ Dropper = Cobblestone, 1:1, 2:1, 3:1, 1:2, 1:3, 3:2, 3:3 | Hopper, 2:2
Repeater = Stone, 1:2, 2:2, 3:2 | RedstoneTorchOn, 1:1, 3:1 | RedstoneDust, 2:1
Comparator = RedstoneTorchOn, 2:1, 1:2, 3:2 | NetherQuartz, 2:2 | Stone, 1:3, 2:3, 3:3
DaylightSensor = Glass, 1:1, 2:1, 3:1 | NetherQuartz, 1:2, 2:2, 3:2 | Woodslab, 1:3, 2:3, 3:3
Hopper = Ironbars, 1:1, 3:1, 1:2, 3:2, 2:3 | Chest, 2:2
Hopper = IronIngot, 1:1, 3:1, 1:2, 3:2, 2:3 | Chest, 2:2
Piston = Planks^-1, 1:1, 2:1, 3:1 | RedstoneDust, 2:3 | Cobblestone, 1:2, 3:2, 1:3, 3:3 | IronIngot, 2:2
StickyPiston = Piston, * | SlimeBall, *
RedstoneLamp = RedstoneDust, 2:1, 1:2, 3:2, 2:3 | Glowstone, 2:2

View File

@ -1,12 +1,14 @@
MCServer [![Build Status](http://img.shields.io/travis/mc-server/MCServer/master.svg?style=flat)](https://travis-ci.org/mc-server/MCServer) [![Coverity Scan Build Status](https://scan.coverity.com/projects/1930/badge.svg)](https://scan.coverity.com/projects/1930) [![weekly tips](http://img.shields.io/gratipay/cuberite_team.svg?style=flat)](http://gratipay.com/cuberite_team) [![tip for next commit](http://tip4commit.com/projects/74.svg)](http://tip4commit.com/projects/74)
MCServer [![Build Status](http://img.shields.io/travis/mc-server/MCServer/master.svg?style=flat)](https://travis-ci.org/mc-server/MCServer) [![Coverity Scan Build Status](https://img.shields.io/coverity/scan/1930.svg)](https://scan.coverity.com/projects/1930) [![weekly tips](http://img.shields.io/gratipay/cuberite_team.svg?style=flat)](http://gratipay.com/cuberite_team)
========
MCServer is a Minecraft server that is written in C++ and designed to be efficient with memory and CPU, as well as having a flexible Lua Plugin API.
MCServer is a Minecraft-compatible multiplayer game server that is written in C++ and designed to be efficient with memory and CPU, as well as having a flexible Lua Plugin API. MCServer is compatible with the vanilla Minecraft client.
MCServer can run on Windows, *nix and Android operating systems. This includes Android phones and tablets as well as Raspberry Pis.
We currently support Release 1.7 and 1.8 (not beta) Minecraft protocol versions.
Subscribe to [the newsletter](http://newsletter.cuberite.org/subscribe.htm) for important updates and project news.
Installation
------------
Hosted MCServer is available DIY on DigitalOcean: [![Install on DigitalOcean](http://doinstall.bearbin.net/button.svg)](http://doinstall.bearbin.net/install?url=https://github.com/mc-server/MCServer) and [Gamososm](https://gamocosm.com) also offers MCServer support.
@ -34,9 +36,7 @@ Check out the [CONTRIBUTING.md](https://github.com/mc-server/MCServer/blob/maste
Other Stuff
-----------
For other stuff, including plugins and discussion, check the [forums](http://forum.mc-server.org) and [Plugin API](http://mc-server.xoft.cz/LuaAPI/).
Earn bitcoins for commits or donate to reward the MCServer developers: [![tip for next commit](http://tip4commit.com/projects/74.svg)](http://tip4commit.com/projects/74)
For other stuff, including plugins and discussion, check out the [forums](http://forum.mc-server.org) and [Plugin API](http://mc-server.xoft.cz/LuaAPI/).
Support Us on Gratipay: [![Support via Gratipay](http://img.shields.io/gittip/cuberite_team.svg)](https://www.gratipay.com/cuberite_team)

View File

@ -4,10 +4,10 @@ PLATFORM=$(uname -m)
echo "Identifying platform: $PLATFORM"
case $PLATFORM in
"i686") DOWNLOADURL="http://builds.cuberite.org/job/MCServer%20Linux%20x86/lastSuccessfulBuild/artifact/MCServer.tar" ;;
"x86_64") DOWNLOADURL="http://builds.cuberite.org/job/MCServer%20Linux%20x64/lastSuccessfulBuild/artifact/MCServer.tar" ;;
"i686") DOWNLOADURL="http://builds.cuberite.org/job/MCServer%20Linux%20x86/lastSuccessfulBuild/artifact/MCServer.tar.gz" ;;
"x86_64") DOWNLOADURL="http://builds.cuberite.org/job/MCServer%20Linux%20x64/lastSuccessfulBuild/artifact/MCServer.tar.gz" ;;
# Assume that all arm devices are a raspi for now.
arm*) DOWNLOADURL="http://builds.cuberite.org/job/MCServer%20Linux%20armhf/lastSuccessfulBuild/artifact/MCServer/MCServer.tar"
arm*) DOWNLOADURL="http://builds.cuberite.org/job/MCServer%20Linux%20armhf/lastSuccessfulBuild/artifact/MCServer/MCServer.tar.gz"
esac
echo "Downloading precompiled binaries."

1
lib/TCLAP Submodule

@ -0,0 +1 @@
Subproject commit 12cee38782897cfe60a1611615c200c45cd99eaf

View File

@ -54,3 +54,11 @@ string.repl = ogsub
-- Lua 5.2+ and LuaJit don't have string.gfind(). Use string.gmatch() instead:
if not(string.gfind) then
string.gfind = string.gmatch
end

View File

@ -1,2 +1,4 @@
lua51.dll
LuaState_Call.inc
LuaState_Declaration.inc
LuaState_Implementation.cpp
LuaState_Typedefs.inc

View File

@ -12,7 +12,7 @@
:: Regenerate the files:
echo Regenerating LUA bindings . . .
"tolua++.exe" -L virtual_method_hooks.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg
"tolua++.exe" -L BindingsProcessor.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg

View File

@ -1,2 +1,2 @@
#!/bin/bash
/usr/bin/tolua++ -L virtual_method_hooks.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg
/usr/bin/tolua++ -L BindingsProcessor.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg

View File

@ -13,7 +13,7 @@
:: Regenerate the files:
echo Regenerating LUA bindings . . .
lua ..\..\lib\tolua++\src\bin\lua\_driver.lua -L virtual_method_hooks.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg
lua ..\..\lib\tolua++\src\bin\lua\_driver.lua -L BindingsProcessor.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg

View File

@ -0,0 +1,161 @@
-- BindingsProcessor.lua
-- Implements additional processing that is done while generating the Lua bindings
local access = {public = 0, protected = 1, private = 2}
--- Defines classes that have a custom manual Push() implementation and should not generate the automatic one
-- Map of classname -> true
local g_HasCustomPushImplementation =
{
cEntity = true
}
function parser_hook(s)
local container = classContainer.curr -- get the current container
-- process access-specifying labels (public, private, etc)
do
local b, e, label = string.find(s, "^%s*(%w*)%s*:[^:]") -- we need to check for [^:], otherwise it would match 'namespace::type'
if b then
-- found a label, get the new access value from the global 'access' table
if access[label] then
container.curr_member_access = access[label]
end -- else ?
return strsub(s, e) -- normally we would use 'e+1', but we need to preserve the [^:]
end
end
end
--- Outputs the helper files supplementing the cLuaState class
-- Writes:
-- LuaState_Declaration.inc
-- LuaState_Implementation.cpp
-- LuaState_Typedefs.inc
local function OutputLuaStateHelpers(a_Package)
-- Collect all class types from ToLua:
local types = {}
for idx, item in ipairs(a_Package) do
local mt = getmetatable(item) or {}
if (mt.classtype == "class") then
table.insert(types, {name = item.name, lname = item.lname})
end
end
table.sort(types,
function(a_Item1, a_Item2)
return (a_Item1.name:lower() < a_Item2.name:lower())
end
)
-- Output the typedefs:
do
local f = assert(io.open("LuaState_Typedefs.inc", "w"))
f:write("\n// LuaState_Typedefs.inc\n\n// This file is generated along with the Lua bindings by ToLua. Do not edit manually, do not commit to repo.\n")
f:write("// Provides a forward declaration and a typedef for a pointer to each class exported to the Lua API.\n")
f:write("\n\n\n\n\n")
for _, item in ipairs(types) do
if not(item.name:match(".*<.*")) then -- Skip templates altogether
-- Classes start with a "c", everything else is a struct:
if (item.name:sub(1, 1) == "c") then
f:write("class " .. item.name .. ";\n")
else
f:write("struct " .. item.name .. ";\n")
end
end
end
f:write("\n\n\n\n\n")
for _, item in ipairs(types) do
f:write("typedef " .. item.name .. " * Ptr" .. item.lname .. ";\n")
end
f:write("\n\n\n\n\n")
f:close()
end
-- Output the Push() and GetStackValue() function declarations:
do
local f = assert(io.open("LuaState_Declaration.inc", "w"))
f:write("\n// LuaState_Declaration.inc\n\n// This file is generated along with the Lua bindings by ToLua. Do not edit manually, do not commit to repo.\n")
f:write("// Implements a Push() and GetStackValue() function for each class exported to the Lua API.\n")
f:write("// This file expects to be included form inside the cLuaState class definition\n")
f:write("\n\n\n\n\n")
for _, item in ipairs(types) do
f:write("void Push(" .. item.name .. " * a_Value);\n")
end
for _, item in ipairs(types) do
f:write("void GetStackValue(int a_StackPos, Ptr" .. item.lname .. " & a_ReturnedVal);\n")
end
f:write("\n\n\n\n\n")
f:close()
end
-- Output the Push() and GetStackValue() function implementations:
do
local f = assert(io.open("LuaState_Implementation.cpp", "w"))
f:write("\n// LuaState_Implementation.cpp\n\n// This file is generated along with the Lua bindings by ToLua. Do not edit manually, do not commit to repo.\n")
f:write("// Implements a Push() and GetStackValue() function for each class exported to the Lua API.\n")
f:write("// This file expects to be compiled as a separate translation unit\n")
f:write("\n\n\n\n\n")
f:write("#include \"Globals.h\"\n#include \"LuaState.h\"\n#include \"tolua++/include/tolua++.h\"\n")
f:write("\n\n\n\n\n")
for _, item in ipairs(types) do
if not(g_HasCustomPushImplementation[item.name]) then
f:write("void cLuaState::Push(" .. item.name .. " * a_Value)\n{\n\tASSERT(IsValid());\n")
f:write("\ttolua_pushusertype(m_LuaState, a_Value, \"" .. item.name .. "\");\n");
f:write("\tm_NumCurrentFunctionArgs += 1;\n")
f:write("}\n\n\n\n\n\n")
end
end
for _, item in ipairs(types) do
f:write("void cLuaState::GetStackValue(int a_StackPos, Ptr" .. item.lname .. " & a_ReturnedVal)\n{\n\tASSERT(IsValid());\n")
f:write("\tif (lua_isnil(m_LuaState, a_StackPos))\n\t{\n")
f:write("\t a_ReturnedVal = nullptr;\n")
f:write("\t return;\n\t}\n")
f:write("\ttolua_Error err;\n")
f:write("\tif (tolua_isusertype(m_LuaState, a_StackPos, \"" .. item.name .. "\", false, &err))\n")
f:write("\t{\n")
f:write("\t a_ReturnedVal = *(reinterpret_cast<" .. item.name .. " **>(lua_touserdata(m_LuaState, a_StackPos)));\n")
f:write("\t}\n")
f:write("}\n\n\n\n\n\n")
end
f:close()
end
end
function pre_output_hook(a_Package)
OutputLuaStateHelpers(a_Package)
end
function post_output_hook()
print("Bindings have been generated.")
end

View File

@ -11,12 +11,14 @@ SET (SRCS
LuaNameLookup.cpp
LuaServerHandle.cpp
LuaState.cpp
LuaState_Implementation.cpp
LuaTCPLink.cpp
LuaUDPEndpoint.cpp
LuaWindow.cpp
ManualBindings.cpp
ManualBindings_Network.cpp
ManualBindings_RankManager.cpp
ManualBindings_World.cpp
Plugin.cpp
PluginLua.cpp
PluginManager.cpp
@ -31,6 +33,8 @@ SET (HDRS
LuaNameLookup.h
LuaServerHandle.h
LuaState.h
LuaState_Declaration.inc
LuaState_Typedefs.inc
LuaTCPLink.h
LuaUDPEndpoint.h
LuaWindow.h
@ -46,12 +50,15 @@ SET (HDRS
set (BINDING_OUTPUTS
${CMAKE_CURRENT_SOURCE_DIR}/Bindings.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Bindings.h
${CMAKE_CURRENT_SOURCE_DIR}/LuaState_Declaration.inc
${CMAKE_CURRENT_SOURCE_DIR}/LuaState_Implementation.cpp
${CMAKE_CURRENT_SOURCE_DIR}/LuaState_Typedefs.inc
)
set(BINDING_DEPENDENCIES
tolua
../Bindings/virtual_method_hooks.lua
../Bindings/AllToLua.pkg
../Bindings/BindingsProcessor.lua
../Bindings/LuaFunctions.h
../Bindings/LuaWindow.h
../Bindings/Plugin.h
@ -126,7 +133,7 @@ if (NOT MSVC)
OUTPUT ${BINDING_OUTPUTS}
# Regenerate bindings:
COMMAND tolua -L virtual_method_hooks.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg
COMMAND tolua -L BindingsProcessor.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
# add any new generation dependencies here
@ -134,8 +141,7 @@ if (NOT MSVC)
)
endif ()
set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.cpp PROPERTIES GENERATED TRUE)
set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.h PROPERTIES GENERATED TRUE)
set_source_files_properties(${BINDING_OUTPUTS} PROPERTIES GENERATED TRUE)
set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.cpp PROPERTIES COMPILE_FLAGS -Wno-error)

View File

@ -19,13 +19,13 @@ extern "C"
#include "../Entities/Entity.h"
#include "../BlockEntities/BlockEntity.h"
// fwd: SQLite/lsqlite3.c
// fwd: "SQLite/lsqlite3.c"
extern "C"
{
int luaopen_lsqlite3(lua_State * L);
}
// fwd: LuaExpat/lxplib.c:
// fwd: "LuaExpat/lxplib.c":
extern "C"
{
int luaopen_lxp(lua_State * L);
@ -107,7 +107,7 @@ void cLuaState::Create(void)
void cLuaState::RegisterAPILibs(void)
{
tolua_AllToLua_open(m_LuaState);
ManualBindings::Bind(m_LuaState);
cManualBindings::Bind(m_LuaState);
DeprecatedBindings::Bind(m_LuaState);
luaopen_lsqlite3(m_LuaState);
luaopen_lxp(m_LuaState);
@ -530,42 +530,6 @@ void cLuaState::Push(bool a_Value)
void cLuaState::Push(cBlockEntity * a_BlockEntity)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_BlockEntity, (a_BlockEntity == nullptr) ? "cBlockEntity" : a_BlockEntity->GetClass());
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cChunkDesc * a_ChunkDesc)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_ChunkDesc, "cChunkDesc");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cClientHandle * a_Client)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Client, "cClientHandle");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cEntity * a_Entity)
{
ASSERT(IsValid());
@ -632,42 +596,6 @@ void cLuaState::Push(cEntity * a_Entity)
void cLuaState::Push(cHopperEntity * a_Hopper)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Hopper, "cHopperEntity");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cItem * a_Item)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Item, "cItem");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cItems * a_Items)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Items, "cItems");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cLuaServerHandle * a_ServerHandle)
{
ASSERT(IsValid());
@ -704,126 +632,6 @@ void cLuaState::Push(cLuaUDPEndpoint * a_UDPEndpoint)
void cLuaState::Push(cMonster * a_Monster)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Monster, "cMonster");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cPickup * a_Pickup)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Pickup, "cPickup");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cPlayer * a_Player)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Player, "cPlayer");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cPlugin * a_Plugin)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Plugin, "cPlugin");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cPluginLua * a_Plugin)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Plugin, "cPluginLua");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cProjectileEntity * a_ProjectileEntity)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_ProjectileEntity, "cProjectileEntity");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cTNTEntity * a_TNTEntity)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_TNTEntity, "cTNTEntity");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cWebAdmin * a_WebAdmin)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_WebAdmin, "cWebAdmin");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cWindow * a_Window)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Window, "cWindow");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(cWorld * a_World)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_World, "cWorld");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(double a_Value)
{
ASSERT(IsValid());
@ -848,42 +656,6 @@ void cLuaState::Push(int a_Value)
void cLuaState::Push(TakeDamageInfo * a_TDI)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_TDI, "TakeDamageInfo");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(Vector3d * a_Vector)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Vector, "Vector3<double>");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(Vector3i * a_Vector)
{
ASSERT(IsValid());
tolua_pushusertype(m_LuaState, a_Vector, "Vector3<int>");
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(void * a_Ptr)
{
UNUSED(a_Ptr);
@ -899,6 +671,10 @@ void cLuaState::Push(void * a_Ptr)
m_NumCurrentFunctionArgs += 1;
}
void cLuaState::Push(std::chrono::milliseconds a_Value)
{
ASSERT(IsValid());
@ -911,6 +687,7 @@ void cLuaState::Push(std::chrono::milliseconds a_Value)
/*
void cLuaState::PushUserType(void * a_Object, const char * a_Type)
{
ASSERT(IsValid());
@ -918,6 +695,7 @@ void cLuaState::PushUserType(void * a_Object, const char * a_Type)
tolua_pushusertype(m_LuaState, a_Object, a_Type);
m_NumCurrentFunctionArgs += 1;
}
*/
@ -958,6 +736,18 @@ void cLuaState::GetStackValue(int a_StackPos, bool & a_ReturnedVal)
void cLuaState::GetStackValue(int a_StackPos, cPluginManager::CommandResult & a_Result)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_Result = static_cast<cPluginManager::CommandResult>(static_cast<int>((tolua_tonumber(m_LuaState, a_StackPos, a_Result))));
}
}
void cLuaState::GetStackValue(int a_StackPos, cRef & a_Ref)
{
a_Ref.RefStack(*this, a_StackPos);
@ -979,6 +769,18 @@ void cLuaState::GetStackValue(int a_StackPos, double & a_ReturnedVal)
void cLuaState::GetStackValue(int a_StackPos, float & a_ReturnedVal)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_ReturnedVal = static_cast<float>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal));
}
}
void cLuaState::GetStackValue(int a_StackPos, eWeather & a_ReturnedVal)
{
if (!lua_isnumber(m_LuaState, a_StackPos))
@ -1007,132 +809,6 @@ void cLuaState::GetStackValue(int a_StackPos, int & a_ReturnedVal)
void cLuaState::GetStackValue(int a_StackPos, pBlockArea & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cBlockArea", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cBlockArea **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pBoundingBox & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cBoundingBox", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cBoundingBox **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pMapManager & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cMapManager", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cMapManager **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pPluginManager & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cPluginManager", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cPluginManager **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pRoot & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cRoot", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cRoot **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pScoreboard & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cScoreboard", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cScoreboard **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
void cLuaState::GetStackValue(int a_StackPos, pWorld & a_ReturnedVal)
{
if (lua_isnil(m_LuaState, a_StackPos))
{
a_ReturnedVal = nullptr;
return;
}
tolua_Error err;
if (tolua_isusertype(m_LuaState, a_StackPos, "cWorld", false, &err))
{
a_ReturnedVal = *(reinterpret_cast<cWorld **>(lua_touserdata(m_LuaState, a_StackPos)));
}
}
bool cLuaState::CallFunction(int a_NumResults)
{
ASSERT (m_NumCurrentFunctionArgs >= 0); // A function must be pushed to stack first
@ -1251,6 +927,9 @@ bool cLuaState::CheckParamTable(int a_StartParam, int a_EndParam)
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?");
BreakIntoDebugger(m_LuaState);
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@ -1398,7 +1077,7 @@ bool cLuaState::CheckParamFunctionOrNil(int a_StartParam, int a_EndParam)
bool cLuaState::CheckParamEnd(int a_Param)
{
tolua_Error tolua_err;
if (tolua_isnoobj(m_LuaState, a_Param, &tolua_err))
if (tolua_isnoobj(m_LuaState, a_Param, &tolua_err) == 1)
{
return true;
}
@ -1415,6 +1094,30 @@ bool cLuaState::CheckParamEnd(int a_Param)
bool cLuaState::IsParamUserType(int a_Param, AString a_UserType)
{
ASSERT(IsValid());
tolua_Error tolua_err;
return (tolua_isusertype(m_LuaState, a_Param, a_UserType.c_str(), 0, &tolua_err) == 1);
}
bool cLuaState::IsParamNumber(int a_Param)
{
ASSERT(IsValid());
tolua_Error tolua_err;
return (tolua_isnumber(m_LuaState, a_Param, 0, &tolua_err) == 1);
}
bool cLuaState::ReportErrors(int a_Status)
{
return ReportErrors(m_LuaState, a_Status);
@ -1494,7 +1197,7 @@ int cLuaState::CallFunctionWithForeignParams(
if (!PushFunction(a_FunctionName.c_str()))
{
LOGWARNING("Function '%s' not found", a_FunctionName.c_str());
lua_pop(m_LuaState, 2);
lua_settop(m_LuaState, OldTop);
return -1;
}
@ -1502,7 +1205,7 @@ int cLuaState::CallFunctionWithForeignParams(
if (CopyStackFrom(a_SrcLuaState, a_SrcParamStart, a_SrcParamEnd) < 0)
{
// Something went wrong, fix the stack and exit
lua_pop(m_LuaState, 2);
lua_settop(m_LuaState, OldTop);
m_NumCurrentFunctionArgs = -1;
m_CurrentFunctionName.clear();
return -1;
@ -1513,13 +1216,8 @@ int cLuaState::CallFunctionWithForeignParams(
if (ReportErrors(s))
{
LOGWARN("Error while calling function '%s' in '%s'", a_FunctionName.c_str(), m_SubsystemName.c_str());
// Fix the stack.
// We don't know how many values have been pushed, so just get rid of any that weren't there initially
int CurTop = lua_gettop(m_LuaState);
if (CurTop > OldTop)
{
lua_pop(m_LuaState, CurTop - OldTop);
}
// Reset the stack:
lua_settop(m_LuaState, OldTop);
// Reset the internal checking mechanisms:
m_NumCurrentFunctionArgs = -1;
@ -1671,6 +1369,7 @@ int cLuaState::ReportFnCallErrors(lua_State * a_LuaState)
{
LOGWARNING("LUA: %s", lua_tostring(a_LuaState, -1));
LogStackTrace(a_LuaState, 1);
BreakIntoDebugger(a_LuaState);
return 1; // We left the error message on the stack as the return value
}
@ -1678,6 +1377,28 @@ int cLuaState::ReportFnCallErrors(lua_State * a_LuaState)
int cLuaState::BreakIntoDebugger(lua_State * a_LuaState)
{
// Call the BreakIntoDebugger function, if available:
lua_getglobal(a_LuaState, "BreakIntoDebugger");
if (!lua_isfunction(a_LuaState, -1))
{
LOGD("LUA: BreakIntoDebugger() not found / not a function");
lua_pop(a_LuaState, 1);
return 1;
}
lua_insert(a_LuaState, -2); // Copy the string that has been passed to us
LOGD("Calling BreakIntoDebugger()...");
lua_call(a_LuaState, 1, 0);
LOGD("Returned from BreakIntoDebugger().");
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// cLuaState::cRef:

View File

@ -32,50 +32,13 @@ extern "C"
#include "../Vector3.h"
#include "../Defines.h"
#include "PluginManager.h"
#include "LuaState_Typedefs.inc"
class cBlockArea;
class cBlockEntity;
class cBoundingBox;
class cChunkDesc;
class cClientHandle;
class cCraftingGrid;
class cCraftingRecipe;
class cEntity;
class cHopperEntity;
class cItem;
class cItems;
// fwd:
class cLuaServerHandle;
class cLuaTCPLink;
class cLuaUDPEndpoint;
class cMapManager;
class cMonster;
class cPickup;
class cPlayer;
class cPlugin;
class cPluginLua;
class cPluginManager;
class cProjectileEntity;
class cRoot;
class cScoreboard;
class cTNTEntity;
class cWebAdmin;
class cWindow;
class cWorld;
struct HTTPRequest;
struct HTTPTemplateRequest;
struct TakeDamageInfo;
typedef cBlockArea * pBlockArea;
typedef cBoundingBox * pBoundingBox;
typedef cMapManager * pMapManager;
typedef cPluginManager * pPluginManager;
typedef cRoot * pRoot;
typedef cScoreboard * pScoreboard;
typedef cWorld * pWorld;
@ -213,52 +176,30 @@ public:
void Push(const Vector3i & a_Vector);
void Push(const Vector3i * a_Vector);
// Push a value onto the stack (keep alpha-sorted):
// Push a simple value onto the stack (keep alpha-sorted):
void Push(bool a_Value);
void Push(cBlockEntity * a_BlockEntity);
void Push(cChunkDesc * a_ChunkDesc);
void Push(cClientHandle * a_ClientHandle);
void Push(cEntity * a_Entity);
void Push(cHopperEntity * a_Hopper);
void Push(cItem * a_Item);
void Push(cItems * a_Items);
void Push(double a_Value);
void Push(int a_Value);
void Push(void * a_Ptr);
void Push(std::chrono::milliseconds a_time);
void Push(cLuaServerHandle * a_ServerHandle);
void Push(cLuaTCPLink * a_TCPLink);
void Push(cLuaUDPEndpoint * a_UDPEndpoint);
void Push(cMonster * a_Monster);
void Push(cPickup * a_Pickup);
void Push(cPlayer * a_Player);
void Push(cPlugin * a_Plugin);
void Push(cPluginLua * a_Plugin);
void Push(cProjectileEntity * a_ProjectileEntity);
void Push(cTNTEntity * a_TNTEntity);
void Push(cWebAdmin * a_WebAdmin);
void Push(cWindow * a_Window);
void Push(cWorld * a_World);
void Push(double a_Value);
void Push(int a_Value);
void Push(TakeDamageInfo * a_TDI);
void Push(Vector3d * a_Vector);
void Push(Vector3i * a_Vector);
void Push(void * a_Ptr);
void Push(std::chrono::milliseconds a_time);
// GetStackValue() retrieves the value at a_StackPos, if it is a valid type. If not, a_Value is unchanged.
// Enum values are clamped to their allowed range.
void GetStackValue(int a_StackPos, AString & a_Value);
void GetStackValue(int a_StackPos, BLOCKTYPE & a_Value);
void GetStackValue(int a_StackPos, bool & a_Value);
void GetStackValue(int a_StackPos, cPluginManager::CommandResult & a_Result);
void GetStackValue(int a_StackPos, cRef & a_Ref);
void GetStackValue(int a_StackPos, double & a_Value);
void GetStackValue(int a_StackPos, eWeather & a_Value);
void GetStackValue(int a_StackPos, float & a_ReturnedVal);
void GetStackValue(int a_StackPos, int & a_Value);
void GetStackValue(int a_StackPos, pBlockArea & a_Value);
void GetStackValue(int a_StackPos, pBoundingBox & a_Value);
void GetStackValue(int a_StackPos, pMapManager & a_Value);
void GetStackValue(int a_StackPos, pPluginManager & a_Value);
void GetStackValue(int a_StackPos, pRoot & a_Value);
void GetStackValue(int a_StackPos, pScoreboard & a_Value);
void GetStackValue(int a_StackPos, pWorld & a_Value);
// Include the auto-generated Push and GetStackValue() functions:
#include "LuaState_Declaration.inc"
/** Call the specified Lua function.
Returns true if call succeeded, false if there was an error.
@ -307,6 +248,10 @@ public:
/** Returns true if the specified parameter on the stack is nil (indicating an end-of-parameters) */
bool CheckParamEnd(int a_Param);
bool IsParamUserType(int a_Param, AString a_UserType);
bool IsParamNumber(int a_Param);
/** If the status is nonzero, prints the text on the top of Lua stack and returns true */
bool ReportErrors(int status);
@ -433,7 +378,7 @@ protected:
bool PushFunction(const cTableRef & a_TableRef);
/** Pushes a usertype of the specified class type onto the stack */
void PushUserType(void * a_Object, const char * a_Type);
// void PushUserType(void * a_Object, const char * a_Type);
/**
Calls the function that has been pushed onto the stack by PushFunction(),
@ -444,6 +389,9 @@ protected:
/** Used as the error reporting function for function calls */
static int ReportFnCallErrors(lua_State * a_LuaState);
/** Tries to break into the MobDebug debugger, if it is installed. */
static int BreakIntoDebugger(lua_State * a_LuaState);
} ;

View File

@ -159,7 +159,7 @@ void cLuaWindow::Destroy(void)
m_Plugin->Unreference(m_LuaRef);
}
// Lua will take care of this object, it will garbage-collect it, so we *must not* delete it!
// Lua will take care of this object, it will garbage-collect it, so we must not delete it!
m_IsDestroyed = false;
}
@ -170,7 +170,7 @@ void cLuaWindow::Destroy(void)
void cLuaWindow::DistributeStack(cItem & a_ItemStack, int a_Slot, cPlayer & a_Player, cSlotArea * a_ClickedArea, bool a_ShouldApply)
{
cSlotAreas Areas;
for (auto Area : m_SlotAreas)
for (auto && Area : m_SlotAreas)
{
if (Area != a_ClickedArea)
{

File diff suppressed because it is too large Load Diff

View File

@ -1,34 +1,567 @@
// ManualBindings.h
// Declares the cManualBindings class used as a namespace for functions exported to the Lua API manually
#pragma once
struct lua_State;
class cPluginLua;
#include "LuaState.h"
// fwd:
struct tolua_Error;
/** Provides namespace for the bindings. */
class ManualBindings
class cManualBindings
{
public:
/** Binds all the manually implemented functions to tolua_S. */
static void Bind(lua_State * tolua_S);
protected:
/** Binds the manually implemented cNetwork-related API to tolua_S.
Implemented in ManualBindings_Network.cpp. */
static void BindNetwork(lua_State * tolua_S);
/** Binds the manually implemented cRankManager glue code to tolua_S.
Implemented in ManualBindings_RankManager.cpp. */
static void BindRankManager(lua_State * tolua_S);
/** Binds the manually implemented cNetwork-related API to tolua_S.
Implemented in ManualBindings_Network.cpp. */
static void BindNetwork(lua_State * tolua_S);
/** Binds the manually implemented cWorld API functions to tolua_S.
Implemented in ManualBindings_World.cpp. */
static void BindWorld(lua_State * tolua_S);
public:
// Helper functions:
static cPluginLua * GetLuaPlugin(lua_State * L);
static int tolua_do_error(lua_State * L, const char * a_pMsg, tolua_Error * a_pToLuaError);
static int lua_do_error(lua_State * L, const char * a_pFormat, ...);
/** Binds the DoWith(ItemName) functions of regular classes. */
template <
class Ty1,
class Ty2,
bool (Ty1::*DoWithFn)(const AString &, cItemCallback<Ty2> &)
>
static int DoWith(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamString(2) ||
!L.CheckParamFunction(3)
)
{
return 0;
}
// Get parameters:
Ty1 * Self;
AString ItemName;
cLuaState::cRef FnRef;
L.GetStackValues(1, Self, ItemName, FnRef);
if (Self == nullptr)
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Invalid 'self'");
}
if (ItemName.empty() || (ItemName[0] == 0))
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a non-empty string for parameter #1");
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #2");
}
class cLuaCallback : public cItemCallback<Ty2>
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FnRef):
m_LuaState(a_LuaState),
m_FnRef(a_FnRef)
{
}
private:
virtual bool Item(Ty2 * a_Item) override
{
bool ret = false;
m_LuaState.Call(m_FnRef, a_Item, cLuaState::Return, ret);
return ret;
}
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
} Callback(L, FnRef);
// Call the DoWith function:
bool res = (Self->*DoWithFn)(ItemName, Callback);
// Push the result as the return value:
L.Push(res);
return 1;
}
/** Template for static functions DoWith(ItemName), on a type that has a static ::Get() function. */
template <
class Ty1,
class Ty2,
bool (Ty1::*DoWithFn)(const AString &, cItemCallback<Ty2> &)
>
static int StaticDoWith(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamString(2) ||
!L.CheckParamFunction(3)
)
{
return 0;
}
// Get parameters:
AString ItemName;
cLuaState::cRef FnRef;
L.GetStackValues(2, ItemName, FnRef);
if (ItemName.empty() || (ItemName[0] == 0))
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a non-empty string for parameter #1");
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #2");
}
class cLuaCallback : public cItemCallback<Ty2>
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FnRef):
m_LuaState(a_LuaState),
m_FnRef(a_FnRef)
{
}
private:
virtual bool Item(Ty2 * a_Item) override
{
bool ret = false;
m_LuaState.Call(m_FnRef, a_Item, cLuaState::Return, ret);
return ret;
}
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
} Callback(L, FnRef);
// Call the DoWith function:
bool res = (Ty1::Get()->*DoWithFn)(ItemName, Callback);
// Push the result as the return value:
L.Push(res);
return 1;
}
template <
class Ty1,
class Ty2,
bool (Ty1::*DoWithFn)(UInt32, cItemCallback<Ty2> &)
>
static int DoWithID(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamNumber(2) ||
!L.CheckParamFunction(3)
)
{
return 0;
}
// Get parameters:
Ty1 * Self = nullptr;
int ItemID;
cLuaState::cRef FnRef;
L.GetStackValues(1, Self, ItemID, FnRef);
if (Self == nullptr)
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Invalid 'self'");
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #2");
}
class cLuaCallback : public cItemCallback<Ty2>
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FnRef):
m_LuaState(a_LuaState),
m_FnRef(a_FnRef)
{
}
private:
virtual bool Item(Ty2 * a_Item) override
{
bool ret = false;
m_LuaState.Call(m_FnRef, a_Item, cLuaState::Return, ret);
return ret;
}
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
} Callback(L, FnRef);
// Call the DoWith function:
bool res = (Self->*DoWithFn)(ItemID, Callback);
// Push the result as the return value:
L.Push(res);
return 1;
}
template <
class Ty1,
class Ty2,
bool (Ty1::*DoWithFn)(int, int, int, cItemCallback<Ty2> &)
>
static int DoWithXYZ(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamNumber(2, 5) ||
!L.CheckParamFunction(6)
)
{
return 0;
}
// Get parameters:
Ty1 * Self = nullptr;
int BlockX, BlockY, BlockZ;
cLuaState::cRef FnRef;
L.GetStackValues(1, Self, BlockX, BlockY, BlockZ, FnRef);
if (Self == nullptr)
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Invalid 'self'");
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #5");
}
class cLuaCallback : public cItemCallback<Ty2>
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FnRef):
m_LuaState(a_LuaState),
m_FnRef(a_FnRef)
{
}
private:
virtual bool Item(Ty2 * a_Item) override
{
bool ret = false;
m_LuaState.Call(m_FnRef, a_Item, cLuaState::Return, ret);
return ret;
}
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
} Callback(L, FnRef);
// Call the DoWith function:
bool res = (Self->*DoWithFn)(BlockX, BlockY, BlockZ, Callback);
// Push the result as the return value:
L.Push(res);
return 1;
}
template <
class Ty1,
class Ty2,
bool (Ty1::*ForEachFn)(int, int, cItemCallback<Ty2> &)
>
static int ForEachInChunk(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamNumber(2, 4) ||
!L.CheckParamFunction(5)
)
{
return 0;
}
// Get parameters:
Ty1 * Self = nullptr;
int ChunkX, ChunkZ;
cLuaState::cRef FnRef;
L.GetStackValues(1, Self, ChunkX, ChunkZ, FnRef);
if (Self == nullptr)
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Invalid 'self'");
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #4");
}
class cLuaCallback : public cItemCallback<Ty2>
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FnRef):
m_LuaState(a_LuaState),
m_FnRef(a_FnRef)
{
}
private:
virtual bool Item(Ty2 * a_Item) override
{
bool ret = false;
m_LuaState.Call(m_FnRef, a_Item, cLuaState::Return, ret);
return ret;
}
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
} Callback(L, FnRef);
// Call the DoWith function:
bool res = (Self->*ForEachFn)(ChunkX, ChunkZ, Callback);
// Push the result as the return value:
L.Push(res);
return 1;
}
template <
class Ty1,
class Ty2,
bool (Ty1::*ForEachFn)(const cBoundingBox &, cItemCallback<Ty2> &)
>
static int ForEachInBox(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cWorld") ||
!L.CheckParamUserType(2, "cBoundingBox") ||
!L.CheckParamFunction(3) ||
!L.CheckParamEnd(4)
)
{
return 0;
}
// Get the params:
Ty1 * Self = nullptr;
cBoundingBox * Box = nullptr;
cLuaState::cRef FnRef;
L.GetStackValues(1, Self, Box, FnRef);
if ((Self == nullptr) || (Box == nullptr))
{
LOGWARNING("Invalid world (%p) or boundingbox (%p)", Self, Box);
L.LogStackTrace();
return 0;
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #2");
}
// Callback wrapper for the Lua function:
class cLuaCallback : public cItemCallback<Ty2>
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FuncRef) :
m_LuaState(a_LuaState),
m_FnRef(a_FuncRef)
{
}
private:
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
// cItemCallback<Ty2> overrides:
virtual bool Item(Ty2 * a_Item) override
{
bool res = false;
if (!m_LuaState.Call(m_FnRef, a_Item, cLuaState::Return, res))
{
LOGWARNING("Failed to call Lua callback");
m_LuaState.LogStackTrace();
return true; // Abort enumeration
}
return res;
}
} Callback(L, FnRef);
bool res = (Self->*ForEachFn)(*Box, Callback);
// Push the result as the return value:
L.Push(res);
return 1;
}
template <
class Ty1,
class Ty2,
bool (Ty1::*ForEachFn)(cItemCallback<Ty2> &)
>
static int ForEach(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamFunction(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Get the params:
Ty1 * Self = nullptr;
cLuaState::cRef FnRef;
L.GetStackValues(1, Self, FnRef);
if (Self == nullptr)
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Invalid 'self'.");
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #1");
}
class cLuaCallback : public cItemCallback<Ty2>
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FnRef):
m_LuaState(a_LuaState),
m_FnRef(a_FnRef)
{
}
private:
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
virtual bool Item(Ty2 * a_Item) override
{
bool res = false; // By default continue the enumeration
m_LuaState.Call(m_FnRef, a_Item, cLuaState::Return, res);
return res;
}
} Callback(L, FnRef);
// Call the enumeration:
bool res = (Self->*ForEachFn)(Callback);
// Push the return value:
L.Push(res);
return 1;
}
/** Implements bindings for ForEach() functions in a class that is static (has a ::Get() static function). */
template <
class Ty1,
class Ty2,
bool (Ty1::*ForEachFn)(cItemCallback<Ty2> &)
>
static int StaticForEach(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamFunction(2) ||
!L.CheckParamEnd(3)
)
{
return 0;
}
// Get the params:
cLuaState::cRef FnRef(L, 2);
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #1");
}
class cLuaCallback : public cItemCallback<Ty2>
{
public:
cLuaCallback(cLuaState & a_LuaState, cLuaState::cRef & a_FnRef):
m_LuaState(a_LuaState),
m_FnRef(a_FnRef)
{
}
private:
cLuaState & m_LuaState;
cLuaState::cRef & m_FnRef;
virtual bool Item(Ty2 * a_Item) override
{
bool res = false; // By default continue the enumeration
m_LuaState.Call(m_FnRef, a_Item, cLuaState::Return, res);
return res;
}
} Callback(L, FnRef);
// Call the enumeration:
bool res = (Ty1::Get()->*ForEachFn)(Callback);
// Push the return value:
L.Push(res);
return 1;
}
};
extern cPluginLua * GetLuaPlugin(lua_State * L);

View File

@ -39,7 +39,7 @@ static int tolua_cNetwork_Connect(lua_State * L)
}
// Get the plugin instance:
cPluginLua * Plugin = GetLuaPlugin(L);
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(L);
if (Plugin == nullptr)
{
// An error message has been already printed in GetLuaPlugin()
@ -92,7 +92,7 @@ static int tolua_cNetwork_CreateUDPEndpoint(lua_State * L)
}
// Get the plugin instance:
cPluginLua * Plugin = GetLuaPlugin(L);
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(L);
if (Plugin == nullptr)
{
// An error message has been already printed in GetLuaPlugin()
@ -171,7 +171,7 @@ static int tolua_cNetwork_HostnameToIP(lua_State * L)
}
// Get the plugin instance:
cPluginLua * Plugin = GetLuaPlugin(L);
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(L);
if (Plugin == nullptr)
{
// An error message has been already printed in GetLuaPlugin()
@ -212,7 +212,7 @@ static int tolua_cNetwork_IPToHostname(lua_State * L)
}
// Get the plugin instance:
cPluginLua * Plugin = GetLuaPlugin(L);
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(L);
if (Plugin == nullptr)
{
// An error message has been already printed in GetLuaPlugin()
@ -253,7 +253,7 @@ static int tolua_cNetwork_Listen(lua_State * L)
}
// Get the plugin instance:
cPluginLua * Plugin = GetLuaPlugin(L);
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(L);
if (Plugin == nullptr)
{
// An error message has been already printed in GetLuaPlugin()
@ -913,16 +913,16 @@ static int tolua_cUDPEndpoint_Send(lua_State * L)
////////////////////////////////////////////////////////////////////////////////
// Register the bindings:
void ManualBindings::BindNetwork(lua_State * tolua_S)
void cManualBindings::BindNetwork(lua_State * tolua_S)
{
// Create the cNetwork API classes:
tolua_usertype(tolua_S, "cNetwork");
tolua_cclass(tolua_S, "cNetwork", "cNetwork", "", nullptr);
tolua_usertype(tolua_S, "cTCPLink");
tolua_cclass(tolua_S, "cTCPLink", "cTCPLink", "", nullptr);
tolua_usertype(tolua_S, "cServerHandle");
tolua_cclass(tolua_S, "cServerHandle", "cServerHandle", "", tolua_collect_cServerHandle);
tolua_usertype(tolua_S, "cTCPLink");
tolua_usertype(tolua_S, "cUDPEndpoint");
tolua_cclass(tolua_S, "cNetwork", "cNetwork", "", nullptr);
tolua_cclass(tolua_S, "cServerHandle", "cServerHandle", "", tolua_collect_cServerHandle);
tolua_cclass(tolua_S, "cTCPLink", "cTCPLink", "", nullptr);
tolua_cclass(tolua_S, "cUDPEndpoint", "cUDPEndpoint", "", tolua_collect_cUDPEndpoint);
// Fill in the functions (alpha-sorted):

View File

@ -1280,7 +1280,7 @@ static int tolua_cRankManager_SetRankVisuals(lua_State * L)
void ManualBindings::BindRankManager(lua_State * tolua_S)
void cManualBindings::BindRankManager(lua_State * tolua_S)
{
// Create the cRankManager class in the API:
tolua_usertype(tolua_S, "cRankManager");

View File

@ -0,0 +1,588 @@
// ManualBindings_World.cpp
// Implements the manual Lua API bindings for the cWorld class
#include "Globals.h"
#include "tolua++/include/tolua++.h"
#include "../World.h"
#include "../Broadcaster.h"
#include "ManualBindings.h"
#include "LuaState.h"
#include "PluginLua.h"
#include "LuaChunkStay.h"
static int tolua_cWorld_BroadcastParticleEffect(lua_State * tolua_S)
{
/* Function signature:
World:BroadcastParticleEffect("Name", PosX, PosY, PosZ, OffX, OffY, OffZ, ParticleData, ParticleAmount, [ExcludeClient], [OptionalParam1], [OptionalParam2]
*/
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cWorld") ||
!L.CheckParamString (2) ||
!L.CheckParamNumber (3, 10)
)
{
return 0;
}
// Read the params:
cWorld * World = nullptr;
AString Name;
float PosX, PosY, PosZ, OffX, OffY, OffZ;
float ParticleData;
int ParticleAmmount;
cClientHandle * ExcludeClient = nullptr;
L.GetStackValues(1, World, Name, PosX, PosY, PosZ, OffX, OffY, OffZ, ParticleData, ParticleAmmount, ExcludeClient);
if (World == nullptr)
{
LOGWARNING("World:BroadcastParticleEffect(): invalid world parameter");
L.LogStackTrace();
return 0;
}
// Read up to 2 more optional data params:
std::array<int, 2> data;
for (int i = 0; (i < 2) && L.IsParamNumber(11 + i); i++)
{
L.GetStackValue(11 + i, data[i]);
}
World->GetBroadcaster().BroadcastParticleEffect(Name, Vector3f(PosX, PosY, PosZ), Vector3f(OffX, OffY, OffZ), ParticleData, ParticleAmmount, ExcludeClient);
return 0;
}
static int tolua_cWorld_ChunkStay(lua_State * tolua_S)
{
/* Function signature:
World:ChunkStay(ChunkCoordTable, OnChunkAvailable, OnAllChunksAvailable)
ChunkCoordTable == { {Chunk1x, Chunk1z}, {Chunk2x, Chunk2z}, ... }
*/
cLuaState L(tolua_S);
if (
!L.CheckParamUserType (1, "cWorld") ||
!L.CheckParamTable (2) ||
!L.CheckParamFunctionOrNil(3, 4)
)
{
return 0;
}
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(tolua_S);
if (Plugin == nullptr)
{
return 0;
}
// Read the params:
cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, nullptr);
if (World == nullptr)
{
LOGWARNING("World:ChunkStay(): invalid world parameter");
L.LogStackTrace();
return 0;
}
cLuaChunkStay * ChunkStay = new cLuaChunkStay(*Plugin);
if (!ChunkStay->AddChunks(2))
{
delete ChunkStay;
ChunkStay = nullptr;
return 0;
}
ChunkStay->Enable(*World->GetChunkMap(), 3, 4);
return 0;
}
static int tolua_cWorld_GetBlockInfo(lua_State * tolua_S)
{
// Exported manually, because tolua would generate useless additional parameters (a_BlockType .. a_BlockSkyLight)
// Function signature: GetBlockInfo(BlockX, BlockY, BlockZ) -> BlockValid, [BlockType, BlockMeta, BlockSkyLight, BlockBlockLight]
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cWorld") ||
!L.CheckParamNumber(2, 4) ||
!L.CheckParamEnd(5)
)
{
return 0;
}
// Get params:
cWorld * Self = nullptr;
int BlockX, BlockY, BlockZ;
L.GetStackValues(1, Self, BlockX, BlockY, BlockZ);
if (Self == nullptr)
{
return cManualBindings::lua_do_error(tolua_S, "Error in function call '#funcname#': Invalid 'self'");
}
// Call the function:
BLOCKTYPE BlockType;
NIBBLETYPE BlockMeta, BlockSkyLight, BlockBlockLight;
bool res = Self->GetBlockInfo(BlockX, BlockY, BlockZ, BlockType, BlockMeta, BlockSkyLight, BlockBlockLight);
// Push the returned values:
L.Push(res);
if (res)
{
L.Push(BlockType);
L.Push(BlockMeta);
L.Push(BlockSkyLight);
L.Push(BlockBlockLight);
return 5;
}
return 1;
}
static int tolua_cWorld_GetBlockTypeMeta(lua_State * tolua_S)
{
// Exported manually, because tolua would generate useless additional parameters (a_BlockType, a_BlockMeta)
// Function signature: GetBlockTypeMeta(BlockX, BlockY, BlockZ) -> BlockValid, [BlockType, BlockMeta]
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cWorld") ||
!L.CheckParamNumber(2, 4) ||
!L.CheckParamEnd(5)
)
{
return 0;
}
// Get params:
cWorld * Self = nullptr;
int BlockX, BlockY, BlockZ;
L.GetStackValues(1, Self, BlockX, BlockY, BlockZ);
if (Self == nullptr)
{
return cManualBindings::lua_do_error(tolua_S, "Error in function call '#funcname#': Invalid 'self'");
}
// Call the function:
BLOCKTYPE BlockType;
NIBBLETYPE BlockMeta;
bool res = Self->GetBlockTypeMeta(BlockX, BlockY, BlockZ, BlockType, BlockMeta);
// Push the returned values:
L.Push(res);
if (res)
{
L.Push(BlockType);
L.Push(BlockMeta);
return 3;
}
return 1;
}
static int tolua_cWorld_GetSignLines(lua_State * tolua_S)
{
// Exported manually, because tolua would generate useless additional parameters (a_Line1 .. a_Line4)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cWorld") ||
!L.CheckParamNumber(2, 4) ||
!L.CheckParamEnd(5)
)
{
return 0;
}
// Get params:
cWorld * Self = nullptr;
int BlockX, BlockY, BlockZ;
L.GetStackValues(1, Self, BlockX, BlockY, BlockZ);
if (Self == nullptr)
{
return cManualBindings::lua_do_error(tolua_S, "Error in function call '#funcname#': Invalid 'self'");
}
// Call the function:
AString Line1, Line2, Line3, Line4;
bool res = Self->GetSignLines(BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4);
// Push the returned values:
L.Push(res);
if (res)
{
L.Push(Line1);
L.Push(Line2);
L.Push(Line3);
L.Push(Line4);
return 5;
}
return 1;
}
static int tolua_cWorld_PrepareChunk(lua_State * tolua_S)
{
/* Function signature:
World:PrepareChunk(ChunkX, ChunkZ, Callback)
*/
// Check the param types:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType (1, "cWorld") ||
!L.CheckParamNumber (2, 3) ||
!L.CheckParamFunctionOrNil(4)
)
{
return 0;
}
// Read the params:
cWorld * world = nullptr;
int chunkX = 0, chunkZ = 0;
L.GetStackValues(1, world, chunkX, chunkZ);
if (world == nullptr)
{
LOGWARNING("World:PrepareChunk(): invalid world parameter");
L.LogStackTrace();
return 0;
}
// Wrap the Lua callback inside a C++ callback class:
class cCallback:
public cChunkCoordCallback
{
public:
cCallback(lua_State * a_LuaState):
m_LuaState(a_LuaState),
m_Callback(m_LuaState, 4)
{
}
// cChunkCoordCallback override:
virtual void Call(int a_CBChunkX, int a_CBChunkZ) override
{
if (m_Callback.IsValid())
{
m_LuaState.Call(m_Callback, a_CBChunkX, a_CBChunkZ);
}
// This is the last reference of this object, we must delete it so that it doesn't leak:
delete this;
}
protected:
cLuaState m_LuaState;
cLuaState::cRef m_Callback;
};
cCallback * callback = new cCallback(tolua_S);
// Call the chunk preparation:
world->PrepareChunk(chunkX, chunkZ, callback);
return 0;
}
class cLuaWorldTask :
public cWorld::cTask,
public cPluginLua::cResettable
{
public:
cLuaWorldTask(cPluginLua & a_Plugin, int a_FnRef) :
cPluginLua::cResettable(a_Plugin),
m_FnRef(a_FnRef)
{
}
protected:
int m_FnRef;
// cWorld::cTask overrides:
virtual void Run(cWorld & a_World) override
{
cCSLock Lock(m_CSPlugin);
if (m_Plugin != nullptr)
{
m_Plugin->Call(m_FnRef, &a_World);
}
}
} ;
static int tolua_cWorld_QueueTask(lua_State * tolua_S)
{
// Binding for cWorld::QueueTask
// Params: function
// Retrieve the cPlugin from the LuaState:
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(tolua_S);
if (Plugin == nullptr)
{
// An error message has been already printed in GetLuaPlugin()
return 0;
}
// Retrieve the args:
cWorld * self = (cWorld *)tolua_tousertype(tolua_S, 1, nullptr);
if (self == nullptr)
{
return cManualBindings::lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance");
}
if (!lua_isfunction(tolua_S, 2))
{
return cManualBindings::lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a function for parameter #1");
}
// Create a reference to the function:
int FnRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX);
if (FnRef == LUA_REFNIL)
{
return cManualBindings::lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #1");
}
auto task = std::make_shared<cLuaWorldTask>(*Plugin, FnRef);
Plugin->AddResettable(task);
self->QueueTask(task);
return 0;
}
static int tolua_cWorld_SetSignLines(lua_State * tolua_S)
{
// Exported manually, because tolua would generate useless additional return values (a_Line1 .. a_Line4)
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cWorld") ||
!L.CheckParamNumber(2, 4) ||
!L.CheckParamString(5, 8) ||
!L.CheckParamEnd(9)
)
{
return 0;
}
// Get params:
cWorld * Self = nullptr;
int BlockX, BlockY, BlockZ;
AString Line1, Line2, Line3, Line4;
L.GetStackValues(1, Self, BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4);
if (Self == nullptr)
{
return cManualBindings::lua_do_error(tolua_S, "Error in function call '#funcname#': Invalid 'self'");
}
// Call the function:
bool res = Self->SetSignLines(BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4);
// Push the returned values:
L.Push(res);
return 1;
}
class cLuaScheduledWorldTask :
public cWorld::cTask,
public cPluginLua::cResettable
{
public:
cLuaScheduledWorldTask(cPluginLua & a_Plugin, int a_FnRef) :
cPluginLua::cResettable(a_Plugin),
m_FnRef(a_FnRef)
{
}
protected:
int m_FnRef;
// cWorld::cTask overrides:
virtual void Run(cWorld & a_World) override
{
cCSLock Lock(m_CSPlugin);
if (m_Plugin != nullptr)
{
m_Plugin->Call(m_FnRef, &a_World);
}
}
};
static int tolua_cWorld_ScheduleTask(lua_State * tolua_S)
{
// Binding for cWorld::ScheduleTask
// Params: function, Ticks
// Retrieve the cPlugin from the LuaState:
cPluginLua * Plugin = cManualBindings::GetLuaPlugin(tolua_S);
if (Plugin == nullptr)
{
// An error message has been already printed in GetLuaPlugin()
return 0;
}
// Retrieve the args:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cWorld") ||
!L.CheckParamNumber (2) ||
!L.CheckParamFunction(3)
)
{
return 0;
}
cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, nullptr);
if (World == nullptr)
{
return cManualBindings::lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance");
}
// Create a reference to the function:
int FnRef = luaL_ref(tolua_S, LUA_REGISTRYINDEX);
if (FnRef == LUA_REFNIL)
{
return cManualBindings::lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #1");
}
int DelayTicks = (int)tolua_tonumber(tolua_S, 2, 0);
auto task = std::make_shared<cLuaScheduledWorldTask>(*Plugin, FnRef);
Plugin->AddResettable(task);
World->ScheduleTask(DelayTicks, task);
return 0;
}
static int tolua_cWorld_TryGetHeight(lua_State * tolua_S)
{
/* Exported manually, because tolua would require the out-only param a_Height to be used when calling
Function signature: world:TryGetHeight(a_World, a_BlockX, a_BlockZ) -> IsValid, Height
*/
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamUserType(1, "cWorld") ||
!L.CheckParamNumber(2, 3) ||
!L.CheckParamEnd(4)
)
{
return 0;
}
// Get params:
cWorld * self = nullptr;
int BlockX, BlockZ;
L.GetStackValues(1, self, BlockX, BlockZ);
if (self == nullptr)
{
tolua_error(tolua_S, "Invalid 'self' in function 'TryGetHeight'", nullptr);
return 0;
}
// Call the implementation:
int Height = 0;
bool res = self->TryGetHeight(BlockX, BlockZ, Height);
L.Push(res ? 1 : 0);
if (res)
{
L.Push(Height);
return 2;
}
return 1;
}
void cManualBindings::BindWorld(lua_State * tolua_S)
{
tolua_beginmodule(tolua_S, nullptr);
tolua_beginmodule(tolua_S, "cWorld");
tolua_function(tolua_S, "BroadcastParticleEffect", tolua_cWorld_BroadcastParticleEffect);
tolua_function(tolua_S, "ChunkStay", tolua_cWorld_ChunkStay);
tolua_function(tolua_S, "DoWithBlockEntityAt", DoWithXYZ<cWorld, cBlockEntity, &cWorld::DoWithBlockEntityAt>);
tolua_function(tolua_S, "DoWithBeaconAt", DoWithXYZ<cWorld, cBeaconEntity, &cWorld::DoWithBeaconAt>);
tolua_function(tolua_S, "DoWithChestAt", DoWithXYZ<cWorld, cChestEntity, &cWorld::DoWithChestAt>);
tolua_function(tolua_S, "DoWithDispenserAt", DoWithXYZ<cWorld, cDispenserEntity, &cWorld::DoWithDispenserAt>);
tolua_function(tolua_S, "DoWithDropSpenserAt", DoWithXYZ<cWorld, cDropSpenserEntity, &cWorld::DoWithDropSpenserAt>);
tolua_function(tolua_S, "DoWithDropperAt", DoWithXYZ<cWorld, cDropperEntity, &cWorld::DoWithDropperAt>);
tolua_function(tolua_S, "DoWithEntityByID", DoWithID< cWorld, cEntity, &cWorld::DoWithEntityByID>);
tolua_function(tolua_S, "DoWithFurnaceAt", DoWithXYZ<cWorld, cFurnaceEntity, &cWorld::DoWithFurnaceAt>);
tolua_function(tolua_S, "DoWithNoteBlockAt", DoWithXYZ<cWorld, cNoteEntity, &cWorld::DoWithNoteBlockAt>);
tolua_function(tolua_S, "DoWithCommandBlockAt", DoWithXYZ<cWorld, cCommandBlockEntity, &cWorld::DoWithCommandBlockAt>);
tolua_function(tolua_S, "DoWithMobHeadAt", DoWithXYZ<cWorld, cMobHeadEntity, &cWorld::DoWithMobHeadAt>);
tolua_function(tolua_S, "DoWithFlowerPotAt", DoWithXYZ<cWorld, cFlowerPotEntity, &cWorld::DoWithFlowerPotAt>);
tolua_function(tolua_S, "DoWithPlayer", DoWith< cWorld, cPlayer, &cWorld::DoWithPlayer>);
tolua_function(tolua_S, "FindAndDoWithPlayer", DoWith< cWorld, cPlayer, &cWorld::FindAndDoWithPlayer>);
tolua_function(tolua_S, "DoWithPlayerByUUID", DoWith< cWorld, cPlayer, &cWorld::DoWithPlayerByUUID>);
tolua_function(tolua_S, "ForEachBlockEntityInChunk", ForEachInChunk<cWorld, cBlockEntity, &cWorld::ForEachBlockEntityInChunk>);
tolua_function(tolua_S, "ForEachChestInChunk", ForEachInChunk<cWorld, cChestEntity, &cWorld::ForEachChestInChunk>);
tolua_function(tolua_S, "ForEachEntity", ForEach< cWorld, cEntity, &cWorld::ForEachEntity>);
tolua_function(tolua_S, "ForEachEntityInBox", ForEachInBox< cWorld, cEntity, &cWorld::ForEachEntityInBox>);
tolua_function(tolua_S, "ForEachEntityInChunk", ForEachInChunk<cWorld, cEntity, &cWorld::ForEachEntityInChunk>);
tolua_function(tolua_S, "ForEachFurnaceInChunk", ForEachInChunk<cWorld, cFurnaceEntity, &cWorld::ForEachFurnaceInChunk>);
tolua_function(tolua_S, "ForEachPlayer", ForEach< cWorld, cPlayer, &cWorld::ForEachPlayer>);
tolua_function(tolua_S, "GetBlockInfo", tolua_cWorld_GetBlockInfo);
tolua_function(tolua_S, "GetBlockTypeMeta", tolua_cWorld_GetBlockTypeMeta);
tolua_function(tolua_S, "GetSignLines", tolua_cWorld_GetSignLines);
tolua_function(tolua_S, "PrepareChunk", tolua_cWorld_PrepareChunk);
tolua_function(tolua_S, "QueueTask", tolua_cWorld_QueueTask);
tolua_function(tolua_S, "ScheduleTask", tolua_cWorld_ScheduleTask);
tolua_function(tolua_S, "SetSignLines", tolua_cWorld_SetSignLines);
tolua_function(tolua_S, "TryGetHeight", tolua_cWorld_TryGetHeight);
tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S);
}

View File

@ -56,7 +56,9 @@ public:
virtual bool OnDisconnect (cClientHandle & a_Client, const AString & a_Reason) = 0;
virtual bool OnEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier) = 0;
virtual bool OnEntityTeleport (cEntity & a_Entity, const Vector3d & a_OldPosition, const Vector3d & a_NewPosition) = 0;
virtual bool OnExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split) = 0;
virtual bool OnEntityChangeWorld (cEntity & a_Entity, cWorld & a_World) = 0;
virtual bool OnEntityChangedWorld (cEntity & a_Entity, cWorld & a_World) = 0;
virtual bool OnExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split, const AString & a_EntireCommand, cPluginManager::CommandResult & a_Result) = 0;
virtual bool OnExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) = 0;
virtual bool OnExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) = 0;
virtual bool OnHandshake (cClientHandle & a_Client, const AString & a_Username) = 0;

View File

@ -534,7 +534,55 @@ bool cPluginLua::OnEntityAddEffect(cEntity & a_Entity, int a_EffectType, int a_E
bool cPluginLua::OnExecuteCommand(cPlayer * a_Player, const AStringVector & a_Split)
bool cPluginLua::OnEntityChangeWorld(cEntity & a_Entity, cWorld & a_World)
{
cCSLock Lock(m_CriticalSection);
if (!m_LuaState.IsValid())
{
return false;
}
bool res = false;
cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_ENTITY_CHANGE_WORLD];
for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr)
{
m_LuaState.Call((int)(**itr), &a_Entity, &a_World, cLuaState::Return, res);
if (res)
{
return true;
}
}
return false;
}
bool cPluginLua::OnEntityChangedWorld(cEntity & a_Entity, cWorld & a_World)
{
cCSLock Lock(m_CriticalSection);
if (!m_LuaState.IsValid())
{
return false;
}
bool res = false;
cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_ENTITY_CHANGED_WORLD];
for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr)
{
m_LuaState.Call((int)(**itr), &a_Entity, &a_World, res);
if (res)
{
return true;
}
}
return false;
}
bool cPluginLua::OnExecuteCommand(cPlayer * a_Player, const AStringVector & a_Split, const AString & a_EntireCommand, cPluginManager::CommandResult & a_Result)
{
cCSLock Lock(m_CriticalSection);
if (!m_LuaState.IsValid())
@ -545,7 +593,7 @@ bool cPluginLua::OnExecuteCommand(cPlayer * a_Player, const AStringVector & a_Sp
cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_EXECUTE_COMMAND];
for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr)
{
m_LuaState.Call((int)(**itr), a_Player, a_Split, cLuaState::Return, res);
m_LuaState.Call((int)(**itr), a_Player, a_Split, a_EntireCommand, cLuaState::Return, res, a_Result);
if (res)
{
return true;
@ -1884,6 +1932,8 @@ const char * cPluginLua::GetHookFnName(int a_HookType)
case cPluginManager::HOOK_DISCONNECT: return "OnDisconnect";
case cPluginManager::HOOK_PLAYER_ANIMATION: return "OnPlayerAnimation";
case cPluginManager::HOOK_ENTITY_ADD_EFFECT: return "OnEntityAddEffect";
case cPluginManager::HOOK_ENTITY_CHANGE_WORLD: return "OnEntityChangeWorld";
case cPluginManager::HOOK_ENTITY_CHANGED_WORLD: return "OnEntityChangedWorld";
case cPluginManager::HOOK_ENTITY_TELEPORT: return "OnEntityTeleport";
case cPluginManager::HOOK_EXECUTE_COMMAND: return "OnExecuteCommand";
case cPluginManager::HOOK_HANDSHAKE: return "OnHandshake";

View File

@ -20,7 +20,7 @@
// fwd: UI/Window.h
// fwd: "UI/Window.h"
class cWindow;
@ -115,7 +115,9 @@ public:
virtual bool OnCraftingNoRecipe (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) override;
virtual bool OnDisconnect (cClientHandle & a_Client, const AString & a_Reason) override;
virtual bool OnEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier) override;
virtual bool OnExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split) override;
virtual bool OnEntityChangeWorld (cEntity & a_Entity, cWorld & a_World) override;
virtual bool OnEntityChangedWorld (cEntity & a_Entity, cWorld & a_World) override;
virtual bool OnExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split, const AString & a_EntireCommand, cPluginManager::CommandResult & a_Result) override;
virtual bool OnExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) override;
virtual bool OnExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) override;
virtual bool OnHandshake (cClientHandle & a_Client, const AString & a_Username) override;

View File

@ -118,7 +118,7 @@ void cPluginManager::ReloadPluginsNow(void)
void cPluginManager::ReloadPluginsNow(cIniFile & a_SettingsIni)
void cPluginManager::ReloadPluginsNow(cSettingsRepositoryInterface & a_Settings)
{
LOG("-- Loading Plugins --");
@ -130,7 +130,7 @@ void cPluginManager::ReloadPluginsNow(cIniFile & a_SettingsIni)
RefreshPluginList();
// Load the plugins:
AStringVector ToLoad = GetFoldersToLoad(a_SettingsIni);
AStringVector ToLoad = GetFoldersToLoad(a_Settings);
for (auto & pluginFolder: ToLoad)
{
LoadPlugin(pluginFolder);
@ -157,16 +157,16 @@ void cPluginManager::ReloadPluginsNow(cIniFile & a_SettingsIni)
void cPluginManager::InsertDefaultPlugins(cIniFile & a_SettingsIni)
void cPluginManager::InsertDefaultPlugins(cSettingsRepositoryInterface & a_Settings)
{
a_SettingsIni.AddKeyName("Plugins");
a_SettingsIni.AddKeyComment("Plugins", " Plugin=Debuggers");
a_SettingsIni.AddKeyComment("Plugins", " Plugin=HookNotify");
a_SettingsIni.AddKeyComment("Plugins", " Plugin=ChunkWorx");
a_SettingsIni.AddKeyComment("Plugins", " Plugin=APIDump");
a_SettingsIni.AddValue("Plugins", "Plugin", "Core");
a_SettingsIni.AddValue("Plugins", "Plugin", "TransAPI");
a_SettingsIni.AddValue("Plugins", "Plugin", "ChatLog");
a_Settings.AddKeyName("Plugins");
a_Settings.AddKeyComment("Plugins", " Plugin=Debuggers");
a_Settings.AddKeyComment("Plugins", " Plugin=HookNotify");
a_Settings.AddKeyComment("Plugins", " Plugin=ChunkWorx");
a_Settings.AddKeyComment("Plugins", " Plugin=APIDump");
a_Settings.AddValue("Plugins", "Plugin", "Core");
a_Settings.AddValue("Plugins", "Plugin", "TransAPI");
a_Settings.AddValue("Plugins", "Plugin", "ChatLog");
}
@ -525,14 +525,50 @@ bool cPluginManager::CallHookEntityTeleport(cEntity & a_Entity, const Vector3d &
bool cPluginManager::CallHookExecuteCommand(cPlayer * a_Player, const AStringVector & a_Split)
bool cPluginManager::CallHookEntityChangeWorld(cEntity & a_Entity, cWorld & a_World)
{
FIND_HOOK(HOOK_ENTITY_CHANGE_WORLD);
VERIFY_HOOK;
for (PluginList::iterator itr = Plugins->second.begin(); itr != Plugins->second.end(); ++itr)
{
if ((*itr)->OnEntityChangeWorld(a_Entity, a_World))
{
return true;
}
}
return false;
}
bool cPluginManager::CallHookEntityChangedWorld(cEntity & a_Entity, cWorld & a_World)
{
FIND_HOOK(HOOK_ENTITY_CHANGED_WORLD);
VERIFY_HOOK;
for (PluginList::iterator itr = Plugins->second.begin(); itr != Plugins->second.end(); ++itr)
{
if ((*itr)->OnEntityChangedWorld(a_Entity, a_World))
{
return true;
}
}
return false;
}
bool cPluginManager::CallHookExecuteCommand(cPlayer * a_Player, const AStringVector & a_Split, const AString & a_EntireCommand, CommandResult & a_Result)
{
FIND_HOOK(HOOK_EXECUTE_COMMAND);
VERIFY_HOOK;
for (PluginList::iterator itr = Plugins->second.begin(); itr != Plugins->second.end(); ++itr)
{
if ((*itr)->OnExecuteCommand(a_Player, a_Split))
if ((*itr)->OnExecuteCommand(a_Player, a_Split, a_EntireCommand, a_Result))
{
return true;
}
@ -1445,14 +1481,25 @@ cPluginManager::CommandResult cPluginManager::HandleCommand(cPlayer & a_Player,
if (cmd == m_Commands.end())
{
// Command not found
// If it started with a slash, ask the plugins if they still want to handle it:
if (!a_Command.empty() && (a_Command[0] == '/'))
{
CommandResult Result = crUnknownCommand;
CallHookExecuteCommand(&a_Player, Split, a_Command, Result);
return Result;
}
return crUnknownCommand;
}
// Ask plugins first if a command is okay to execute the command:
if (CallHookExecuteCommand(&a_Player, Split))
CommandResult Result = crBlocked;
if (CallHookExecuteCommand(&a_Player, Split, a_Command, Result))
{
if (Result == crBlocked)
{
LOGINFO("Player %s tried executing command \"%s\" that was stopped by the HOOK_EXECUTE_COMMAND hook", a_Player.GetName().c_str(), Split[0].c_str());
return crBlocked;
}
return Result;
}
if (
@ -1750,7 +1797,10 @@ bool cPluginManager::ExecuteConsoleCommand(const AStringVector & a_Split, cComma
if (cmd == m_ConsoleCommands.end())
{
// Command not found
return false;
// Still notify the plugins (so that plugins such as Aliases can intercept unknown commands).
CommandResult res = crBlocked;
CallHookExecuteCommand(nullptr, a_Split, a_Command, res);
return (res == crExecuted);
}
if (cmd->second.m_Plugin == nullptr)
@ -1760,10 +1810,10 @@ bool cPluginManager::ExecuteConsoleCommand(const AStringVector & a_Split, cComma
}
// Ask plugins first if a command is okay to execute the console command:
if (CallHookExecuteCommand(nullptr, a_Split))
CommandResult res = crBlocked;
if (CallHookExecuteCommand(nullptr, a_Split, a_Command, res))
{
a_Output.Out("Command \"%s\" was stopped by the HOOK_EXECUTE_COMMAND hook", a_Split[0].c_str());
return false;
return (res == crExecuted);
}
return cmd->second.m_Plugin->HandleConsoleCommand(a_Split, a_Output, a_Command);
@ -1882,25 +1932,23 @@ size_t cPluginManager::GetNumLoadedPlugins(void) const
AStringVector cPluginManager::GetFoldersToLoad(cIniFile & a_SettingsIni)
AStringVector cPluginManager::GetFoldersToLoad(cSettingsRepositoryInterface & a_Settings)
{
// Check if the Plugins section exists.
int KeyNum = a_SettingsIni.FindKey("Plugins");
if (KeyNum == -1)
if (a_Settings.KeyExists("Plugins"))
{
InsertDefaultPlugins(a_SettingsIni);
KeyNum = a_SettingsIni.FindKey("Plugins");
InsertDefaultPlugins(a_Settings);
}
// Get the list of plugins to load:
AStringVector res;
int NumPlugins = a_SettingsIni.GetNumValues(KeyNum);
for (int i = 0; i < NumPlugins; i++)
auto Values = a_Settings.GetValues("Plugins");
for (auto NameValue : Values)
{
AString ValueName = a_SettingsIni.GetValueName(KeyNum, i);
AString ValueName = NameValue.first;
if (ValueName.compare("Plugin") == 0)
{
AString PluginFile = a_SettingsIni.GetValue(KeyNum, i);
AString PluginFile = NameValue.second;
if (!PluginFile.empty())
{
res.push_back(PluginFile);

View File

@ -24,6 +24,7 @@ class cPlayer;
class cPlugin;
class cProjectileEntity;
class cWorld;
class cSettingsRepositoryInterface;
struct TakeDamageInfo;
typedef SharedPtr<cPlugin> cPluginPtr;
@ -85,6 +86,8 @@ public:
HOOK_DISCONNECT,
HOOK_PLAYER_ANIMATION,
HOOK_ENTITY_ADD_EFFECT,
HOOK_ENTITY_CHANGE_WORLD,
HOOK_ENTITY_CHANGED_WORLD,
HOOK_EXECUTE_COMMAND,
HOOK_EXPLODED,
HOOK_EXPLODING,
@ -200,7 +203,9 @@ public:
bool CallHookDisconnect (cClientHandle & a_Client, const AString & a_Reason);
bool CallHookEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier);
bool CallHookEntityTeleport (cEntity & a_Entity, const Vector3d & a_OldPosition, const Vector3d & a_NewPosition);
bool CallHookExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split); // If a_Player == nullptr, it is a console cmd
bool CallHookEntityChangeWorld (cEntity & a_Entity, cWorld & a_World);
bool CallHookEntityChangedWorld (cEntity & a_Entity, cWorld & a_World);
bool CallHookExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split, const AString & a_EntireCommand, CommandResult & a_Result); // If a_Player == nullptr, it is a console cmd
bool CallHookExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData);
bool CallHookExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData);
bool CallHookHandshake (cClientHandle & a_ClientHandle, const AString & a_Username);
@ -299,7 +304,9 @@ public:
/** Returns true if the console command is in the command map */
bool IsConsoleCommandBound(const AString & a_Command); // tolua_export
/** Executes the command split into a_Split, as if it was given on the console. Returns true if executed. Output is sent to the a_Output callback */
/** Executes the command split into a_Split, as if it was given on the console.
Returns true if executed. Output is sent to the a_Output callback
Exported in ManualBindings.cpp with a different signature. */
bool ExecuteConsoleCommand(const AStringVector & a_Split, cCommandOutputCallback & a_Output, const AString & a_Command);
/** Appends all commands beginning with a_Text (case-insensitive) into a_Results.
@ -362,20 +369,20 @@ private:
/** Reloads all plugins, defaulting to settings.ini for settings location */
void ReloadPluginsNow(void);
/** Reloads all plugins with a cIniFile object expected to be initialised to settings.ini */
void ReloadPluginsNow(cIniFile & a_SettingsIni);
/** Reloads all plugins with a settings repo expected to be initialised to settings.ini */
void ReloadPluginsNow(cSettingsRepositoryInterface & a_Settings);
/** Unloads all plugins */
void UnloadPluginsNow(void);
/** Handles writing default plugins if 'Plugins' key not found using a cIniFile object expected to be intialised to settings.ini */
void InsertDefaultPlugins(cIniFile & a_SettingsIni);
/** Handles writing default plugins if 'Plugins' key not found using a settings repo expected to be intialised to settings.ini */
void InsertDefaultPlugins(cSettingsRepositoryInterface & a_Settings);
/** Tries to match a_Command to the internal table of commands, if a match is found, the corresponding plugin is called. Returns crExecuted if the command is executed. */
CommandResult HandleCommand(cPlayer & a_Player, const AString & a_Command, bool a_ShouldCheckPermissions);
/** Returns the folders that are specified in the settings ini to load plugins from. */
AStringVector GetFoldersToLoad(cIniFile & a_SettingsIni);
AStringVector GetFoldersToLoad(cSettingsRepositoryInterface & a_Settings);
} ; // tolua_export

View File

@ -1,518 +0,0 @@
-- flags
local disable_virtual_hooks = true
local enable_pure_virtual = true
local default_private_access = false
local access = {public = 0, protected = 1, private = 2}
function preparse_hook(p)
if default_private_access then
-- we need to make all structs 'public' by default
p.code = string.gsub(p.code, "(struct[^;]*{)", "%1\npublic:\n")
end
end
function parser_hook(s)
local container = classContainer.curr -- get the current container
if default_private_access then
if not container.curr_member_access and container.classtype == 'class' then
-- default access for classes is private
container.curr_member_access = access.private
end
end
-- try labels (public, private, etc)
do
local b,e,label = string.find(s, "^%s*(%w*)%s*:[^:]") -- we need to check for [^:], otherwise it would match 'namespace::type'
if b then
-- found a label, get the new access value from the global 'access' table
if access[label] then
container.curr_member_access = access[label]
end -- else ?
return strsub(s, e) -- normally we would use 'e+1', but we need to preserve the [^:]
end
end
local ret = nil
if disable_virtual_hooks then
return ret
end
local b,e,decl,arg = string.find(s, "^%s*virtual%s+([^%({~]+)(%b())")
local const
if b then
local ret = string.sub(s, e+1)
if string.find(ret, "^%s*const") then
const = "const"
ret = string.gsub(ret, "^%s*const", "")
end
local purev = false
if string.find(ret, "^%s*=%s*0") then
purev = true
ret = string.gsub(ret, "^%s*=%s*0", "")
end
ret = string.gsub(ret, "^%s*%b{}", "")
local func = Function(decl, arg, const)
func.pure_virtual = purev
--func.access = access
func.original_sig = decl
local curflags = classContainer.curr.flags
if not curflags.virtual_class then
curflags.virtual_class = VirtualClass()
end
curflags.virtual_class:add(func)
curflags.pure_virtual = curflags.pure_virtual or purev
return ret
end
return ret
end
-- class VirtualClass
classVirtualClass = {
classtype = 'class',
name = '',
base = '',
type = '',
btype = '',
ctype = '',
}
classVirtualClass.__index = classVirtualClass
setmetatable(classVirtualClass,classClass)
function classVirtualClass:add(f)
local parent = classContainer.curr
pop()
table.insert(self.methods, {f=f})
local name,sig
-- doble negative means positive
if f.name == 'new' and ((not self.flags.parent_object.flags.pure_virtual) or (enable_pure_virtual)) then
name = self.original_name
elseif f.name == 'delete' then
name = '~'..self.original_name
else
if f.access ~= 2 and (not f.pure_virtual) and f.name ~= 'new' and f.name ~= 'delete' then
name = f.mod.." "..f.type..f.ptr.." "..self.flags.parent_object.lname.."__"..f.name
end
end
if name then
sig = name..self:get_arg_list(f, true)..";\n"
push(self)
sig = preprocess(sig)
self:parse(sig)
pop()
end
push(parent)
end
function preprocess(sig)
sig = gsub(sig,"([^%w_])void%s*%*","%1_userdata ") -- substitute 'void*'
sig = gsub(sig,"([^%w_])void%s*%*","%1_userdata ") -- substitute 'void*'
sig = gsub(sig,"([^%w_])char%s*%*","%1_cstring ") -- substitute 'char*'
sig = gsub(sig,"([^%w_])lua_State%s*%*","%1_lstate ") -- substitute 'lua_State*'
return sig
end
function classVirtualClass:get_arg_list(f, decl)
local ret = ""
local sep = ""
local i=1
while f.args[i] do
local arg = f.args[i]
if decl then
local ptr
if arg.ret ~= '' then
ptr = arg.ret
else
ptr = arg.ptr
end
local def = ""
if arg.def and arg.def ~= "" then
def = " = "..arg.def
end
ret = ret..sep..arg.mod.." "..arg.type..ptr.." "..arg.name..def
else
ret = ret..sep..arg.name
end
sep = ","
i = i+1
end
return "("..ret..")"
end
function classVirtualClass:add_parent_virtual_methods(parent)
parent = parent or _global_classes[self.flags.parent_object.btype]
if not parent then return end
if parent.flags.virtual_class then
local vclass = parent.flags.virtual_class
for k,v in ipairs(vclass.methods) do
if v.f.name ~= 'new' and v.f.name ~= 'delete' and (not self:has_method(v.f)) then
table.insert(self.methods, {f=v.f})
end
end
end
parent = _global_classes[parent.btype]
if parent then
self:add_parent_virtual_methods(parent)
end
end
function classVirtualClass:has_method(f)
for k,v in pairs(self.methods) do
-- just match name for now
if v.f.name == f.name then
return true
end
end
return false
end
function classVirtualClass:add_constructors()
local i=1
while self.flags.parent_object[i] do
local v = self.flags.parent_object[i]
if getmetatable(v) == classFunction and (v.name == 'new' or v.name == 'delete') then
self:add(v)
end
i = i+1
end
end
--[[
function classVirtualClass:requirecollection(t)
self:add_constructors()
local req = classClass.requirecollection(self, t)
if req then
output('class ',self.name,";")
end
return req
end
--]]
function classVirtualClass:supcode()
-- pure virtual classes can have no default constructors on gcc 4
if self.flags.parent_object.flags.pure_virtual and not enable_pure_virtual then
output('#if (__GNUC__ == 4) || (__GNUC__ > 4 ) // I hope this works on Microsoft Visual studio .net server 2003 XP Compiler\n')
end
local ns
if self.prox.classtype == 'namespace' then
output('namespace ',self.prox.name, " {")
ns = true
end
output("class "..self.original_name.." : public "..self.btype..", public ToluaBase {")
output("public:\n")
self:add_parent_virtual_methods()
self:output_methods(self.btype)
self:output_parent_methods()
self:add_constructors()
-- no constructor for pure virtual classes
if (not self.flags.parent_object.flags.pure_virtual) or enable_pure_virtual then
self:output_constructors()
end
output("};\n\n")
if ns then
output("};")
end
classClass.supcode(self)
if self.flags.parent_object.flags.pure_virtual and not enable_pure_virtual then
output('#endif // __GNUC__ >= 4\n')
end
-- output collector for custom class if required
if self:requirecollection(_collect) and _collect[self.type] then
output('\n')
output('/* function to release collected object via destructor */')
output('#ifdef __cplusplus\n')
--for i,v in pairs(collect) do
i,v = self.type, _collect[self.type]
output('\nstatic int '..v..' (lua_State* tolua_S)')
output('{')
output(' '..i..'* self = ('..i..'*) tolua_tousertype(tolua_S,1,0);')
output(' delete self;')
output(' return 0;')
output('}')
--end
output('#endif\n\n')
end
end
function classVirtualClass:register(pre)
-- pure virtual classes can have no default constructors on gcc 4
if self.flags.parent_object.flags.pure_virtual and not enable_pure_virtual then
output('#if (__GNUC__ == 4) || (__GNUC__ > 4 )\n')
end
classClass.register(self, pre)
if self.flags.parent_object.flags.pure_virtual and not enable_pure_virtual then
output('#endif // __GNUC__ >= 4\n')
end
end
--function classVirtualClass:requirecollection(_c)
-- if self.flags.parent_object.flags.pure_virtual then
-- return false
-- end
-- return classClass.requirecollection(self, _c)
--end
function classVirtualClass:output_parent_methods()
for k,v in ipairs(self.methods) do
if v.f.access ~= 2 and (not v.f.pure_virtual) and v.f.name ~= 'new' and v.f.name ~= 'delete' then
local rettype = v.f.mod.." "..v.f.type..v.f.ptr.." "
local parent_name = rettype..self.btype.."__"..v.f.name
local par_list = self:get_arg_list(v.f, true)
local var_list = self:get_arg_list(v.f, false)
-- the parent's virtual function
output("\t"..parent_name..par_list.." {")
output("\t\treturn (",rettype,")"..self.btype.."::"..v.f.name..var_list..";")
output("\t};")
end
end
end
function classVirtualClass:output_methods(btype)
for k,v in ipairs(self.methods) do
if v.f.name ~= 'new' and v.f.name ~= 'delete' then
self:output_method(v.f, btype)
end
end
output("\n")
end
function classVirtualClass:output_constructors()
for k,v in ipairs(self.methods) do
if v.f.name == 'new' then
local par_list = self:get_arg_list(v.f, true)
local var_list = self:get_arg_list(v.f, false)
output("\t",self.original_name,par_list,":",self.btype,var_list,"{};")
end
end
end
function classVirtualClass:output_method(f, btype)
if f.access == 2 then -- private
return
end
local ptr
if f.ret ~= '' then
ptr = f.ret
else
ptr = f.ptr
end
local rettype = f.mod.." "..f.type..f.ptr.." "
local par_list = self:get_arg_list(f, true)
local var_list = self:get_arg_list(f, false)
if string.find(rettype, "%s*LuaQtGenericFlags%s*") then
_,_,rettype = string.find(f.original_sig, "^%s*([^%s]+)%s+")
end
-- the caller of the lua method
output("\t"..rettype.." "..f.name..par_list..f.const.." {")
local fn = f.cname
if f.access == 1 then
fn = "NULL"
end
output('\t\tif (push_method("',f.lname,'", ',fn,')) {')
--if f.type ~= 'void' then
-- output("\t\t\tint top = lua_gettop(lua_state)-1;")
--end
-- push the parameters
local argn = 0
for i,arg in ipairs(f.args) do
if arg.type ~= 'void' then
local t,ct = isbasic(arg.type)
if t and t ~= '' then
if arg.ret == "*" then
t = 'userdata'
ct = 'void*'
end
output("\t\t\ttolua_push"..t.."(lua_state, ("..ct..")"..arg.name..");");
else
local m = arg.ptr
if m and m~= "" then
if m == "*" then m = "" end
output("\t\t\ttolua_pushusertype(lua_state, (void*)"..m..arg.name..", \""..arg.type.."\");")
else
output("\t\t\tvoid* tolua_obj" .. argn .." = (void*)new "..arg.type.."("..arg.name..");\n")
output('\t\t\ttolua_pushusertype_and_takeownership(lua_state, tolua_obj' .. argn .. ', "'..arg.type..'");\n')
end
end
argn = argn+1
end
end
-- call the function
output("\t\t\tToluaBase::dbcall(lua_state, ",argn+1,", ")
-- return value
if f.type ~= 'void' then
output("1);")
local t,ct = isbasic(f.type)
if t and t ~= '' then
--output("\t\t\treturn ("..rettype..")tolua_to"..t.."(lua_state, top, 0);")
output("\t\t\t",rettype,"tolua_ret = ("..rettype..")tolua_to"..t.."(lua_state, -1, 0);")
else
local mod = ""
if f.ptr ~= "*" then
mod = "*("..f.type.."*)"
end
--output("\t\t\treturn ("..rettype..")"..mod.."tolua_tousertype(lua_state, top, 0);")
output("\t\t\t",rettype,"tolua_ret = ("..rettype..")"..mod.."tolua_tousertype(lua_state, -1, 0);")
end
output("\t\t\tlua_pop(lua_state, 1);")
output("\t\t\treturn tolua_ret;")
else
output("0);")
end
-- handle non-implemeted function
output("\t\t} else {")
if f.pure_virtual then
output('\t\t\tif (lua_state)')
--output('\t\t\t\ttolua_error(lua_state, "pure-virtual method '..btype.."::"..f.name..' not implemented.", NULL);')
output('\t\t\t\tLOG("pure-virtual method '..btype.."::"..f.name..' not implemented.");')
output('\t\t\telse {')
output('\t\t\t\tLOG("pure-virtual method '..btype.."::"..f.name..' called with no lua_state. Aborting");')
output('\t\t\t\t::abort();')
output('\t\t\t};')
if( rettype == " std::string " ) then
output('\t\t\treturn "";')
else
output('\t\t\treturn (',rettype,')0;')
end
else
output('\t\t\treturn (',rettype,')',btype,'::',f.name,var_list,';')
end
output("\t\t};")
output("\t};")
end
function VirtualClass()
local parent = classContainer.curr
pop()
local name = "Lua__"..parent.original_name
local c = _Class(_Container{name=name, base=parent.name, extra_bases=nil})
setmetatable(c, classVirtualClass)
local ft = getnamespace(c.parent)..c.original_name
append_global_type(ft, c)
push(parent)
c.flags.parent_object = parent
c.methods = {}
push(c)
c:parse("\nvoid tolua__set_instance(_lstate L, lua_Object lo);\n")
pop()
return c
end
function post_output_hook()
print("Bindings have been generated.")
end

View File

@ -430,7 +430,7 @@ bool cHopperEntity::MoveItemsFromFurnace(cChunk & a_Chunk)
}
// Try move from the output slot:
if (MoveItemsFromSlot(*Furnace, cFurnaceEntity::fsOutput, true))
if (MoveItemsFromSlot(*Furnace, cFurnaceEntity::fsOutput))
{
cItem NewOutput(Furnace->GetOutputSlot());
Furnace->SetOutputSlot(NewOutput.AddCount(-1));
@ -440,7 +440,7 @@ bool cHopperEntity::MoveItemsFromFurnace(cChunk & a_Chunk)
// No output moved, check if we can move an empty bucket out of the fuel slot:
if (Furnace->GetFuelSlot().m_ItemType == E_ITEM_BUCKET)
{
if (MoveItemsFromSlot(*Furnace, cFurnaceEntity::fsFuel, true))
if (MoveItemsFromSlot(*Furnace, cFurnaceEntity::fsFuel))
{
Furnace->SetFuelSlot(cItem());
return true;
@ -460,28 +460,13 @@ bool cHopperEntity::MoveItemsFromGrid(cBlockEntityWithItems & a_Entity)
cItemGrid & Grid = a_Entity.GetContents();
int NumSlots = Grid.GetNumSlots();
// First try adding items of types already in the hopper:
for (int i = 0; i < NumSlots; i++)
{
if (Grid.IsSlotEmpty(i))
{
continue;
}
if (MoveItemsFromSlot(a_Entity, i, false))
{
Grid.ChangeSlotCount(i, -1);
return true;
}
}
// No already existing stack can be topped up, try again with allowing new stacks:
for (int i = 0; i < NumSlots; i++)
{
if (Grid.IsSlotEmpty(i))
{
continue;
}
if (MoveItemsFromSlot(a_Entity, i, true))
if (MoveItemsFromSlot(a_Entity, i))
{
Grid.ChangeSlotCount(i, -1);
return true;
@ -495,21 +480,19 @@ bool cHopperEntity::MoveItemsFromGrid(cBlockEntityWithItems & a_Entity)
/// Moves one piece of the specified a_Entity's slot itemstack into this hopper. Returns true if contents have changed. Doesn't change the itemstack.
bool cHopperEntity::MoveItemsFromSlot(cBlockEntityWithItems & a_Entity, int a_SlotNum, bool a_AllowNewStacks)
bool cHopperEntity::MoveItemsFromSlot(cBlockEntityWithItems & a_Entity, int a_SlotNum)
{
cItem One(a_Entity.GetSlot(a_SlotNum).CopyOne());
for (int i = 0; i < ContentsWidth * ContentsHeight; i++)
{
if (m_Contents.IsSlotEmpty(i))
{
if (a_AllowNewStacks)
{
if (cPluginManager::Get()->CallHookHopperPullingItem(*m_World, *this, i, a_Entity, a_SlotNum))
{
// Plugin disagrees with the move
continue;
}
}
m_Contents.SetSlot(i, One);
return true;
}
@ -521,10 +504,16 @@ bool cHopperEntity::MoveItemsFromSlot(cBlockEntityWithItems & a_Entity, int a_Sl
continue;
}
auto PreviousCount = m_Contents.GetSlot(i).m_ItemCount;
m_Contents.ChangeSlotCount(i, 1);
if (PreviousCount == m_Contents.GetSlot(i).m_ItemCount + 1)
{
// Successfully added a new item. (Failure condition consistutes: stack full)
return true;
}
}
}
return false;
}

View File

@ -74,7 +74,7 @@ protected:
bool MoveItemsFromGrid(cBlockEntityWithItems & a_Entity);
/// Moves one piece from the specified itemstack into this hopper. Returns true if contents have changed. Doesn't change the itemstack.
bool MoveItemsFromSlot(cBlockEntityWithItems & a_Entity, int a_SrcSlotNum, bool a_AllowNewStacks);
bool MoveItemsFromSlot(cBlockEntityWithItems & a_Entity, int a_SrcSlotNum);
/// Moves items to the chest at the specified coords. Returns true if contents have changed
bool MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_BlockY, int a_BlockZ);

View File

@ -14,7 +14,7 @@ void cBlockBedHandler::OnDestroyed(cChunkInterface & a_ChunkInterface, cWorldInt
NIBBLETYPE OldMeta = a_ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ);
Vector3i ThisPos( a_BlockX, a_BlockY, a_BlockZ);
Vector3i Direction = MetaDataToDirection( OldMeta & 0x7);
Vector3i Direction = MetaDataToDirection( OldMeta & 0x3);
if (OldMeta & 0x8)
{
// Was pillow
@ -111,7 +111,7 @@ void cBlockBedHandler::OnUse(cChunkInterface & a_ChunkInterface, cWorldInterface
// Is foot end
VERIFY((Meta & 0x4) != 0x4); // Occupied flag should never be set, else our compilator (intended) is broken
PillowDirection = MetaDataToDirection(Meta & 0x7);
PillowDirection = MetaDataToDirection(Meta & 0x3);
if (a_ChunkInterface.GetBlock(a_BlockX + PillowDirection.x, a_BlockY, a_BlockZ + PillowDirection.z) == E_BLOCK_BED) // Must always use pillow location for sleeping
{
a_WorldInterface.GetBroadcastManager().BroadcastUseBed(*a_Player, a_BlockX + PillowDirection.x, a_BlockY, a_BlockZ + PillowDirection.z);

View File

@ -40,22 +40,34 @@ public:
{
cFastRandom rand;
// Old leaves - 3 bits contain display; new leaves - 1st bit, shifted left two for saplings to understand
if (rand.NextInt(6) == 0)
// There is a chance to drop a sapling that varies depending on the type of leaf broken.
// TODO: Take into account fortune for sapling drops.
int chance;
if ((m_BlockType == E_BLOCK_LEAVES) && ((a_BlockMeta & 0x03) == E_META_LEAVES_JUNGLE))
{
// Jungle leaves have a 2.5% chance of dropping a sapling.
chance = rand.NextInt(40);
}
else
{
// Other leaves have a 5% chance of dropping a sapling.
chance = rand.NextInt(20);
}
if (chance == 0)
{
a_Pickups.push_back(
cItem(
E_BLOCK_SAPLING,
1,
(m_BlockType == E_BLOCK_LEAVES) ? (a_BlockMeta & 0x03) : (2 << (a_BlockMeta & 0x01))
(m_BlockType == E_BLOCK_LEAVES) ? (a_BlockMeta & 0x03) : (4 + (a_BlockMeta & 0x01))
)
);
}
// 1 % chance of dropping an apple, if the leaves' type is Apple Leaves
// 0.5 % chance of dropping an apple, if the leaves' type is Apple Leaves
if ((m_BlockType == E_BLOCK_LEAVES) && ((a_BlockMeta & 0x03) == E_META_LEAVES_APPLE))
{
if (rand.NextInt(101) == 0)
if (rand.NextInt(200) == 0)
{
a_Pickups.push_back(cItem(E_ITEM_RED_APPLE, 1, 0));
}

47
src/Broadcaster.cpp Normal file
View File

@ -0,0 +1,47 @@
#include "Globals.h"
#include "Broadcaster.h"
#include "World.h"
#include "Chunk.h"
cBroadcaster::cBroadcaster(cWorld * a_World) :
m_World(a_World)
{
}
void cBroadcaster::BroadcastParticleEffect(const AString & a_ParticleName, const Vector3f a_Src, const Vector3f a_Offset, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude)
{
m_World->DoWithChunkAt(a_Src,
[=](cChunk & a_Chunk) -> bool
{
for (auto && client : a_Chunk.GetAllClients())
{
if (client == a_Exclude)
{
continue;
}
client->SendParticleEffect(a_ParticleName, a_Src.x, a_Src.y, a_Src.z, a_Offset.x, a_Offset.y, a_Offset.z, a_ParticleData, a_ParticleAmount);
};
return true;
});
}
void cBroadcaster::BroadcastParticleEffect(const AString & a_ParticleName, const Vector3f a_Src, const Vector3f a_Offset, float a_ParticleData, int a_ParticleAmount, std::array<int, 2> a_Data, cClientHandle * a_Exclude)
{
m_World->DoWithChunkAt(a_Src,
[=](cChunk & a_Chunk) -> bool
{
for (auto && client : a_Chunk.GetAllClients())
{
if (client == a_Exclude)
{
continue;
}
client->SendParticleEffect(a_ParticleName, a_Src, a_Offset, a_ParticleData, a_ParticleAmount, a_Data);
};
return true;
});
}

20
src/Broadcaster.h Normal file
View File

@ -0,0 +1,20 @@
class cWorld;
#include <array>
class cBroadcaster
{
public:
cBroadcaster(cWorld * a_World);
void BroadcastParticleEffect(const AString & a_ParticleName, const Vector3f a_Src, const Vector3f a_Offset, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = nullptr);
void BroadcastParticleEffect(const AString & a_ParticleName, const Vector3f a_Src, const Vector3f a_Offset, float a_ParticleData, int a_ParticleAmount, std::array<int, 2> a_Data, cClientHandle * a_Exclude = nullptr);
private:
cWorld * m_World;
};

View File

@ -18,6 +18,7 @@ SET (SRCS
BlockArea.cpp
BlockID.cpp
BlockInfo.cpp
Broadcaster.cpp
BoundingBox.cpp
ByteBuffer.cpp
ChatColor.cpp
@ -47,11 +48,13 @@ SET (SRCS
Logger.cpp
Map.cpp
MapManager.cpp
MemorySettingsRepository.cpp
MobCensus.cpp
MobFamilyCollecter.cpp
MobProximityCounter.cpp
MobSpawner.cpp
MonsterConfig.cpp
OverridesSettingsRepository.cpp
ProbabDistrib.cpp
RankManager.cpp
RCONServer.cpp
@ -77,6 +80,7 @@ SET (HDRS
BlockInServerPluginInterface.h
BlockInfo.h
BlockTracer.h
Broadcaster.h
BoundingBox.h
BuildInfo.h.cmake
ByteBuffer.h
@ -114,11 +118,13 @@ SET (HDRS
Map.h
MapManager.h
Matrix4.h
MemorySettingsRepository.h
MobCensus.h
MobFamilyCollecter.h
MobProximityCounter.h
MobSpawner.h
MonsterConfig.h
OverridesSettingsRepository.h
ProbabDistrib.h
RankManager.h
RCONServer.h
@ -126,6 +132,7 @@ SET (HDRS
Scoreboard.h
Server.h
SetChunkData.h
SettingsRepositoryInterface.h
Statistics.h
StringCompression.h
StringUtils.h
@ -140,6 +147,7 @@ SET (HDRS
include_directories(".")
include_directories ("${CMAKE_CURRENT_SOURCE_DIR}/../lib/sqlite")
include_directories ("${CMAKE_CURRENT_SOURCE_DIR}/../lib/SQLiteCpp/include")
include_directories (SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/../lib/TCLAP/include")
configure_file("BuildInfo.h.cmake" "${CMAKE_CURRENT_SOURCE_DIR}/BuildInfo.h")
@ -276,7 +284,7 @@ if (MSVC)
COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_SOURCE_DIR}/MCServer/lua51.dll ./lua51.dll
# Regenerate bindings:
COMMAND tolua -L virtual_method_hooks.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg
COMMAND tolua -L BindingsProcessor.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/Bindings/
# add any new generation dependencies here

View File

@ -43,6 +43,7 @@ local g_IgnoredFiles =
{
"Bindings/Bindings.h",
"Bindings/Bindings.cpp",
"Bindings/LuaState_Implementation.cpp",
"LeakFinder.cpp",
"LeakFinder.h",
"MersenneTwister.h",
@ -149,6 +150,39 @@ local g_ViolationPatterns =
-- No space before a closing parenthesis:
{" %)", "Remove the space before \")\""},
-- Check spaces around "+":
{"^[a-zA-Z0-9]+%+[a-zA-Z0-9]+", "Add space around +"},
{"[!@#$%%%^&*() %[%]\t][a-zA-Z0-9]+%+[a-zA-Z0-9]+", "Add space around +"},
--[[
-- Cannot check these because of text such as "X+" and "+2" appearing in some comments.
{"^[a-zA-Z0-9]+ %+[a-zA-Z0-9]+", "Add space after +"},
{"[!@#$%%%^&*() %[%]\t][a-zA-Z0-9]+ %+[a-zA-Z0-9]+", "Add space after +"},
{"^[a-zA-Z0-9]+%+ [a-zA-Z0-9]+", "Add space before +"},
{"[!@#$%%%^&*() %[%]\t][a-zA-Z0-9]+%+ [a-zA-Z0-9]+", "Add space before +"},
--]]
-- Cannot check spaces around "-", because the minus is sometimes used as a hyphen between-words
-- Check spaces around "*":
{"^[a-zA-Z0-9]+%*[a-zA-Z0-9]+", "Add space around *"},
{"^[^\"]*[!@#$%%%^&*() %[%]\t][a-zA-Z0-9]+%*[a-zA-Z0-9]+", "Add space around *"},
{"^[a-zB-Z0-9]+%* [a-zA-Z0-9]+", "Add space before *"},
{"^[^\"]*[!@#$%%%^&*() %[%]\t][a-zB-Z0-9]+%* [a-zA-Z0-9]+", "Add space before *"},
-- Check spaces around "/":
{"^[a-zA-Z0-9]+%/[a-zA-Z0-9]+", "Add space around /"},
{"^[^\"]*[!@#$%%%^&*() %[%]\t][a-zA-Z0-9]+%/[a-zA-Z0-9]+", "Add space around /"},
-- Check spaces around "&":
{"^[a-zA-Z0-9]+%&[a-zA-Z0-9]+", "Add space around /"},
{"^[^\"]*[!@#$%%%^&*() %[%]\t][a-zA-Z0-9]+%&[a-zA-Z0-9]+", "Add space around /"},
{"^[a-zA-Z0-9]+%& [a-zA-Z0-9]+", "Add space before &"},
{"^[^\"]*[!@#$%%%^&*() %[%]\t][a-zA-Z0-9]+%& [a-zA-Z0-9]+", "Add space before &"},
-- We don't like "Type const *" and "Type const &". Use "const Type *" and "const Type &" instead:
{"const %&", "Use 'const Type &' instead of 'Type const &'"},
{"const %*", "Use 'const Type *' instead of 'Type const *'"},
}

View File

@ -477,21 +477,21 @@ void cChunk::CollectMobCensus(cMobCensus& toFill)
toFill.CollectSpawnableChunk(*this);
std::list<const Vector3d *> playerPositions;
cPlayer * currentPlayer;
for (cClientHandleList::iterator itr = m_LoadedByClient.begin(), end = m_LoadedByClient.end(); itr != end; ++itr)
for (auto itr = m_LoadedByClient.begin(), end = m_LoadedByClient.end(); itr != end; ++itr)
{
currentPlayer = (*itr)->GetPlayer();
playerPositions.push_back(&(currentPlayer->GetPosition()));
}
Vector3d currentPosition;
for (cEntityList::iterator itr = m_Entities.begin(); itr != m_Entities.end(); ++itr)
for (auto itr = m_Entities.begin(); itr != m_Entities.end(); ++itr)
{
// LOGD("Counting entity #%i (%s)", (*itr)->GetUniqueID(), (*itr)->GetClass());
if ((*itr)->IsMob())
{
cMonster& Monster = (cMonster&)(**itr);
auto & Monster = reinterpret_cast<cMonster &>(**itr);
currentPosition = Monster.GetPosition();
for (std::list<const Vector3d*>::const_iterator itr2 = playerPositions.begin(); itr2 != playerPositions.end(); ++itr2)
for (auto itr2 = playerPositions.cbegin(); itr2 != playerPositions.cend(); ++itr2)
{
toFill.CollectMob(Monster, *this, (currentPosition - **itr2).SqrLength());
}
@ -1827,7 +1827,7 @@ bool cChunk::SetSignLines(int a_PosX, int a_PosY, int a_PosZ, const AString & a_
)
{
MarkDirty();
(reinterpret_cast<cSignEntity *>(*itr))->SetLines(a_Line1, a_Line2, a_Line3, a_Line4);
reinterpret_cast<cSignEntity *>(*itr)->SetLines(a_Line1, a_Line2, a_Line3, a_Line4);
m_World->BroadcastBlockEntity(a_PosX, a_PosY, a_PosZ);
return true;
}

View File

@ -439,6 +439,9 @@ public:
as at least one requests is active the chunk will be ticked). */
void SetAlwaysTicked(bool a_AlwaysTicked);
// Makes a copy of the list
cClientHandleList GetAllClients(void) const {return m_LoadedByClient; }
private:
friend class cChunkMap;
@ -531,9 +534,6 @@ private:
/** Wakes up each simulator for its specific blocks; through all the blocks in the chunk */
void WakeUpSimulators(void);
// Makes a copy of the list
cClientHandleList GetAllClients(void) const {return m_LoadedByClient; }
/** Sends m_PendingSendBlocks to all clients */
void BroadcastPendingBlockChanges(void);

View File

@ -791,6 +791,28 @@ bool cChunkMap::DoWithChunk(int a_ChunkX, int a_ChunkZ, cChunkCallback & a_Callb
}
bool cChunkMap::DoWithChunkAt(Vector3i a_BlockPos, std::function<bool(cChunk &)> a_Callback)
{
int ChunkX, ChunkZ;
cChunkDef::BlockToChunk(a_BlockPos.x, a_BlockPos.z, ChunkX, ChunkZ);
struct cCallBackWrapper : cChunkCallback
{
cCallBackWrapper(std::function<bool(cChunk &)> a_InnerCallback) :
m_Callback(a_InnerCallback)
{
}
virtual bool Item(cChunk * a_Chunk)
{
return m_Callback(*a_Chunk);
}
private:
std::function<bool(cChunk &)> m_Callback;
} callback(a_Callback);
return DoWithChunk(ChunkX, ChunkZ, callback);
}
@ -2697,9 +2719,9 @@ void cChunkMap::SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ)
void cChunkMap::CollectMobCensus(cMobCensus & a_ToFill)
{
cCSLock Lock(m_CSLayers);
for (cChunkLayerList::iterator itr = m_Layers.begin(); itr != m_Layers.end(); ++itr)
for (auto && layer: m_Layers)
{
(*itr)->CollectMobCensus(a_ToFill);
layer->CollectMobCensus(a_ToFill);
} // for itr - m_Layers
}
@ -2711,9 +2733,9 @@ void cChunkMap::CollectMobCensus(cMobCensus& a_ToFill)
void cChunkMap::SpawnMobs(cMobSpawner & a_MobSpawner)
{
cCSLock Lock(m_CSLayers);
for (cChunkLayerList::iterator itr = m_Layers.begin(); itr != m_Layers.end(); ++itr)
for (auto && layer: m_Layers)
{
(*itr)->SpawnMobs(a_MobSpawner);
layer->SpawnMobs(a_MobSpawner);
} // for itr - m_Layers
}

View File

@ -104,6 +104,9 @@ public:
/** Calls the callback for the chunk specified, with ChunkMapCS locked; returns false if the chunk doesn't exist, otherwise returns the same value as the callback */
bool DoWithChunk(int a_ChunkX, int a_ChunkZ, cChunkCallback & a_Callback);
/** Calls the callback for the chunk at the block position specified, with ChunkMapCS locked; returns false if the chunk doesn't exist, otherwise returns the same value as the callback **/
bool DoWithChunkAt(Vector3i a_BlockPos, std::function<bool(cChunk &)> a_Callback);
/** Wakes up simulators for the specified block */
void WakeUpSimulators(int a_BlockX, int a_BlockY, int a_BlockZ);
@ -361,7 +364,7 @@ public:
/** Sets the blockticking to start at the specified block. Only one blocktick per chunk may be set, second call overwrites the first call */
void SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ);
/** Make a Mob census, of all mobs, their family, their chunk and theyr distance to closest player */
/** Make a Mob census, of all mobs, their family, their chunk and their distance to closest player */
void CollectMobCensus(cMobCensus & a_ToFill);
/** Try to Spawn Monsters inside all Chunks */
@ -431,6 +434,7 @@ private:
/** Collect a mob census, of all mobs, their megatype, their chunk and their distance o closest player */
void CollectMobCensus(cMobCensus & a_ToFill);
/** Try to Spawn Monsters inside all Chunks */
void SpawnMobs(cMobSpawner & a_MobSpawner);

View File

@ -13,7 +13,7 @@ And once they do, it requests the chunk data and sends it all away, either
sends to a specific client (QueueSendChunkTo)
Chunk data is queried using the cChunkDataCallback interface.
It is cached inside the ChunkSender object during the query and then processed after the query ends.
Note that the data needs to be compressed only *after* the query finishes,
Note that the data needs to be compressed only after the query finishes,
because the query callbacks run with ChunkMap's CS locked.
A client may remove itself from all direct requests(QueueSendChunkTo()) by calling RemoveClient();

View File

@ -1473,7 +1473,7 @@ void cClientHandle::HandleChat(const AString & a_Message)
Color.clear();
}
Msg.AddTextPart(AString("<") + m_Player->GetName() + "> ", Color);
Msg.ParseText(a_Message);
Msg.ParseText(Message);
Msg.UnderlineUrls();
m_Player->GetWorld()->BroadcastChat(Msg);
}
@ -2374,6 +2374,15 @@ void cClientHandle::SendParticleEffect(const AString & a_ParticleName, float a_S
void cClientHandle::SendParticleEffect(const AString & a_ParticleName, const Vector3f a_Src, const Vector3f a_Offset, float a_ParticleData, int a_ParticleAmount, std::array<int, 2> a_Data)
{
m_Protocol->SendParticleEffect(a_ParticleName, a_Src, a_Offset, a_ParticleData, a_ParticleAmount, a_Data);
}
void cClientHandle::SendPickupSpawn(const cPickup & a_Pickup)
{
m_Protocol->SendPickupSpawn(a_Pickup);

View File

@ -22,6 +22,7 @@
#include "ChunkSender.h"
#include <array>
@ -177,6 +178,7 @@ public: // tolua_export
void SendMapInfo (int a_ID, unsigned int a_Scale);
void SendPaintingSpawn (const cPainting & a_Painting);
void SendParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount);
void SendParticleEffect (const AString & a_ParticleName, const Vector3f a_Src, const Vector3f a_Offset, float a_ParticleData, int a_ParticleAmount, std::array<int, 2> a_Data);
void SendPickupSpawn (const cPickup & a_Pickup);
void SendPlayerAbilities (void);
void SendPlayerListAddPlayer (const cPlayer & a_Player);
@ -389,7 +391,7 @@ private:
cPlayer * m_Player;
bool m_HasSentDC; ///< True if a D/C packet has been sent in either direction
bool m_HasSentDC; ///< True if a Disconnect packet has been sent in either direction
// Chunk position when the last StreamChunks() was called; used to avoid re-streaming while in the same chunk
int m_LastStreamedChunkX;

View File

@ -29,29 +29,32 @@ void cCommandOutputCallback::Out(const char * a_Fmt, ...)
////////////////////////////////////////////////////////////////////////////////
// cLogCommandOutputCallback:
// cStringAccumCommandOutputCallback:
void cLogCommandOutputCallback::Out(const AString & a_Text)
void cStringAccumCommandOutputCallback::Out(const AString & a_Text)
{
m_Buffer.append(a_Text);
m_Accum.append(a_Text);
}
////////////////////////////////////////////////////////////////////////////////
// cLogCommandOutputCallback:
void cLogCommandOutputCallback::Finished(void)
{
// Log each line separately:
size_t len = m_Buffer.length();
size_t len = m_Accum.length();
size_t last = 0;
for (size_t i = 0; i < len; i++)
{
switch (m_Buffer[i])
switch (m_Accum[i])
{
case '\n':
{
LOG("%s", m_Buffer.substr(last, i - last).c_str());
LOG("%s", m_Accum.substr(last, i - last).c_str());
last = i + 1;
break;
}
@ -59,11 +62,11 @@ void cLogCommandOutputCallback::Finished(void)
} // for i - m_Buffer[]
if (last < len)
{
LOG("%s", m_Buffer.substr(last).c_str());
LOG("%s", m_Accum.substr(last).c_str());
}
// Clear the buffer for the next command output:
m_Buffer.clear();
m_Accum.clear();
}

View File

@ -47,18 +47,36 @@ class cNullCommandOutputCallback :
/// Sends all command output to a log, line by line, when the command finishes processing
class cLogCommandOutputCallback :
/** Accumulates all command output into a string. */
class cStringAccumCommandOutputCallback:
public cCommandOutputCallback
{
typedef cCommandOutputCallback super;
public:
// cCommandOutputCallback overrides:
virtual void Out(const AString & a_Text) override;
virtual void Finished(void) override;
virtual void Finished(void) override {}
/** Returns the accumulated command output in a string. */
const AString & GetAccum(void) const { return m_Accum; }
protected:
/// Output is stored here until the command finishes processing
AString m_Buffer;
/** Output is stored here until the command finishes processing */
AString m_Accum;
} ;
/// Sends all command output to a log, line by line, when the command finishes processing
class cLogCommandOutputCallback :
public cStringAccumCommandOutputCallback
{
public:
// cStringAccumCommandOutputCallback overrides:
virtual void Finished(void) override;
} ;

View File

@ -14,7 +14,7 @@
// fwd: WorldStorage/FastNBT.h
// fwd: "WorldStorage/FastNBT.h"
class cFastNBTWriter;
class cParsedNBT;
@ -138,7 +138,7 @@ public:
bool operator !=(const cEnchantments & a_Other) const;
/** Writes the enchantments into the specified NBT writer; begins with the LIST tag of the specified name ("ench" or "StoredEnchantments") */
friend void EnchantmentSerializer::WriteToNBTCompound(cEnchantments const& a_Enchantments, cFastNBTWriter & a_Writer, const AString & a_ListTagName);
friend void EnchantmentSerializer::WriteToNBTCompound(const cEnchantments & a_Enchantments, cFastNBTWriter & a_Writer, const AString & a_ListTagName);
/** Reads the enchantments from the specified NBT list tag (ench or StoredEnchantments) */
friend void EnchantmentSerializer::ParseFromNBT(cEnchantments & a_Enchantments, const cParsedNBT & a_NBT, int a_EnchListTagIdx);

View File

@ -1309,7 +1309,8 @@ bool cEntity::DetectPortal()
if (IsPlayer())
{
((cPlayer *)this)->GetClientHandle()->SendRespawn(dimOverworld); // Send a respawn packet before world is loaded/generated so the client isn't left in limbo
// Send a respawn packet before world is loaded / generated so the client isn't left in limbo
((cPlayer *)this)->GetClientHandle()->SendRespawn(dimOverworld);
}
return MoveToWorld(cRoot::Get()->CreateAndInitializeWorld(GetWorld()->GetLinkedOverworldName()), false);
@ -1402,14 +1403,25 @@ bool cEntity::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn)
return false;
}
// Ask the plugins if the entity is allowed to change the world
if (cRoot::Get()->GetPluginManager()->CallHookEntityChangeWorld(*this, *a_World))
{
// A Plugin doesn't allow the entity to change the world
return false;
}
// Remove all links to the old world
SetWorldTravellingFrom(GetWorld()); // cChunk::Tick() handles entity removal
GetWorld()->BroadcastDestroyEntity(*this);
// Queue add to new world
a_World->AddEntity(this);
cWorld * OldWorld = cRoot::Get()->GetWorld(GetWorld()->GetName()); // Required for the hook HOOK_ENTITY_CHANGED_WORLD
SetWorld(a_World);
// Entity changed the world, call the hook
cRoot::Get()->GetPluginManager()->CallHookEntityChangedWorld(*this, *OldWorld);
return true;
}

View File

@ -474,7 +474,7 @@ protected:
static cCriticalSection m_CSCount;
static UInt32 m_EntityCount;
/** Measured in meter/second (m/s) */
/** Measured in meters / second (m / s) */
Vector3d m_Speed;
/** The ID of the entity that is guaranteed to be unique within a single run of the server.

View File

@ -6,7 +6,7 @@
#include "Floater.h"
#include "Player.h"
#include "../ClientHandle.h"
#include "Broadcaster.h"
@ -145,12 +145,12 @@ void cFloater::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
LOGD("Started producing particles for floater %i", GetUniqueID());
m_ParticlePos.Set(GetPosX() + (-4 + m_World->GetTickRandomNumber(8)), GetPosY(), GetPosZ() + (-4 + m_World->GetTickRandomNumber(8)));
m_World->BroadcastParticleEffect("splash", (float) m_ParticlePos.x, (float) m_ParticlePos.y, (float) m_ParticlePos.z, 0, 0, 0, 0, 15);
m_World->GetBroadcaster().BroadcastParticleEffect("splash", static_cast<Vector3f>(m_ParticlePos), Vector3f{}, 0, 15);
}
else if (m_CountDownTime < 20)
{
m_ParticlePos = (m_ParticlePos + (GetPosition() - m_ParticlePos) / 6);
m_World->BroadcastParticleEffect("splash", (float) m_ParticlePos.x, (float) m_ParticlePos.y, (float) m_ParticlePos.z, 0, 0, 0, 0, 15);
m_World->GetBroadcaster().BroadcastParticleEffect("splash", static_cast<Vector3f>(m_ParticlePos), Vector3f{}, 0, 15);
}
m_CountDownTime--;

View File

@ -905,7 +905,7 @@ bool cMinecart::TestEntityCollision(NIBBLETYPE a_RailMeta)
}
/* Check to which side the minecart is to be pushed.
Let's consider a z-x-coordinate system where the minecart is the center (0/0).
Let's consider a z-x-coordinate system where the minecart is the center (0, 0).
The minecart moves along the line x = -z, the perpendicular line to this is x = z.
In order to decide to which side the minecart is to be pushed, it must be checked on what side of the perpendicular line the pushing entity is located. */
if (
@ -954,7 +954,7 @@ bool cMinecart::TestEntityCollision(NIBBLETYPE a_RailMeta)
}
/* Check to which side the minecart is to be pushed.
Let's consider a z-x-coordinate system where the minecart is the center (0/0).
Let's consider a z-x-coordinate system where the minecart is the center (0, 0).
The minecart moves along the line x = z, the perpendicular line to this is x = -z.
In order to decide to which side the minecart is to be pushed, it must be checked on what side of the perpendicular line the pushing entity is located. */
if (

View File

@ -54,8 +54,7 @@ protected:
cMinecart(ePayload a_Payload, double a_X, double a_Y, double a_Z);
/** Handles physics on normal rails
For each tick, slow down on flat rails, speed up or slow down on ascending/descending rails (depending on direction), and turn on curved rails
*/
For each tick, slow down on flat rails, speed up or slow down on ascending / descending rails (depending on direction), and turn on curved rails. */
void HandleRailPhysics(NIBBLETYPE a_RailMeta, std::chrono::milliseconds a_Dt);
/** Handles powered rail physics

View File

@ -364,7 +364,7 @@ float cPlayer::GetXpPercentage()
bool cPlayer::SetCurrentExperience(int a_CurrentXp)
{
if (!(a_CurrentXp >= 0) || (a_CurrentXp > (std::numeric_limits<int>().max() - m_LifetimeTotalXp)))
if (!(a_CurrentXp >= 0) || (a_CurrentXp > (std::numeric_limits<int>::max() - m_LifetimeTotalXp)))
{
LOGWARNING("Tried to update experiece with an invalid Xp value: %d", a_CurrentXp);
return false; // oops, they gave us a dodgey number
@ -1606,6 +1606,12 @@ bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn)
return false;
}
if (cRoot::Get()->GetPluginManager()->CallHookEntityChangeWorld(*this, *a_World))
{
// A Plugin doesn't allow the player to change the world
return false;
}
// Send the respawn packet:
if (a_ShouldSendRespawn && (m_ClientHandle != nullptr))
{
@ -1621,6 +1627,7 @@ bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn)
// Queue adding player to the new world, including all the necessary adjustments to the object
a_World->AddPlayer(this);
cWorld * OldWorld = cRoot::Get()->GetWorld(GetWorld()->GetName()); // Required for the hook HOOK_ENTITY_CHANGED_WORLD
SetWorld(a_World); // Chunks may be streamed before cWorld::AddPlayer() sets the world to the new value
// Update the view distance.
@ -1635,6 +1642,9 @@ bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn)
// Broadcast the player into the new world.
a_World->BroadcastSpawnEntity(*this);
// Player changed the world, call the hook
cRoot::Get()->GetPluginManager()->CallHookEntityChangedWorld(*this, *OldWorld);
return true;
}

View File

@ -6,12 +6,28 @@
#include "Globals.h"
#include "FastRandom.h"
#include <random>
#ifdef _WIN32
#define thread_local __declspec(thread)
#define thread_local static __declspec(thread)
#elif defined __APPLE__
#define thread_local static __thread
#endif
thread_local unsigned int m_Counter = 0;
static unsigned int GetRandomSeed()
{
thread_local bool SeedCounterInitialized = 0;
thread_local unsigned int SeedCounter = 0;
if (!SeedCounterInitialized)
{
std::random_device rd;
std::uniform_int_distribution<unsigned int> dist;
SeedCounter = dist(rd);
SeedCounterInitialized = true;
}
return ++SeedCounter;
}
@ -92,7 +108,7 @@ public:
cFastRandom::cFastRandom(void) :
m_LinearRand(m_Counter++)
m_LinearRand(GetRandomSeed())
{
}
@ -136,7 +152,7 @@ int cFastRandom::GenerateRandomInteger(int a_Begin, int a_End)
// MTRand:
MTRand::MTRand() :
m_MersenneRand(m_Counter++)
m_MersenneRand(GetRandomSeed())
{
}

View File

@ -529,7 +529,7 @@ void cCaveTunnel::ProcessChunk(
/*
#ifdef _DEBUG
// For debugging purposes, outline the shape of the cave using glowstone, *after* carving the entire cave:
// For debugging purposes, outline the shape of the cave using glowstone, after carving the entire cave:
for (cCaveDefPoints::const_iterator itr = m_Points.begin(), end = m_Points.end(); itr != end; ++itr)
{
int DifX = itr->m_BlockX - BlockStartX; // substitution for faster calc

View File

@ -209,7 +209,7 @@ void cChunkGenerator::Execute(void)
{
if ((NumChunksGenerated > 16) && (clock() - LastReportTick > CLOCKS_PER_SEC))
{
LOG("Chunk generator performance: %.2f ch/s (%d ch total)",
LOG("Chunk generator performance: %.2f ch / sec (%d ch total)",
(double)NumChunksGenerated * CLOCKS_PER_SEC/ (clock() - GenerationStart),
NumChunksGenerated
);
@ -241,7 +241,7 @@ void cChunkGenerator::Execute(void)
// Display perf info once in a while:
if ((NumChunksGenerated > 16) && (clock() - LastReportTick > 2 * CLOCKS_PER_SEC))
{
LOG("Chunk generator performance: %.2f ch/s (%d ch total)",
LOG("Chunk generator performance: %.2f ch / sec (%d ch total)",
(double)NumChunksGenerated * CLOCKS_PER_SEC / (clock() - GenerationStart),
NumChunksGenerated
);

View File

@ -1274,6 +1274,7 @@ bool cFinishGenPassiveMobs::TrySpawnAnimals(cChunkDesc & a_ChunkDesc, int a_RelX
double AnimalZ = static_cast<double>(a_ChunkDesc.GetChunkZ() * cChunkDef::Width + a_RelZ + 0.5);
cMonster * NewMob = cMonster::NewMonsterFromType(AnimalToSpawn);
NewMob->SetHealth(NewMob->GetMaxHealth());
NewMob->SetPosition(AnimalX, AnimalY, AnimalZ);
a_ChunkDesc.GetEntities().push_back(NewMob);
LOGD("Spawning %s #%i at {%.02f, %.02f, %.02f}", NewMob->GetClass(), NewMob->GetUniqueID(), AnimalX, AnimalY, AnimalZ);

View File

@ -5,7 +5,7 @@
/*
The integers generated may be interpreted in several ways:
- land/see designators
- land / sea designators
- 0 = ocean
- >0 = land
- biome group

View File

@ -34,7 +34,7 @@ protected:
/** Maximum depth of the generator tree*/
int m_MaxDepth;
/** Maximum size, in X/Z blocks, of the base (radius from the origin) */
/** Maximum size, in X / Z blocks, of the structure (radius from the origin) */
int m_MaxSize;

View File

@ -34,7 +34,7 @@ protected:
/** Maximum depth of the generator tree */
int m_MaxDepth;
/** Maximum size, in X/Z blocks, of the base (radius from the origin) */
/** Maximum size, in X / Z blocks, of the structure (radius from the origin) */
int m_MaxSize;

View File

@ -61,7 +61,7 @@ protected:
/** The noise used as a pseudo-random generator */
cNoise m_Noise;
/** Maximum size, in X/Z blocks, of the village (radius from the origin) */
/** Maximum size, in X / Z blocks, of the base (radius from the origin) */
int m_MaxSize;
/** Borders of the vilalge - no item may reach out of this cuboid. */

View File

@ -34,7 +34,7 @@ protected:
/** Maximum depth of the generator tree*/
int m_MaxDepth;
/** Maximum size, in X/Z blocks, of the base (radius from the origin) */
/** Maximum size, in X / Z blocks, of the structure (radius from the origin) */
int m_MaxSize;
/** The underlying biome generator that defines whether the base is created or not */

View File

@ -433,10 +433,14 @@ typename std::enable_if<std::is_arithmetic<T>::value, C>::type CeilC(T a_Value)
//temporary replacement for std::make_unique until we get c++14
namespace cpp14
{
template <class T, class... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(args...));
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
// a tick is 50 ms

View File

@ -5,7 +5,7 @@
// email suggested changes to me.
//
// Rewritten by: Shane Hill
// Date: 21/08/2001
// Date: 2001-08-21
// Email: Shane.Hill@dsto.defence.gov.au
// Reason: Remove dependancy on MFC. Code should compile on any
// platform.
@ -49,6 +49,9 @@ cIniFile::cIniFile(void) :
bool cIniFile::ReadFile(const AString & a_FileName, bool a_AllowExampleRedirect)
{
m_Filename = a_FileName;
// Normally you would use ifstream, but the SGI CC compiler has
// a few bugs with ifstream. So ... fstream used.
fstream f;
@ -57,6 +60,7 @@ bool cIniFile::ReadFile(const AString & a_FileName, bool a_AllowExampleRedirect)
AString::size_type pLeft, pRight;
bool IsFromExampleRedirect = false;
f.open((FILE_IO_PREFIX + a_FileName).c_str(), ios::in);
if (f.fail())
{
@ -650,7 +654,7 @@ void cIniFile::Clear(void)
bool cIniFile::HasValue(const AString & a_KeyName, const AString & a_ValueName)
bool cIniFile::HasValue(const AString & a_KeyName, const AString & a_ValueName) const
{
// Find the key:
int keyID = FindKey(a_KeyName);
@ -889,8 +893,36 @@ void cIniFile::RemoveBom(AString & a_line) const
bool cIniFile::KeyExists(AString a_keyname) const
{
return FindKey(a_keyname) != noID;
}
std::vector<std::pair<AString, AString>> cIniFile::GetValues(AString a_keyName)
{
std::vector<std::pair<AString, AString>> ret;
int keyID = FindKey(a_keyName);
if (keyID == noID)
{
return ret;
}
for (size_t valueID = 0; valueID < keys[keyID].names.size(); ++valueID)
{
ret.emplace_back(keys[keyID].names[valueID], keys[keyID].values[valueID]);
}
return ret;
}
AStringVector ReadUpgradeIniPorts(
cIniFile & a_IniFile,
cSettingsRepositoryInterface & a_Settings,
const AString & a_KeyName,
const AString & a_PortsValueName,
const AString & a_OldIPv4ValueName,
@ -899,23 +931,34 @@ AStringVector ReadUpgradeIniPorts(
)
{
// Read the regular value, but don't use the default (in order to detect missing value for upgrade):
AStringVector Ports = StringSplitAndTrim(a_IniFile.GetValue(a_KeyName, a_PortsValueName), ";,");
AStringVector Ports;
for (auto pair : a_Settings.GetValues(a_KeyName))
{
if (pair.first != a_PortsValueName)
{
continue;
}
AStringVector temp = StringSplitAndTrim(pair.second, ";,");
Ports.insert(Ports.end(), temp.begin(), temp.end());
}
if (Ports.empty())
{
// Historically there were two separate entries for IPv4 and IPv6, merge them and migrate:
AString Ports4 = a_IniFile.GetValue(a_KeyName, a_OldIPv4ValueName, a_DefaultValue);
AString Ports6 = a_IniFile.GetValue(a_KeyName, a_OldIPv6ValueName);
AString Ports4 = a_Settings.GetValue(a_KeyName, a_OldIPv4ValueName, a_DefaultValue);
AString Ports6 = a_Settings.GetValue(a_KeyName, a_OldIPv6ValueName);
Ports = MergeStringVectors(StringSplitAndTrim(Ports4, ";,"), StringSplitAndTrim(Ports6, ";,"));
a_IniFile.DeleteValue(a_KeyName, a_OldIPv4ValueName);
a_IniFile.DeleteValue(a_KeyName, a_OldIPv6ValueName);
a_Settings.DeleteValue(a_KeyName, a_OldIPv4ValueName);
a_Settings.DeleteValue(a_KeyName, a_OldIPv6ValueName);
// If those weren't present or were empty, use the default:"
if (Ports.empty())
{
Ports = StringSplitAndTrim(a_DefaultValue, ";,");
}
a_IniFile.SetValue(a_KeyName, a_PortsValueName, StringsConcat(Ports, ','));
a_Settings.SetValue(a_KeyName, a_PortsValueName, StringsConcat(Ports, ','));
}
return Ports;
@ -923,4 +966,3 @@ AStringVector ReadUpgradeIniPorts(

View File

@ -5,7 +5,7 @@
// email suggested changes to me.
//
// Rewritten by: Shane Hill
// Date: 21/08/2001
// Date: 2001-08-21
// Email: Shane.Hill@dsto.defence.gov.au
// Reason: Remove dependancy on MFC. Code should compile on any
// platform. Tested on Windows / Linux / Irix
@ -18,7 +18,7 @@
#pragma once
#include "SettingsRepositoryInterface.h"
#define MAX_KEYNAME 128
#define MAX_VALUENAME 128
@ -30,11 +30,13 @@
// tolua_begin
class cIniFile
class cIniFile : public cSettingsRepositoryInterface
{
private:
bool m_IsCaseInsensitive;
AString m_Filename;
struct key
{
std::vector<AString> names;
@ -54,14 +56,18 @@ private:
public:
enum errors
{
noID = -1,
};
/// Creates a new instance with no data
cIniFile(void);
// tolua_end
virtual ~cIniFile() = default;
virtual std::vector<std::pair<AString, AString>> GetValues(AString a_keyName) override;
virtual bool KeyExists(const AString a_keyName) const override;
// tolua_begin
// Sets whether or not keynames and valuenames should be case sensitive.
// The default is case insensitive.
void CaseSensitive (void) { m_IsCaseInsensitive = false; }
@ -77,11 +83,13 @@ public:
/// Writes data stored in class to the specified ini file
bool WriteFile(const AString & a_FileName) const;
virtual bool Flush() override { return WriteFile(m_Filename); }
/// Deletes all stored ini data (but doesn't touch the file)
void Clear(void);
/** Returns true iff the specified value exists. */
bool HasValue(const AString & a_KeyName, const AString & a_ValueName);
bool HasValue(const AString & a_KeyName, const AString & a_ValueName) const;
/// Returns index of specified key, or noID if not found
int FindKey(const AString & keyname) const;
@ -222,7 +230,7 @@ Reads the list of ports from a_PortsValueName. If that value doesn't exist or is
in a_OldIPv4ValueName and a_OldIPv6ValueName; in this case the old values are removed from the INI file.
If there is none of the three values or they are all empty, the default is used and stored in the Ports value. */
AStringVector ReadUpgradeIniPorts(
cIniFile & a_IniFile,
cSettingsRepositoryInterface & a_Settings,
const AString & a_KeyName,
const AString & a_PortsValueName,
const AString & a_OldIPv4ValueName,

View File

@ -78,7 +78,7 @@ public:
!BlockHandler(PlaceBlock)->DoesIgnoreBuildCollision(&a_Player, PlaceMeta)
)
{
// Tried to place a block *into* another?
// Tried to place a block into another?
// Happens when you place a block aiming at side of block with a torch on it or stem beside it
return false;
}

View File

@ -362,7 +362,7 @@ bool cItemHandler::OnPlayerPlace(
!BlockHandler(PlaceBlock)->DoesIgnoreBuildCollision(&a_Player, PlaceMeta)
)
{
// Tried to place a block *into* another?
// Tried to place a block into another?
// Happens when you place a block aiming at side of block with a torch on it or stem beside it
return false;
}
@ -543,8 +543,9 @@ char cItemHandler::GetMaxStackSize(void)
case E_ITEM_COMPASS: return 64;
case E_ITEM_COOKED_CHICKEN: return 64;
case E_ITEM_COOKED_FISH: return 64;
case E_ITEM_COOKED_PORKCHOP: return 64;
case E_ITEM_COOKED_MUTTON: return 64;
case E_ITEM_COOKED_PORKCHOP: return 64;
case E_ITEM_COOKED_RABBIT: return 64;
case E_ITEM_COOKIE: return 64;
case E_ITEM_DARK_OAK_DOOR: return 64;
case E_ITEM_DIAMOND: return 64;
@ -579,6 +580,7 @@ char cItemHandler::GetMaxStackSize(void)
case E_ITEM_MELON_SEEDS: return 64;
case E_ITEM_MELON_SLICE: return 64;
case E_ITEM_NETHER_BRICK: return 64;
case E_ITEM_NETHER_QUARTZ: return 64;
case E_ITEM_NETHER_WART: return 64;
case E_ITEM_PAINTING: return 64;
case E_ITEM_PAPER: return 64;
@ -595,6 +597,7 @@ char cItemHandler::GetMaxStackSize(void)
case E_ITEM_RAW_FISH: return 64;
case E_ITEM_RAW_MUTTON: return 64;
case E_ITEM_RAW_PORKCHOP: return 64;
case E_ITEM_RAW_RABBIT: return 64;
case E_ITEM_RED_APPLE: return 64;
case E_ITEM_REDSTONE_DUST: return 64;
case E_ITEM_REDSTONE_REPEATER: return 64;

View File

@ -0,0 +1,312 @@
#include "Globals.h"
#include "MemorySettingsRepository.h"
bool cMemorySettingsRepository::KeyExists(const AString keyname) const
{
return m_Map.count(keyname) != 0;
}
bool cMemorySettingsRepository::HasValue(const AString & a_KeyName, const AString & a_ValueName) const
{
auto outerIter = m_Map.find(a_KeyName);
if (outerIter == m_Map.end())
{
return false;
}
auto iter = outerIter->second.find(a_ValueName);
if (iter == outerIter->second.end())
{
return false;
}
return true;
}
int cMemorySettingsRepository::AddKeyName(const AString & a_keyname)
{
m_Map.emplace(a_keyname, std::unordered_multimap<AString, sValue>{});
return 0;
}
bool cMemorySettingsRepository::AddKeyComment(const AString & keyname, const AString & comment)
{
return false;
}
AString cMemorySettingsRepository::GetKeyComment(const AString & keyname, const int commentID) const
{
return "";
}
bool cMemorySettingsRepository::DeleteKeyComment(const AString & keyname, const int commentID)
{
return false;
}
void cMemorySettingsRepository::AddValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value)
{
if (m_Writable)
{
m_Map[a_KeyName].emplace(a_ValueName, sValue(a_Value));
}
}
void cMemorySettingsRepository::AddValue (const AString & a_KeyName, const AString & a_ValueName, Int64 a_Value)
{
if (m_Writable)
{
m_Map[a_KeyName].emplace(a_ValueName, sValue(a_Value));
}
}
void cMemorySettingsRepository::AddValue (const AString & a_KeyName, const AString & a_ValueName, bool a_Value)
{
if (m_Writable)
{
m_Map[a_KeyName].emplace(a_ValueName, sValue(a_Value));
}
}
std::vector<std::pair<AString, AString>> cMemorySettingsRepository::GetValues(AString a_keyName)
{
std::vector<std::pair<AString, AString>> ret;
for (auto pair : m_Map[a_keyName])
{
ret.emplace_back(pair.first, pair.second.getStringValue());
}
return ret;
}
AString cMemorySettingsRepository::GetValue (const AString & a_KeyName, const AString & a_ValueName, const AString & defValue) const
{
auto outerIter = m_Map.find(a_KeyName);
if (outerIter == m_Map.end())
{
return defValue;
}
auto iter = outerIter->second.find(a_ValueName);
if (iter == outerIter->second.end())
{
return defValue;
}
return iter->second.getStringValue();
}
AString cMemorySettingsRepository::GetValueSet (const AString & a_KeyName, const AString & a_ValueName, const AString & defValue)
{
auto outerIter = m_Map.find(a_KeyName);
if (outerIter == m_Map.end())
{
AddValue(a_KeyName, a_ValueName, defValue);
return defValue;
}
auto iter = outerIter->second.find(a_ValueName);
if (iter == outerIter->second.end())
{
AddValue(a_KeyName, a_ValueName, defValue);
return defValue;
}
return iter->second.getStringValue();
}
int cMemorySettingsRepository::GetValueSetI(const AString & a_KeyName, const AString & a_ValueName, const int defValue)
{
auto outerIter = m_Map.find(a_KeyName);
if (outerIter == m_Map.end())
{
AddValue(a_KeyName, a_ValueName, static_cast<Int64>(defValue));
return defValue;
}
auto iter = outerIter->second.find(a_ValueName);
if (iter == outerIter->second.end())
{
AddValue(a_KeyName, a_ValueName, static_cast<Int64>(defValue));
return defValue;
}
return static_cast<int>(iter->second.getIntValue());
}
Int64 cMemorySettingsRepository::GetValueSetI(const AString & a_KeyName, const AString & a_ValueName, const Int64 defValue)
{
auto outerIter = m_Map.find(a_KeyName);
if (outerIter == m_Map.end())
{
AddValue(a_KeyName, a_ValueName, defValue);
return defValue;
}
auto iter = outerIter->second.find(a_ValueName);
if (iter == outerIter->second.end())
{
AddValue(a_KeyName, a_ValueName, defValue);
return defValue;
}
return iter->second.getIntValue();
}
bool cMemorySettingsRepository::GetValueSetB(const AString & a_KeyName, const AString & a_ValueName, const bool defValue)
{
auto outerIter = m_Map.find(a_KeyName);
if (outerIter == m_Map.end())
{
AddValue(a_KeyName, a_ValueName, defValue);
return defValue;
}
auto iter = outerIter->second.find(a_ValueName);
if (iter == outerIter->second.end())
{
AddValue(a_KeyName, a_ValueName, defValue);
return defValue;
}
return iter->second.getBoolValue();
}
bool cMemorySettingsRepository::SetValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value, const bool a_CreateIfNotExists)
{
if (!m_Writable)
{
return false;
}
auto outerIter = m_Map.find(a_KeyName);
if (outerIter == m_Map.end())
{
if (a_CreateIfNotExists)
{
AddValue(a_KeyName, a_ValueName, a_Value);
}
return a_CreateIfNotExists;
}
auto iter = outerIter->second.find(a_ValueName);
if (iter == outerIter->second.end())
{
if (a_CreateIfNotExists)
{
AddValue(a_KeyName, a_ValueName, a_Value);
}
return a_CreateIfNotExists;
}
iter->second = sValue(a_Value);
return true;
}
bool cMemorySettingsRepository::SetValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value, const bool a_CreateIfNotExists)
{
if (!m_Writable)
{
return false;
}
auto outerIter = m_Map.find(a_KeyName);
if (outerIter == m_Map.end())
{
if (a_CreateIfNotExists)
{
AddValue(a_KeyName, a_ValueName, static_cast<Int64>(a_Value));
}
return a_CreateIfNotExists;
}
auto iter = outerIter->second.find(a_ValueName);
if (iter == outerIter->second.end())
{
if (a_CreateIfNotExists)
{
AddValue(a_KeyName, a_ValueName, static_cast<Int64>(a_Value));
}
return a_CreateIfNotExists;
}
iter->second = sValue(static_cast<Int64>(a_Value));
return true;
}
bool cMemorySettingsRepository::DeleteValue(const AString & a_KeyName, const AString & a_ValueName)
{
if (!m_Writable)
{
return false;
}
auto outerIter = m_Map.find(a_KeyName);
if (outerIter == m_Map.end())
{
return false;
}
auto iter = outerIter->second.find(a_ValueName);
if (iter == outerIter->second.end())
{
return false;
}
outerIter->second.erase(iter);
return true;
}
bool cMemorySettingsRepository::Flush()
{
return true;
}

View File

@ -0,0 +1,80 @@
#pragma once
#include "SettingsRepositoryInterface.h"
#include <unordered_map>
class cMemorySettingsRepository : public cSettingsRepositoryInterface
{
public:
virtual bool KeyExists(const AString keyname) const override;
virtual bool HasValue(const AString & a_KeyName, const AString & a_ValueName) const override;
virtual int AddKeyName(const AString & keyname) override;
virtual bool AddKeyComment(const AString & keyname, const AString & comment) override;
virtual AString GetKeyComment(const AString & keyname, const int commentID) const override;
virtual bool DeleteKeyComment(const AString & keyname, const int commentID) override;
virtual void AddValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value) override;
void AddValue (const AString & a_KeyName, const AString & a_ValueName, const Int64 a_Value);
void AddValue (const AString & a_KeyName, const AString & a_ValueName, const bool a_Value);
virtual std::vector<std::pair<AString, AString>> GetValues(AString a_keyName) override;
virtual AString GetValue (const AString & keyname, const AString & valuename, const AString & defValue = "") const override;
virtual AString GetValueSet (const AString & keyname, const AString & valuename, const AString & defValue = "") override;
virtual int GetValueSetI(const AString & keyname, const AString & valuename, const int defValue = 0) override;
virtual Int64 GetValueSetI(const AString & keyname, const AString & valuename, const Int64 defValue = 0) override;
virtual bool GetValueSetB(const AString & keyname, const AString & valuename, const bool defValue = false) override;
virtual bool SetValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value, const bool a_CreateIfNotExists = true) override;
virtual bool SetValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value, const bool a_CreateIfNotExists = true) override;
virtual bool DeleteValue(const AString & keyname, const AString & valuename) override;
virtual bool Flush() override;
void SetReadOnly()
{
m_Writable = false;
}
private:
bool m_Writable = true;
struct sValue
{
sValue(AString value) : m_Type(eType::String), m_stringValue (value) {}
sValue(Int64 value) : m_Type(eType::Int64), m_intValue(value) {}
sValue(bool value) : m_Type(eType::Bool), m_boolValue(value) {}
AString getStringValue() const { ASSERT(m_Type == eType::String); return m_stringValue; }
Int64 getIntValue() const { ASSERT(m_Type == eType::Int64); return m_intValue; }
bool getBoolValue() const { ASSERT(m_Type == eType::Bool); return m_boolValue; }
private:
enum class eType
{
String,
Int64,
Bool
} m_Type;
AString m_stringValue;
union
{
Int64 m_intValue;
bool m_boolValue;
};
};
std::unordered_map<AString, std::unordered_multimap<AString, sValue>> m_Map{};
};

View File

@ -32,7 +32,7 @@ public:
// MG TODO : code the correct rule (not loaded chunk but short distant from players)
void CollectSpawnableChunk(cChunk & a_Chunk);
/// Collect a mob - it's distance to player, it's family ...
/// Collect a mob - its distance to player, its family ...
void CollectMob(cMonster & a_Monster, cChunk & a_Chunk, double a_Distance);
/// Returns true if the family is capped (i.e. there are more mobs of this family than max)

View File

@ -6,6 +6,10 @@
#include "Entities/Entity.h"
#include "Chunk.h"
void cMobProximityCounter::CollectMob(cEntity & a_Monster, cChunk & a_Chunk, double a_Distance)
{
// LOGD("Collecting monster %s, with distance %f", a_Monster->GetClass(), a_Distance);

View File

@ -36,7 +36,6 @@ void cAggressiveMonster::InStateChasing(std::chrono::milliseconds a_Dt)
return;
}
}
MoveToPosition(m_Target->GetPosition());
}
}

View File

@ -7,7 +7,7 @@
cMagmaCube::cMagmaCube(int a_Size) :
super("MagmaCube", mtMagmaCube, "mob.MagmaCube.big", "mob.MagmaCube.big", 0.6 * a_Size, 0.6 * a_Size),
super("MagmaCube", mtMagmaCube, Printf("mob.magmacube.%s", GetSizeName(a_Size).c_str()), Printf("mob.magmacube.%s", GetSizeName(a_Size).c_str()), 0.6 * a_Size, 0.6 * a_Size),
m_Size(a_Size)
{
}
@ -27,4 +27,14 @@ void cMagmaCube::GetDrops(cItems & a_Drops, cEntity * a_Killer)
AString cMagmaCube::GetSizeName(int a_Size)
{
if (a_Size > 1)
{
return "big";
}
else
{
return "small";
}
}

View File

@ -20,9 +20,13 @@ public:
virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override;
int GetSize(void) const { return m_Size; }
/** Returns the text describing the slime's size, as used by the client's resource subsystem for sounds.
Returns either "big" or "small". */
static AString GetSizeName(int a_Size);
protected:
/// Size of the MagmaCube, 1 .. 3, with 1 being the smallest
/// Size of the MagmaCube, 1, 2 and 4, with 1 being the smallest
int m_Size;
} ;

View File

@ -89,7 +89,7 @@ cMonster::cMonster(const AString & a_ConfigName, eMonsterType a_MobType, const A
, m_SoundDeath(a_SoundDeath)
, m_AttackRate(3)
, m_AttackDamage(1)
, m_AttackRange(2)
, m_AttackRange(1)
, m_AttackInterval(0)
, m_SightDistance(25)
, m_DropChanceWeapon(0.085f)
@ -147,21 +147,40 @@ bool cMonster::TickPathFinding(cChunk & a_Chunk)
(Recalculate lots when close, calculate rarely when far) */
if (
((GetPosition() - m_PathFinderDestination).Length() < 0.25) ||
((m_TicksSinceLastPathReset > 10) && (m_TicksSinceLastPathReset > (0.15 * (m_FinalDestination - GetPosition()).SqrLength())))
((m_TicksSinceLastPathReset > 10) && (m_TicksSinceLastPathReset > (0.4 * (m_FinalDestination - GetPosition()).SqrLength())))
)
{
/* Re-calculating is expensive when there's no path to target, and it results in mobs freezing very often as a result of always recalculating.
This is a workaround till we get better path recalculation. */
if (!m_NoPathToTarget)
{
ResetPathFinding();
}
}
}
if (m_Path == nullptr)
{
if (!EnsureProperDestination(a_Chunk))
{
StopMovingToPosition(); // Invalid chunks, probably world is loading or something, cancel movement.
return false;
}
m_NoPathToTarget = false;
m_NoMoreWayPoints = false;
m_PathFinderDestination = m_FinalDestination;
m_Path = new cPath(a_Chunk, GetPosition().Floor(), m_PathFinderDestination.Floor(), 20);
}
switch (m_Path->Step(a_Chunk))
{
case ePathFinderStatus::NEARBY_FOUND:
{
m_NoPathToTarget = true;
m_Path->AcceptNearbyPath();
break;
}
case ePathFinderStatus::PATH_NOT_FOUND:
{
StopMovingToPosition(); // Give up pathfinding to that destination.
@ -174,16 +193,23 @@ bool cMonster::TickPathFinding(cChunk & a_Chunk)
}
case ePathFinderStatus::PATH_FOUND:
{
if (--m_GiveUpCounter == 0)
if (m_NoMoreWayPoints || (--m_GiveUpCounter == 0))
{
ResetPathFinding(); // Try to calculate a path again.
return false;
}
else if (!m_Path->IsLastPoint() && (m_Path->IsFirstPoint() || ReachedNextWaypoint())) // Have we arrived at the next cell, as denoted by m_NextWayPointPosition?
else if (!m_Path->IsLastPoint()) // Have we arrived at the next cell, as denoted by m_NextWayPointPosition?
{
if ((m_Path->IsFirstPoint() || ReachedNextWaypoint()))
{
m_NextWayPointPosition = Vector3d(0.5, 0, 0.5) + m_Path->GetNextPoint();
m_GiveUpCounter = 40; // Give up after 40 ticks (2 seconds) if failed to reach m_NextWayPointPosition.
}
}
else
{
m_NoMoreWayPoints = true;
}
return true;
}
}
@ -199,10 +225,12 @@ void cMonster::MoveToWayPoint(cChunk & a_Chunk)
{
if (m_JumpCoolDown == 0)
{
// We're not moving (or barely moving), and waypoint is above us, it means we are hitting something and we should jump.
if ((GetSpeedX() < 0.1) && (GetSpeedZ() < 0.1) && DoesPosYRequireJump(FloorC(m_NextWayPointPosition.y)))
if (DoesPosYRequireJump(FloorC(m_NextWayPointPosition.y)))
{
if (IsOnGround() || IsSwimming())
if (
(IsOnGround() && (GetSpeedX() == 0) && (GetSpeedY() == 0)) ||
(IsSwimming() && (m_GiveUpCounter < 15))
)
{
m_bOnGround = false;
m_JumpCoolDown = 20;
@ -252,6 +280,103 @@ void cMonster::MoveToWayPoint(cChunk & a_Chunk)
bool cMonster::EnsureProperDestination(cChunk & a_Chunk)
{
cChunk * Chunk = a_Chunk.GetNeighborChunk(FloorC(m_FinalDestination.x), FloorC(m_FinalDestination.z));
BLOCKTYPE BlockType;
NIBBLETYPE BlockMeta;
if ((Chunk == nullptr) || !Chunk->IsValid())
{
return false;
}
int RelX = FloorC(m_FinalDestination.x) - Chunk->GetPosX() * cChunkDef::Width;
int RelZ = FloorC(m_FinalDestination.z) - Chunk->GetPosZ() * cChunkDef::Width;
// If destination in the air, first try to go 1 block north, or east, or west.
// This fixes the player leaning issue.
// If that failed, we instead go down to the lowest air block.
Chunk->GetBlockTypeMeta(RelX, FloorC(m_FinalDestination.y) - 1, RelZ, BlockType, BlockMeta);
if (!cBlockInfo::IsSolid(BlockType))
{
bool InTheAir = true;
int x, z;
for (z = -1; z <= 1; ++z)
{
for (x = -1; x <= 1; ++x)
{
if ((x==0) && (z==0))
{
continue;
}
Chunk = a_Chunk.GetNeighborChunk(FloorC(m_FinalDestination.x+x), FloorC(m_FinalDestination.z+z));
if ((Chunk == nullptr) || !Chunk->IsValid())
{
return false;
}
RelX = FloorC(m_FinalDestination.x+x) - Chunk->GetPosX() * cChunkDef::Width;
RelZ = FloorC(m_FinalDestination.z+z) - Chunk->GetPosZ() * cChunkDef::Width;
Chunk->GetBlockTypeMeta(RelX, FloorC(m_FinalDestination.y) - 1, RelZ, BlockType, BlockMeta);
if (cBlockInfo::IsSolid(BlockType))
{
m_FinalDestination.x += x;
m_FinalDestination.z += z;
InTheAir = false;
goto breakBothLoops;
}
}
}
breakBothLoops:
// Go down to the lowest air block.
if (InTheAir)
{
while (m_FinalDestination.y > 0)
{
Chunk->GetBlockTypeMeta(RelX, FloorC(m_FinalDestination.y) - 1, RelZ, BlockType, BlockMeta);
if (cBlockInfo::IsSolid(BlockType))
{
break;
}
m_FinalDestination.y -= 1;
}
}
}
// If destination in water, go up to the highest water block.
// If destination in solid, go up to first air block.
bool InWater = false;
while (m_FinalDestination.y < cChunkDef::Height)
{
Chunk->GetBlockTypeMeta(RelX, FloorC(m_FinalDestination.y), RelZ, BlockType, BlockMeta);
if (BlockType == E_BLOCK_STATIONARY_WATER)
{
InWater = true;
}
else if (cBlockInfo::IsSolid(BlockType))
{
InWater = false;
}
else
{
break;
}
m_FinalDestination.y += 1;
}
if (InWater)
{
m_FinalDestination.y -= 1;
}
return true;
}
void cMonster::MoveToPosition(const Vector3d & a_Position)
{
m_FinalDestination = a_Position;
@ -292,7 +417,7 @@ void cMonster::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
if (m_Health <= 0)
{
// The mob is dead, but we're still animating the "puff" they leave when they die
// The mob is dead, but we're still animating the "puff" they leave when they die.
m_DestroyTimer += a_Dt;
if (m_DestroyTimer > std::chrono::seconds(1))
{
@ -310,11 +435,19 @@ void cMonster::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
m_Target = nullptr;
}
// Process the undead burning in daylight
// Process the undead burning in daylight.
HandleDaylightBurning(*Chunk, WouldBurnAt(GetPosition(), *Chunk));
if (TickPathFinding(*Chunk))
{
if (m_BurnsInDaylight && WouldBurnAt(m_NextWayPointPosition, *Chunk->GetNeighborChunk(FloorC(m_NextWayPointPosition.x), FloorC(m_NextWayPointPosition.z))) && !IsOnFire() && (m_TicksSinceLastDamaged == 100))
/* If I burn in daylight, and I won't burn where I'm standing, and I'll burn in my next position, and at least one of those is true:
1. I am idle
2. I was not hurt by a player recently.
Then STOP. */
if (
m_BurnsInDaylight && ((m_TicksSinceLastDamaged >= 100) || (m_EMState == IDLE)) &&
WouldBurnAt(m_NextWayPointPosition, *Chunk) &&
!WouldBurnAt(GetPosition(), *Chunk)
)
{
// If we burn in daylight, and we would burn at the next step, and we won't burn where we are right now, and we weren't provoked recently:
StopMovingToPosition();
@ -373,21 +506,29 @@ void cMonster::SetPitchAndYawFromDestination()
}
}
Vector3d BodyDistance = m_NextWayPointPosition - GetPosition();
double BodyRotation, BodyPitch;
BodyDistance.Normalize();
VectorToEuler(BodyDistance.x, BodyDistance.y, BodyDistance.z, BodyRotation, BodyPitch);
SetYaw(BodyRotation);
Vector3d Distance = FinalDestination - GetPosition();
{
double Rotation, Pitch;
double HeadRotation, HeadPitch;
Distance.Normalize();
VectorToEuler(Distance.x, Distance.y, Distance.z, Rotation, Pitch);
SetHeadYaw(Rotation);
SetPitch(-Pitch);
}
VectorToEuler(Distance.x, Distance.y, Distance.z, HeadRotation, HeadPitch);
if (std::abs(BodyRotation - HeadRotation) < 120)
{
Vector3d BodyDistance = m_NextWayPointPosition - GetPosition();
double Rotation, Pitch;
BodyDistance.Normalize();
VectorToEuler(BodyDistance.x, BodyDistance.y, BodyDistance.z, Rotation, Pitch);
SetYaw(Rotation);
SetHeadYaw(HeadRotation);
SetPitch(-HeadPitch);
}
else // We're not an owl. If it's more than 120, don't look behind and instead look at where you're walking.
{
SetHeadYaw(BodyRotation);
SetPitch(-BodyPitch);
}
}
}
@ -886,7 +1027,7 @@ cMonster * cMonster::NewMonsterFromType(eMonsterType a_MobType)
{
case mtMagmaCube:
{
toReturn = new cMagmaCube(Random.NextInt(2) + 1);
toReturn = new cMagmaCube(1 << Random.NextInt(3)); // Size 1, 2 or 4
break;
}
case mtSlime:
@ -1098,12 +1239,19 @@ void cMonster::HandleDaylightBurning(cChunk & a_Chunk, bool WouldBurn)
bool cMonster::WouldBurnAt(Vector3d a_Location, cChunk & a_Chunk)
{
int RelX = FloorC(a_Location.x) - a_Chunk.GetPosX() * cChunkDef::Width;
cChunk * Chunk = a_Chunk.GetNeighborChunk(FloorC(a_Location.x), FloorC(a_Location.z));
if ((Chunk == nullptr) || (!Chunk->IsValid()))
{
return false;
}
int RelX = FloorC(a_Location.x) - Chunk->GetPosX() * cChunkDef::Width;
int RelY = FloorC(a_Location.y);
int RelZ = FloorC(a_Location.z) - a_Chunk.GetPosZ() * cChunkDef::Width;
int RelZ = FloorC(a_Location.z) - Chunk->GetPosZ() * cChunkDef::Width;
if (
(a_Chunk.GetSkyLight(RelX, RelY, RelZ) == 15) && // In the daylight
(a_Chunk.GetBlock(RelX, RelY, RelZ) != E_BLOCK_SOULSAND) && // Not on soulsand
(Chunk->GetSkyLight(RelX, RelY, RelZ) == 15) && // In the daylight
(Chunk->GetBlock(RelX, RelY, RelZ) != E_BLOCK_SOULSAND) && // Not on soulsand
(GetWorld()->GetTimeOfDay() < (12000 + 1000)) && // It is nighttime
GetWorld()->IsWeatherSunnyAt(POSX_TOINT, POSZ_TOINT) // Not raining
)
@ -1121,7 +1269,3 @@ cMonster::eFamily cMonster::GetMobFamily(void) const
{
return FamilyFromType(m_MobType);
}

View File

@ -180,6 +180,13 @@ protected:
/** Coordinates for the ultimate, final destination last given to the pathfinder. */
Vector3d m_PathFinderDestination;
/** True if there's no path to target and we're walking to an approximated location. */
bool m_NoPathToTarget;
/** Whether The mob has finished their path, note that this does not imply reaching the destination,
the destination may sometimes differ from the current path. */
bool m_NoMoreWayPoints;
/** Finds the lowest non-air block position (not the highest, as cWorld::GetHeight does)
If current Y is nonsolid, goes down to try to find a solid block, then returns that + 1
If current Y is solid, goes up to find first nonsolid block, and returns that.
@ -203,8 +210,18 @@ protected:
Returns if a path is ready, and therefore if the mob should move to m_NextWayPointPosition
*/
bool TickPathFinding(cChunk & a_Chunk);
/** Move in a straight line to the next waypoint in the path, will jump if needed. */
void MoveToWayPoint(cChunk & a_Chunk);
/** Ensures the destination is not buried underground or under water. Also ensures the destination is not in the air.
Only the Y coordinate of m_FinalDestination might be changed.
1. If m_FinalDestination is the position of a water block, m_FinalDestination's Y will be modified to point to the heighest water block in the pool in the current column.
2. If m_FinalDestination is the position of a solid, m_FinalDestination's Y will be modified to point to the first airblock above the solid in the current column.
3. If m_FinalDestination is the position of an air block, Y will keep decreasing until hitting either a solid or water.
Now either 1 or 2 is performed. */
bool EnsureProperDestination(cChunk & a_Chunk);
/** Resets a pathfinding task, be it due to failure or something else
Resets the pathfinder. If m_IsFollowingPath is true, TickPathFinding starts a brand new path.
Should only be called by the pathfinder, cMonster::Tick or StopMovingToPosition. */

View File

@ -1,3 +1,4 @@
#include "Globals.h"
#include <cmath>
@ -7,7 +8,7 @@
#define DISTANCE_MANHATTAN 0 // 1: More speed, a bit less accuracy 0: Max accuracy, less speed.
#define HEURISTICS_ONLY 0 // 1: Much more speed, much less accurate.
#define CALCULATIONS_PER_STEP 60 // Higher means more CPU load but faster path calculations.
#define CALCULATIONS_PER_STEP 10 // Higher means more CPU load but faster path calculations.
// The only version which guarantees the shortest path is 0, 0.
enum class eCellStatus {OPENLIST, CLOSEDLIST, NOLIST};
@ -43,7 +44,8 @@ cPath::cPath(
m_Destination(a_EndingPoint.Floor()),
m_Source(a_StartingPoint.Floor()),
m_CurrentPoint(0), // GetNextPoint increments this to 1, but that's fine, since the first cell is always a_StartingPoint
m_Chunk(&a_Chunk)
m_Chunk(&a_Chunk),
m_BadChunkFound(false)
{
// TODO: if src not walkable OR dest not walkable, then abort.
// Borrow a new "isWalkable" from ProcessIfWalkable, make ProcessIfWalkable also call isWalkable
@ -54,31 +56,7 @@ cPath::cPath(
return;
}
// If destination in water, set water surface as destination.
cChunk * Chunk = m_Chunk->GetNeighborChunk(m_Destination.x, m_Destination.z);
if ((Chunk != nullptr) && Chunk->IsValid())
{
BLOCKTYPE BlockType;
NIBBLETYPE BlockMeta;
int RelX = m_Destination.x - Chunk->GetPosX() * cChunkDef::Width;
int RelZ = m_Destination.z - Chunk->GetPosZ() * cChunkDef::Width;
bool inwater = false;
for (;;)
{
Chunk->GetBlockTypeMeta(RelX, m_Destination.y, RelZ, BlockType, BlockMeta);
if (BlockType != E_BLOCK_STATIONARY_WATER)
{
break;
}
inwater = true;
m_Destination+=Vector3d(0, 1, 0);
}
if (inwater)
{
m_Destination+=Vector3d(0, -1, 0);
}
}
m_NearestPointToTarget = GetCell(m_Source);
m_Status = ePathFinderStatus::CALCULATING;
m_StepsLeft = a_MaxSteps;
@ -105,15 +83,20 @@ cPath::~cPath()
ePathFinderStatus cPath::Step(cChunk & a_Chunk)
{
m_Chunk = &a_Chunk;
if (m_Status != ePathFinderStatus::CALCULATING)
{
return m_Status;
}
if (m_StepsLeft == 0)
if (m_BadChunkFound)
{
FinishCalculation(ePathFinderStatus::PATH_NOT_FOUND);
return m_Status;
}
if (m_StepsLeft == 0)
{
AttemptToFindAlternative();
}
else
{
@ -126,9 +109,9 @@ ePathFinderStatus cPath::Step(cChunk & a_Chunk)
break; // if we're here, m_Status must have changed either to PATH_FOUND or PATH_NOT_FOUND.
}
}
}
m_Chunk = nullptr;
}
return m_Status;
}
@ -136,6 +119,17 @@ ePathFinderStatus cPath::Step(cChunk & a_Chunk)
Vector3i cPath::AcceptNearbyPath()
{
ASSERT(m_Status == ePathFinderStatus::NEARBY_FOUND);
m_Status = ePathFinderStatus::PATH_FOUND;
return m_Destination;
}
bool cPath::IsSolid(const Vector3i & a_Location)
{
ASSERT(m_Chunk != nullptr);
@ -143,6 +137,7 @@ bool cPath::IsSolid(const Vector3i & a_Location)
auto Chunk = m_Chunk->GetNeighborChunk(a_Location.x, a_Location.z);
if ((Chunk == nullptr) || !Chunk->IsValid())
{
m_BadChunkFound = true;
return true;
}
m_Chunk = Chunk;
@ -173,34 +168,29 @@ bool cPath::Step_Internal()
{
cPathCell * CurrentCell = OpenListPop();
// Path not reachable, open list exauhsted.
// Path not reachable.
if (CurrentCell == nullptr)
{
FinishCalculation(ePathFinderStatus::PATH_NOT_FOUND);
ASSERT(m_Status == ePathFinderStatus::PATH_NOT_FOUND);
AttemptToFindAlternative();
return true;
}
// Path found.
if (
(CurrentCell->m_Location == m_Destination + Vector3i(0, 0, 1)) ||
(CurrentCell->m_Location == m_Destination + Vector3i(1, 0, 0)) ||
(CurrentCell->m_Location == m_Destination + Vector3i(-1, 0, 0)) ||
(CurrentCell->m_Location == m_Destination + Vector3i(0, 0, -1)) ||
(CurrentCell->m_Location == m_Destination + Vector3i(0, -1, 0))
)
if (CurrentCell->m_Location == m_Destination)
{
do
{
m_PathPoints.push_back(CurrentCell->m_Location); // Populate the cPath with points.
CurrentCell = CurrentCell->m_Parent;
} while (CurrentCell != nullptr);
BuildPath();
FinishCalculation(ePathFinderStatus::PATH_FOUND);
return true;
}
// Calculation not finished yet, process a currentCell by inspecting all neighbors.
// Calculation not finished yet.
// Check if we have a new NearestPoint.
if (CurrentCell->m_H < m_NearestPointToTarget->m_H)
{
m_NearestPointToTarget = CurrentCell;
}
// process a currentCell by inspecting all neighbors.
// Check North, South, East, West on all 3 different heights.
int i;
@ -237,15 +227,42 @@ bool cPath::Step_Internal()
void cPath::FinishCalculation()
void cPath::AttemptToFindAlternative()
{
for (auto && pair : m_Map)
if (m_NearestPointToTarget == GetCell(m_Source))
{
delete pair.second;
FinishCalculation(ePathFinderStatus::PATH_NOT_FOUND);
}
else
{
m_Destination = m_NearestPointToTarget->m_Location;
BuildPath();
FinishCalculation(ePathFinderStatus::NEARBY_FOUND);
}
}
void cPath::BuildPath()
{
cPathCell * CurrentCell = GetCell(m_Destination);
do
{
m_PathPoints.push_back(CurrentCell->m_Location); // Populate the cPath with points.
CurrentCell = CurrentCell->m_Parent;
} while (CurrentCell != nullptr);
}
void cPath::FinishCalculation()
{
m_Map.clear();
m_OpenList.empty();
m_OpenList = std::priority_queue<cPathCell *, std::vector<cPathCell *>, compareHeuristics>{};
}
@ -254,6 +271,10 @@ void cPath::FinishCalculation()
void cPath::FinishCalculation(ePathFinderStatus a_NewStatus)
{
if (m_BadChunkFound)
{
a_NewStatus = ePathFinderStatus::PATH_NOT_FOUND;
}
m_Status = a_NewStatus;
FinishCalculation();
}
@ -279,7 +300,7 @@ cPathCell * cPath::OpenListPop() // Popping from the open list also means addin
{
if (m_OpenList.size() == 0)
{
return nullptr; // We've exhausted the search space and nothing was found, this will trigger a PATH_NOT_FOUND status.
return nullptr; // We've exhausted the search space and nothing was found, this will trigger a PATH_NOT_FOUND or NEARBY_FOUND status.
}
cPathCell * Ret = m_OpenList.top();
@ -372,7 +393,7 @@ cPathCell * cPath::GetCell(const Vector3i & a_Location)
{
Cell = new cPathCell();
Cell->m_Location = a_Location;
m_Map[a_Location] = Cell;
m_Map[a_Location] = UniquePtr<cPathCell>(Cell);
Cell->m_IsSolid = IsSolid(a_Location);
Cell->m_Status = eCellStatus::NOLIST;
#ifdef COMPILING_PATHFIND_DEBUGGER
@ -384,6 +405,6 @@ cPathCell * cPath::GetCell(const Vector3i & a_Location)
}
else
{
return m_Map[a_Location];
return m_Map[a_Location].get();
}
}

View File

@ -1,3 +1,4 @@
#pragma once
/* Wanna use the pathfinder? Put this in your header file:
@ -22,7 +23,7 @@ Put this in your .cpp:
class cChunk;
/* Various little structs and classes */
enum class ePathFinderStatus {CALCULATING, PATH_FOUND, PATH_NOT_FOUND};
enum class ePathFinderStatus {CALCULATING, PATH_FOUND, PATH_NOT_FOUND, NEARBY_FOUND};
struct cPathCell; // Defined inside Path.cpp
class compareHeuristics
{
@ -61,9 +62,17 @@ public:
/** Destroys the path and frees its memory. */
~cPath();
/** Performs part of the path calculation and returns true if the path computation has finished. */
/** Performs part of the path calculation and returns the appropriate status.
If NEARBY_FOUND is returned, it means that the destination is not reachable, but a nearby destination
is reachable. If the user likes the alternative destination, they can call AcceptNearbyPath to treat the path as found,
and to make consequent calls to step return PATH_FOUND*/
ePathFinderStatus Step(cChunk & a_Chunk);
/** Called after the PathFinder's step returns NEARBY_FOUND.
Changes the PathFinder status from NEARBY_FOUND to PATH_FOUND, returns the nearby destination that
the PathFinder found a path to. */
Vector3i AcceptNearbyPath();
/* Point retrieval functions, inlined for performance. */
/** Returns the next point in the path. */
inline Vector3i GetNextPoint()
@ -92,7 +101,10 @@ public:
/** Returns the total number of points this path has. */
inline int GetPointCount()
{
ASSERT(m_Status == ePathFinderStatus::PATH_FOUND);
if (m_Status != ePathFinderStatus::PATH_FOUND)
{
return 0;
}
return m_PathPoints.size();
}
@ -118,6 +130,8 @@ private:
bool Step_Internal(); // The public version just calls this version * CALCULATIONS_PER_CALL times.
void FinishCalculation(); // Clears the memory used for calculating the path.
void FinishCalculation(ePathFinderStatus a_NewStatus); // Clears the memory used for calculating the path and changes the status.
void AttemptToFindAlternative();
void BuildPath();
/* Openlist and closedlist management */
void OpenListAdd(cPathCell * a_Cell);
@ -130,10 +144,11 @@ private:
/* Pathfinding fields */
std::priority_queue<cPathCell *, std::vector<cPathCell *>, compareHeuristics> m_OpenList;
std::unordered_map<Vector3i, cPathCell *, VectorHasher> m_Map;
std::unordered_map<Vector3i, UniquePtr<cPathCell>, VectorHasher> m_Map;
Vector3i m_Destination;
Vector3i m_Source;
int m_StepsLeft;
cPathCell * m_NearestPointToTarget;
/* Control fields */
ePathFinderStatus m_Status;
@ -144,6 +159,7 @@ private:
/* Interfacing with the world */
cChunk * m_Chunk; // Only valid inside Step()!
bool m_BadChunkFound;
#ifdef COMPILING_PATHFIND_DEBUGGER
#include "../path_irrlicht.cpp"
#endif

View File

@ -89,7 +89,7 @@ void cSlime::KilledBy(TakeDamageInfo & a_TDI)
const AString cSlime::GetSizeName(int a_Size) const
AString cSlime::GetSizeName(int a_Size)
{
if (a_Size > 1)
{

View File

@ -27,7 +27,7 @@ public:
/** Returns the text describing the slime's size, as used by the client's resource subsystem for sounds.
Returns either "big" or "small". */
const AString GetSizeName(int a_Size) const;
static AString GetSizeName(int a_Size);
protected:

View File

@ -5,6 +5,7 @@
#include "../World.h"
#include "../Entities/Player.h"
#include "../Items/ItemHandler.h"
#include "Broadcaster.h"
@ -83,13 +84,13 @@ void cWolf::OnRightClicked(cPlayer & a_Player)
SetIsTame(true);
SetOwner(a_Player.GetName(), a_Player.GetUUID());
m_World->BroadcastEntityStatus(*this, esWolfTamed);
m_World->BroadcastParticleEffect("heart", (float) GetPosX(), (float) GetPosY(), (float) GetPosZ(), 0, 0, 0, 0, 5);
m_World->GetBroadcaster().BroadcastParticleEffect("heart", static_cast<Vector3f>(GetPosition()), Vector3f{}, 0, 5);
}
else
{
// Taming failed
m_World->BroadcastEntityStatus(*this, esWolfTaming);
m_World->BroadcastParticleEffect("smoke", (float) GetPosX(), (float) GetPosY(), (float) GetPosZ(), 0, 0, 0, 0, 5);
m_World->GetBroadcaster().BroadcastParticleEffect("smoke", static_cast<Vector3f>(GetPosition()), Vector3f{}, 0, 5);
}
}
}

View File

@ -0,0 +1,273 @@
#include "Globals.h"
#include "OverridesSettingsRepository.h"
cOverridesSettingsRepository::cOverridesSettingsRepository(std::unique_ptr<cSettingsRepositoryInterface> a_Main, std::unique_ptr<cSettingsRepositoryInterface> a_Overrides) :
m_Main(std::move(a_Main)),
m_Overrides(std::move(a_Overrides))
{
}
bool cOverridesSettingsRepository::KeyExists(const AString a_keyName) const
{
return m_Overrides->KeyExists(a_keyName) || m_Main->KeyExists(a_keyName);
}
bool cOverridesSettingsRepository::HasValue(const AString & a_KeyName, const AString & a_ValueName) const
{
return m_Overrides->HasValue(a_KeyName, a_ValueName) || m_Main->HasValue(a_KeyName, a_ValueName);
}
int cOverridesSettingsRepository::AddKeyName(const AString & a_keyname)
{
if (m_Overrides->KeyExists(a_keyname))
{
m_Overrides->AddKeyName(a_keyname);
return 0;
}
return m_Main->AddKeyName(a_keyname);
}
bool cOverridesSettingsRepository::AddKeyComment(const AString & a_keyname, const AString & a_comment)
{
if (m_Overrides->KeyExists(a_keyname))
{
return m_Overrides->AddKeyComment(a_keyname, a_comment);
}
return m_Main->AddKeyComment(a_keyname, a_comment);
}
AString cOverridesSettingsRepository::GetKeyComment(const AString & a_keyname, const int a_commentID) const
{
if (m_Overrides->KeyExists(a_keyname))
{
return m_Overrides->GetKeyComment(a_keyname, a_commentID);
}
return m_Main->GetKeyComment(a_keyname, a_commentID);
}
bool cOverridesSettingsRepository::DeleteKeyComment(const AString & a_keyname, const int a_commentID)
{
if (m_Overrides->KeyExists(a_keyname))
{
return m_Overrides->DeleteKeyComment(a_keyname, a_commentID);
}
return m_Main->DeleteKeyComment(a_keyname, a_commentID);
}
void cOverridesSettingsRepository::AddValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value)
{
if (m_Overrides->HasValue(a_KeyName, a_ValueName))
{
m_Overrides->AddValue(a_KeyName, a_ValueName, a_Value);
}
else
{
m_Main->AddValue(a_KeyName, a_ValueName, a_Value);
}
}
std::vector<std::pair<AString, AString>> cOverridesSettingsRepository::GetValues(AString a_keyName)
{
auto overrides = m_Overrides->GetValues(a_keyName);
auto main = m_Main->GetValues(a_keyName);
std::sort(overrides.begin(), overrides.end(), [](std::pair<AString, AString> a, std::pair<AString, AString> b) -> bool { return a < b ;});
std::sort(main.begin(), main.end(), [](std::pair<AString, AString> a, std::pair<AString, AString> b) -> bool { return a < b ;});
std::vector<std::pair<AString, AString>> ret;
size_t overridesIndex = 0;
for (auto pair : main)
{
if (overridesIndex >= overrides.size())
{
ret.push_back(pair);
continue;
}
if (pair.first == overrides[overridesIndex].first)
{
continue;
}
while (pair.first > overrides[overridesIndex].first)
{
ret.push_back(overrides[overridesIndex]);
overridesIndex++;
}
ret.push_back(pair);
}
return ret;
}
AString cOverridesSettingsRepository::GetValue(const AString & a_KeyName, const AString & a_ValueName, const AString & defValue) const
{
if (m_Overrides->HasValue(a_KeyName, a_ValueName))
{
return m_Overrides->GetValue(a_KeyName, a_ValueName, defValue);
}
else
{
return m_Main->GetValue(a_KeyName, a_ValueName, defValue);
}
}
AString cOverridesSettingsRepository::GetValueSet (const AString & a_KeyName, const AString & a_ValueName, const AString & defValue)
{
if (m_Overrides->HasValue(a_KeyName, a_ValueName))
{
return m_Overrides->GetValueSet(a_KeyName, a_ValueName, defValue);
}
else
{
return m_Main->GetValueSet(a_KeyName, a_ValueName, defValue);
}
}
int cOverridesSettingsRepository::GetValueSetI(const AString & a_KeyName, const AString & a_ValueName, const int defValue)
{
if (m_Overrides->HasValue(a_KeyName, a_ValueName))
{
return m_Overrides->GetValueSetI(a_KeyName, a_ValueName, defValue);
}
else
{
return m_Main->GetValueSetI(a_KeyName, a_ValueName, defValue);
}
}
Int64 cOverridesSettingsRepository::GetValueSetI(const AString & a_KeyName, const AString & a_ValueName, const Int64 defValue)
{
if (m_Overrides->HasValue(a_KeyName, a_ValueName))
{
return m_Overrides->GetValueSetI(a_KeyName, a_ValueName, defValue);
}
else
{
return m_Main->GetValueSetI(a_KeyName, a_ValueName, defValue);
}
}
bool cOverridesSettingsRepository::GetValueSetB(const AString & a_KeyName, const AString & a_ValueName, const bool defValue)
{
if (m_Overrides->HasValue(a_KeyName, a_ValueName))
{
return m_Overrides->GetValueSetB(a_KeyName, a_ValueName, defValue);
}
else
{
return m_Main->GetValueSetB(a_KeyName, a_ValueName, defValue);
}
}
bool cOverridesSettingsRepository::SetValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value, const bool a_CreateIfNotExists)
{
if (m_Overrides->HasValue(a_KeyName, a_ValueName))
{
return m_Overrides->SetValue(a_KeyName, a_ValueName, a_Value, a_CreateIfNotExists);
}
else
{
return m_Main->SetValue(a_KeyName, a_ValueName, a_Value, a_CreateIfNotExists);
}
}
bool cOverridesSettingsRepository::SetValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value, const bool a_CreateIfNotExists)
{
if (m_Overrides->HasValue(a_KeyName, a_ValueName))
{
return m_Overrides->SetValueI(a_KeyName, a_ValueName, a_Value, a_CreateIfNotExists);
}
else
{
return m_Main->SetValueI(a_KeyName, a_ValueName, a_Value, a_CreateIfNotExists);
}
}
bool cOverridesSettingsRepository::DeleteValue(const AString & a_KeyName, const AString & a_ValueName)
{
if (m_Overrides->HasValue(a_KeyName, a_ValueName))
{
return m_Overrides->DeleteValue(a_KeyName, a_ValueName);
}
else
{
return m_Overrides->DeleteValue(a_KeyName, a_ValueName);
}
}
bool cOverridesSettingsRepository::Flush()
{
return m_Overrides->Flush() && m_Main->Flush();
}

View File

@ -0,0 +1,52 @@
#pragma once
#include "SettingsRepositoryInterface.h"
#include <unordered_map>
class cOverridesSettingsRepository : public cSettingsRepositoryInterface
{
public:
cOverridesSettingsRepository(std::unique_ptr<cSettingsRepositoryInterface> a_Main, std::unique_ptr<cSettingsRepositoryInterface> a_Overrides);
virtual ~cOverridesSettingsRepository() = default;
virtual bool KeyExists(const AString keyname) const override;
virtual bool HasValue(const AString & a_KeyName, const AString & a_ValueName) const override;
virtual int AddKeyName(const AString & keyname) override;
virtual bool AddKeyComment(const AString & keyname, const AString & comment) override;
virtual AString GetKeyComment(const AString & keyname, const int commentID) const override;
virtual bool DeleteKeyComment(const AString & keyname, const int commentID) override;
virtual void AddValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value) override;
virtual std::vector<std::pair<AString, AString>> GetValues(AString a_keyName) override;
virtual AString GetValue (const AString & keyname, const AString & valuename, const AString & defValue = "") const override;
virtual AString GetValueSet (const AString & keyname, const AString & valuename, const AString & defValue = "") override;
virtual int GetValueSetI(const AString & keyname, const AString & valuename, const int defValue = 0) override;
virtual Int64 GetValueSetI(const AString & keyname, const AString & valuename, const Int64 defValue = 0) override;
virtual bool GetValueSetB(const AString & keyname, const AString & valuename, const bool defValue = false) override;
virtual bool SetValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value, const bool a_CreateIfNotExists = true) override;
virtual bool SetValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value, const bool a_CreateIfNotExists = true) override;
virtual bool DeleteValue(const AString & keyname, const AString & valuename) override;
virtual bool Flush() override;
private:
std::unique_ptr<cSettingsRepositoryInterface> m_Main;
std::unique_ptr<cSettingsRepositoryInterface> m_Overrides;
};

View File

@ -133,6 +133,7 @@ int cProbabDistrib::MapValue(int a_OrigValue) const
// Linearly interpolate between Lo and Hi:
int ProbDif = m_Cumulative[Hi].m_Probability - m_Cumulative[Lo].m_Probability;
ProbDif = (ProbDif != 0) ? ProbDif : 1;
int ValueDif = m_Cumulative[Hi].m_Value - m_Cumulative[Lo].m_Value;
return m_Cumulative[Lo].m_Value + (a_OrigValue - m_Cumulative[Lo].m_Probability) * ValueDif / ProbDif;
}

View File

@ -40,11 +40,11 @@ cAuthenticator::~cAuthenticator()
void cAuthenticator::ReadINI(cIniFile & IniFile)
void cAuthenticator::ReadSettings(cSettingsRepositoryInterface & a_Settings)
{
m_Server = IniFile.GetValueSet ("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = IniFile.GetValueSet ("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
m_Server = a_Settings.GetValueSet ("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = a_Settings.GetValueSet ("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = a_Settings.GetValueSetB("Authentication", "Authenticate", true);
}
@ -69,9 +69,9 @@ void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, co
void cAuthenticator::Start(cIniFile & IniFile)
void cAuthenticator::Start(cSettingsRepositoryInterface & a_Settings)
{
ReadINI(IniFile);
ReadSettings(a_Settings);
m_ShouldTerminate = false;
super::Start();
}

View File

@ -14,7 +14,7 @@
#include "../OSSupport/IsThread.h"
class cSettingsRepositoryInterface;
@ -40,13 +40,13 @@ public:
~cAuthenticator();
/** (Re-)read server and address from INI: */
void ReadINI(cIniFile & IniFile);
void ReadSettings(cSettingsRepositoryInterface & a_Settings);
/** Queues a request for authenticating a user. If the auth fails, the user will be kicked */
void Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash);
/** Starts the authenticator thread. The thread may be started and stopped repeatedly */
void Start(cIniFile & IniFile);
void Start(cSettingsRepositoryInterface & a_Settings);
/** Stops the authenticator thread. The thread may be started and stopped repeatedly */
void Stop(void);

View File

@ -68,7 +68,7 @@ const AString & cChunkDataSerializer::Serialize(int a_Version, int a_ChunkX, int
void cChunkDataSerializer::Serialize29(AString & a_Data)
{
// TODO: Do not copy data and then compress it; rather, compress partial blocks of data (zlib *can* stream)
// TODO: Do not copy data and then compress it; rather, compress partial blocks of data (zlib can stream)
const int BiomeDataSize = cChunkDef::Width * cChunkDef::Width;
const int MetadataOffset = sizeof(m_BlockTypes);
@ -126,7 +126,7 @@ void cChunkDataSerializer::Serialize29(AString & a_Data)
void cChunkDataSerializer::Serialize39(AString & a_Data)
{
// TODO: Do not copy data and then compress it; rather, compress partial blocks of data (zlib *can* stream)
// TODO: Do not copy data and then compress it; rather, compress partial blocks of data (zlib can stream)
const int BiomeDataSize = cChunkDef::Width * cChunkDef::Width;
const int MetadataOffset = sizeof(m_BlockTypes);

View File

@ -226,12 +226,12 @@ cMojangAPI::~cMojangAPI()
void cMojangAPI::Start(cIniFile & a_SettingsIni, bool a_ShouldAuth)
void cMojangAPI::Start(cSettingsRepositoryInterface & a_Settings, bool a_ShouldAuth)
{
m_NameToUUIDServer = a_SettingsIni.GetValueSet("MojangAPI", "NameToUUIDServer", DEFAULT_NAME_TO_UUID_SERVER);
m_NameToUUIDAddress = a_SettingsIni.GetValueSet("MojangAPI", "NameToUUIDAddress", DEFAULT_NAME_TO_UUID_ADDRESS);
m_UUIDToProfileServer = a_SettingsIni.GetValueSet("MojangAPI", "UUIDToProfileServer", DEFAULT_UUID_TO_PROFILE_SERVER);
m_UUIDToProfileAddress = a_SettingsIni.GetValueSet("MojangAPI", "UUIDToProfileAddress", DEFAULT_UUID_TO_PROFILE_ADDRESS);
m_NameToUUIDServer = a_Settings.GetValueSet("MojangAPI", "NameToUUIDServer", DEFAULT_NAME_TO_UUID_SERVER);
m_NameToUUIDAddress = a_Settings.GetValueSet("MojangAPI", "NameToUUIDAddress", DEFAULT_NAME_TO_UUID_ADDRESS);
m_UUIDToProfileServer = a_Settings.GetValueSet("MojangAPI", "UUIDToProfileServer", DEFAULT_UUID_TO_PROFILE_SERVER);
m_UUIDToProfileAddress = a_Settings.GetValueSet("MojangAPI", "UUIDToProfileAddress", DEFAULT_UUID_TO_PROFILE_ADDRESS);
LoadCachesFromDisk();
if (a_ShouldAuth)
{
@ -667,7 +667,7 @@ void cMojangAPI::QueryNamesToUUIDs(AStringVector & a_NamesToQuery)
Request += "User-Agent: MCServer\r\n";
Request += "Connection: close\r\n";
Request += "Content-Type: application/json\r\n";
Request += Printf("Content-Length: %u\r\n", (unsigned)RequestBody.length());
Request += Printf("Content-Length: %u\r\n", static_cast<unsigned>(RequestBody.length()));
Request += "\r\n";
Request += RequestBody;

Some files were not shown because too many files have changed in this diff Show More