1
0
Fork 0

Merge remote-tracking branch 'origin/master' into foldermove2

Conflicts:
	GNUmakefile
This commit is contained in:
Alexander Harkness 2013-11-24 14:37:03 +00:00
commit c3cd436ec3
131 changed files with 6157 additions and 3632 deletions

View File

@ -46,8 +46,9 @@ ifeq ($(release),1)
################
# release build - fastest run-time, no gdb support
################
CC_OPTIONS = -s -g -O3 -DNDEBUG
CXX_OPTIONS = -s -g -O3 -DNDEBUG
CC_OPTIONS = -g -O3 -DNDEBUG
CXX_OPTIONS = -g -O3 -DNDEBUG
LNK_OPTIONS = -pthread -O3
BUILDDIR = build/release/
@ -56,6 +57,7 @@ ifeq ($(profile),1)
################
# profile build - a release build with symbols and profiling engine built in
################
CC_OPTIONS = -s -g -ggdb -O3 -pg -DNDEBUG
CXX_OPTIONS = -s -g -ggdb -O3 -pg -DNDEBUG
LNK_OPTIONS = -pthread -ggdb -O3 -pg
@ -66,6 +68,7 @@ else
# debug build - fully traceable by gdb in C++ code, slowest
# Since C code is used only for supporting libraries (zlib, lua), it is still O3-optimized
################
CC_OPTIONS = -s -ggdb -g -D_DEBUG -O3
CXX_OPTIONS = -s -ggdb -g -D_DEBUG -Og
LNK_OPTIONS = -pthread -g -ggdb -Og
@ -74,6 +77,10 @@ endif
endif
endif
##################################################
# Always be warning.
CXX_OPTIONS += -Wall
###################################################
# Fix Crypto++ warnings in clang
@ -93,7 +100,7 @@ endif
UNAME := $(shell uname -s)
ifeq ($(UNAME),Linux)
LNK_LIBS = -lstdc++ -ldl
LNK_LIBS = -lstdc++ -ldl -lm
else
LNK_LIBS = -lstdc++ -lltdl
endif
@ -130,7 +137,6 @@ endif
###################################################
# INCLUDE directories for MCServer
#
INCLUDE = -I.\
-Isource\
@ -152,9 +158,6 @@ INCLUDE = -I.\
###################################################
# Build MCServer
#
# 2012_11_08 _X: Removed: squirrel_3_0_1_stable
SOURCES := $(shell find CryptoPP lua-5.1.4 jsoncpp-src-0.5.0 zlib-1.2.7 source tolua++-1.0.93 iniFile expat '(' -name '*.cpp' -o -name '*.c' ')')
SOURCES := $(filter-out %minigzip.c %lua.c %tolua.c %toluabind.c %LeakFinder.cpp %StackWalker.cpp %example.c,$(SOURCES))

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,243 @@
return
{
cBlockEntity =
{
Desc = [[
Block entities are simply blocks in the world that have persistent data, such as the text for a sign
or contents of a chest. All block entities are also saved in the chunk data of the chunk they reside in.
The cBlockEntity class acts as a common ancestor for all the individual block entities.
]],
Functions =
{
GetBlockType = { Params = "", Return = "BLOCKTYPE", Notes = "Returns the blocktype which is represented by this blockentity. This is the primary means of type-identification" },
GetChunkX = { Params = "", Return = "number", Notes = "Returns the chunk X-coord of the block entity's chunk" },
GetChunkZ = { Params = "", Return = "number", Notes = "Returns the chunk Z-coord of the block entity's chunk" },
GetPosX = { Params = "", Return = "number", Notes = "Returns the block X-coord of the block entity's block" },
GetPosY = { Params = "", Return = "number", Notes = "Returns the block Y-coord of the block entity's block" },
GetPosZ = { Params = "", Return = "number", Notes = "Returns the block Z-coord of the block entity's block" },
GetRelX = { Params = "", Return = "number", Notes = "Returns the relative X coord of the block entity's block within the chunk" },
GetRelZ = { Params = "", Return = "number", Notes = "Returns the relative Z coord of the block entity's block within the chunk" },
GetWorld = { Params = "", Return = "{{cWorld|cWorld}}", Notes = "Returns the world to which the block entity belongs" },
},
},
cBlockEntityWithItems =
{
Desc = [[
This class is a common ancestor for all {{cBlockEntity|block entities}} that provide item storage.
Internally, the object has a {{cItemGrid|cItemGrid}} object for storing the items; this ItemGrid is
accessible through the API. The storage is a grid of items, items in it can be addressed either by a slot
number, or by XY coords within the grid. If a UI window is opened for this block entity, the item storage
is monitored for changes and the changes are immediately sent to clients of the UI window.
]],
Inherits = "cBlockEntity",
Functions =
{
GetContents = { Params = "", Return = "{{cItemGrid|cItemGrid}}", Notes = "Returns the cItemGrid object representing the items stored within this block entity" },
GetSlot =
{
{ Params = "SlotNum", Return = "{{cItem|cItem}}", Notes = "Returns the cItem for the specified slot number. Returns nil for invalid slot numbers" },
{ Params = "X, Y", Return = "{{cItem|cItem}}", Notes = "Returns the cItem for the specified slot coords. Returns nil for invalid slot coords" },
},
SetSlot =
{
{ Params = "SlotNum, {{cItem|cItem}}", Return = "", Notes = "Sets the cItem for the specified slot number. Ignored if invalid slot number" },
{ Params = "X, Y, {{cItem|cItem}}", Return = "", Notes = "Sets the cItem for the specified slot coords. Ignored if invalid slot coords" },
},
},
},
cChestEntity =
{
Desc = [[
A chest entity is a {{cBlockEntityWithItems|cBlockEntityWithItems}} descendant that represents a chest
in the world. Note that doublechests consist of two separate cChestEntity objects, they do not collaborate
in any way.</p>
<p>
To manipulate a chest already in the game, you need to use {{cWorld}}'s callback mechanism with
either DoWithChestAt() or ForEachChestInChunk() function. See the code example below
]],
Inherits = "cBlockEntityWithItems",
Constants =
{
ContentsHeight = { Notes = "Height of the contents' {{cItemGrid|ItemGrid}}, as required by the parent class, {{cBlockEntityWithItems}}" },
ContentsWidth = { Notes = "Width of the contents' {{cItemGrid|ItemGrid}}, as required by the parent class, {{cBlockEntityWithItems}}" },
},
AdditionalInfo =
{
{
Header = "Code example",
Contents = [[
The following example code sets the top-left item of each chest in the same chunk as Player to
64 * diamond:
<pre class="prettyprint lang-lua">
-- Player is a {{cPlayer}} object instance
local World = Player:GetWorld();
World:ForEachChestInChunk(Player:GetChunkX(), Player:GetChunkZ(),
function (ChestEntity)
ChestEntity:SetSlot(0, 0, cItem(E_ITEM_DIAMOND, 64));
end
);
</pre>
]],
},
}, -- AdditionalInfo
},
cDispenserEntity =
{
Desc = [[
This class represents a dispenser block entity in the world. Most of this block entity's
functionality is implemented in the {{cDropSpenserEntity|cDropSpenserEntity}} class that represents
the behavior common with a {{cDropperEntity|dropper}} entity.
]],
Inherits = "cDropSpenserEntity",
},
cDropperEntity =
{
Desc = [[
This class represents a dropper block entity in the world. Most of this block entity's functionality
is implemented in the {{cDropSpenserEntity|cDropSpenserEntity}} class that represents the behavior
common with the {{cDispenserEntity|dispenser}} entity.</p>
<p>
An object of this class can be created from scratch when generating chunks ({{OnChunkGenerated|OnChunkGenerated}} and {{OnChunkGenerating|OnChunkGenerating}} hooks).
]],
Inherits = "cDropSpenserEntity",
}, -- cDropperEntity
cDropSpenserEntity =
{
Desc = [[
This is a class that implements behavior common to both {{cDispenserEntity|dispensers}} and {{cDropperEntity|droppers}}.
]],
Functions =
{
Activate = { Params = "", Return = "", Notes = "Sets the block entity to dropspense an item in the next tick" },
AddDropSpenserDir = { Params = "BlockX, BlockY, BlockZ, BlockMeta", Return = "BlockX, BlockY, BlockZ", Notes = "Adjusts the block coords to where the dropspenser items materialize" },
SetRedstonePower = { Params = "IsPowered", Return = "", Notes = "Sets the redstone status of the dropspenser. If the redstone power goes from off to on, the dropspenser will be activated" },
},
Constants =
{
ContentsWidth = { Notes = "Width (X) of the {{cItemGrid}} representing the contents" },
ContentsHeight = { Notes = "Height (Y) of the {{cItemGrid}} representing the contents" },
},
Inherits = "cBlockEntityWithItems";
}, -- cDropSpenserEntity
cFurnaceEntity =
{
Desc = [[
This class represents a furnace block entity in the world.</p>
<p>
See also {{cRoot}}'s GetFurnaceRecipe() and GetFurnaceFuelBurnTime() functions
]],
Functions =
{
GetCookTimeLeft = { Params = "", Return = "number", Notes = "Returns the time until the current item finishes cooking, in ticks" },
GetFuelBurnTimeLeft = { Params = "", Return = "number", Notes = "Returns the time until the current fuel is depleted, in ticks" },
GetFuelSlot = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the item in the fuel slot" },
GetInputSlot = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the item in the input slot" },
GetOutputSlot = { Params = "", Return = "{{cItem|cItem}}", Notes = "Returns the item in the output slot" },
GetTimeCooked = { Params = "", Return = "number", Notes = "Returns the time that the current item has been cooking, in ticks" },
HasFuelTimeLeft = { Params = "", Return = "bool", Notes = "Returns true if there's time before the current fuel is depleted" },
SetFuelSlot = { Params = "{{cItem|cItem}}", Return = "", Notes = "Sets the item in the fuel slot" },
SetInputSlot = { Params = "{{cItem|cItem}}", Return = "", Notes = "Sets the item in the input slot" },
SetOutputSlot = { Params = "{{cItem|cItem}}", Return = "", Notes = "Sets the item in the output slot" },
},
Constants =
{
fsInput = { Notes = "Index of the input slot" },
fsFuel = { Notes = "Index of the fuel slot" },
fsOutput = { Notes = "Index of the output slot" },
ContentsWidth = { Notes = "Width (X) of the {{cItemGrid|cItemGrid}} representing the contents" },
ContentsHeight = { Notes = "Height (Y) of the {{cItemGrid|cItemGrid}} representing the contents" },
},
ConstantGroups =
{
SlotIndices =
{
Include = "fs.*",
TextBefore = "When using the GetSlot() or SetSlot() function, use these constants for slot index:",
},
},
Inherits = "cBlockEntityWithItems"
}, -- cFurnaceEntity
cHopperEntity =
{
Desc = [[
This class represents a hopper block entity in the world.
]],
Functions =
{
GetOutputBlockPos = { Params = "BlockMeta", Return = "bool, BlockX, BlockY, BlockZ", Notes = "Returns whether the hopper is attached, and if so, the block coords of the block receiving the output items, based on the given meta." },
},
Constants =
{
ContentsHeight = { Notes = "Height (Y) of the internal {{cItemGrid}} representing the hopper contents." },
ContentsWidth = { Notes = "Width (X) of the internal {{cItemGrid}} representing the hopper contents." },
TICKS_PER_TRANSFER = { Notes = "Number of ticks between when the hopper transfers items." },
},
Inherits = "cBlockEntityWithItems",
}, -- cHopperEntity
cJukeboxEntity =
{
Desc = [[
This class represents a jukebox in the world. It can play the records, either when the
{{cPlayer|player}} uses the record on the jukebox, or when a plugin instructs it to play.
]],
Inherits = "cBlockEntity",
Functions =
{
EjectRecord = { Params = "", Return = "", Notes = "Ejects the current record as a {{cPickup|pickup}}. No action if there's no current record. To remove record without generating the pickup, use SetRecord(0)" },
GetRecord = { Params = "", Return = "number", Notes = "Returns the record currently present. Zero for no record, E_ITEM_*_DISC for records." },
PlayRecord = { Params = "", Return = "", Notes = "Plays the currently present record. No action if there's no current record." },
SetRecord = { Params = "number", Return = "", Notes = "Sets the currently present record. Use zero for no record, or E_ITEM_*_DISC for records." },
},
}, -- cJukeboxEntity
cNoteEntity =
{
Desc = [[
This class represents a note block entity in the world. It takes care of the note block's pitch,
and also can play the sound, either when the {{cPlayer|player}} right-clicks it, redstone activates
it, or upon a plugin's request.</p>
<p>
The pitch is stored as an integer between 0 and 24.
]],
Functions =
{
GetPitch = { Params = "", Return = "number", Notes = "Returns the current pitch set for the block" },
IncrementPitch = { Params = "", Return = "", Notes = "Adds 1 to the current pitch. Wraps around to 0 when the pitch cannot go any higher." },
MakeSound = { Params = "", Return = "", Notes = "Plays the sound for all {{cClientHandle|clients}} near this block." },
SetPitch = { Params = "Pitch", Return = "", Notes = "Sets a new pitch for the block." },
},
Inherits = "cBlockEntity",
}, -- cNoteEntity
cSignEntity =
{
Desc = [[
A sign entity represents a sign in the world. This class is only used when generating chunks, so
that the plugins may generate signs within new chunks. See the code example in {{cChunkDesc}}.
]],
Functions =
{
GetLine = { Params = "LineIndex", Return = "string", Notes = "Returns the specified line. LineIndex is expected between 0 and 3. Returns empty string and logs to server console when LineIndex is invalid." },
SetLine = { Params = "LineIndex, LineText", Return = "", Notes = "Sets the specified line. LineIndex is expected between 0 and 3. Logs to server console when LineIndex is invalid." },
SetLines = { Params = "Line1, Line2, Line3, Line4", Return = "", Notes = "Sets all the sign's lines at once." },
},
Inherits = "cBlockEntity";
}, -- cSignEntity
}

View File

@ -0,0 +1,111 @@
return
{
cArrowEntity =
{
Desc = [[
Represents the arrow when it is shot from the bow. A subclass of the {{cProjectileEntity}}.
]],
Functions =
{
CanPickup = { Params = "{{cPlayer|Player}}", Return = "bool", Notes = "Returns true if the specified player can pick the arrow when it's on the ground" },
GetDamageCoeff = { Params = "", Return = "number", Notes = "Returns the damage coefficient stored within the arrow. The damage dealt by this arrow is multiplied by this coeff" },
GetPickupState = { Params = "", Return = "PickupState", Notes = "Returns the pickup state (one of the psXXX constants, above)" },
IsCritical = { Params = "", Return = "bool", Notes = "Returns true if the arrow should deal critical damage. Based on the bow charge when the arrow was shot." },
SetDamageCoeff = { Params = "number", Return = "", Notes = "Sets the damage coefficient. The damage dealt by this arrow is multiplied by this coeff" },
SetIsCritical = { Params = "bool", Return = "", Notes = "Sets the IsCritical flag on the arrow. Critical arrow deal additional damage" },
SetPickupState = { Params = "PickupState", Return = "", Notes = "Sets the pickup state (one of the psXXX constants, above)" },
},
Constants =
{
psInCreative = { Notes = "The arrow can be picked up only by players in creative gamemode" },
psInSurvivalOrCreative = { Notes = "The arrow can be picked up by players in survival or creative gamemode" },
psNoPickup = { Notes = "The arrow cannot be picked up at all" },
},
ConstantGroups =
{
PickupState =
{
Include = "ps.*",
TextBefore = [[
The following constants are used to signalize whether the arrow, once it lands, can be picked by
players:
]],
},
},
Inherits = "cProjectileEntity",
}, -- cArrowEntity
cFireChargeEntity =
{
Desc = "",
Functions = {},
Inherits = "cProjectileEntity",
}, -- cFireChargeEntity
cGhastFireballEntity =
{
Desc = "",
Functions = {},
Inherits = "cProjectileEntity",
}, -- cGhastFireballEntity
cProjectileEntity =
{
Desc = "",
Functions =
{
GetCreator = { Params = "", Return = "{{cEntity}} descendant", Notes = "Returns the entity who created this projectile. May return nil." },
GetMCAClassName = { Params = "", Return = "string", Notes = "Returns the string that identifies the projectile type (class name) in MCA files" },
GetProjectileKind = { Params = "", Return = "ProjectileKind", Notes = "Returns the kind of this projectile (pkXXX constant)" },
IsInGround = { Params = "", Return = "bool", Notes = "Returns true if this projectile has hit the ground." },
},
Constants =
{
pkArrow = { Notes = "The projectile is an {{cArrowEntity|arrow}}" },
pkEgg = { Notes = "The projectile is a {{cThrownEggEntity|thrown egg}}" },
pkEnderPearl = { Notes = "The projectile is a {{cThrownEnderPearlEntity|thrown enderpearl}}" },
pkExpBottle = { Notes = "The projectile is a thrown exp bottle (NYI)" },
pkFireCharge = { Notes = "The projectile is a {{cFireChargeEntity|fire charge}}" },
pkFirework = { Notes = "The projectile is a (flying) firework (NYI)" },
pkFishingFloat = { Notes = "The projectile is a fishing float (NYI)" },
pkGhastFireball = { Notes = "The projectile is a {{cGhastFireballEntity|ghast fireball}}" },
pkSnowball = { Notes = "The projectile is a {{cThrownSnowballEntity|thrown snowball}}" },
pkSplashPotion = { Notes = "The projectile is a thrown splash potion (NYI)" },
pkWitherSkull = { Notes = "The projectile is a wither skull (NYI)" },
},
ConstantGroups =
{
ProjectileKind =
{
Include = "pk.*",
TextBefore = "The following constants are used to distinguish between the different projectile kinds:",
},
},
Inherits = "cEntity",
}, -- cProjectileEntity
cThrownEggEntity =
{
Desc = "",
Functions = {},
Inherits = "cProjectileEntity",
}, -- cThrownEggEntity
cThrownEnderPearlEntity =
{
Desc = "",
Functions = {},
Inherits = "cProjectileEntity",
}, -- cThrownEnderPearlEntity
cThrownSnowballEntity =
{
Desc = "",
Functions = {},
Inherits = "cProjectileEntity",
}, -- cThrownSnowballEntity
}

View File

@ -0,0 +1,62 @@
return
{
HOOK_BLOCK_TO_PICKUPS =
{
CalledWhen = "A block is about to be dug ({{cPlayer|player}}, {{cEntity|entity}} or natural reason), plugins may override what pickups that will produce.",
DefaultFnName = "OnBlockToPickups", -- also used as pagename
Desc = [[
This callback gets called whenever a block is about to be dug. This includes {{cPlayer|players}}
digging blocks, entities causing blocks to disappear ({{cTNTEntity|TNT}}, Endermen) and natural
causes (water washing away a block). Plugins may override the amount and kinds of pickups this
action produces.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world in which the block resides" },
{ Name = "Digger", Type = "{{cEntity}} descendant", Notes = "The entity causing the digging. May be a {{cPlayer}}, {{cTNTEntity}} or even nil (natural causes)" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockType", Type = "BLOCKTYPE", Notes = "Block type of the block" },
{ Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "Block meta of the block" },
{ Name = "Pickups", Type = "{{cItems}}", Notes = "Items that will be spawned as pickups" },
},
Returns = [[
If the function returns false or no value, the next callback in the hook chain will be called. If
the function returns true, no other callbacks in the chain will be called.</p>
<p>
Either way, the server will then spawn pickups specified in the Pickups parameter, so to disable
pickups, you need to Clear the object first, then return true.
]],
CodeExamples =
{
{
Title = "Modify pickups",
Desc = "This example callback function makes tall grass drop diamonds when digged by natural causes (washed away by water).",
Code = [[
function OnBlockToPickups(a_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_Pickups)
if (a_Digger ~= nil) then
-- Not a natural cause
return false;
end
if (a_BlockType ~= E_BLOCK_TALL_GRASS) then
-- Not a tall grass being washed away
return false;
end
-- Remove all pickups suggested by MCServer:
a_Pickups:Clear();
-- Drop a diamond:
a_Pickups:Add(cItem(E_ITEM_DIAMOND));
return true;
end;
]],
},
} , -- CodeExamples
}, -- HOOK_BLOCK_TO_PICKUPS
}

View File

@ -0,0 +1,29 @@
return
{
HOOK_CHAT =
{
CalledWhen = "Player sends a chat message",
DefaultFnName = "OnChat", -- also used as pagename
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.
]],
Params = {
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who sent the message" },
{ Name = "Message", Type = "string", Notes = "The message" },
},
Returns = [[
The plugin may return 2 values. The first is a boolean specifying whether the hook handling is to be
stopped or not. If it is false, the message is broadcast to all players in the world. If it is true,
no message is broadcast and no further action is taken.</p>
<p>
The second value is specifies the message to broadcast. This way, plugins may modify the message. If
the second value is not provided, the original message is used.
]],
}, -- HOOK_CHAT
}

View File

@ -0,0 +1,27 @@
return
{
HOOK_CHUNK_AVAILABLE =
{
CalledWhen = "A chunk has just been added to world, either generated or loaded. ",
DefaultFnName = "OnChunkAvailable", -- also used as pagename
Desc = [[
This hook is called after a chunk is either generated or loaded from the disk. The chunk is
already available for manipulation using the {{cWorld}} API. This is a notification-only callback,
there is no behavior that plugins could override.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk belongs" },
{ Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
{ Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
},
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_CHUNK_AVAILABLE
}

View File

@ -0,0 +1,67 @@
return
{
HOOK_CHUNK_GENERATED =
{
CalledWhen = "After a chunk was generated. Notification only.",
DefaultFnName = "OnChunkGenerated", -- also used as pagename
Desc = [[
This hook is called when world generator finished its work on a chunk. The chunk data has already
been generated and is about to be stored in the {{cWorld|world}}. A plugin may provide some
last-minute finishing touches to the generated data. Note that the chunk is not yet stored in the
world, so regular {{cWorld}} block API will not work! Instead, use the {{cChunkDesc}} object
received as the parameter.</p>
<p>
See also the {{OnChunkGenerating|HOOK_CHUNK_GENERATING}} hook.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk will be added" },
{ Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
{ Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
{ Name = "ChunkDesc", Type = "{{cChunkDesc}}", Notes = "Generated chunk data. Plugins may still modify the chunk data contained." },
},
Returns = [[
If the plugin returns false or no value, MCServer will call other plugins' callbacks for this event.
If a plugin returns true, no other callback is called for this event.</p>
<p>
In either case, MCServer will then store the data from ChunkDesc as the chunk's contents in the world.
]],
CodeExamples =
{
{
Title = "Generate emerald ore",
Desc = "This example callback function generates one block of emerald ore in each chunk, under the condition that the randomly chosen location is in an ExtremeHills biome.",
Code = [[
function OnChunkGenerated(a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc)
-- Generate a psaudorandom value that is always the same for the same X/Z pair, but is otherwise random enough:
-- This is actually similar to how MCServer does its noise functions
local PseudoRandom = (a_ChunkX * 57 + a_ChunkZ) * 57 + 19785486
PseudoRandom = PseudoRandom * 8192 + PseudoRandom;
PseudoRandom = ((PseudoRandom * (PseudoRandom * PseudoRandom * 15731 + 789221) + 1376312589) % 0x7fffffff;
PseudoRandom = PseudoRandom / 7;
-- Based on the PseudoRandom value, choose a location for the ore:
local OreX = PseudoRandom % 16;
local OreY = 2 + ((PseudoRandom / 16) % 20);
local OreZ = (PseudoRandom / 320) % 16;
-- Check if the location is in ExtremeHills:
if (a_ChunkDesc:GetBiome(OreX, OreZ) ~= biExtremeHills) then
return false;
end
-- Only replace allowed blocks with the ore:
local CurrBlock = a_ChunDesc:GetBlockType(OreX, OreY, OreZ);
if (
(CurrBlock == E_BLOCK_STONE) or
(CurrBlock == E_BLOCK_DIRT) or
(CurrBlock == E_BLOCK_GRAVEL)
) then
a_ChunkDesc:SetBlockTypeMeta(OreX, OreY, OreZ, E_BLOCK_EMERALD_ORE, 0);
end
end;
]],
},
} , -- CodeExamples
}, -- HOOK_CHUNK_GENERATED
}

View File

@ -0,0 +1,35 @@
return
{
HOOK_CHUNK_GENERATING =
{
CalledWhen = "A chunk is about to be generated. Plugin can override the built-in generator.",
DefaultFnName = "OnChunkGenerating", -- also used as pagename
Desc = [[
This hook is called before the world generator starts generating a chunk. The plugin may provide
some or all parts of the generation, by-passing the built-in generator. The function is given access
to the {{cChunkDesc|ChunkDesc}} object representing the contents of the chunk. It may override parts
of the built-in generator by using the object's <i>SetUseDefaultXXX(false)</i> functions. After all
the callbacks for a chunk have been processed, the server will generate the chunk based on the
{{cChunkDesc|ChunkDesc}} description - those parts that are set for generating (by default
everything) are generated, the rest are read from the ChunkDesc object.</p>
<p>
See also the {{OnChunkGenerated|HOOK_CHUNK_GENERATED}} hook.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk will be added" },
{ Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
{ Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
{ Name = "ChunkDesc", Type = "{{cChunkDesc}}", Notes = "Generated chunk data." },
},
Returns = [[
If this function returns true, the server will not call any other plugin with the same chunk. If
this function returns false, the server will call the rest of the plugins with the same chunk,
possibly overwriting the ChunkDesc's contents.
]],
}, -- HOOK_CHUNK_GENERATING
}

View File

@ -0,0 +1,28 @@
return
{
HOOK_CHUNK_UNLOADED =
{
CalledWhen = "A chunk has been unloaded from the memory.",
DefaultFnName = "OnChunkUnloaded", -- also used as pagename
Desc = [[
This hook is called when a chunk is unloaded from the memory. Though technically still in memory,
the plugin should behave as if the chunk was already not present. In particular, {{cWorld}} block
API should not be used in the area of the specified chunk.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world from which the chunk is unloading" },
{ Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
{ Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
},
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. There is no behavior that plugins could
override.
]],
}, -- HOOK_CHUNK_UNLOADED
}

View File

@ -0,0 +1,30 @@
return
{
HOOK_CHUNK_UNLOADING =
{
CalledWhen = " A chunk is about to be unloaded from the memory. Plugins may refuse the unload.",
DefaultFnName = "OnChunkUnloading", -- also used as pagename
Desc = [[
MCServer calls this function when a chunk is about to be unloaded from the memory. A plugin may
force MCServer to keep the chunk in memory by returning true.</p>
<p>
FIXME: The return value should be used only for event propagation stopping, not for the actual
decision whether to unload.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world from which the chunk is unloading" },
{ Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" },
{ Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called and finally MCServer
unloads the chunk. If the function returns true, no other callback is called for this event and the
chunk is left in the memory.
]],
}, -- HOOK_CHUNK_UNLOADING
}

View File

@ -0,0 +1,32 @@
return
{
HOOK_COLLECTING_PICKUP =
{
CalledWhen = "Player is about to collect a pickup. Plugin can refuse / override behavior. ",
DefaultFnName = "OnCollectingPickup", -- also used as pagename
Desc = [[
This hook is called when a player is about to collect a pickup. Plugins may refuse the action.</p>
<p>
Pickup collection happens within the world tick, so if the collecting is refused, it will be tried
again in the next world tick, as long as the player is within reach of the pickup.</p>
<p>
FIXME: There is no OnCollectedPickup() callback.</p>
<p>
FIXME: This callback is called even if the pickup doesn't fit into the player's inventory.</p>
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who's collecting the pickup" },
{ Name = "Pickup", Type = "{{cPickup}}", Notes = "The pickup being collected" },
},
Returns = [[
If the function returns false or no value, MCServer calls other plugins' callbacks and finally the
pickup is collected. If the function returns true, no other plugins are called for this event and
the pickup is not collected.
]],
}, -- HOOK_COLLECTING_PICKUP
}

View File

@ -0,0 +1,32 @@
return
{
HOOK_CRAFTING_NO_RECIPE =
{
CalledWhen = " No built-in crafting recipe is found. Plugin may provide a recipe.",
DefaultFnName = "OnCraftingNoRecipe", -- also used as pagename
Desc = [[
This callback is called when a player places items in their {{cCraftingGrid|crafting grid}} and
MCServer cannot find a built-in {{cCraftingRecipe|recipe}} for the combination. Plugins may provide
a recipe for the ingredients given.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player whose crafting is reported in this hook" },
{ Name = "Grid", Type = "{{cCraftingGrid}}", Notes = "Contents of the player's crafting grid" },
{ Name = "Recipe", Type = "{{cCraftingRecipe}}", Notes = "The recipe that will be used (can be filled by plugins)" },
},
Returns = [[
If the function returns false or no value, no recipe will be used. If the function returns true, no
other plugin will have their callback called for this event and MCServer will use the crafting
recipe in Recipe.</p>
<p>
FIXME: To allow plugins give suggestions and overwrite other plugins' suggestions, we should change
the behavior with returning false, so that the recipe will still be used, but fill the recipe with
empty values by default.
]],
}, -- HOOK_CRAFTING_NO_RECIPE
}

View File

@ -0,0 +1,32 @@
return
{
HOOK_DISCONNECT =
{
CalledWhen = "A player has explicitly disconnected.",
DefaultFnName = "OnDisconnect", -- also used as pagename
Desc = [[
This hook is called when a client sends the disconnect packet and is about to be disconnected from
the server.</p>
<p>
Note that this callback is not called if the client drops the connection or is kicked by the
server.</p>
<p>
FIXME: There is no callback for "client destroying" that would be called in all circumstances.</p>
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has disconnected" },
{ Name = "Reason", Type = "string", Notes = "The reason that the client has sent in the disconnect packet" },
},
Returns = [[
If the function returns false or no value, MCServer calls other plugins' callbacks for this event
and finally broadcasts a disconnect message to the player's world. If the function returns true, no
other plugins are called for this event and the disconnect message is not broadcast. In either case,
the player is disconnected.
]],
}, -- HOOK_DISCONNECT
}

View File

@ -0,0 +1,31 @@
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.",
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
players and console commands executed by the server admin. The function is called for every in-game
command sent from any player and for those server console commands that are not built in in the
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.
]],
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" },
},
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.
]],
}, -- HOOK_EXECUTE_COMMAND
}

View File

@ -0,0 +1,49 @@
return
{
HOOK_EXPLODED =
{
CalledWhen = "An explosion has happened",
DefaultFnName = "OnExploded", -- also used as pagename
Desc = [[
This hook is called after an explosion has been processed in a world.</p>
<p>
See also {{OnExploding|HOOK_EXPLODING}} for a similar hook called before the explosion.</p>
<p>
The explosion carries with it the type of its source - whether it's a creeper exploding, or TNT,
etc. It also carries the identification of the actual source. The exact type of the identification
depends on the source kind:
<table>
<tr><th>Source</th><th>SourceData Type</th><th>Notes</th></tr>
<tr><td>esPrimedTNT</td><td>{{cTNTEntity}}</td><td>An exploding primed TNT entity</td></tr>
<tr><td>esCreeper</td><td>{{cCreeper}}</td><td>An exploding creeper or charged creeper</td></tr>
<tr><td>esBed</td><td>{{Vector3i}}</td><td>A bed exploding in the Nether or in the End. The bed coords are given.</td></tr>
<tr><td>esEnderCrystal</td><td>{{Vector3i}}</td><td>An ender crystal exploding upon hit. The block coords are given.</td></tr>
<tr><td>esGhastFireball</td><td>{{cGhastFireballEntity}}</td><td>A ghast fireball hitting ground or an {{cEntity|entity}}.</td></tr>
<tr><td>esWitherSkullBlack</td><td><i>TBD</i></td><td>A black wither skull hitting ground or an {{cEntity|entity}}.</td></tr>
<tr><td>esWitherSkullBlue</td><td><i>TBD</i></td><td>A blue wither skull hitting ground or an {{cEntity|entity}}.</td></tr>
<tr><td>esWitherBirth</td><td><i>TBD</i></td><td>A wither boss being created</td></tr>
<tr><td>esOther</td><td><i>TBD</i></td><td>Any other previously unspecified type.</td></tr>
<tr><td>esPlugin</td><td>object</td><td>An explosion created by a plugin. The plugin may specify any kind of data.</td></tr>
</table></p>
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world where the explosion happened" },
{ Name = "ExplosionSize", Type = "number", Notes = "The relative explosion size" },
{ Name = "CanCauseFire", Type = "bool", Notes = "True if the explosion has turned random air blocks to fire (such as a ghast fireball)" },
{ Name = "X", Type = "number", Notes = "X-coord of the explosion center" },
{ Name = "Y", Type = "number", Notes = "Y-coord of the explosion center" },
{ Name = "Z", Type = "number", Notes = "Z-coord of the explosion center" },
{ Name = "Source", Type = "eExplosionSource", Notes = "Source of the explosion. See the table above." },
{ Name = "SourceData", Type = "varies", Notes = "Additional data for the source. The exact type varies by the source. See the table above." },
},
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. There is no overridable behaviour.
]],
}, -- HOOK_EXPLODED
}

View File

@ -0,0 +1,50 @@
return
{
HOOK_EXPLODING =
{
CalledWhen = "An explosion is about to be processed",
DefaultFnName = "OnExploding", -- also used as pagename
Desc = [[
This hook is called before an explosion has been processed in a world.</p>
<p>
See also {{OnExploded|HOOK_EXPLODED}} for a similar hook called after the explosion.</p>
<p>
The explosion carries with it the type of its source - whether it's a creeper exploding, or TNT,
etc. It also carries the identification of the actual source. The exact type of the identification
depends on the source kind:
<table>
<tr><th>Source</th><th>SourceData Type</th><th>Notes</th></tr>
<tr><td>esPrimedTNT</td><td>{{cTNTEntity}}</td><td>An exploding primed TNT entity</td></tr>
<tr><td>esCreeper</td><td>{{cCreeper}}</td><td>An exploding creeper or charged creeper</td></tr>
<tr><td>esBed</td><td>{{Vector3i}}</td><td>A bed exploding in the Nether or in the End. The bed coords are given.</td></tr>
<tr><td>esEnderCrystal</td><td>{{Vector3i}}</td><td>An ender crystal exploding upon hit. The block coords are given.</td></tr>
<tr><td>esGhastFireball</td><td>{{cGhastFireballEntity}}</td><td>A ghast fireball hitting ground or an {{cEntity|entity}}.</td></tr>
<tr><td>esWitherSkullBlack</td><td><i>TBD</i></td><td>A black wither skull hitting ground or an {{cEntity|entity}}.</td></tr>
<tr><td>esWitherSkullBlue</td><td><i>TBD</i></td><td>A blue wither skull hitting ground or an {{cEntity|entity}}.</td></tr>
<tr><td>esWitherBirth</td><td><i>TBD</i></td><td>A wither boss being created</td></tr>
<tr><td>esOther</td><td><i>TBD</i></td><td>Any other previously unspecified type.</td></tr>
<tr><td>esPlugin</td><td>object</td><td>An explosion created by a plugin. The plugin may specify any kind of data.</td></tr>
</table></p>
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world where the explosion happens" },
{ Name = "ExplosionSize", Type = "number", Notes = "The relative explosion size" },
{ Name = "CanCauseFire", Type = "bool", Notes = "True if the explosion will turn random air blocks to fire (such as a ghast fireball)" },
{ Name = "X", Type = "number", Notes = "X-coord of the explosion center" },
{ Name = "Y", Type = "number", Notes = "Y-coord of the explosion center" },
{ Name = "Z", Type = "number", Notes = "Z-coord of the explosion center" },
{ Name = "Source", Type = "eExplosionSource", Notes = "Source of the explosion. See the table above." },
{ Name = "SourceData", Type = "varies", Notes = "Additional data for the source. The exact type varies by the source. See the table above." },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called, and finally
MCServer will process the explosion - destroy blocks and push + hurt entities. If the function
returns true, no other callback is called for this event and the explosion will not occur.
]],
}, -- HOOK_EXPLODING
}

View File

@ -0,0 +1,29 @@
return
{
HOOK_HANDSHAKE =
{
CalledWhen = "A client is connecting.",
DefaultFnName = "OnHandshake", -- also used as pagename
Desc = [[
This hook is called when a client sends the Handshake packet. At this stage, only the client IP and
(unverified) username are known. Plugins may refuse access to the server based on this
information.</p>
<p>
Note that the username is not authenticated - the authentication takes place only after this hook is
processed.
]],
Params =
{
{ Name = "Client", Type = "{{cClientHandle}}", Notes = "The client handle representing the connection. Note that there's no {{cPlayer}} object for this client yet." },
{ Name = "UserName", Type = "string", Notes = "The username presented in the packet. Note that this username is unverified." },
},
Returns = [[
If the function returns false, the user is let in to the server. If the function returns true, no
other plugin's callback is called, the user is kicked and the connection is closed.
]],
}, -- HOOK_HANDSHAKE
}

View File

@ -0,0 +1,30 @@
return
{
HOOK_HOPPER_PULLING_ITEM =
{
CalledWhen = "A hopper is pulling an item from another block entity.",
DefaultFnName = "OnHopperPullingItem", -- also used as pagename
Desc = [[
This callback is called whenever a {{cHopperEntity|hopper}} transfers an {{cItem|item}} from another
block entity into its own internal storage. A plugin may decide to disallow the move by returning
true. Note that in such a case, the hook may be called again for the same hopper, with different
slot numbers.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "World where the hopper resides" },
{ Name = "Hopper", Type = "{{cHopperEntity}}", Notes = "The hopper that is pulling the item" },
{ Name = "DstSlot", Type = "number", Notes = "The destination slot in the hopper's {{cItemGrid|internal storage}}" },
{ Name = "SrcBlockEntity", Type = "{{cBlockEntityWithItems}}", Notes = "The block entity that is losing the item" },
{ Name = "SrcSlot", Type = "number", Notes = "Slot in SrcBlockEntity from which the item will be pulled" },
},
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 hopper will not pull the item.
]],
}, -- HOOK_HOPPER_PULLING_ITEM
}

View File

@ -0,0 +1,30 @@
return
{
HOOK_HOPPER_PUSHING_ITEM =
{
CalledWhen = "A hopper is pushing an item into another block entity. ",
DefaultFnName = "OnHopperPushingItem", -- also used as pagename
Desc = [[
This hook is called whenever a {{cHopperEntity|hopper}} transfers an {{cItem|item}} from its own
internal storage into another block entity. A plugin may decide to disallow the move by returning
true. Note that in such a case, the hook may be called again for the same hopper and block, with
different slot numbers.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "World where the hopper resides" },
{ Name = "Hopper", Type = "{{cHopperEntity}}", Notes = "The hopper that is pushing the item" },
{ Name = "SrcSlot", Type = "number", Notes = "Slot in the hopper that will lose the item" },
{ Name = "DstBlockEntity", Type = "{{cBlockEntityWithItems}}", Notes = " The block entity that will receive the item" },
{ Name = "DstSlot", Type = "number", Notes = " Slot in DstBlockEntity's internal storage where the item will be stored" },
},
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 hopper will not push the item.
]],
}, -- HOOK_HOPPER_PUSHING_ITEM
}

View File

@ -0,0 +1,33 @@
return
{
HOOK_KILLING =
{
CalledWhen = "A player or a mob is dying.",
DefaultFnName = "OnKilling", -- also used as pagename
Desc = [[
This hook is called whenever a {{cPawn|pawn}}'s (a player's or a mob's) health reaches zero. This
means that the pawn is about to be killed, unless a plugin "revives" them by setting their health
back to a positive value.</p>
<p>
FIXME: There is no HOOK_KILLED notification hook yet; this is deliberate because HOOK_KILLED has
been recently renamed to HOOK_KILLING, and plugins need to be updated. Once updated, the HOOK_KILLED
notification will be implemented.
]],
Params =
{
{ Name = "Victim", Type = "{{cPawn}}", Notes = "The player or mob that is about to be killed" },
{ Name = "Killer", Type = "{{cEntity}}", Notes = "The entity that has caused the victim to lose the last point of health. May be nil for environment damage" },
},
Returns = [[
If the function returns false or no value, MCServer calls other plugins with this event. If the
function returns true, no other plugin is called for this event.</p>
<p>
In either case, the victim's health is then re-checked and if it is greater than zero, the victim is
"revived" with that health amount. If the health is less or equal to zero, the victim is killed.
]],
}, -- HOOK_KILLING
}

View File

@ -0,0 +1,31 @@
return
{
HOOK_LOGIN =
{
CalledWhen = "Right before player authentication. If auth is disabled, right after the player sends their name.",
DefaultFnName = "OnLogin", -- also used as pagename
Desc = [[
This hook is called whenever a client logs in. It is called right before the client's name is sent
to be authenticated. Plugins may refuse the client from accessing the server. Note that when this
callback is called, the {{cPlayer}} object for this client doesn't exist yet - the client has no
representation in any world. To process new players when their world is known, use a later callback,
such as {{OnPlayerJoined|HOOK_PLAYER_JOINED}} or {{OnPlayerSpawned|HOOK_PLAYER_SPAWNED}}.
]],
Params =
{
{ Name = "Client", Type = "{{cClientHandle}}", Notes = "The client handle representing the connection" },
{ Name = "ProtocolVersion", Type = "number", Notes = "Versio of the protocol that the client is talking" },
{ Name = "UserName", Type = "string", Notes = "The name that the client has presented for authentication. This name will be given to the {{cPlayer}} object when it is created for this client." },
},
Returns = [[
If the function returns true, no other plugins are called for this event and the client is kicked.
If the function returns false or no value, MCServer calls other plugins' callbacks and finally
sends an authentication request for the client's username to the auth server. If the auth server
is disabled in the server settings, the player object is immediately created.
]],
}, -- HOOK_LOGIN
}

View File

@ -0,0 +1,28 @@
return
{
HOOK_PLAYER_ANIMATION =
{
CalledWhen = "A client has sent an Animation packet (0x12)",
DefaultFnName = "OnPlayerAnimation", -- also used as pagename
Desc = [[
This hook is called when the server receives an Animation packet (0x12) from the client.</p>
<p>
For the list of animations that are sent by the client, see the
<a href="http://wiki.vg/Protocol#0x12">Protocol wiki</a>.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player from whom the packet was received" },
{ Name = "Animation", Type = "number", Notes = "The kind of animation" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called. Afterwards, the
server broadcasts the animation packet to all nearby clients. If the function returns true, no other
callback is called for this event and the packet is not broadcasted.
]],
}, -- HOOK_PLAYER_ANIMATION
}

View File

@ -0,0 +1,36 @@
return
{
HOOK_PLAYER_BREAKING_BLOCK =
{
CalledWhen = "Just before a player breaks a block. Plugin may override / refuse. ",
DefaultFnName = "OnPlayerBreakingBlock", -- also used as pagename
Desc = [[
This hook is called when a {{cPlayer|player}} breaks a block, before the block is actually broken in
the {{cWorld|World}}. Plugins may refuse the breaking.</p>
<p>
See also the {{OnPlayerBrokenBlock|HOOK_PLAYER_BROKEN_BLOCK}} hook for a similar hook called after
the block is broken.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is digging the block" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player is acting. One of the BLOCK_FACE_ constants" },
{ Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block being broken" },
{ Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block being broken " },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called, and then the block
is broken. If the function returns true, no other plugin's callback is called and the block breaking
is cancelled. The server re-sends the block back to the player to replace it (the player's client
already thinks the block was broken).
]],
}, -- HOOK_PLAYER_BREAKING_BLOCK
}

View File

@ -0,0 +1,36 @@
return
{
HOOK_PLAYER_BROKEN_BLOCK =
{
CalledWhen = "After a player has broken a block. Notification only.",
DefaultFnName = "OnPlayerBrokenBlock", -- also used as pagename
Desc = [[
This function is called after a {{cPlayer|player}} breaks a block. The block is already removed
from the {{cWorld|world}} and {{cPickup|pickups}} have been spawned. To get the world in which the
block has been dug, use the {{cPlayer}}:GetWorld() function.</p>
<p>
See also the {{OnPlayerBreakingBlock|HOOK_PLAYER_BREAKING_BLOCK}} hook for a similar hook called
before the block is broken. To intercept the creation of pickups, see the
{{OnBlockToPickups|HOOK_BLOCK_TO_PICKUPS}} hook.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who broke the block" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player interacted. One of the BLOCK_FACE_ constants" },
{ Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block" },
{ Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block" },
},
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_PLAYER_BROKEN_BLOCK
}

View File

@ -0,0 +1,27 @@
return
{
HOOK_PLAYER_EATING =
{
CalledWhen = "When the player starts eating",
DefaultFnName = "OnPlayerEating", -- also used as pagename
Desc = [[
This hook gets called when the {{cPlayer|player}} starts eating, after the server checks that the
player can indeed eat (is not satiated and is holding food). Plugins may still refuse the eating by
returning true.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who started eating" },
},
Returns = [[
If the function returns false or no value, the server calls the next plugin handler, and finally
lets the player eat. If the function returns true, the server doesn't call any more callbacks for
this event and aborts the eating. A "disallow" packet is sent to the client.
]],
}, -- HOOK_PLAYER_EATING
}

View File

@ -0,0 +1,29 @@
return
{
HOOK_PLAYER_JOINED =
{
CalledWhen = "After Login and before Spawned, before being added to world. ",
DefaultFnName = "OnPlayerJoined", -- also used as pagename
Desc = [[
This hook is called whenever a {{cPlayer|player}} has completely logged in. If authentication is
enabled, this function is called after their name has been authenticated. It is called after
{{OnLogin|HOOK_LOGIN}} and before {{OnPlayerSpawned|HOOK_PLAYER_SPAWNED}}, right after the player's
entity is created, but not added to the world yet. The player is not yet visible to other players.
This is a notification-only event, plugins wishing to refuse player's entry should kick the player
using the {{cPlayer}}:Kick() function.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has joined the game" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called. If the function
returns true, no other callbacks are called for this event. Either way the player is let in.
]],
}, -- HOOK_PLAYER_JOINED
}

View File

@ -0,0 +1,47 @@
return
{
HOOK_PLAYER_LEFT_CLICK =
{
CalledWhen = "A left-click packet is received from the client. Plugin may override / refuse.",
DefaultFnName = "OnPlayerLeftClick", -- also used as pagename
Desc = [[
This hook is called when MCServer receives a left-click packet from the {{cClientHandle|client}}. It
is called before any processing whatsoever is performed on the packet, meaning that hacked /
malicious clients may be trigerring this event very often and with unchecked parameters. Therefore
plugin authors are advised to use extreme caution with this callback.</p>
<p>
Plugins may refuse the default processing for the packet, causing MCServer to behave as if the
packet has never arrived. This may, however, create inconsistencies in the client - the client may
think that they broke a block, while the server didn't process the breaking, etc. For this reason,
if a plugin refuses the processing, MCServer sends the block specified in the packet back to the
client (as if placed anew), if the status code specified a block-break action. For other actions,
plugins must rectify the situation on their own.</p>
<p>
The client sends the left-click packet for several other occasions, such as dropping the held item
(Q keypress) or shooting an arrow. This is reflected in the Status code. Consult the
<a href="http://wiki.vg/Protocol#0x0E">protocol documentation</a> for details on the actions.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player whose client sent the packet" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player interacted. One of the BLOCK_FACE_ constants" },
{ Name = "Action", Type = "number", Notes = "Action to be performed on the block (\"status\" in the protocol docs)" },
},
Returns = [[
If the function returns false or no value, MCServer calls other plugins' callbacks and finally sends
the packet for further processing.</p>
<p>
If the function returns true, no other plugins are called, processing is halted. If the action was a
block dig, MCServer sends the block specified in the coords back to the client. The packet is
dropped.
]],
}, -- HOOK_PLAYER_LEFT_CLICK
}

View File

@ -0,0 +1,27 @@
return
{
HOOK_PLAYER_MOVING =
{
CalledWhen = "Player tried to move in the tick being currently processed. Plugin may refuse movement.",
DefaultFnName = "OnPlayerMoving", -- also used as pagename
Desc = [[
This function is called in each server tick for each {{cPlayer|player}} that has sent any of the
player-move packets. Plugins may refuse the movement.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has moved. The object already has the new position stored in it." },
},
Returns = [[
If the function returns true, movement is prohibited. FIXME: The player's client is not informed.</p>
<p>
If the function returns false or no value, other plugins' callbacks are called and finally the new
position is permanently stored in the cPlayer object.</p>
]],
}, -- HOOK_PLAYER_MOVING
}

View File

@ -0,0 +1,40 @@
return
{
HOOK_PLAYER_PLACED_BLOCK =
{
CalledWhen = "After a player has placed a block. Notification only.",
DefaultFnName = "OnPlayerPlacedBlock", -- also used as pagename
Desc = [[
This hook is called after a {{cPlayer|player}} has placed a block in the {{cWorld|world}}. The block
is already added to the world and the corresponding item removed from player's
{{cInventory|inventory}}.</p>
<p>
Use the {{cPlayer}}:GetWorld() function to get the world to which the block belongs.</p>
<p>
See also the {{OnPlayerPlacingBlock|HOOK_PLAYER_PLACING_BLOCK}} hook for a similar hook called
before the placement.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who placed the block" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of the existing block upon which the player interacted. One of the BLOCK_FACE_ constants" },
{ Name = "CursorX", Type = "number", Notes = "X-coord of the cursor within the block face (0 .. 15)" },
{ Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor within the block face (0 .. 15)" },
{ Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor within the block face (0 .. 15)" },
{ Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block" },
{ Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block" },
},
Returns = [[
If this function returns false or no value, MCServer calls other plugins with the same event. If
this function returns true, no other plugin is called for this event.
]],
}, -- HOOK_PLAYER_PLACED_BLOCK
}

View File

@ -0,0 +1,45 @@
return
{
HOOK_PLAYER_PLACING_BLOCK =
{
CalledWhen = "Just before a player places a block. Plugin may override / refuse.",
DefaultFnName = "OnPlayerPlacingBlock", -- also used as pagename
Desc = [[
This hook is called just before a {{cPlayer|player}} places a block in the {{cWorld|world}}. The
block is not yet placed, plugins may choose to override the default behavior or refuse the placement
at all.</p>
<p>
Note that the client already expects that the block has been placed. For that reason, if a plugin
refuses the placement, MCServer sends the old block at the provided coords to the client.</p>
<p>
Use the {{cPlayer}}:GetWorld() function to get the world to which the block belongs.</p>
<p>
See also the {{OnPlayerPlacedBlock|HOOK_PLAYER_PLACED_BLOCK}} hook for a similar hook called after
the placement.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is placing the block" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of the existing block upon which the player is interacting. One of the BLOCK_FACE_ constants" },
{ Name = "CursorX", Type = "number", Notes = "X-coord of the cursor within the block face (0 .. 15)" },
{ Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor within the block face (0 .. 15)" },
{ Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor within the block face (0 .. 15)" },
{ Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block" },
{ Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block" },
},
Returns = [[
If this function returns false or no value, MCServer calls other plugins with the same event and
finally places the block and removes the corresponding item from player's inventory. If this
function returns true, no other plugin is called for this event, MCServer sends the old block at
the specified coords to the client and drops the packet.
]],
}, -- HOOK_PLAYER_PLACING_BLOCK
}

View File

@ -0,0 +1,37 @@
return
{
HOOK_PLAYER_RIGHT_CLICK =
{
CalledWhen = "A right-click packet is received from the client. Plugin may override / refuse.",
DefaultFnName = "OnPlayerRightClick", -- also used as pagename
Desc = [[
This hook is called when MCServer receives a right-click packet from the {{cClientHandle|client}}. It
is called before any processing whatsoever is performed on the packet, meaning that hacked /
malicious clients may be trigerring this event very often and with unchecked parameters. Therefore
plugin authors are advised to use extreme caution with this callback.</p>
<p>
Plugins may refuse the default processing for the packet, causing MCServer to behave as if the
packet has never arrived. This may, however, create inconsistencies in the client - the client may
think that they placed a block, while the server didn't process the placing, etc.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player whose client sent the packet" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of the block upon which the player interacted. One of the BLOCK_FACE_ constants" },
},
Returns = [[
If the function returns false or no value, MCServer calls other plugins' callbacks and finally sends
the packet for further processing.</p>
<p>
If the function returns true, no other plugins are called, processing is halted.
]],
}, -- HOOK_PLAYER_RIGHT_CLICK
}

View File

@ -0,0 +1,27 @@
return
{
HOOK_PLAYER_RIGHT_CLICKING_ENTITY =
{
CalledWhen = "A player has right-clicked an entity. Plugins may override / refuse.",
DefaultFnName = "OnPlayerRightClickingEntity", -- also used as pagename
Desc = [[
This hook is called when the {{cPlayer|player}} right-clicks an {{cEntity|entity}}. Plugins may
override the default behavior or even cancel the default processing.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has right-clicked the entity" },
{ Name = "Entity", Type = "{{cEntity}} descendant", Notes = "The entity that has been right-clicked" },
},
Returns = [[
If the functino returns false or no value, MCServer calls other plugins' callbacks and finally does
the default processing for the right-click. If the function returns true, no other callbacks are
called and the default processing is skipped.
]],
}, -- HOOK_PLAYER_RIGHT_CLICKING_ENTITY
}

View File

@ -0,0 +1,32 @@
return
{
HOOK_PLAYER_SHOOTING =
{
CalledWhen = "When the player releases the bow, shooting an arrow (other projectiles: unknown)",
DefaultFnName = "OnPlayerShooting", -- also used as pagename
Desc = [[
This hook is called when the {{cPlayer|player}} shoots their bow. It is called for the actual
release of the {{cArrowEntity|arrow}}. FIXME: It is currently unknown whether other
{{cProjectileEntity|projectiles}} (snowballs, eggs) trigger this hook.</p>
<p>
To get the player's position and direction, use the {{cPlayer}}:GetEyePosition() and
cPlayer:GetLookVector() functions. Note that for shooting a bow, the position for the arrow creation
is not at the eye pos, some adjustments are required. FIXME: Export the {{cPlayer}} function for
this adjustment.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player shooting" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called, and finally
MCServer creates the projectile. If the functino returns true, no other callback is called and no
projectile is created.
]],
}, -- HOOK_PLAYER_SHOOTING
}

View File

@ -0,0 +1,32 @@
return
{
HOOK_PLAYER_SPAWNED =
{
CalledWhen = "After a player (re)spawns in the world to which they belong to.",
DefaultFnName = "OnPlayerSpawned", -- also used as pagename
Desc = [[
This hook is called after a {{cPlayer|player}} has spawned in the world. It is called after
{{OnLogin|HOOK_LOGIN}} and {{OnPlayerJoined|HOOK_PLAYER_JOINED}}, after the player name has been
authenticated, the initial worldtime, inventory and health have been sent to the player and the
player spawn packet has been broadcast to all players near enough to the player spawn place. This is
a notification-only event, plugins wishing to refuse player's entry should kick the player using the
{{cPlayer}}:Kick() function.</p>
<p>
This hook is also called when the player respawns after death (and a respawn packet is received from
the client, meaning the player has already clicked the Respawn button).
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has (re)spawned" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called. If the function
returns true, no other callbacks are called for this event. There is no overridable behavior.
]],
}, -- HOOK_PLAYER_SPAWNED
}

View File

@ -0,0 +1,30 @@
return
{
HOOK_PLAYER_TOSSING_ITEM =
{
CalledWhen = "A player is tossing an item. Plugin may override / refuse.",
DefaultFnName = "OnPlayerTossingItem", -- also used as pagename
Desc = [[
This hook is called when a {{cPlayer|player}} has tossed an item (Q keypress). The
{{cPickup|pickup}} has not been spawned yet. Plugins may disallow the tossing, but in that case they
need to clean up - the player's client already thinks the item has been tossed so the
{{cInventory|inventory}} needs to be re-sent to the player.</p>
<p>
To get the item that is about to be tossed, call the {{cPlayer}}:GetEquippedItem() function.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player tossing an item" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called and finally MCServer
creates the pickup for the item and tosses it, using {{cPlayer}}:TossItem. If the function returns
true, no other callbacks are called for this event and MCServer doesn't toss the item.
]],
}, -- HOOK_PLAYER_TOSSING_ITEM
}

View File

@ -0,0 +1,46 @@
return
{
HOOK_PLAYER_USED_BLOCK =
{
CalledWhen = "A player has just used a block (chest, furnace…). Notification only.",
DefaultFnName = "OnPlayerUsedBlock", -- also used as pagename
Desc = [[
This hook is called after a {{cPlayer|player}} has right-clicked a block that can be used, such as a
{{cChestEntity|chest}} or a lever. It is called after MCServer processes the usage (sends the UI
handling packets / toggles redstone). Note that for UI-related blocks, the player is most likely
still using the UI. This is a notification-only event.</p>
<p>
Note that the block coords given in this callback are for the (solid) block that is being clicked,
not the air block between it and the player.</p>
<p>
To get the world at which the right-click occurred, use the {{cPlayer}}:GetWorld() function.</p>
<p>
See also the {{OnPlayerUsingBlock|HOOK_PLAYER_USING_BLOCK}} for a similar hook called before the
use, the {{OnPlayerUsingItem|HOOK_PLAYER_USING_ITEM}} and {{OnPlayerUsedItem|HOOK_PLAYER_USED_ITEM}}
for similar hooks called when a player interacts with any block with a usable item in hand, such as
a bucket.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who used the block" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the clicked block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the clicked block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the clicked block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of clicked block which has been clicked. One of the BLOCK_FACE_ constants" },
{ Name = "CursorX", Type = "number", Notes = "X-coord of the cursor crosshair on the block being clicked" },
{ Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor crosshair on the block being clicked" },
{ Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor crosshair on the block being clicked" },
{ Name = "BlockType", Type = "number", Notes = "Block type of the clicked block" },
{ Name = "BlockMeta", Type = "number", Notes = "Block meta of the clicked block" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called. If the function
returns true, no other callbacks are called for this event.
]],
}, -- HOOK_PLAYER_USED_BLOCK
}

View File

@ -0,0 +1,46 @@
return
{
HOOK_PLAYER_USED_ITEM =
{
CalledWhen = "A player has used an item in hand (bucket...)",
DefaultFnName = "OnPlayerUsedItem", -- also used as pagename
Desc = [[
This hook is called after a {{cPlayer|player}} has right-clicked a block with an {{cItem|item}} that
can be used (is not placeable, is not food and clicked block is not use-able), such as a bucket or a
hoe. It is called after MCServer processes the usage (places fluid / turns dirt to farmland).
This is an information-only hook, there is no way to cancel the event anymore.</p>
<p>
Note that the block coords given in this callback are for the (solid) block that is being clicked,
not the air block between it and the player.</p>
<p>
To get the world at which the right-click occurred, use the {{cPlayer}}:GetWorld() function. To get
the item that the player is using, use the {{cPlayer}}:GetEquippedItem() function.</p>
<p>
See also the {{OnPlayerUsingItem|HOOK_PLAYER_USING_ITEM}} for a similar hook called before the use,
the {{OnPlayerUsingBlock|HOOK_PLAYER_USING_BLOCK}} and {{OnPlayerUsedBlock|HOOK_PLAYER_USED_BLOCK}}
for similar hooks called when a player interacts with a block, such as a chest.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who used the item" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the clicked block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the clicked block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the clicked block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of clicked block which has been clicked. One of the BLOCK_FACE_ constants" },
{ Name = "CursorX", Type = "number", Notes = "X-coord of the cursor crosshair on the block being clicked" },
{ Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor crosshair on the block being clicked" },
{ Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor crosshair on the block being clicked" },
{ Name = "BlockType", Type = "number", Notes = "Block type of the clicked block" },
{ Name = "BlockMeta", Type = "number", Notes = "Block meta of the clicked block" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called. If the function
returns true, no other callbacks are called for this event.
]],
}, -- HOOK_PLAYER_USED_ITEM
}

View File

@ -0,0 +1,46 @@
return
{
HOOK_PLAYER_USING_BLOCK =
{
CalledWhen = "Just before a player uses a block (chest, furnace...). Plugin may override / refuse.",
DefaultFnName = "OnPlayerUsingBlock", -- also used as pagename
Desc = [[
This hook is called when a {{cPlayer|player}} has right-clicked a block that can be used, such as a
{{cChestEntity|chest}} or a lever. It is called before MCServer processes the usage (sends the UI
handling packets / toggles redstone). Plugins may refuse the interaction by returning true.</p>
<p>
Note that the block coords given in this callback are for the (solid) block that is being clicked,
not the air block between it and the player.</p>
<p>
To get the world at which the right-click occurred, use the {{cPlayer}}:GetWorld() function.</p>
<p>
See also the {{OnPlayerUsedBlock|HOOK_PLAYER_USED_BLOCK}} for a similar hook called after the use, the
{{OnPlayerUsingItem|HOOK_PLAYER_USING_ITEM}} and {{OnPlayerUsedItem|HOOK_PLAYER_USED_ITEM}} for
similar hooks called when a player interacts with any block with a usable item in hand, such as a
bucket.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is using the block" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the clicked block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the clicked block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the clicked block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of clicked block which has been clicked. One of the BLOCK_FACE_ constants" },
{ Name = "CursorX", Type = "number", Notes = "X-coord of the cursor crosshair on the block being clicked" },
{ Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor crosshair on the block being clicked" },
{ Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor crosshair on the block being clicked" },
{ Name = "BlockType", Type = "number", Notes = "Block type of the clicked block" },
{ Name = "BlockMeta", Type = "number", Notes = "Block meta of the clicked block" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called and then MCServer
processes the interaction. If the function returns true, no other callbacks are called for this
event and the interaction is silently dropped.
]],
}, -- HOOK_PLAYER_USING_BLOCK
}

View File

@ -0,0 +1,47 @@
return
{
HOOK_PLAYER_USING_ITEM =
{
CalledWhen = "Just before a player uses an item in hand (bucket...). Plugin may override / refuse.",
DefaultFnName = "OnPlayerUsingItem", -- also used as pagename
Desc = [[
This hook is called when a {{cPlayer|player}} has right-clicked a block with an {{cItem|item}} that
can be used (is not placeable, is not food and clicked block is not use-able), such as a bucket or a
hoe. It is called before MCServer processes the usage (places fluid / turns dirt to farmland).
Plugins may refuse the interaction by returning true.</p>
<p>
Note that the block coords given in this callback are for the (solid) block that is being clicked,
not the air block between it and the player.</p>
<p>
To get the world at which the right-click occurred, use the {{cPlayer}}:GetWorld() function. To get
the item that the player is using, use the {{cPlayer}}:GetEquippedItem() function.</p>
<p>
See also the {{OnPlayerUsedItem|HOOK_PLAYER_USED_ITEM}} for a similar hook called after the use, the
{{OnPlayerUsingBlock|HOOK_PLAYER_USING_BLOCK}} and {{OnPlayerUsedBlock|HOOK_PLAYER_USED_BLOCK}} for
similar hooks called when a player interacts with a block, such as a chest.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is using the item" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the clicked block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the clicked block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the clicked block" },
{ Name = "BlockFace", Type = "number", Notes = "Face of clicked block which has been clicked. One of the BLOCK_FACE_ constants" },
{ Name = "CursorX", Type = "number", Notes = "X-coord of the cursor crosshair on the block being clicked" },
{ Name = "CursorY", Type = "number", Notes = "Y-coord of the cursor crosshair on the block being clicked" },
{ Name = "CursorZ", Type = "number", Notes = "Z-coord of the cursor crosshair on the block being clicked" },
{ Name = "BlockType", Type = "number", Notes = "Block type of the clicked block" },
{ Name = "BlockMeta", Type = "number", Notes = "Block meta of the clicked block" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called and then MCServer
processes the interaction. If the function returns true, no other callbacks are called for this
event and the interaction is silently dropped.
]],
}, -- HOOK_PLAYER_USING_ITEM
}

View File

@ -0,0 +1,36 @@
return
{
HOOK_POST_CRAFTING =
{
CalledWhen = "After the built-in recipes are checked and a recipe was found.",
DefaultFnName = "OnPostCrafting", -- also used as pagename
Desc = [[
This hook is called when a {{cPlayer|player}} changes contents of their
{{cCraftingGrid|crafting grid}}, after the recipe has been established by MCServer. Plugins may use
this to modify the resulting recipe or provide an alternate recipe.</p>
<p>
If a plugin implements custom recipes, it should do so using the {{OnPreCrafting|HOOK_PRE_CRAFTING}}
hook, because that will save the server from going through the built-in recipes. The
HOOK_POST_CRAFTING hook is intended as a notification, with a chance to tweak the result.</p>
<p>
Note that this hook is not called if a built-in recipe is not found;
{{OnCraftingNoRecipe|HOOK_CRAFTING_NO_RECIPE}} is called instead in such a case.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has changed their crafting grid contents" },
{ Name = "Grid", Type = "{{cCraftingGrid}}", Notes = "The new crafting grid contents" },
{ Name = "Recipe", Type = "{{cCraftingRecipe}}", Notes = "The recipe that MCServer has decided to use (can be tweaked by plugins)" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called. If the function
returns true, no other callbacks are called for this event. In either case, MCServer uses the value
of Recipe as the recipe to be presented to the player.
]],
}, -- HOOK_POST_CRAFTING
}

View File

@ -0,0 +1,37 @@
return
{
HOOK_PRE_CRAFTING =
{
CalledWhen = "Before the built-in recipes are checked.",
DefaultFnName = "OnPreCrafting", -- also used as pagename
Desc = [[
This hook is called when a {{cPlayer|player}} changes contents of their
{{cCraftingGrid|crafting grid}}, before the built-in recipes are searched for a match by MCServer.
Plugins may use this hook to provide a custom recipe.</p>
<p>
If you intend to tweak built-in recipes, use the {{OnPostCrafting|HOOK_POST_CRAFTING}} hook, because
that will be called once the built-in recipe is matched.</p>
<p>
Also note a third hook, {{OnCraftingNoRecipe|HOOK_CRAFTING_NO_RECIPE}}, that is called when MCServer
cannot find any built-in recipe for the given ingredients.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who has changed their crafting grid contents" },
{ Name = "Grid", Type = "{{cCraftingGrid}}", Notes = "The new crafting grid contents" },
{ Name = "Recipe", Type = "{{cCraftingRecipe}}", Notes = "The recipe that MCServer will use. Modify this object to change the recipe" },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called and then MCServer
searches the built-in recipes. The Recipe output parameter is ignored in this case.</p>
<p>
If the function returns true, no other callbacks are called for this event and MCServer uses the
recipe stored in the Recipe output parameter.
]],
}, -- HOOK_PRE_CRAFTING
}

View File

@ -0,0 +1,31 @@
return
{
HOOK_SPAWNED_ENTITY =
{
CalledWhen = "After an entity is spawned in the world.",
DefaultFnName = "OnSpawnedEntity", -- also used as pagename
Desc = [[
This hook is called after the server spawns an {{cEntity|entity}}. This is an information-only
callback, the entity is already spawned by the time it is called. If the entity spawned is a
{{cMonster|monster}}, the {{OnSpawnedMonster|HOOK_SPAWNED_MONSTER}} hook is called before this
hook.</p>
<p>
See also the {{OnSpawningEntity|HOOK_SPAWNING_ENTITY}} hook for a similar hook called before the
entity is spawned.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world in which the entity has spawned" },
{ Name = "Entity", Type = "{{cEntity}} descentant", Notes = "The entity that has spawned" },
},
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_SPAWNED_ENTITY
}

View File

@ -0,0 +1,30 @@
return
{
HOOK_SPAWNED_MONSTER =
{
CalledWhen = "After a monster is spawned in the world",
DefaultFnName = "OnSpawnedMonster", -- also used as pagename
Desc = [[
This hook is called after the server spawns a {{cMonster|monster}}. This is an information-only
callback, the monster is already spawned by the time it is called. After this hook is called, the
{{OnSpawnedEntity|HOOK_SPAWNED_ENTITY}} is called for the monster entity.</p>
<p>
See also the {{OnSpawningMonster|HOOK_SPAWNING_MONSTER}} hook for a similar hook called before the
monster is spawned.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world in which the monster has spawned" },
{ Name = "Monster", Type = "{{cMonster}} descendant", Notes = "The monster that has spawned" },
},
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_SPAWNED_MONSTER
}

View File

@ -0,0 +1,32 @@
return
{
HOOK_SPAWNING_ENTITY =
{
CalledWhen = "Before an entity is spawned in the world.",
DefaultFnName = "OnSpawningEntity", -- also used as pagename
Desc = [[
This hook is called before the server spawns an {{cEntity|entity}}. The plugin can either modify the
entity before it is spawned, or disable the spawning altogether. If the entity spawning is a
monster, the {{OnSpawningMonster|HOOK_SPAWNING_MONSTER}} hook is called before this hook.</p>
<p>
See also the {{OnSpawnedEntity|HOOK_SPAWNED_ENTITY}} hook for a similar hook called after the
entity is spawned.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world in which the entity will spawn" },
{ Name = "Entity", Type = "{{cEntity}} descentant", Notes = "The entity that will spawn" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called. Finally, the server
spawns the entity with whatever parameters have been set on the {{cEntity}} object by the callbacks.
If the function returns true, no other callback is called for this event and the entity is not
spawned.
]],
}, -- HOOK_SPAWNING_ENTITY
}

View File

@ -0,0 +1,33 @@
return
{
HOOK_SPAWNING_MONSTER =
{
CalledWhen = "Before a monster is spawned in the world.",
DefaultFnName = "OnSpawningMonster", -- also used as pagename
Desc = [[
This hook is called before the server spawns a {{cMonster|monster}}. The plugins may modify the
monster's parameters in the {{cMonster}} class, or disallow the spawning altogether. This hook is
called before the {{OnSpawningEntity|HOOK_SPAWNING_ENTITY}} is called for the monster entity.</p>
<p>
See also the {{OnSpawnedMonster|HOOK_SPAWNED_MONSTER}} hook for a similar hook called after the
monster is spawned.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world in which the entity will spawn" },
{ Name = "Monster", Type = "{{cMonster}} descentant", Notes = "The monster that will spawn" },
},
Returns = [[
If the function returns false or no value, the next plugin's callback is called. Finally, the server
spawns the monster with whatever parameters the plugins set in the cMonster parameter.</p>
<p>
If the function returns true, no other callback is called for this event and the monster won't
spawn.
]],
}, -- HOOK_SPAWNING_MONSTER
}

View File

@ -0,0 +1,31 @@
return
{
HOOK_TAKE_DAMAGE =
{
CalledWhen = "An {{cEntity|entity}} is taking any kind of damage",
DefaultFnName = "OnTakeDamage", -- also used as pagename
Desc = [[
This hook is called when any {{cEntity}} descendant, such as a {{cPlayer|player}} or a
{{cMonster|mob}}, takes any kind of damage. The plugins may modify the amount of damage or effects
with this hook by editting the {{TakeDamageInfo}} object passed.</p>
<p>
This hook is called after the final damage is calculated, including all the possible weapon
{{cEnchantments|enchantments}}, armor protection and potion effects.
]],
Params =
{
{ Name = "Receiver", Type = "{{cEntity}} descendant", Notes = "The entity taking damage" },
{ Name = "TDI", Type = "{{TakeDamageInfo}}", Notes = "The damage type, cause and effects. Plugins may modify this object to alter the final damage applied." },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called and then the server
applies the final values from the TDI object to Receiver. If the function returns true, no other
callbacks are called, and no damage nor effects are applied.
]],
}, -- HOOK_TAKE_DAMAGE
}

View File

@ -0,0 +1,29 @@
return
{
HOOK_TICK =
{
CalledWhen = "Every server tick (approximately 20 times per second)",
DefaultFnName = "OnTick", -- also used as pagename
Desc = [[
This hook is called every game tick (50 msec, or 20 times a second). If the server is overloaded,
the interval is larger, which is indicated by the TimeDelta parameter.</p>
<p>
This hook is called in the context of the server-tick thread, that is, the thread that takes care of
{{cClientHandle|client connections}} before they're assigned to {{cPlayer|player entities}}, and
processing console commands.
]],
Params =
{
{ Name = "TimeDelta", Type = "number", Notes = "The number of milliseconds elapsed since the last server tick. Will not be less than 50 msec." },
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called. If the function
returns true, no other callbacks are called. There is no overridable behavior.
]],
}, -- HOOK_TICK
}

View File

@ -0,0 +1,38 @@
return
{
HOOK_UPDATED_SIGN =
{
CalledWhen = "After the sign text is updated. Notification only.",
DefaultFnName = "OnUpdatedSign", -- also used as pagename
Desc = [[
This hook is called after a sign has had its text updated. The text is already updated at this
point.</p>
<p>The update may have been caused either by a {{cPlayer|player}} directly updating the sign, or by
a plugin changing the sign text using the API.</p>
<p>
See also the {{OnUpdatingSign|HOOK_UPDATING_SIGN}} hook for a similar hook called before the update,
with a chance to modify the text.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world in which the sign resides" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the sign" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the sign" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the sign" },
{ Name = "Line1", Type = "string", Notes = "1st line of the new text" },
{ Name = "Line2", Type = "string", Notes = "2nd line of the new text" },
{ Name = "Line3", Type = "string", Notes = "3rd line of the new text" },
{ Name = "Line4", Type = "string", Notes = "4th line of the new text" },
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is changing the text. May be nil for non-player updates." }
},
Returns = [[
If the function returns false or no value, other plugins' callbacks are called. If the function
returns true, no other callbacks are called. There is no overridable behavior.
]],
}, -- HOOK_UPDATED_SIGN
}

View File

@ -0,0 +1,58 @@
return
{
HOOK_UPDATING_SIGN =
{
CalledWhen = "Before the sign text is updated. Plugin may modify the text / refuse.",
DefaultFnName = "OnUpdatingSign", -- also used as pagename
Desc = [[
This hook is called when a sign text is about to be updated, either as a result of player's
manipulation or any other event, such as a plugin setting the sign text. Plugins may modify the text
or refuse the update altogether.</p>
<p>
See also the {{OnUpdatedSign|HOOK_UPDATED_SIGN}} hook for a similar hook called after the update.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "The world in which the sign resides" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the sign" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the sign" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the sign" },
{ Name = "Line1", Type = "string", Notes = "1st line of the new text" },
{ Name = "Line2", Type = "string", Notes = "2nd line of the new text" },
{ Name = "Line3", Type = "string", Notes = "3rd line of the new text" },
{ Name = "Line4", Type = "string", Notes = "4th line of the new text" },
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is changing the text. May be nil for non-player updates." }
},
Returns = [[
The function may return up to five values. If the function returns true as the first value, no other
callbacks are called for this event and the sign is not updated. If the function returns no value or
false as its first value, other plugins' callbacks are called.</p>
<p>
The other up to four values returned are used to update the sign text, line by line, respectively.
Note that other plugins may again update the texts (if the first value returned is false).
]],
CodeExamples =
{
{
Title = "Add player signature",
Desc = "The following example appends a player signature to the last line, if the sign is updated by a player:",
Code = [[
function OnUpdatingSign(World, BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4, Player)
if (Player == nil) then
-- Not changed by a player
return false;
end
-- Sign with playername, allow other plugins to interfere:
return false, Line1, Line2, Line3, Line4 .. Player:GetName();
end
]],
}
} ,
}, -- HOOK_UPDATING_SIGN
}

View File

@ -0,0 +1,28 @@
return
{
HOOK_WEATHER_CHANGED =
{
CalledWhen = "The weather has changed",
DefaultFnName = "OnWeatherChanged", -- also used as pagename
Desc = [[
This hook is called after the weather has changed in a {{cWorld|world}}. The new weather has already
been sent to the clients.</p>
<p>
See also the {{OnWeatherChanging|HOOK_WEATHER_CHANGING}} hook for a similar hook called before the
change.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "World for which the weather has changed" },
},
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. There is no overridable behavior.
]],
}, -- HOOK_WEATHER_CHANGED
}

View File

@ -0,0 +1,32 @@
return
{
HOOK_WEATHER_CHANGING =
{
CalledWhen = "The weather is about to change",
DefaultFnName = "OnWeatherChanging", -- also used as pagename
Desc = [[
This hook is called when the current weather has expired and a new weather is selected. Plugins may
override the new weather setting.</p>
<p>
The new weather setting is sent to the clients only after this hook has been processed.</p>
<p>
See also the {{OnWeatherChanged|HOOK_WEATHER_CHANGED}} hook for a similar hook called after the
change.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "World for which the weather is changing" },
{ Name = "Weather", Type = "number", Notes = "The newly selected weather. One of wSunny, wRain, wStorm" },
},
Returns = [[
If the function returns false or no value, the server calls other plugins' callbacks and finally
sets the weather. If the function returns true, the server takes the second returned value (wSunny
by default) and sets it as the new weather. No other plugins' callbacks are called in this case.
]],
}, -- HOOK_WEATHER_CHANGING
}

View File

@ -0,0 +1,29 @@
return
{
HOOK_WORLD_TICK =
{
CalledWhen = "Every world tick (about 20 times per second), separately for each world",
DefaultFnName = "OnWorldTick", -- also used as pagename
Desc = [[
This hook is called for each {{cWorld|world}} every tick (50 msec, or 20 times a second). If the
world is overloaded, the interval is larger, which is indicated by the TimeDelta parameter.</p>
<p>
This hook is called in the world's tick thread context and thus has access to all world data
guaranteed without blocking.
]],
Params =
{
{ Name = "World", Type = "{{cWorld}}", Notes = "World that is ticking" },
{ Name = "TimeDelta", Type = "number", Notes = "The number of milliseconds since the previous game tick. Will not be less than 50 msec" },
},
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. There is no overridable behavior.
]],
}, -- HOOK_WORLD_TICK
}

View File

@ -38,9 +38,19 @@ function Initialize(Plugin)
Plugin:SetName("APIDump");
Plugin:SetVersion(1);
LOG("Initialised " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
LOG("Initialising " .. Plugin:GetName() .. " v." .. Plugin:GetVersion())
g_PluginFolder = Plugin:GetLocalFolder();
-- Load the API descriptions from the Classes and Hooks subfolders:
if (g_APIDesc.Classes == nil) then
g_APIDesc.Classes = {};
end
if (g_APIDesc.Hooks == nil) then
g_APIDesc.Hooks = {};
end
LoadAPIFiles("/Classes/", g_APIDesc.Classes);
LoadAPIFiles("/Hooks/", g_APIDesc.Hooks);
-- dump all available API functions and objects:
-- DumpAPITxt();
@ -48,6 +58,8 @@ function Initialize(Plugin)
-- Dump all available API object in HTML format into a subfolder:
DumpAPIHtml();
LOG("APIDump finished");
return true
end
@ -55,6 +67,29 @@ end
function LoadAPIFiles(a_Folder, a_DstTable)
local Folder = g_PluginFolder .. a_Folder;
for idx, fnam in ipairs(cFile:GetFolderContents(Folder)) do
local FileName = Folder .. fnam;
-- We only want .lua files from the folder:
if (cFile:IsFile(FileName) and fnam:match(".*%.lua$")) then
local TablesFn, Err = loadfile(FileName);
if (TablesFn == nil) then
LOGWARNING("Cannot load API descriptions from " .. FileName .. ", Lua error '" .. Err .. "'.");
else
local Tables = TablesFn();
for k, cls in pairs(Tables) do
a_DstTable[k] = cls;
end
end -- if (TablesFn)
end -- if (is lua file)
end -- for fnam - Folder[]
end
function DumpAPITxt()
LOG("Dumping all available functions to API.txt...");
function dump (prefix, a, Output)
@ -254,50 +289,53 @@ function DumpAPIHtml()
end
f:write([[<!DOCTYPE html>
<html>
<head>
<html>
<head>
<title>MCServer API - Index</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
</head>
<body>
<div id="content">
<header>
<h1>MCServer API - Index</h1>
<hr />
</header>
<p>The API reference is divided into the following sections:</p>
<ul>
<li><a href="#classes">Class index</a></li>
<li><a href="#hooks">Hooks</a></li>
<li><a href="#extra">Extra pages</a></li>
<li><a href="#docstats">Documentation statistics</a></li>
</ul>
<hr />
<a name="classes"><h2>Class index</h2></a>
<p>The following classes are available in the MCServer Lua scripting language:</p>
<ul>
]]);
<header>
<h1>MCServer API - Index</h1>
<hr />
</header>
<p>The API reference is divided into the following sections:</p>
<ul>
<li><a href="#classes">Class index</a></li>
<li><a href="#hooks">Hooks</a></li>
<li><a href="#extra">Extra pages</a></li>
<li><a href="#docstats">Documentation statistics</a></li>
</ul>
<hr />
<a name="classes"><h2>Class index</h2></a>
<p>The following classes are available in the MCServer Lua scripting language:
<ul>
]]);
for i, cls in ipairs(API) do
f:write(" <li><a href=\"" .. cls.Name .. ".html\">" .. cls.Name .. "</a></li>\n");
f:write("<li><a href=\"", cls.Name, ".html\">", cls.Name, "</a></li>\n");
WriteHtmlClass(cls, API);
end
f:write([[ </ul>
<hr />
<a name="hooks"><h2>Hooks</h2></a>
<p>A plugin can register to be called whenever an "interesting event" occurs. It does so by calling <a href="cPluginManager.html">cPluginManager</a>'s AddHook() function and implementing a callback function to handle the event.</p>
<p>A plugin can decide whether it will let the event pass through to the rest of the plugins, or hide it from them. This is determined by the return value from the hook callback function. If the function returns false or no value, the event is propagated further. If the function returns true, the processing is stopped, no other plugin receives the notification (and possibly MCServer disables the default behavior for the event). See each hook's details to see the exact behavior.</p>
<table>
<tr>
<th>Hook name</th>
<th>Called when</th>
</tr>
]]);
f:write([[
</ul></p>
<hr />
<a name="hooks"><h2>Hooks</h2></a>
<p>
A plugin can register to be called whenever an "interesting event" occurs. It does so by calling
<a href="cPluginManager.html">cPluginManager</a>'s AddHook() function and implementing a callback
function to handle the event.</p>
<p>
A plugin can decide whether it will let the event pass through to the rest of the plugins, or hide it
from them. This is determined by the return value from the hook callback function. If the function
returns false or no value, the event is propagated further. If the function returns true, the processing
is stopped, no other plugin receives the notification (and possibly MCServer disables the default
behavior for the event). See each hook's details to see the exact behavior.</p>
<table>
<tr>
<th>Hook name</th>
<th>Called when</th>
</tr>
]]);
for i, hook in ipairs(Hooks) do
if (hook.DefaultFnName == nil) then
-- The hook is not documented yet
@ -430,6 +468,11 @@ function ReadDescriptions(a_API)
-- Process the documentation for each class:
for i, cls in ipairs(a_API) do
-- Initialize default values for each class:
cls.ConstantGroups = {};
cls.NumConstantsInGroups = 0;
cls.NumConstantsInGroupsForDescendants = 0;
-- Rename special functions:
for j, fn in ipairs(cls.Functions) do
if (fn.Name == ".call") then
@ -562,6 +605,52 @@ function ReadDescriptions(a_API)
end
end -- else if (APIDesc.Variables ~= nil)
if (APIDesc.ConstantGroups ~= nil) then
-- Create links between the constants and the groups:
local NumInGroups = 0;
local NumInDescendantGroups = 0;
for j, group in pairs(APIDesc.ConstantGroups) do
group.Name = j;
group.Constants = {};
if (type(group.Include) == "string") then
group.Include = { group.Include };
end
local NumInGroup = 0;
for idx, incl in ipairs(group.Include or {}) do
for cidx, cons in ipairs(cls.Constants) do
if ((cons.Group == nil) and cons.Name:match(incl)) then
cons.Group = group;
table.insert(group.Constants, cons);
NumInGroup = NumInGroup + 1;
end
end -- for cidx - cls.Constants[]
end -- for idx - group.Include[]
NumInGroups = NumInGroups + NumInGroup;
if (group.ShowInDescendants) then
NumInDescendantGroups = NumInDescendantGroups + NumInGroup;
end
-- Sort the constants:
table.sort(group.Constants,
function(c1, c2)
return (c1.Name < c2.Name);
end
);
end -- for j - APIDesc.ConstantGroups[]
cls.ConstantGroups = APIDesc.ConstantGroups;
cls.NumConstantsInGroups = NumInGroups;
cls.NumConstantsInGroupsForDescendants = NumInDescendantGroups;
-- Remove grouped constants from the normal list:
local NewConstants = {};
for idx, cons in ipairs(cls.Constants) do
if (cons.Group == nil) then
table.insert(NewConstants, cons);
end
end
cls.Constants = NewConstants;
end -- if (ConstantGroups ~= nil)
else -- if (APIDesc ~= nil)
-- Class is not documented at all, add all its members to Undocumented lists:
@ -740,34 +829,51 @@ function WriteHtmlClass(a_ClassAPI, a_AllAPI)
end
if (a_InheritedName ~= nil) then
cf:write(" <h2>Functions inherited from " .. a_InheritedName .. "</h2>\n");
cf:write("<h2>Functions inherited from ", a_InheritedName, "</h2>\n");
end
cf:write(" <table>\n <tr>\n <th>Name</th>\n <th>Parameters</th>\n <th>Return value</th>\n <th>Notes</th>\n </tr>\n");
cf:write("<table>\n<tr><th>Name</th><th>Parameters</th><th>Return value</th><th>Notes</th></tr>\n");
for i, func in ipairs(a_Functions) do
cf:write(" <tr>\n <td>" .. func.Name .. "</td>\n");
cf:write(" <td>" .. LinkifyString(func.Params or "", (a_InheritedName or a_ClassAPI.Name)).. "</td>\n");
cf:write(" <td>" .. LinkifyString(func.Return or "", (a_InheritedName or a_ClassAPI.Name)).. "</td>\n");
cf:write(" <td>" .. LinkifyString(func.Notes or "<i>(undocumented)</i>", (a_InheritedName or a_ClassAPI.Name)) .. "</td>\n </tr>\n");
cf:write("<tr><td>", func.Name, "</td>\n");
cf:write("<td>", LinkifyString(func.Params or "", (a_InheritedName or a_ClassAPI.Name)), "</td>\n");
cf:write("<td>", LinkifyString(func.Return or "", (a_InheritedName or a_ClassAPI.Name)), "</td>\n");
cf:write("<td>", LinkifyString(func.Notes or "<i>(undocumented)</i>", (a_InheritedName or a_ClassAPI.Name)), "</td></tr>\n");
end
cf:write(" </table>\n\n");
cf:write("</table>\n");
end
local function WriteConstants(a_Constants, a_InheritedName)
if (#a_Constants == 0) then
local function WriteConstantTable(a_Constants, a_Source)
cf:write("<table>\n<tr><th>Name</th><th>Value</th><th>Notes</th></tr>\n");
for i, cons in ipairs(a_Constants) do
cf:write("<tr><td>", cons.Name, "</td>\n");
cf:write("<td>", cons.Value, "</td>\n");
cf:write("<td>", LinkifyString(cons.Notes or "", a_Source), "</td></tr>\n");
end
cf:write("</table>\n\n");
end
local function WriteConstants(a_Constants, a_ConstantGroups, a_NumConstantGroups, a_InheritedName)
if ((#a_Constants == 0) and (a_NumConstantGroups == 0)) then
return;
end
local Source = a_ClassAPI.Name
if (a_InheritedName ~= nil) then
cf:write(" <h2>Constants inherited from " .. a_InheritedName .. "</h2>\n");
cf:write("<h2>Constants inherited from ", a_InheritedName, "</h2>\n");
Source = a_InheritedName;
end
cf:write(" <table>\n <tr>\n <th>Name</th>\n <th>Value</th>\n <th>Notes</th>\n </tr>\n");
for i, cons in ipairs(a_Constants) do
cf:write(" <tr>\n <td>" .. cons.Name .. "</td>\n");
cf:write(" <td>" .. cons.Value .. "</td>\n");
cf:write(" <td>" .. LinkifyString(cons.Notes or "", a_InheritedName or a_ClassAPI.Name) .. "</td>\n </tr>\n");
if (#a_Constants > 0) then
WriteConstantTable(a_Constants, Source);
end
for k, group in pairs(a_ConstantGroups) do
if ((a_InheritedName == nil) or group.ShowInDescendants) then
cf:write("<a name='", group.Name, "'><p>");
cf:write(LinkifyString(group.TextBefore or "", Source));
WriteConstantTable(group.Constants, a_InheritedName or a_ClassAPI.Name);
cf:write(LinkifyString(group.TextAfter or "", Source), "</a></p>");
end
end
cf:write(" </table>\n\n");
end
local function WriteVariables(a_Variables, a_InheritedName)
@ -776,16 +882,16 @@ function WriteHtmlClass(a_ClassAPI, a_AllAPI)
end
if (a_InheritedName ~= nil) then
cf:write(" <h2>Member variables inherited from " .. a_InheritedName .. "</h2>\n");
cf:write("<h2>Member variables inherited from ", a_InheritedName, "</h2>\n");
end
cf:write(" <table>\n <tr>\n <th>Name</th>\n <th>Type</th>\n <th>Notes</th>\n </tr>\n");
cf:write("<table><tr><th>Name</th><th>Type</th><th>Notes</th></tr>\n");
for i, var in ipairs(a_Variables) do
cf:write(" <tr>\n <td>" .. var.Name .. "</td>\n");
cf:write(" <td>" .. LinkifyString(var.Type or "<i>(undocumented)</i>", a_InheritedName or a_ClassAPI.Name) .. "</td>\n");
cf:write(" <td>" .. LinkifyString(var.Notes or "", a_InheritedName or a_ClassAPI.Name) .. "</td>\n </tr>\n");
cf:write("<tr><td>", var.Name, "</td>\n");
cf:write("<td>", LinkifyString(var.Type or "<i>(undocumented)</i>", a_InheritedName or a_ClassAPI.Name), "</td>\n");
cf:write("<td>", LinkifyString(var.Notes or "", a_InheritedName or a_ClassAPI.Name), "</td>\n </tr>\n");
end
cf:write(" </table>\n\n");
cf:write("</table>\n\n");
end
local function WriteDescendants(a_Descendants)
@ -794,7 +900,7 @@ function WriteHtmlClass(a_ClassAPI, a_AllAPI)
end
cf:write("<ul>");
for i, desc in ipairs(a_Descendants) do
cf:write("<li><a href=\"".. desc.Name .. ".html\">" .. desc.Name .. "</a>");
cf:write("<li><a href=\"", desc.Name, ".html\">", desc.Name, "</a>");
WriteDescendants(desc.Descendants);
cf:write("</li>\n");
end
@ -811,95 +917,93 @@ function WriteHtmlClass(a_ClassAPI, a_AllAPI)
CurrInheritance = CurrInheritance.Inherits;
end
cf:write([[<!DOCTYPE html>
<html>
<head>
<title>MCServer API - ]] .. a_ClassAPI.Name .. [[ Class</title>
cf:write([[<!DOCTYPE html><html>
<head>
<title>MCServer API - ]], a_ClassAPI.Name, [[ Class</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<link rel="stylesheet" type="text/css" href="prettify.css" />
<script src="prettify.js"></script>
<script src="lang-lua.js"></script>
</head>
<body>
</head>
<body>
<div id="content">
<header>
<h1>]] .. a_ClassAPI.Name .. [[</h1>
<hr />
</header>
<h1>Contents</h1>
<ul>
]]);
<header>
<h1>]], a_ClassAPI.Name, [[</h1>
<hr />
</header>
<h1>Contents</h1>
<p><ul>
]]);
local HasInheritance = ((#a_ClassAPI.Descendants > 0) or (a_ClassAPI.Inherits ~= nil));
local HasConstants = (#a_ClassAPI.Constants > 0);
local HasConstants = (#a_ClassAPI.Constants > 0) or (a_ClassAPI.NumConstantsInGroups > 0);
local HasFunctions = (#a_ClassAPI.Functions > 0);
local HasVariables = (#a_ClassAPI.Variables > 0);
for idx, cls in ipairs(InheritanceChain) do
HasConstants = HasConstants or (#cls.Constants > 0);
HasConstants = HasConstants or (#cls.Constants > 0) or (cls.NumConstantsInGroupsForDescendants > 0);
HasFunctions = HasFunctions or (#cls.Functions > 0);
HasVariables = HasVariables or (#cls.Variables > 0);
end
-- Write the table of contents:
if (HasInheritance) then
cf:write(" <li><a href=\"#inherits\">Inheritance</a></li>\n");
cf:write("<li><a href=\"#inherits\">Inheritance</a></li>\n");
end
if (HasConstants) then
cf:write(" <li><a href=\"#constants\">Constants</a></li>\n");
cf:write("<li><a href=\"#constants\">Constants</a></li>\n");
end
if (HasVariables) then
cf:write(" <li><a href=\"#variables\">Member variables</a></li>\n");
cf:write("<li><a href=\"#variables\">Member variables</a></li>\n");
end
if (HasFunctions) then
cf:write(" <li><a href=\"#functions\">Functions</a></li>\n");
cf:write("<li><a href=\"#functions\">Functions</a></li>\n");
end
if (a_ClassAPI.AdditionalInfo ~= nil) then
for i, additional in ipairs(a_ClassAPI.AdditionalInfo) do
cf:write(" <li><a href=\"#additionalinfo_" .. i .. "\">" .. (additional.Header or "<i>(No header)</i>").. "</a></li>\n");
cf:write("<li><a href=\"#additionalinfo_", i, "\">", (additional.Header or "<i>(No header)</i>"), "</a></li>\n");
end
end
cf:write(" </ul>\n\n");
cf:write("</ul></p>\n");
-- Write the class description:
cf:write(" <a name=\"desc\"><hr /><h1>" .. ClassName .. " class</h1></a>\n");
cf:write("<hr /><a name=\"desc\"><h1>", ClassName, " class</h1></a>\n");
if (a_ClassAPI.Desc ~= nil) then
cf:write(" <p>");
cf:write("<p>");
cf:write(LinkifyString(a_ClassAPI.Desc, ClassName));
cf:write(" </p>\n\n");
cf:write("</p>\n\n");
end;
-- Write the inheritance, if available:
if (HasInheritance) then
cf:write(" <a name=\"inherits\">\n <hr /><h1>Inheritance</h1></a>\n");
cf:write("<hr /><a name=\"inherits\"><h1>Inheritance</h1></a>\n");
if (#InheritanceChain > 0) then
cf:write(" <p>This class inherits from the following parent classes:</p>\n\n <ul>\n");
cf:write("<p>This class inherits from the following parent classes:<ul>\n");
for i, cls in ipairs(InheritanceChain) do
cf:write(" <li><a href=\"" .. cls.Name .. ".html\">" .. cls.Name .. "</a></li>\n");
cf:write("<li><a href=\"", cls.Name, ".html\">", cls.Name, "</a></li>\n");
end
cf:write(" </ul>\n\n");
cf:write("</ul></p>\n");
end
if (#a_ClassAPI.Descendants > 0) then
cf:write(" <p>This class has the following descendants:\n");
cf:write("<p>This class has the following descendants:\n");
WriteDescendants(a_ClassAPI.Descendants);
cf:write(" </p>\n\n");
cf:write("</p>\n\n");
end
end
-- Write the constants:
if (HasConstants) then
cf:write(" <a name=\"constants\"><hr /><h1>Constants</h1></a>\n");
WriteConstants(a_ClassAPI.Constants, nil);
g_Stats.NumTotalConstants = g_Stats.NumTotalConstants + #a_ClassAPI.Constants;
cf:write("<a name=\"constants\"><hr /><h1>Constants</h1></a>\n");
WriteConstants(a_ClassAPI.Constants, a_ClassAPI.ConstantGroups, a_ClassAPI.NumConstantsInGroups, nil);
g_Stats.NumTotalConstants = g_Stats.NumTotalConstants + #a_ClassAPI.Constants + (a_ClassAPI.NumConstantsInGroups or 0);
for i, cls in ipairs(InheritanceChain) do
WriteConstants(cls.Constants, cls.Name);
WriteConstants(cls.Constants, cls.ConstantGroups, cls.NumConstantsInGroupsForDescendants, cls.Name);
end;
end;
-- Write the member variables:
if (HasVariables) then
cf:write(" <a name=\"variables\"><hr /><h1>Member variables</h1></a>\n");
cf:write("<a name=\"variables\"><hr /><h1>Member variables</h1></a>\n");
WriteVariables(a_ClassAPI.Variables, nil);
g_Stats.NumTotalVariables = g_Stats.NumTotalVariables + #a_ClassAPI.Variables;
for i, cls in ipairs(InheritanceChain) do
@ -909,7 +1013,7 @@ function WriteHtmlClass(a_ClassAPI, a_AllAPI)
-- Write the functions, including the inherited ones:
if (HasFunctions) then
cf:write(" <a name=\"functions\"><hr /><h1>Functions</h1></a>\n");
cf:write("<a name=\"functions\"><hr /><h1>Functions</h1></a>\n");
WriteFunctions(a_ClassAPI.Functions, nil);
g_Stats.NumTotalFunctions = g_Stats.NumTotalFunctions + #a_ClassAPI.Functions;
for i, cls in ipairs(InheritanceChain) do
@ -920,19 +1024,12 @@ function WriteHtmlClass(a_ClassAPI, a_AllAPI)
-- Write the additional infos:
if (a_ClassAPI.AdditionalInfo ~= nil) then
for i, additional in ipairs(a_ClassAPI.AdditionalInfo) do
cf:write(" <a name=\"additionalinfo_" .. i .. "\"><h1>" .. additional.Header .. "</h1></a>\n");
cf:write("<a name=\"additionalinfo_", i, "\"><h1>", additional.Header, "</h1></a>\n");
cf:write(LinkifyString(additional.Contents, ClassName));
end
end
cf:write([[
</div>
<script>
prettyPrint();
</script>
</body>
</html>
]]);
cf:write([[</div><script>prettyPrint();</script></body></html>]]);
cf:close();
end
@ -949,27 +1046,26 @@ function WriteHtmlHook(a_Hook)
end
local HookName = a_Hook.DefaultFnName;
f:write([[<!DOCTYPE html>
<html>
<head>
<title>MCServer API - ]] .. HookName .. [[ Hook</title>
f:write([[<!DOCTYPE html><html>
<head>
<title>MCServer API - ]], HookName, [[ Hook</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<link rel="stylesheet" type="text/css" href="prettify.css" />
<script src="prettify.js"></script>
<script src="lang-lua.js"></script>
</head>
<body>
</head>
<body>
<div id="content">
<header>
<h1>]] .. a_Hook.Name .. [[</h1>
<hr />
</header>
<p>
]]);
<header>
<h1>]], a_Hook.Name, [[</h1>
<hr />
</header>
<p>
]]);
f:write(LinkifyString(a_Hook.Desc, HookName));
f:write(" </p>\n <hr /><h1>Callback function</h1>\n <p>The default name for the callback function is ");
f:write(a_Hook.DefaultFnName .. ". It has the following signature:\n\n");
f:write(" <pre class=\"prettyprint lang-lua\">function " .. HookName .. "(");
f:write("</p>\n<hr /><h1>Callback function</h1>\n<p>The default name for the callback function is ");
f:write(a_Hook.DefaultFnName, ". It has the following signature:\n");
f:write("<pre class=\"prettyprint lang-lua\">function ", HookName, "(");
if (a_Hook.Params == nil) then
a_Hook.Params = {};
end
@ -979,30 +1075,22 @@ function WriteHtmlHook(a_Hook)
end
f:write(param.Name);
end
f:write(")</pre>\n\n <hr /><h1>Parameters:</h1>\n\n <table>\n <tr>\n <th>Name</th>\n <th>Type</th>\n <th>Notes</th>\n </tr>\n");
f:write(")</pre>\n<hr /><h1>Parameters:</h1>\n<table><tr><th>Name</th><th>Type</th><th>Notes</th></tr>\n");
for i, param in ipairs(a_Hook.Params) do
f:write(" <tr>\n <td>" .. param.Name .. "</td>\n <td>" .. LinkifyString(param.Type, HookName) .. "</td>\n <td>" .. LinkifyString(param.Notes, HookName) .. "</td>\n </tr>\n");
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\n <p>" .. (a_Hook.Returns or "") .. "</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("</table>\n<p>" .. (a_Hook.Returns or "") .. "</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 .. [[);]]);
f:write("</pre>\n\n");
local Examples = a_Hook.CodeExamples or {};
for i, example in ipairs(Examples) do
f:write(" <h2>" .. (example.Title or "<i>missing Title</i>") .. "</h2>\n");
f:write(" <p>" .. (example.Desc or "<i>missing Desc</i>") .. "</p>\n\n");
f:write(" <pre class=\"prettyprint lang-lua\">" .. (example.Code or "<i>missing Code</i>") .. "\n </pre>\n\n");
f:write("<h2>", (example.Title or "<i>missing Title</i>"), "</h2>\n");
f:write("<p>", (example.Desc or "<i>missing Desc</i>"), "</p>\n");
f:write("<pre class=\"prettyprint lang-lua\">", (example.Code or "<i>missing Code</i>"), "\n</pre>\n\n");
end
f:write([[ </div>
<script>
prettyPrint();
</script>
</body>
</html>]]);
f:write([[</div><script>prettyPrint();</script></body></html>]]);
f:close();
end
@ -1180,7 +1268,7 @@ end
function WriteStats(f)
local function ExportMeter(a_Percent)
local Color;
if (a_Percent > 95) then
if (a_Percent > 99) then
Color = "green";
elseif (a_Percent > 50) then
Color = "orange";

@ -1 +1 @@
Subproject commit 9ec55bcdcaf8b3eea8e98e3e502890295dda14d6
Subproject commit de53a607f30c583e08c06b6e5eb936cd278ab8cd

View File

@ -28,23 +28,30 @@ function Initialize(Plugin)
cPluginManager.AddHook(cPluginManager.HOOK_WORLD_TICK, OnWorldTick);
cPluginManager.AddHook(cPluginManager.HOOK_CHUNK_GENERATED, OnChunkGenerated);
PluginManager = cRoot:Get():GetPluginManager();
PluginManager:BindCommand("/le", "debuggers", HandleListEntitiesCmd, "- Shows a list of all the loaded entities");
PluginManager:BindCommand("/ke", "debuggers", HandleKillEntitiesCmd, "- Kills all the loaded entities");
PluginManager:BindCommand("/wool", "debuggers", HandleWoolCmd, "- Sets all your armor to blue wool");
PluginManager:BindCommand("/testwnd", "debuggers", HandleTestWndCmd, "- Opens up a window using plugin API");
PluginManager:BindCommand("/gc", "debuggers", HandleGCCmd, "- Activates the Lua garbage collector");
PluginManager:BindCommand("/fast", "debuggers", HandleFastCmd, "- Switches between fast and normal movement speed");
PluginManager:BindCommand("/dash", "debuggers", HandleDashCmd, "- Switches between fast and normal sprinting speed");
PluginManager:BindCommand("/hunger", "debuggers", HandleHungerCmd, "- Lists the current hunger-related variables");
PluginManager:BindCommand("/poison", "debuggers", HandlePoisonCmd, "- Sets food-poisoning for 15 seconds");
PluginManager:BindCommand("/starve", "debuggers", HandleStarveCmd, "- Sets the food level to zero");
PluginManager:BindCommand("/fl", "debuggers", HandleFoodLevelCmd, "- Sets the food level to the given value");
PluginManager:BindCommand("/spidey", "debuggers", HandleSpideyCmd, "- Shoots a line of web blocks until it hits non-air");
PluginManager:BindCommand("/ench", "debuggers", HandleEnchCmd, "- Provides an instant dummy enchantment window");
PluginManager:BindCommand("/fs", "debuggers", HandleFoodStatsCmd, "- Turns regular foodstats message on or off");
PluginManager:BindCommand("/arr", "debuggers", HandleArrowCmd, "- Creates an arrow going away from the player");
PluginManager:BindCommand("/fb", "debuggers", HandleFireballCmd, "- Creates a ghast fireball as if shot by the player");
PM = cRoot:Get():GetPluginManager();
PM:BindCommand("/le", "debuggers", HandleListEntitiesCmd, "- Shows a list of all the loaded entities");
PM:BindCommand("/ke", "debuggers", HandleKillEntitiesCmd, "- Kills all the loaded entities");
PM:BindCommand("/wool", "debuggers", HandleWoolCmd, "- Sets all your armor to blue wool");
PM:BindCommand("/testwnd", "debuggers", HandleTestWndCmd, "- Opens up a window using plugin API");
PM:BindCommand("/gc", "debuggers", HandleGCCmd, "- Activates the Lua garbage collector");
PM:BindCommand("/fast", "debuggers", HandleFastCmd, "- Switches between fast and normal movement speed");
PM:BindCommand("/dash", "debuggers", HandleDashCmd, "- Switches between fast and normal sprinting speed");
PM:BindCommand("/hunger", "debuggers", HandleHungerCmd, "- Lists the current hunger-related variables");
PM:BindCommand("/poison", "debuggers", HandlePoisonCmd, "- Sets food-poisoning for 15 seconds");
PM:BindCommand("/starve", "debuggers", HandleStarveCmd, "- Sets the food level to zero");
PM:BindCommand("/fl", "debuggers", HandleFoodLevelCmd, "- Sets the food level to the given value");
PM:BindCommand("/spidey", "debuggers", HandleSpideyCmd, "- Shoots a line of web blocks until it hits non-air");
PM:BindCommand("/ench", "debuggers", HandleEnchCmd, "- Provides an instant dummy enchantment window");
PM:BindCommand("/fs", "debuggers", HandleFoodStatsCmd, "- Turns regular foodstats message on or off");
PM:BindCommand("/arr", "debuggers", HandleArrowCmd, "- Creates an arrow going away from the player");
PM:BindCommand("/fb", "debuggers", HandleFireballCmd, "- Creates a ghast fireball as if shot by the player");
PM:BindCommand("/xpa", "debuggers", HandleAddExperience, "- Adds 200 experience to the player");
PM:BindCommand("/xpr", "debuggers", HandleRemoveXp, "- Remove all xp");
PM:BindCommand("/fill", "debuggers", HandleFill, "- Fills all block entities in current chunk with junk");
PM:BindCommand("/fr", "debuggers", HandleFurnaceRecipe, "- Shows the furnace recipe for the currently held item");
PM:BindCommand("/ff", "debuggers", HandleFurnaceFuel, "- Shows how long the currently held item would burn in a furnace");
Plugin:AddWebTab("Debuggers", HandleRequest_Debuggers);
-- Enable the following line for BlockArea / Generator interface testing:
-- PluginManager:AddHook(Plugin, cPluginManager.HOOK_CHUNK_GENERATED);
@ -846,3 +853,104 @@ end
function HandleAddExperience(a_Split, a_Player)
a_Player:DeltaExperience(200);
return true;
end
function HandleRemoveXp(a_Split, a_Player)
a_Player:SetCurrentExperience(0);
return true;
end
function HandleFill(a_Split, a_Player)
local World = a_Player:GetWorld();
local ChunkX = a_Player:GetChunkX();
local ChunkZ = a_Player:GetChunkZ();
World:ForEachBlockEntityInChunk(ChunkX, ChunkZ,
function(a_BlockEntity)
local BlockType = a_BlockEntity:GetBlockType();
if (
(BlockType == E_BLOCK_CHEST) or
(BlockType == E_BLOCK_DISPENSER) or
(BlockType == E_BLOCK_DROPPER) or
(BlockType == E_BLOCK_FURNACE) or
(BlockType == E_BLOCK_HOPPER)
) then
-- This block entity has items (inherits from cBlockEntityWithItems), fill it:
-- Note that we're not touching lit furnaces, don't wanna mess them up
local EntityWithItems = tolua.cast(a_BlockEntity, "cBlockEntityWithItems");
local ItemGrid = EntityWithItems:GetContents();
local NumSlots = ItemGrid:GetNumSlots();
local ItemToSet = cItem(E_ITEM_GOLD_NUGGET);
for i = 0, NumSlots - 1 do
if (ItemGrid:GetSlot(i):IsEmpty()) then
ItemGrid:SetSlot(i, ItemToSet);
end
end
end
end
);
return true;
end
function HandleFurnaceRecipe(a_Split, a_Player)
local HeldItem = a_Player:GetEquippedItem();
local Out, NumTicks, In = cRoot:GetFurnaceRecipe(HeldItem);
if (Out ~= nil) then
a_Player:SendMessage(
"Furnace turns " .. ItemToFullString(In) ..
" to " .. ItemToFullString(Out) ..
" in " .. NumTicks .. " ticks (" ..
tostring(NumTicks / 20) .. " seconds)."
);
else
a_Player:SendMessage("There is no furnace recipe that would smelt " .. ItemToString(HeldItem));
end
return true;
end
function HandleFurnaceFuel(a_Split, a_Player)
local HeldItem = a_Player:GetEquippedItem();
local NumTicks = cRoot:GetFurnaceFuelBurnTime(HeldItem);
if (NumTicks > 0) then
a_Player:SendMessage(
ItemToFullString(HeldItem) .. " would power a furnace for " .. NumTicks ..
" ticks (" .. tostring(NumTicks / 20) .. " seconds)."
);
else
a_Player:SendMessage(ItemToString(HeldItem) .. " will not power furnaces.");
end
return true;
end
function HandleRequest_Debuggers(a_Request)
local FolderContents = cFile:GetFolderContents("./");
return "<p>The following objects have been returned by cFile:GetFolderContents():<ul><li>" .. table.concat(FolderContents, "</li><li>") .. "</li></ul></p>";
end

View File

@ -119,10 +119,18 @@ redwool=35:14
blackwool=35:15
dandelion=37
; Obsolete, use "dandelion" instead (kept for compatibility, will be removed)
flower=37
; Renamed in 1.7, use "poppy" instead; kept for compatibility reasons, will be removed later on.
rose=38
flower=38
poppy=38
blueorchid=38:1
allium=38:2
redtulip=38:4
orangetulip=38:5
whitetulip=38:6
pinktulip=38:7
oxeyedaisy=38:8
brownmushroom=39
redmushroom=40
gold=41

7
Tools/RCONClient/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
Debug/
logs/
Release/
*.suo
*.user
*.ncb
*.sdf

View File

@ -0,0 +1,10 @@
// Globals.cpp
// This file is used for precompiled header generation in MSVC environments
#include "Globals.h"

208
Tools/RCONClient/Globals.h Normal file
View File

@ -0,0 +1,208 @@
// Globals.h
// This file gets included from every module in the project, so that global symbols may be introduced easily
// Also used for precompiled header generation in MSVC environments
// Compiler-dependent stuff:
#if defined(_MSC_VER)
// MSVC produces warning C4481 on the override keyword usage, so disable the warning altogether
#pragma warning(disable:4481)
// Disable some warnings that we don't care about:
#pragma warning(disable:4100)
#define OBSOLETE __declspec(deprecated)
// No alignment needed in MSVC
#define ALIGN_8
#define ALIGN_16
#elif defined(__GNUC__)
// TODO: Can GCC explicitly mark classes as abstract (no instances can be created)?
#define abstract
// TODO: Can GCC mark virtual methods as overriding (forcing them to have a virtual function of the same signature in the base class)
#define override
#define OBSOLETE __attribute__((deprecated))
#define ALIGN_8 __attribute__((aligned(8)))
#define ALIGN_16 __attribute__((aligned(16)))
// Some portability macros :)
#define stricmp strcasecmp
#else
#error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler"
/*
// Copy and uncomment this into another #elif section based on your compiler identification
// Explicitly mark classes as abstract (no instances can be created)
#define abstract
// Mark virtual methods as overriding (forcing them to have a virtual function of the same signature in the base class)
#define override
// Mark functions as obsolete, so that their usage results in a compile-time warning
#define OBSOLETE
// Mark types / variables for alignment. Do the platforms need it?
#define ALIGN_8
#define ALIGN_16
*/
#endif
// Integral types with predefined sizes:
typedef long long Int64;
typedef int Int32;
typedef short Int16;
typedef unsigned long long UInt64;
typedef unsigned int UInt32;
typedef unsigned short UInt16;
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for any class that shouldn't allow copying itself
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName &); \
void operator=(const TypeName &)
// A macro that is used to mark unused function parameters, to avoid pedantic warnings in gcc
#define UNUSED(X) (void)(X)
// OS-dependent stuff:
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x501 // We want to target WinXP and higher
#include <Windows.h>
#include <winsock2.h>
#include <Ws2tcpip.h> // IPv6 stuff
// Windows SDK defines min and max macros, messing up with our std::min and std::max usage
#undef min
#undef max
// Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant
#ifdef GetFreeSpace
#undef GetFreeSpace
#endif // GetFreeSpace
#else
#include <sys/types.h>
#include <sys/stat.h> // for mkdir
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <dirent.h>
#include <errno.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
#include <fcntl.h>
#if !defined(ANDROID_NDK)
#include <tr1/memory>
#endif
#endif
#if !defined(ANDROID_NDK)
#define USE_SQUIRREL
#endif
#if defined(ANDROID_NDK)
#define FILE_IO_PREFIX "/sdcard/mcserver/"
#else
#define FILE_IO_PREFIX ""
#endif
// CRT stuff:
#include <sys/stat.h>
#include <assert.h>
#include <stdio.h>
#include <math.h>
#include <stdarg.h>
#include <time.h>
// STL stuff:
#include <vector>
#include <list>
#include <deque>
#include <string>
#include <map>
#include <algorithm>
#include <memory>
// Common headers (part 1, without macros):
#include "StringUtils.h"
#include "OSSupport/CriticalSection.h"
#include "OSSupport/File.h"
#include "MCLogger.h"
// Common definitions:
/// Evaluates to the number of elements in an array (compile-time!)
#define ARRAYCOUNT(X) (sizeof(X) / sizeof(*(X)))
/// Allows arithmetic expressions like "32 KiB" (but consider using parenthesis around it, "(32 KiB)" )
#define KiB * 1024
/// Faster than (int)floorf((float)x / (float)div)
#define FAST_FLOOR_DIV( x, div ) ( (x) < 0 ? (((int)x / div) - 1) : ((int)x / div) )
// Own version of assert() that writes failed assertions to the log for review
#ifdef NDEBUG
#define ASSERT(x) ((void)0)
#else
#define ASSERT assert
#endif
// Pretty much the same as ASSERT() but stays in Release builds
#define VERIFY( x ) ( !!(x) || ( LOGERROR("Verification failed: %s, file %s, line %i", #x, __FILE__, __LINE__ ), exit(1), 0 ) )

View File

@ -0,0 +1,332 @@
// RCONClient.cpp
// Implements the main app entrypoint
#include "Globals.h"
#include "OSSupport/Socket.h"
#include "ByteBuffer.h"
// If set to true, verbose messages are output to stderr. Use the "-v" or "--verbose" param to turn on
bool g_IsVerbose = false;
/// This class can read and write RCON packets to / from a connected socket
class cRCONPacketizer
{
public:
enum
{
ptCommand = 2,
ptLogin = 3,
} ;
cRCONPacketizer(cSocket & a_Socket);
/// Sends the packet to the socket and waits until the response is received.
/// Returns true if response successfully received, false if the client disconnected or protocol error.
/// Dumps the reply payload to stdout.
bool SendPacket(int a_PacketType, const AString & a_PacketPayload);
protected:
/// The socket to use for reading incoming data and writing outgoing data:
cSocket & m_Socket;
/// The RequestID of the packet that is being sent. Incremented when the reply is received
int m_RequestID;
/// Receives the full response and dumps its payload to stdout.
/// Returns true if successful, false if the client disconnected or protocol error.
bool ReceiveResponse(void);
/// Parses the received response packet and dumps its payload to stdout.
/// Returns true if successful, false on protocol error
/// Assumes that the packet length has already been read from the packet
/// If the packet is successfully parsed, increments m_RequestID
bool ParsePacket(cByteBuffer & a_Buffer, int a_PacketLength);
} ;
cRCONPacketizer::cRCONPacketizer(cSocket & a_Socket) :
m_Socket(a_Socket),
m_RequestID(0)
{
}
bool cRCONPacketizer::SendPacket(int a_PacketType, const AString & a_PacketPayload)
{
// Send the packet:
cByteBuffer bb(a_PacketPayload.size() + 30);
bb.WriteLEInt(m_RequestID);
bb.WriteLEInt(a_PacketType);
bb.WriteBuf(a_PacketPayload.data(), a_PacketPayload.size());
bb.WriteBEShort(0); // Padding
AString Packet;
bb.ReadAll(Packet);
size_t Length = Packet.size();
if (!m_Socket.Send((const char *)&Length, 4))
{
fprintf(stderr, "Network error while sending packet: %d (%s). Aborting.",
cSocket::GetLastError(), cSocket::GetLastErrorString().c_str()
);
return false;
}
if (!m_Socket.Send(Packet.data(), Packet.size()))
{
fprintf(stderr, "Network error while sending packet: %d (%s). Aborting.",
cSocket::GetLastError(), cSocket::GetLastErrorString().c_str()
);
return false;
}
return ReceiveResponse();
}
bool cRCONPacketizer::ReceiveResponse(void)
{
// Receive the response:
cByteBuffer Buffer(64 KiB);
while (true)
{
char buf[1024];
int NumReceived = m_Socket.Receive(buf, sizeof(buf), 0);
if (NumReceived == 0)
{
fprintf(stderr, "The remote end closed the connection. Aborting.");
return false;
}
if (NumReceived < 0)
{
fprintf(stderr, "Network error while receiving response: %d, %d (%s). Aborting.",
NumReceived, cSocket::GetLastError(), cSocket::GetLastErrorString().c_str()
);
return false;
}
Buffer.Write(buf, NumReceived);
Buffer.ResetRead();
// Check if the buffer contains the full packet:
if (!Buffer.CanReadBytes(14))
{
// 14 is the minimum packet size for RCON
continue;
}
int PacketSize;
VERIFY(Buffer.ReadLEInt(PacketSize));
if (!Buffer.CanReadBytes(PacketSize))
{
// The packet is not complete yet
continue;
}
// Parse the packet
return ParsePacket(Buffer, PacketSize);
}
}
bool cRCONPacketizer::ParsePacket(cByteBuffer & a_Buffer, int a_PacketLength)
{
// Check that the request ID is equal
bool IsValid = true;
int RequestID = 0;
VERIFY(a_Buffer.ReadLEInt(RequestID));
if (RequestID != m_RequestID)
{
if ((RequestID == -1) && (m_RequestID == 0))
{
fprintf(stderr, "Login failed. Aborting.");
IsValid = false;
// Continue, so that the payload is printed before the program aborts.
}
else
{
fprintf(stderr, "The server returned an invalid request ID, got %d, exp. %d. Aborting.", RequestID, m_RequestID);
return false;
}
}
// Check the packet type:
int PacketType = 0;
VERIFY(a_Buffer.ReadLEInt(PacketType));
if (PacketType != ptCommand)
{
fprintf(stderr, "The server returned an unknown packet type: %d. Aborting.", PacketType);
IsValid = false;
// Continue, so that the payload is printed before the program aborts.
}
AString Payload;
VERIFY(a_Buffer.ReadString(Payload, a_PacketLength - 10));
// Dump the payload to stdout, in a binary mode
fwrite(Payload.data(), Payload.size(), 1, stdout);
if (IsValid)
{
m_RequestID++;
return true;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// main:
int RealMain(int argc, char * argv[])
{
new cMCLogger; // Create a new logger
// Parse the cmdline params for server IP, port, password and the commands to send:
AString ServerAddress, Password;
int ServerPort = -1;
AStringVector Commands;
for (int i = 1; i < argc; i++)
{
if (((NoCaseCompare(argv[i], "-s") == 0) || (NoCaseCompare(argv[i], "--server") == 0)) && (i < argc - 1))
{
ServerAddress = argv[i + 1];
i++;
continue;
}
if (((NoCaseCompare(argv[i], "-p") == 0) || (NoCaseCompare(argv[i], "--port") == 0)) && (i < argc - 1))
{
ServerPort = atoi(argv[i + 1]);
i++;
continue;
}
if (((NoCaseCompare(argv[i], "-w") == 0) || (NoCaseCompare(argv[i], "--password") == 0)) && (i < argc - 1))
{
Password = argv[i + 1];
i++;
continue;
}
if (((NoCaseCompare(argv[i], "-c") == 0) || (NoCaseCompare(argv[i], "--cmd") == 0) || (NoCaseCompare(argv[i], "--command") == 0)) && (i < argc - 1))
{
Commands.push_back(argv[i + 1]);
i++;
continue;
}
if (((NoCaseCompare(argv[i], "-f") == 0) || (NoCaseCompare(argv[i], "--file") == 0)) && (i < argc - 1))
{
i++;
cFile f(argv[i], cFile::fmRead);
if (!f.IsOpen())
{
fprintf(stderr, "Cannot read commands from file \"%s\", aborting.", argv[i]);
return 2;
}
AString cmd;
f.ReadRestOfFile(cmd);
Commands.push_back(cmd);
continue;
}
if ((NoCaseCompare(argv[i], "-v") == 0) || (NoCaseCompare(argv[i], "--verbose") == 0))
{
fprintf(stderr, "Verbose output enabled\n");
g_IsVerbose = true;
continue;
}
fprintf(stderr, "Unknown parameter: \"%s\". Aborting.", argv[i]);
return 1;
} // for i - argv[]
if (ServerAddress.empty() || (ServerPort < 0))
{
fprintf(stderr, "Server address or port not set. Use the --server and --port parameters to set them. Aborting.");
return 1;
}
// Connect:
if (cSocket::WSAStartup() != 0)
{
fprintf(stderr, "Cannot initialize network stack. Aborting\n");
return 6;
}
if (g_IsVerbose)
{
fprintf(stderr, "Connecting to \"%s:%d\"...\n", ServerAddress.c_str(), ServerPort);
}
cSocket s = cSocket::CreateSocket(cSocket::IPv4);
if (!s.ConnectIPv4(ServerAddress, (unsigned short)ServerPort))
{
fprintf(stderr, "Cannot connect to \"%s:%d\": %s\n", ServerAddress.c_str(), ServerPort, cSocket::GetLastErrorString().c_str());
return 3;
}
cRCONPacketizer Packetizer(s);
// Authenticate using the provided password:
if (!Password.empty())
{
if (g_IsVerbose)
{
fprintf(stderr, "Sending the login packet...\n");
}
if (!Packetizer.SendPacket(cRCONPacketizer::ptLogin, Password))
{
// Error message has already been printed, bail out
return 4;
}
}
else
{
if (g_IsVerbose)
{
fprintf(stderr, "No password provided, not sending a login packet.\n");
}
}
for (AStringVector::const_iterator itr = Commands.begin(), end = Commands.end(); itr != end; ++itr)
{
if (g_IsVerbose)
{
fprintf(stderr, "Sending command \"%s\"...\n", itr->c_str());
}
if (!Packetizer.SendPacket(cRCONPacketizer::ptCommand, *itr))
{
return 5;
}
}
return 0;
}
int main(int argc, char * argv[])
{
// This redirection function is only so that debugging the program is easier in MSVC - when RealMain exits, it's still possible to place a breakpoint
int res = RealMain(argc, argv);
return res;
}

View File

@ -0,0 +1,20 @@

Microsoft Visual Studio Solution File, Format Version 10.00
# Visual C++ Express 2008
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RCONClient", "RCONClient.vcproj", "{1A48B032-07D0-4DDD-8362-66C0FC7F7849}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1A48B032-07D0-4DDD-8362-66C0FC7F7849}.Debug|Win32.ActiveCfg = Debug|Win32
{1A48B032-07D0-4DDD-8362-66C0FC7F7849}.Debug|Win32.Build.0 = Debug|Win32
{1A48B032-07D0-4DDD-8362-66C0FC7F7849}.Release|Win32.ActiveCfg = Release|Win32
{1A48B032-07D0-4DDD-8362-66C0FC7F7849}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,287 @@
<?xml version="1.0" encoding="windows-1250"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9,00"
Name="RCONClient"
ProjectGUID="{1A48B032-07D0-4DDD-8362-66C0FC7F7849}"
RootNamespace="RCONClient"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="../../source"
PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="3"
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="Globals.h"
WarningLevel="3"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="1"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
IntermediateDirectory="$(ConfigurationName)"
ConfigurationType="1"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
AdditionalIncludeDirectories="../../source"
PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="Globals.h"
WarningLevel="3"
DebugInformationFormat="3"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
LinkIncremental="1"
GenerateDebugInformation="true"
SubSystem="1"
OptimizeReferences="2"
EnableCOMDATFolding="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\Globals.cpp"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"
/>
</FileConfiguration>
</File>
<File
RelativePath=".\Globals.h"
>
</File>
<File
RelativePath=".\RCONClient.cpp"
>
</File>
<Filter
Name="shared"
>
<File
RelativePath="..\..\source\ByteBuffer.cpp"
>
</File>
<File
RelativePath="..\..\source\ByteBuffer.h"
>
</File>
<File
RelativePath="..\..\source\Log.cpp"
>
</File>
<File
RelativePath="..\..\source\Log.h"
>
</File>
<File
RelativePath="..\..\source\MCLogger.cpp"
>
</File>
<File
RelativePath="..\..\source\MCLogger.h"
>
</File>
<File
RelativePath="..\..\source\StringUtils.cpp"
>
</File>
<File
RelativePath="..\..\source\StringUtils.h"
>
</File>
<Filter
Name="OSSupport"
>
<File
RelativePath="..\..\source\OSSupport\CriticalSection.cpp"
>
</File>
<File
RelativePath="..\..\source\OSSupport\CriticalSection.h"
>
</File>
<File
RelativePath="..\..\source\OSSupport\File.cpp"
>
</File>
<File
RelativePath="..\..\source\OSSupport\File.h"
>
</File>
<File
RelativePath="..\..\source\OSSupport\IsThread.cpp"
>
</File>
<File
RelativePath="..\..\source\OSSupport\IsThread.h"
>
</File>
<File
RelativePath="..\..\source\OSSupport\Socket.cpp"
>
</File>
<File
RelativePath="..\..\source\OSSupport\Socket.h"
>
</File>
</Filter>
</Filter>
</Filter>
<Filter
Name="Resource Files"
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

1
VC2013/.gitignore vendored
View File

@ -7,3 +7,4 @@ ipch/**
*.ncb
*.suo
*.obj
*.sdf

Binary file not shown.

View File

@ -1,6 +1,6 @@
/*
** Lua binding: AllToLua
** Generated automatically by tolua++-1.0.92 on 11/15/13 10:14:19.
** Generated automatically by tolua++-1.0.92 on 11/23/13 19:57:30.
*/
#ifndef __cplusplus
@ -190,7 +190,7 @@ static void tolua_reg_types (lua_State* tolua_S)
tolua_usertype(tolua_S,"cThrownEnderPearlEntity");
tolua_usertype(tolua_S,"cFurnaceEntity");
tolua_usertype(tolua_S,"cEntity");
tolua_usertype(tolua_S,"cCuboid");
tolua_usertype(tolua_S,"cExpBottleEntity");
tolua_usertype(tolua_S,"cEnchantments");
tolua_usertype(tolua_S,"cMonster");
tolua_usertype(tolua_S,"cPluginLua");
@ -199,9 +199,8 @@ static void tolua_reg_types (lua_State* tolua_S)
tolua_usertype(tolua_S,"cPickup");
tolua_usertype(tolua_S,"sWebAdminPage");
tolua_usertype(tolua_S,"cFireChargeEntity");
tolua_usertype(tolua_S,"cWorld");
tolua_usertype(tolua_S,"cClientHandle");
tolua_usertype(tolua_S,"cChunkDesc");
tolua_usertype(tolua_S,"cFurnaceRecipe");
tolua_usertype(tolua_S,"cPluginManager");
tolua_usertype(tolua_S,"Vector3f");
tolua_usertype(tolua_S,"cCraftingRecipes");
@ -212,49 +211,51 @@ static void tolua_reg_types (lua_State* tolua_S)
tolua_usertype(tolua_S,"cLineBlockTracer");
tolua_usertype(tolua_S,"cListeners");
tolua_usertype(tolua_S,"cThrownSnowballEntity");
tolua_usertype(tolua_S,"Vector3d");
tolua_usertype(tolua_S,"cFireworkEntity");
tolua_usertype(tolua_S,"TakeDamageInfo");
tolua_usertype(tolua_S,"cCraftingRecipe");
tolua_usertype(tolua_S,"cPlugin");
tolua_usertype(tolua_S,"cItemGrid");
tolua_usertype(tolua_S,"cHTTPServer::cCallbacks");
tolua_usertype(tolua_S,"cLuaWindow");
tolua_usertype(tolua_S,"cInventory");
tolua_usertype(tolua_S,"cServer");
tolua_usertype(tolua_S,"cHopperEntity");
tolua_usertype(tolua_S,"std::vector<AString>");
tolua_usertype(tolua_S,"cBlockEntityWithItems");
tolua_usertype(tolua_S,"cWindow");
tolua_usertype(tolua_S,"cCraftingGrid");
tolua_usertype(tolua_S,"cItem");
tolua_usertype(tolua_S,"cWorld");
tolua_usertype(tolua_S,"cBlockArea");
tolua_usertype(tolua_S,"cItem");
tolua_usertype(tolua_S,"cGroup");
tolua_usertype(tolua_S,"cArrowEntity");
tolua_usertype(tolua_S,"cDropSpenserEntity");
tolua_usertype(tolua_S,"cGroup");
tolua_usertype(tolua_S,"cTracer");
tolua_usertype(tolua_S,"cBoundingBox");
tolua_usertype(tolua_S,"cCuboid");
tolua_usertype(tolua_S,"cNoteEntity");
tolua_usertype(tolua_S,"Vector3i");
tolua_usertype(tolua_S,"cBlockEntity");
tolua_usertype(tolua_S,"cCriticalSection");
tolua_usertype(tolua_S,"HTTPTemplateRequest");
tolua_usertype(tolua_S,"cPlayer");
tolua_usertype(tolua_S,"cServer");
tolua_usertype(tolua_S,"cSignEntity");
tolua_usertype(tolua_S,"Vector3d");
tolua_usertype(tolua_S,"cFile");
tolua_usertype(tolua_S,"cItems");
tolua_usertype(tolua_S,"cClientHandle");
tolua_usertype(tolua_S,"cIniFile");
tolua_usertype(tolua_S,"cWebPlugin");
tolua_usertype(tolua_S,"cChatColor");
tolua_usertype(tolua_S,"cPawn");
tolua_usertype(tolua_S,"cThrownEggEntity");
tolua_usertype(tolua_S,"cGroupManager");
tolua_usertype(tolua_S,"cWebAdmin");
tolua_usertype(tolua_S,"cChatColor");
tolua_usertype(tolua_S,"cIniFile");
tolua_usertype(tolua_S,"HTTPRequest");
tolua_usertype(tolua_S,"cProjectileEntity");
tolua_usertype(tolua_S,"HTTPFormData");
tolua_usertype(tolua_S,"cPawn");
tolua_usertype(tolua_S,"cPlayer");
tolua_usertype(tolua_S,"cGroupManager");
tolua_usertype(tolua_S,"cSignEntity");
tolua_usertype(tolua_S,"cItemGrid::cListener");
tolua_usertype(tolua_S,"cProjectileEntity");
tolua_usertype(tolua_S,"cDropperEntity");
tolua_usertype(tolua_S,"cInventory");
tolua_usertype(tolua_S,"cThrownEggEntity");
}
/* method: new of class cIniFile */
@ -2302,6 +2303,37 @@ static int tolua_AllToLua_cFile_CreateFolder00(lua_State* tolua_S)
}
#endif //#ifndef TOLUA_DISABLE
/* method: ReadWholeFile of class cFile */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cFile_ReadWholeFile00
static int tolua_AllToLua_cFile_ReadWholeFile00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"cFile",0,&tolua_err) ||
!tolua_iscppstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
const AString a_FileName = ((const AString) tolua_tocppstring(tolua_S,2,0));
{
AString tolua_ret = (AString) cFile::ReadWholeFile(a_FileName);
tolua_pushcppstring(tolua_S,(const char*)tolua_ret);
tolua_pushcppstring(tolua_S,(const char*)a_FileName);
}
}
return 2;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'ReadWholeFile'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* function: BlockStringToType */
#ifndef TOLUA_DISABLE_tolua_AllToLua_BlockStringToType00
static int tolua_AllToLua_BlockStringToType00(lua_State* tolua_S)
@ -7650,9 +7682,9 @@ static int tolua_AllToLua_cEntity_IsInvisible00(lua_State* tolua_S)
}
#endif //#ifndef TOLUA_DISABLE
/* method: SetExperience of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_SetExperience00
static int tolua_AllToLua_cPlayer_SetExperience00(lua_State* tolua_S)
/* method: SetCurrentExperience of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_SetCurrentExperience00
static int tolua_AllToLua_cPlayer_SetCurrentExperience00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
@ -7666,27 +7698,27 @@ static int tolua_AllToLua_cPlayer_SetExperience00(lua_State* tolua_S)
#endif
{
cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0);
int a_XpTotal = ((int) tolua_tonumber(tolua_S,2,0));
short a_XpTotal = ((short) tolua_tonumber(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SetExperience'", NULL);
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SetCurrentExperience'", NULL);
#endif
{
bool tolua_ret = (bool) self->SetExperience(a_XpTotal);
bool tolua_ret = (bool) self->SetCurrentExperience(a_XpTotal);
tolua_pushboolean(tolua_S,(bool)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'SetExperience'.",&tolua_err);
tolua_error(tolua_S,"#ferror in function 'SetCurrentExperience'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: AddExperience of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_AddExperience00
static int tolua_AllToLua_cPlayer_AddExperience00(lua_State* tolua_S)
/* method: DeltaExperience of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_DeltaExperience00
static int tolua_AllToLua_cPlayer_DeltaExperience00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
@ -7700,27 +7732,27 @@ static int tolua_AllToLua_cPlayer_AddExperience00(lua_State* tolua_S)
#endif
{
cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0);
int a_Xp_delta = ((int) tolua_tonumber(tolua_S,2,0));
short a_Xp_delta = ((short) tolua_tonumber(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'AddExperience'", NULL);
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'DeltaExperience'", NULL);
#endif
{
int tolua_ret = (int) self->AddExperience(a_Xp_delta);
short tolua_ret = (short) self->DeltaExperience(a_Xp_delta);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'AddExperience'.",&tolua_err);
tolua_error(tolua_S,"#ferror in function 'DeltaExperience'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: XpGetTotal of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_XpGetTotal00
static int tolua_AllToLua_cPlayer_XpGetTotal00(lua_State* tolua_S)
/* method: GetXpLifetimeTotal of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_GetXpLifetimeTotal00
static int tolua_AllToLua_cPlayer_GetXpLifetimeTotal00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
@ -7734,25 +7766,25 @@ static int tolua_AllToLua_cPlayer_XpGetTotal00(lua_State* tolua_S)
{
cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'XpGetTotal'", NULL);
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetXpLifetimeTotal'", NULL);
#endif
{
int tolua_ret = (int) self->XpGetTotal();
short tolua_ret = (short) self->GetXpLifetimeTotal();
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'XpGetTotal'.",&tolua_err);
tolua_error(tolua_S,"#ferror in function 'GetXpLifetimeTotal'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: XpGetLevel of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_XpGetLevel00
static int tolua_AllToLua_cPlayer_XpGetLevel00(lua_State* tolua_S)
/* method: GetCurrentXp of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_GetCurrentXp00
static int tolua_AllToLua_cPlayer_GetCurrentXp00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
@ -7766,25 +7798,25 @@ static int tolua_AllToLua_cPlayer_XpGetLevel00(lua_State* tolua_S)
{
cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'XpGetLevel'", NULL);
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetCurrentXp'", NULL);
#endif
{
int tolua_ret = (int) self->XpGetLevel();
short tolua_ret = (short) self->GetCurrentXp();
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'XpGetLevel'.",&tolua_err);
tolua_error(tolua_S,"#ferror in function 'GetCurrentXp'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: XpGetPercentage of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_XpGetPercentage00
static int tolua_AllToLua_cPlayer_XpGetPercentage00(lua_State* tolua_S)
/* method: GetXpLevel of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_GetXpLevel00
static int tolua_AllToLua_cPlayer_GetXpLevel00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
@ -7798,17 +7830,109 @@ static int tolua_AllToLua_cPlayer_XpGetPercentage00(lua_State* tolua_S)
{
cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'XpGetPercentage'", NULL);
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetXpLevel'", NULL);
#endif
{
float tolua_ret = (float) self->XpGetPercentage();
short tolua_ret = (short) self->GetXpLevel();
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'XpGetPercentage'.",&tolua_err);
tolua_error(tolua_S,"#ferror in function 'GetXpLevel'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: GetXpPercentage of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_GetXpPercentage00
static int tolua_AllToLua_cPlayer_GetXpPercentage00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"cPlayer",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
cPlayer* self = (cPlayer*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetXpPercentage'", NULL);
#endif
{
float tolua_ret = (float) self->GetXpPercentage();
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'GetXpPercentage'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: XpForLevel of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_XpForLevel00
static int tolua_AllToLua_cPlayer_XpForLevel00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"cPlayer",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
short int a_Level = ((short int) tolua_tonumber(tolua_S,2,0));
{
short tolua_ret = (short) cPlayer::XpForLevel(a_Level);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'XpForLevel'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: CalcLevelFromXp of class cPlayer */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cPlayer_CalcLevelFromXp00
static int tolua_AllToLua_cPlayer_CalcLevelFromXp00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"cPlayer",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
short int a_CurrentXp = ((short int) tolua_tonumber(tolua_S,2,0));
{
short tolua_ret = (short) cPlayer::CalcLevelFromXp(a_CurrentXp);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'CalcLevelFromXp'.",&tolua_err);
return 0;
#endif
}
@ -19621,33 +19745,31 @@ static int tolua_AllToLua_cRoot_GetCraftingRecipes00(lua_State* tolua_S)
}
#endif //#ifndef TOLUA_DISABLE
/* method: GetFurnaceRecipe of class cRoot */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cRoot_GetFurnaceRecipe00
static int tolua_AllToLua_cRoot_GetFurnaceRecipe00(lua_State* tolua_S)
/* method: GetFurnaceFuelBurnTime of class cRoot */
#ifndef TOLUA_DISABLE_tolua_AllToLua_cRoot_GetFurnaceFuelBurnTime00
static int tolua_AllToLua_cRoot_GetFurnaceFuelBurnTime00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"cRoot",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
!tolua_isusertable(tolua_S,1,"cRoot",0,&tolua_err) ||
(tolua_isvaluenil(tolua_S,2,&tolua_err) || !tolua_isusertype(tolua_S,2,"const cItem",0,&tolua_err)) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
cRoot* self = (cRoot*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetFurnaceRecipe'", NULL);
#endif
const cItem* a_Fuel = ((const cItem*) tolua_tousertype(tolua_S,2,0));
{
cFurnaceRecipe* tolua_ret = (cFurnaceRecipe*) self->GetFurnaceRecipe();
tolua_pushusertype(tolua_S,(void*)tolua_ret,"cFurnaceRecipe");
int tolua_ret = (int) cRoot::GetFurnaceFuelBurnTime(*a_Fuel);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'GetFurnaceRecipe'.",&tolua_err);
tolua_error(tolua_S,"#ferror in function 'GetFurnaceFuelBurnTime'.",&tolua_err);
return 0;
#endif
}
@ -29447,6 +29569,7 @@ TOLUA_API int tolua_AllToLua_open (lua_State* tolua_S)
tolua_function(tolua_S,"IsFile",tolua_AllToLua_cFile_IsFile00);
tolua_function(tolua_S,"GetSize",tolua_AllToLua_cFile_GetSize00);
tolua_function(tolua_S,"CreateFolder",tolua_AllToLua_cFile_CreateFolder00);
tolua_function(tolua_S,"ReadWholeFile",tolua_AllToLua_cFile_ReadWholeFile00);
tolua_endmodule(tolua_S);
tolua_constant(tolua_S,"E_BLOCK_AIR",E_BLOCK_AIR);
tolua_constant(tolua_S,"E_BLOCK_STONE",E_BLOCK_STONE);
@ -30417,11 +30540,14 @@ TOLUA_API int tolua_AllToLua_open (lua_State* tolua_S)
tolua_constant(tolua_S,"EATING_TICKS",cPlayer::EATING_TICKS);
tolua_constant(tolua_S,"MAX_AIR_LEVEL",cPlayer::MAX_AIR_LEVEL);
tolua_constant(tolua_S,"DROWNING_TICKS",cPlayer::DROWNING_TICKS);
tolua_function(tolua_S,"SetExperience",tolua_AllToLua_cPlayer_SetExperience00);
tolua_function(tolua_S,"AddExperience",tolua_AllToLua_cPlayer_AddExperience00);
tolua_function(tolua_S,"XpGetTotal",tolua_AllToLua_cPlayer_XpGetTotal00);
tolua_function(tolua_S,"XpGetLevel",tolua_AllToLua_cPlayer_XpGetLevel00);
tolua_function(tolua_S,"XpGetPercentage",tolua_AllToLua_cPlayer_XpGetPercentage00);
tolua_function(tolua_S,"SetCurrentExperience",tolua_AllToLua_cPlayer_SetCurrentExperience00);
tolua_function(tolua_S,"DeltaExperience",tolua_AllToLua_cPlayer_DeltaExperience00);
tolua_function(tolua_S,"GetXpLifetimeTotal",tolua_AllToLua_cPlayer_GetXpLifetimeTotal00);
tolua_function(tolua_S,"GetCurrentXp",tolua_AllToLua_cPlayer_GetCurrentXp00);
tolua_function(tolua_S,"GetXpLevel",tolua_AllToLua_cPlayer_GetXpLevel00);
tolua_function(tolua_S,"GetXpPercentage",tolua_AllToLua_cPlayer_GetXpPercentage00);
tolua_function(tolua_S,"XpForLevel",tolua_AllToLua_cPlayer_XpForLevel00);
tolua_function(tolua_S,"CalcLevelFromXp",tolua_AllToLua_cPlayer_CalcLevelFromXp00);
tolua_function(tolua_S,"GetEyeHeight",tolua_AllToLua_cPlayer_GetEyeHeight00);
tolua_function(tolua_S,"GetEyePosition",tolua_AllToLua_cPlayer_GetEyePosition00);
tolua_function(tolua_S,"IsOnGround",tolua_AllToLua_cPlayer_IsOnGround00);
@ -30509,6 +30635,7 @@ TOLUA_API int tolua_AllToLua_open (lua_State* tolua_S)
tolua_constant(tolua_S,"pkEnderPearl",cProjectileEntity::pkEnderPearl);
tolua_constant(tolua_S,"pkExpBottle",cProjectileEntity::pkExpBottle);
tolua_constant(tolua_S,"pkSplashPotion",cProjectileEntity::pkSplashPotion);
tolua_constant(tolua_S,"pkFirework",cProjectileEntity::pkFirework);
tolua_constant(tolua_S,"pkWitherSkull",cProjectileEntity::pkWitherSkull);
tolua_constant(tolua_S,"pkFishingFloat",cProjectileEntity::pkFishingFloat);
tolua_function(tolua_S,"GetProjectileKind",tolua_AllToLua_cProjectileEntity_GetProjectileKind00);
@ -30538,6 +30665,12 @@ TOLUA_API int tolua_AllToLua_open (lua_State* tolua_S)
tolua_cclass(tolua_S,"cThrownSnowballEntity","cThrownSnowballEntity","cProjectileEntity",NULL);
tolua_beginmodule(tolua_S,"cThrownSnowballEntity");
tolua_endmodule(tolua_S);
tolua_cclass(tolua_S,"cExpBottleEntity","cExpBottleEntity","cProjectileEntity",NULL);
tolua_beginmodule(tolua_S,"cExpBottleEntity");
tolua_endmodule(tolua_S);
tolua_cclass(tolua_S,"cFireworkEntity","cFireworkEntity","cProjectileEntity",NULL);
tolua_beginmodule(tolua_S,"cFireworkEntity");
tolua_endmodule(tolua_S);
tolua_cclass(tolua_S,"cGhastFireballEntity","cGhastFireballEntity","cProjectileEntity",NULL);
tolua_beginmodule(tolua_S,"cGhastFireballEntity");
tolua_endmodule(tolua_S);
@ -31022,7 +31155,7 @@ TOLUA_API int tolua_AllToLua_open (lua_State* tolua_S)
tolua_function(tolua_S,"SetPrimaryServerVersion",tolua_AllToLua_cRoot_SetPrimaryServerVersion00);
tolua_function(tolua_S,"GetGroupManager",tolua_AllToLua_cRoot_GetGroupManager00);
tolua_function(tolua_S,"GetCraftingRecipes",tolua_AllToLua_cRoot_GetCraftingRecipes00);
tolua_function(tolua_S,"GetFurnaceRecipe",tolua_AllToLua_cRoot_GetFurnaceRecipe00);
tolua_function(tolua_S,"GetFurnaceFuelBurnTime",tolua_AllToLua_cRoot_GetFurnaceFuelBurnTime00);
tolua_function(tolua_S,"GetWebAdmin",tolua_AllToLua_cRoot_GetWebAdmin00);
tolua_function(tolua_S,"GetPluginManager",tolua_AllToLua_cRoot_GetPluginManager00);
tolua_function(tolua_S,"QueueExecuteConsoleCommand",tolua_AllToLua_cRoot_QueueExecuteConsoleCommand00);

View File

@ -1,6 +1,6 @@
/*
** Lua binding: AllToLua
** Generated automatically by tolua++-1.0.92 on 11/15/13 10:14:20.
** Generated automatically by tolua++-1.0.92 on 11/23/13 19:57:31.
*/
/* Exported function */

View File

@ -52,6 +52,11 @@ public:
/// Returns NULL for unknown block types
static cBlockEntity * CreateByBlockType(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World = NULL);
static const char * GetClassStatic(void) // Needed for ManualBindings's ForEach templates
{
return "cBlockEntity";
}
// tolua_begin
// Position, in absolute block coordinates:

View File

@ -461,23 +461,26 @@ eDimension StringToDimension(const AString & a_DimensionString)
/// Translates damage type constant to a string representation (built-in).
AString DamageTypeToString(eDamageType a_DamageType)
{
// Make sure to keep this alpha-sorted.
switch (a_DamageType)
{
case dtAdmin: return "dtAdmin";
case dtAttack: return "dtAttack";
case dtRangedAttack: return "dtRangedAttack";
case dtLightning: return "dtLightning";
case dtFalling: return "dtFalling";
case dtDrowning: return "dtDrowning";
case dtSuffocating: return "dtSuffocation";
case dtStarving: return "dtStarving";
case dtCactusContact: return "dtCactusContact";
case dtLavaContact: return "dtLavaContact";
case dtPoisoning: return "dtPoisoning";
case dtOnFire: return "dtOnFire";
case dtDrowning: return "dtDrowning";
case dtEnderPearl: return "dtEnderPearl";
case dtFalling: return "dtFalling";
case dtFireContact: return "dtFireContact";
case dtInVoid: return "dtInVoid";
case dtLavaContact: return "dtLavaContact";
case dtLightning: return "dtLightning";
case dtOnFire: return "dtOnFire";
case dtPoisoning: return "dtPoisoning";
case dtPotionOfHarming: return "dtPotionOfHarming";
case dtAdmin: return "dtAdmin";
case dtRangedAttack: return "dtRangedAttack";
case dtStarving: return "dtStarving";
case dtSuffocating: return "dtSuffocation";
}
// Unknown damage type:
@ -666,13 +669,13 @@ public:
g_BlockTransparent[E_BLOCK_FLOWER_POT] = true;
g_BlockTransparent[E_BLOCK_GLASS] = true;
g_BlockTransparent[E_BLOCK_GLASS_PANE] = true;
g_BlockTransparent[E_BLOCK_STAINED_GLASS] = true;
g_BlockTransparent[E_BLOCK_STAINED_GLASS_PANE] = true;
g_BlockTransparent[E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE] = true;
g_BlockTransparent[E_BLOCK_ICE] = true;
g_BlockTransparent[E_BLOCK_IRON_DOOR] = true;
g_BlockTransparent[E_BLOCK_LAVA] = true;
g_BlockTransparent[E_BLOCK_LEAVES] = true;
g_BlockTransparent[E_BLOCK_LEVER] = true;
g_BlockTransparent[E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE] = true;
g_BlockTransparent[E_BLOCK_MELON_STEM] = true;
g_BlockTransparent[E_BLOCK_NETHER_BRICK_FENCE] = true;
g_BlockTransparent[E_BLOCK_NEW_LEAVES] = true;
@ -684,6 +687,8 @@ public:
g_BlockTransparent[E_BLOCK_RED_MUSHROOM] = true;
g_BlockTransparent[E_BLOCK_SIGN_POST] = true;
g_BlockTransparent[E_BLOCK_SNOW] = true;
g_BlockTransparent[E_BLOCK_STAINED_GLASS] = true;
g_BlockTransparent[E_BLOCK_STAINED_GLASS_PANE] = true;
g_BlockTransparent[E_BLOCK_STATIONARY_LAVA] = true;
g_BlockTransparent[E_BLOCK_STATIONARY_WATER] = true;
g_BlockTransparent[E_BLOCK_STONE_PRESSURE_PLATE] = true;
@ -697,7 +702,7 @@ public:
// TODO: Any other transparent blocks?
// One hit break blocks
// One hit break blocks:
g_BlockOneHitDig[E_BLOCK_ACTIVE_COMPARATOR] = true;
g_BlockOneHitDig[E_BLOCK_BIG_FLOWER] = true;
g_BlockOneHitDig[E_BLOCK_BROWN_MUSHROOM] = true;
@ -708,7 +713,6 @@ public:
g_BlockOneHitDig[E_BLOCK_FLOWER] = true;
g_BlockOneHitDig[E_BLOCK_FLOWER_POT] = true;
g_BlockOneHitDig[E_BLOCK_INACTIVE_COMPARATOR] = true;
g_BlockOneHitDig[E_BLOCK_LOCKED_CHEST] = true;
g_BlockOneHitDig[E_BLOCK_MELON_STEM] = true;
g_BlockOneHitDig[E_BLOCK_POTATOES] = true;
g_BlockOneHitDig[E_BLOCK_PUMPKIN_STEM] = true;
@ -724,7 +728,7 @@ public:
g_BlockOneHitDig[E_BLOCK_TALL_GRASS] = true;
g_BlockOneHitDig[E_BLOCK_TORCH] = true;
// Blocks that breaks when pushed by piston
// Blocks that break when pushed by piston:
g_BlockPistonBreakable[E_BLOCK_ACTIVE_COMPARATOR] = true;
g_BlockPistonBreakable[E_BLOCK_AIR] = true;
g_BlockPistonBreakable[E_BLOCK_BED] = true;
@ -762,11 +766,12 @@ public:
g_BlockPistonBreakable[E_BLOCK_TORCH] = true;
g_BlockPistonBreakable[E_BLOCK_VINES] = true;
g_BlockPistonBreakable[E_BLOCK_WATER] = true;
g_BlockPistonBreakable[E_BLOCK_WOODEN_BUTTON] = true;
g_BlockPistonBreakable[E_BLOCK_WOODEN_DOOR] = true;
g_BlockPistonBreakable[E_BLOCK_WOODEN_PRESSURE_PLATE] = true;
// Blocks that can be snowed over:
// Blocks that cannot be snowed over:
g_BlockIsSnowable[E_BLOCK_ACTIVE_COMPARATOR] = false;
g_BlockIsSnowable[E_BLOCK_AIR] = false;
g_BlockIsSnowable[E_BLOCK_BIG_FLOWER] = false;
@ -782,7 +787,6 @@ public:
g_BlockIsSnowable[E_BLOCK_INACTIVE_COMPARATOR] = false;
g_BlockIsSnowable[E_BLOCK_LAVA] = false;
g_BlockIsSnowable[E_BLOCK_LILY_PAD] = false;
g_BlockIsSnowable[E_BLOCK_LOCKED_CHEST] = false;
g_BlockIsSnowable[E_BLOCK_REDSTONE_REPEATER_OFF] = false;
g_BlockIsSnowable[E_BLOCK_REDSTONE_REPEATER_ON] = false;
g_BlockIsSnowable[E_BLOCK_REDSTONE_TORCH_OFF] = false;
@ -793,6 +797,8 @@ public:
g_BlockIsSnowable[E_BLOCK_SAPLING] = false;
g_BlockIsSnowable[E_BLOCK_SIGN_POST] = false;
g_BlockIsSnowable[E_BLOCK_SNOW] = false;
g_BlockIsSnowable[E_BLOCK_STAINED_GLASS] = false;
g_BlockIsSnowable[E_BLOCK_STAINED_GLASS_PANE] = false;
g_BlockIsSnowable[E_BLOCK_STATIONARY_LAVA] = false;
g_BlockIsSnowable[E_BLOCK_STATIONARY_WATER] = false;
g_BlockIsSnowable[E_BLOCK_TALL_GRASS] = false;
@ -803,7 +809,7 @@ public:
g_BlockIsSnowable[E_BLOCK_WATER] = false;
// Blocks that don't drop without a special tool
// Blocks that don't drop without a special tool:
g_BlockRequiresSpecialTool[E_BLOCK_BRICK] = true;
g_BlockRequiresSpecialTool[E_BLOCK_CAULDRON] = true;
g_BlockRequiresSpecialTool[E_BLOCK_COAL_ORE] = true;
@ -838,7 +844,7 @@ public:
g_BlockRequiresSpecialTool[E_BLOCK_STONE_SLAB] = true;
g_BlockRequiresSpecialTool[E_BLOCK_VINES] = true;
// Nonsolid Blocks:
// Nonsolid blocks:
g_BlockIsSolid[E_BLOCK_ACTIVATOR_RAIL] = false;
g_BlockIsSolid[E_BLOCK_AIR] = false;
g_BlockIsSolid[E_BLOCK_BIG_FLOWER] = false;
@ -857,11 +863,8 @@ public:
g_BlockIsSolid[E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE] = false;
g_BlockIsSolid[E_BLOCK_MELON_STEM] = false;
g_BlockIsSolid[E_BLOCK_NETHER_PORTAL] = false;
g_BlockIsSolid[E_BLOCK_PISTON] = false;
g_BlockIsSolid[E_BLOCK_PISTON_EXTENSION] = false;
g_BlockIsSolid[E_BLOCK_RAIL] = false;
g_BlockIsSolid[E_BLOCK_REDSTONE_REPEATER_OFF] = false;
g_BlockIsSolid[E_BLOCK_REDSTONE_REPEATER_ON] = false;
g_BlockIsSolid[E_BLOCK_REDSTONE_TORCH_OFF] = false;
g_BlockIsSolid[E_BLOCK_REDSTONE_TORCH_ON] = false;
g_BlockIsSolid[E_BLOCK_REDSTONE_WIRE] = false;
@ -884,7 +887,7 @@ public:
g_BlockIsSolid[E_BLOCK_WOODEN_PRESSURE_PLATE] = false;
g_BlockIsSolid[E_BLOCK_WOODEN_SLAB] = false;
// Torch placeable
// Torch placeable blocks:
g_BlockIsTorchPlaceable[E_BLOCK_BEDROCK] = true;
g_BlockIsTorchPlaceable[E_BLOCK_BLOCK_OF_COAL] = true;
g_BlockIsTorchPlaceable[E_BLOCK_BLOCK_OF_REDSTONE] = true;
@ -930,7 +933,7 @@ public:
g_BlockIsTorchPlaceable[E_BLOCK_NETHER_QUARTZ_ORE] = true;
g_BlockIsTorchPlaceable[E_BLOCK_NOTE_BLOCK] = true;
g_BlockIsTorchPlaceable[E_BLOCK_OBSIDIAN] = true;
g_BlockIsTorchPlaceable[E_BLOCK_PACKED_ICE] = true;
g_BlockIsTorchPlaceable[E_BLOCK_PACKED_ICE] = true;
g_BlockIsTorchPlaceable[E_BLOCK_PLANKS] = true;
g_BlockIsTorchPlaceable[E_BLOCK_PUMPKIN] = true;
g_BlockIsTorchPlaceable[E_BLOCK_QUARTZ_BLOCK] = true;
@ -952,3 +955,4 @@ public:

View File

@ -17,21 +17,14 @@ cBlockButtonHandler::cBlockButtonHandler(BLOCKTYPE a_BlockType)
void cBlockButtonHandler::OnUse(cWorld *a_World, cPlayer *a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ)
{
// Flip the ON bit on/off. Using XOR bitwise operation to turn it on/off.
// Flip the ON bit on/off using the XOR bitwise operation
NIBBLETYPE Meta = ((a_World->GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) ^ 0x08) & 0x0f);
a_World->SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, Meta);
a_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, m_BlockType, Meta);
a_World->BroadcastSoundEffect("random.click", a_BlockX * 8, a_BlockY * 8, a_BlockZ * 8, 0.5f, (Meta & 0x08) ? 0.6f : 0.5f);
if (Meta & 0x08)
{
a_World->BroadcastSoundEffect("random.click", a_BlockX * 8, a_BlockY * 8, a_BlockZ * 8, 0.5f, 0.6f);
}
else
{
a_World->BroadcastSoundEffect("random.click", a_BlockX * 8, a_BlockY * 8, a_BlockZ * 8, 0.5f, 0.5f);
}
// Queue a button reset (unpress), with a GetBlock to prevent duplication of buttons (press, break, wait for reset)
a_World->QueueSetBlock(a_BlockX, a_BlockY, a_BlockZ, a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ), ((a_World->GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) ^ 0x08) & 0x0f), m_BlockType == E_BLOCK_STONE_BUTTON ? 20 : 25);
// Queue a button reset (unpress)
a_World->QueueSetBlock(a_BlockX, a_BlockY, a_BlockZ, m_BlockType, ((a_World->GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) ^ 0x08) & 0x0f), m_BlockType == E_BLOCK_STONE_BUTTON ? 20 : 30);
}

View File

@ -14,11 +14,11 @@ public:
virtual void OnUse(cWorld * a_World, cPlayer * a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ) override;
virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override
{
// Reset meta to 0
a_Pickups.push_back(cItem(m_BlockType == E_BLOCK_WOODEN_BUTTON ? E_BLOCK_WOODEN_BUTTON : E_BLOCK_STONE_BUTTON, 1, 0));
a_Pickups.push_back(cItem(m_BlockType, 1, 0));
}
@ -51,10 +51,10 @@ public:
{
switch (a_BlockFace)
{
case BLOCK_FACE_ZP: { return 0x4; }
case BLOCK_FACE_ZM: { return 0x3; }
case BLOCK_FACE_XP: { return 0x2; }
case BLOCK_FACE_XM: { return 0x1; }
case BLOCK_FACE_ZM: { return 0x4; }
case BLOCK_FACE_ZP: { return 0x3; }
case BLOCK_FACE_XM: { return 0x2; }
case BLOCK_FACE_XP: { return 0x1; }
default:
{
ASSERT(!"Unhandled block face!");
@ -62,6 +62,30 @@ public:
}
}
}
inline static NIBBLETYPE BlockMetaDataToBlockFace(NIBBLETYPE a_Meta)
{
switch (a_Meta & 0x7)
{
case 0x1: return BLOCK_FACE_XP;
case 0x2: return BLOCK_FACE_XM;
case 0x3: return BLOCK_FACE_ZP;
case 0x4: return BLOCK_FACE_ZM;
default:
{
ASSERT(!"Unhandled block meta!");
return BLOCK_FACE_NONE;
}
}
}
virtual bool CanBeAt(int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override
{
NIBBLETYPE Meta = a_Chunk.GetMeta(a_RelX, a_RelY, a_RelZ);
AddFaceDirection(a_RelX, a_RelY, a_RelZ, BlockMetaDataToBlockFace(Meta), true);
return (a_RelY > 0) && (g_BlockIsSolid[a_Chunk.GetBlock(a_RelX, a_RelY, a_RelZ)]);
}
} ;

View File

@ -1,7 +1,7 @@
#include "Globals.h"
#include "BlockComparator.h"
#include "../Simulator/RedstoneSimulator.h"
#include "BlockRedstoneRepeater.h"
#include "../Entities/Player.h"
@ -44,7 +44,7 @@ bool cBlockComparatorHandler::GetPlacementBlockTypeMeta(
)
{
a_BlockType = m_BlockType;
a_BlockMeta = cRedstoneSimulator::RepeaterRotationToMetaData(a_Player->GetRotation());
a_BlockMeta = cBlockRedstoneRepeaterHandler::RepeaterRotationToMetaData(a_Player->GetRotation());
return true;
}

View File

@ -19,18 +19,11 @@ cBlockLeverHandler::cBlockLeverHandler(BLOCKTYPE a_BlockType)
void cBlockLeverHandler::OnUse(cWorld *a_World, cPlayer *a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ)
{
// Flip the ON bit on/off. Using XOR bitwise operation to turn it on/off.
// Flip the ON bit on/off using the XOR bitwise operation
NIBBLETYPE Meta = ((a_World->GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) ^ 0x08) & 0x0f);
a_World->SetBlockMeta(a_BlockX, a_BlockY, a_BlockZ, Meta);
if (Meta & 0x08)
{
a_World->BroadcastSoundEffect("random.click", a_BlockX * 8, a_BlockY * 8, a_BlockZ * 8, 0.5f, 0.6f);
}
else
{
a_World->BroadcastSoundEffect("random.click", a_BlockX * 8, a_BlockY * 8, a_BlockZ * 8, 0.5f, 0.5f);
}
a_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, m_BlockType, Meta);
a_World->BroadcastSoundEffect("random.click", a_BlockX * 8, a_BlockY * 8, a_BlockZ * 8, 0.5f, (Meta & 0x08) ? 0.6f : 0.5f);
}

View File

@ -1,7 +1,6 @@
#pragma once
#include "BlockHandler.h"
#include "../Simulator/RedstoneSimulator.h"
@ -37,11 +36,27 @@ public:
) override
{
a_BlockType = m_BlockType;
a_BlockMeta = cRedstoneSimulator::LeverDirectionToMetaData(a_BlockFace);
a_BlockMeta = LeverDirectionToMetaData(a_BlockFace);
return true;
}
inline static NIBBLETYPE LeverDirectionToMetaData(char a_Dir)
{
// Determine lever direction:
switch (a_Dir)
{
case BLOCK_FACE_TOP: return 0x6;
case BLOCK_FACE_EAST: return 0x1;
case BLOCK_FACE_WEST: return 0x2;
case BLOCK_FACE_SOUTH: return 0x3;
case BLOCK_FACE_NORTH: return 0x4;
case BLOCK_FACE_BOTTOM: return 0x0;
default: return 0x6;
}
}
virtual const char * GetStepSound(void) override
{
return "step.wood";

View File

@ -1,7 +1,6 @@
#include "Globals.h"
#include "BlockRedstoneRepeater.h"
#include "../Simulator/RedstoneSimulator.h"
#include "../Entities/Player.h"
@ -42,7 +41,7 @@ bool cBlockRedstoneRepeaterHandler::GetPlacementBlockTypeMeta(
)
{
a_BlockType = m_BlockType;
a_BlockMeta = cRedstoneSimulator::RepeaterRotationToMetaData(a_Player->GetRotation());
a_BlockMeta = RepeaterRotationToMetaData(a_Player->GetRotation());
return true;
}

View File

@ -48,6 +48,33 @@ public:
{
return "step.wood";
}
inline static NIBBLETYPE RepeaterRotationToMetaData(double a_Rotation)
{
a_Rotation += 90 + 45; // So its not aligned with axis
if (a_Rotation > 360)
{
a_Rotation -= 360;
}
if ((a_Rotation >= 0) && (a_Rotation < 90))
{
return 0x1;
}
else if ((a_Rotation >= 180) && (a_Rotation < 270))
{
return 0x3;
}
else if ((a_Rotation >= 90) && (a_Rotation < 180))
{
return 0x2;
}
else
{
return 0x0;
}
}
} ;

View File

@ -169,8 +169,6 @@ public:
virtual bool CanBeAt(int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override
{
char Face = MetaDataToDirection(a_Chunk.GetMeta(a_RelX, a_RelY, a_RelZ));
int BlockX = a_RelX + a_Chunk.GetPosX() * cChunkDef::Width;
int BlockZ = a_RelZ + a_Chunk.GetPosZ() * cChunkDef::Width;
AddFaceDirection(a_RelX, a_RelY, a_RelZ, Face, true);
BLOCKTYPE BlockInQuestion;

View File

@ -13,6 +13,25 @@
// Try to determine endianness:
#if ( \
defined(__i386__) || defined(__alpha__) || \
defined(__ia64) || defined(__ia64__) || \
defined(_M_IX86) || defined(_M_IA64) || \
defined(_M_ALPHA) || defined(__amd64) || \
defined(__amd64__) || defined(_M_AMD64) || \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_X64) || defined(__bfin__) || \
defined(__ARMEL__) || \
(defined(_WIN32) && defined(__ARM__) && defined(_MSC_VER)) \
)
#define IS_LITTLE_ENDIAN
#elif defined (__ARMEB__)
#define IS_BIG_ENDIAN
#else
#error Cannot determine endianness of this platform
#endif
// If a string sent over the protocol is larger than this, a warning is emitted to the console
#define MAX_STRING_SIZE (512 KiB)
@ -416,6 +435,25 @@ bool cByteBuffer::ReadVarUTF8String(AString & a_Value)
bool cByteBuffer::ReadLEInt(int & a_Value)
{
CHECK_THREAD;
CheckValid();
NEEDBYTES(4);
ReadBuf(&a_Value, 4);
#ifdef IS_BIG_ENDIAN
// Convert:
a_Value = ((a_Value >> 24) & 0xff) | ((a_Value >> 16) & 0xff00) | ((a_Value >> 8) & 0xff0000) | (a_Value & 0xff000000);
#endif
return true;
}
bool cByteBuffer::WriteChar(char a_Value)
{
CHECK_THREAD;
@ -572,6 +610,22 @@ bool cByteBuffer::WriteVarUTF8String(const AString & a_Value)
bool cByteBuffer::WriteLEInt(int a_Value)
{
CHECK_THREAD;
CheckValid();
#ifdef IS_LITTLE_ENDIAN
return WriteBuf((const char *)&a_Value, 4);
#else
int Value = ((a_Value >> 24) & 0xff) | ((a_Value >> 16) & 0xff00) | ((a_Value >> 8) & 0xff0000) | (a_Value & 0xff000000);
return WriteBuf((const char *)&Value, 4);
#endif
}
bool cByteBuffer::ReadBuf(void * a_Buffer, int a_Count)
{
CHECK_THREAD;

View File

@ -60,6 +60,7 @@ public:
bool ReadBEUTF16String16(AString & a_Value); // string length as BE short, then string as UTF-16BE
bool ReadVarInt (UInt32 & a_Value);
bool ReadVarUTF8String (AString & a_Value); // string length as VarInt, then string as UTF-8
bool ReadLEInt (int & a_Value);
/// Reads VarInt, assigns it to anything that can be assigned from an UInt32 (unsigned short, char, Byte, double, ...)
template <typename T> bool ReadVarInt(T & a_Value)
@ -85,6 +86,7 @@ public:
bool WriteBEUTF16String16(const AString & a_Value); // string length as BE short, then string as UTF-16BE
bool WriteVarInt (UInt32 a_Value);
bool WriteVarUTF8String (const AString & a_Value); // string length as VarInt, then string as UTF-8
bool WriteLEInt (int a_Value);
/// Reads a_Count bytes into a_Buffer; returns true if successful
bool ReadBuf(void * a_Buffer, int a_Count);

View File

@ -682,18 +682,18 @@ void cChunk::ProcessQueuedSetBlocks(void)
Int64 CurrTick = m_World->GetWorldAge();
for (sSetBlockQueueVector::iterator itr = m_SetBlockQueue.begin(); itr != m_SetBlockQueue.end();)
{
if (itr->m_Tick < CurrTick)
if (itr->m_Tick <= CurrTick)
{
// Current world age is bigger than/equal to target world age - delay time reached
SetBlock(itr->m_RelX, itr->m_RelY, itr->m_RelZ, itr->m_BlockType, itr->m_BlockMeta);
itr = m_SetBlockQueue.erase(itr);
}
else
{
// Not yet
++itr;
continue;
}
else
{
// Now is the time to set the block
SetBlock(itr->m_RelX, itr->m_RelY, itr->m_RelZ, itr->m_BlockType, itr->m_BlockMeta);
itr = m_SetBlockQueue.erase(itr);
}
} // for itr - m_SetBlockQueue[]
}
@ -1840,6 +1840,24 @@ bool cChunk::DoWithEntityByID(int a_EntityID, cEntityCallback & a_Callback, bool
bool cChunk::ForEachBlockEntity(cBlockEntityCallback & a_Callback)
{
// The blockentity list is locked by the parent chunkmap's CS
for (cBlockEntityList::iterator itr = m_BlockEntities.begin(), itr2 = itr; itr != m_BlockEntities.end(); itr = itr2)
{
++itr2;
if (a_Callback.Item(*itr))
{
return false;
}
} // for itr - m_BlockEntitites[]
return true;
}
bool cChunk::ForEachChest(cChestCallback & a_Callback)
{
// The blockentity list is locked by the parent chunkmap's CS
@ -1958,6 +1976,32 @@ bool cChunk::ForEachFurnace(cFurnaceCallback & a_Callback)
bool cChunk::DoWithBlockEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBlockEntityCallback & a_Callback)
{
// The blockentity list is locked by the parent chunkmap's CS
for (cBlockEntityList::iterator itr = m_BlockEntities.begin(), itr2 = itr; itr != m_BlockEntities.end(); itr = itr2)
{
++itr2;
if (((*itr)->GetPosX() != a_BlockX) || ((*itr)->GetPosY() != a_BlockY) || ((*itr)->GetPosZ() != a_BlockZ))
{
continue;
}
if (a_Callback.Item(*itr))
{
return false;
}
return true;
} // for itr - m_BlockEntitites[]
// Not found:
return false;
}
bool cChunk::DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, cChestCallback & a_Callback)
{
// The blockentity list is locked by the parent chunkmap's CS

View File

@ -6,6 +6,7 @@
#include "Simulator/FireSimulator.h"
#include "Simulator/SandSimulator.h"
#include "Simulator/RedstoneSimulator.h"
@ -206,6 +207,9 @@ public:
/// Calls the callback if the entity with the specified ID is found, with the entity object as the callback param. Returns true if entity found.
bool DoWithEntityByID(int a_EntityID, cEntityCallback & a_Callback, bool & a_CallbackResult); // Lua-accessible
/// Calls the callback for each block entity; returns true if all block entities processed, false if the callback aborted by returning true
bool ForEachBlockEntity(cBlockEntityCallback & a_Callback); // Lua-accessible
/// Calls the callback for each chest; returns true if all chests processed, false if the callback aborted by returning true
bool ForEachChest(cChestCallback & a_Callback); // Lua-accessible
@ -221,6 +225,9 @@ public:
/// Calls the callback for each furnace; returns true if all furnaces processed, false if the callback aborted by returning true
bool ForEachFurnace(cFurnaceCallback & a_Callback); // Lua-accessible
/// Calls the callback for the block entity at the specified coords; returns false if there's no block entity at those coords, true if found
bool DoWithBlockEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBlockEntityCallback & a_Callback); // Lua-acessible
/// Calls the callback for the chest at the specified coords; returns false if there's no chest at those coords, true if found
bool DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, cChestCallback & a_Callback); // Lua-acessible
@ -338,6 +345,7 @@ public:
cFluidSimulatorData * GetWaterSimulatorData(void) { return m_WaterSimulatorData; }
cFluidSimulatorData * GetLavaSimulatorData (void) { return m_LavaSimulatorData; }
cSandSimulatorChunkData & GetSandSimulatorData (void) { return m_SandSimulatorData; }
cRedstoneSimulatorChunkData & GetRedstoneSimulatorData(void) { return m_RedstoneSimulatorData; }
cBlockEntity * GetBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ);
cBlockEntity * GetBlockEntity(const Vector3i & a_BlockPos) { return GetBlockEntity(a_BlockPos.x, a_BlockPos.y, a_BlockPos.z); }
@ -407,6 +415,7 @@ private:
cFluidSimulatorData * m_WaterSimulatorData;
cFluidSimulatorData * m_LavaSimulatorData;
cSandSimulatorChunkData m_SandSimulatorData;
cRedstoneSimulatorChunkData m_RedstoneSimulatorData;
// pick up a random block of this chunk

View File

@ -1702,6 +1702,21 @@ bool cChunkMap::DoWithEntityByID(int a_UniqueID, cEntityCallback & a_Callback)
bool cChunkMap::ForEachBlockEntityInChunk(int a_ChunkX, int a_ChunkZ, cBlockEntityCallback & a_Callback)
{
cCSLock Lock(m_CSLayers);
cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, ZERO_CHUNK_Y, a_ChunkZ);
if ((Chunk == NULL) && !Chunk->IsValid())
{
return false;
}
return Chunk->ForEachBlockEntity(a_Callback);
}
bool cChunkMap::ForEachChestInChunk(int a_ChunkX, int a_ChunkZ, cChestCallback & a_Callback)
{
cCSLock Lock(m_CSLayers);
@ -1777,6 +1792,24 @@ bool cChunkMap::ForEachFurnaceInChunk(int a_ChunkX, int a_ChunkZ, cFurnaceCallba
bool cChunkMap::DoWithBlockEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBlockEntityCallback & a_Callback)
{
int ChunkX, ChunkZ;
int BlockX = a_BlockX, BlockY = a_BlockY, BlockZ = a_BlockZ;
cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ);
cCSLock Lock(m_CSLayers);
cChunkPtr Chunk = GetChunkNoGen(ChunkX, ZERO_CHUNK_Y, ChunkZ);
if ((Chunk == NULL) && !Chunk->IsValid())
{
return false;
}
return Chunk->DoWithBlockEntityAt(a_BlockX, a_BlockY, a_BlockZ, a_Callback);
}
bool cChunkMap::DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, cChestCallback & a_Callback)
{
int ChunkX, ChunkZ;

View File

@ -32,6 +32,7 @@ class cMobSpawner;
typedef std::list<cClientHandle *> cClientHandleList;
typedef cChunk * cChunkPtr;
typedef cItemCallback<cEntity> cEntityCallback;
typedef cItemCallback<cBlockEntity> cBlockEntityCallback;
typedef cItemCallback<cChestEntity> cChestCallback;
typedef cItemCallback<cDispenserEntity> cDispenserCallback;
typedef cItemCallback<cDropperEntity> cDropperCallback;
@ -191,8 +192,11 @@ public:
/// Calls the callback if the entity with the specified ID is found, with the entity object as the callback param. Returns true if entity found and callback returned false.
bool DoWithEntityByID(int a_UniqueID, cEntityCallback & a_Callback); // Lua-accessible
/// Calls the callback for each block entity in the specified chunk; returns true if all block entities processed, false if the callback aborted by returning true
bool ForEachBlockEntityInChunk(int a_ChunkX, int a_ChunkZ, cBlockEntityCallback & a_Callback); // Lua-accessible
/// Calls the callback for each chest in the specified chunk; returns true if all chests processed, false if the callback aborted by returning true
bool ForEachChestInChunk (int a_ChunkX, int a_ChunkZ, cChestCallback & a_Callback); // Lua-accessible
bool ForEachChestInChunk(int a_ChunkX, int a_ChunkZ, cChestCallback & a_Callback); // Lua-accessible
/// Calls the callback for each dispenser in the specified chunk; returns true if all dispensers processed, false if the callback aborted by returning true
bool ForEachDispenserInChunk(int a_ChunkX, int a_ChunkZ, cDispenserCallback & a_Callback);
@ -206,8 +210,11 @@ public:
/// Calls the callback for each furnace in the specified chunk; returns true if all furnaces processed, false if the callback aborted by returning true
bool ForEachFurnaceInChunk(int a_ChunkX, int a_ChunkZ, cFurnaceCallback & a_Callback); // Lua-accessible
/// Calls the callback for the block entity at the specified coords; returns false if there's no block entity at those coords, true if found
bool DoWithBlockEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBlockEntityCallback & a_Callback); // Lua-acessible
/// Calls the callback for the chest at the specified coords; returns false if there's no chest at those coords, true if found
bool DoWithChestAt (int a_BlockX, int a_BlockY, int a_BlockZ, cChestCallback & a_Callback); // Lua-acessible
bool DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, cChestCallback & a_Callback); // Lua-acessible
/// Calls the callback for the dispenser at the specified coords; returns false if there's no dispenser at those coords or callback returns true, returns true if found
bool DoWithDispenserAt(int a_BlockX, int a_BlockY, int a_BlockZ, cDispenserCallback & a_Callback); // Lua-accessible

View File

@ -260,6 +260,9 @@ void cClientHandle::Authenticate(void)
// Send health
m_Player->SendHealth();
// Send experience
m_Player->SendExperience();
// Send gamemode (1.6.1 movementSpeed):
SendGameMode(m_Player->GetGameMode());
@ -1873,6 +1876,15 @@ void cClientHandle::SendRespawn(void)
void cClientHandle::SendExperience(void)
{
m_Protocol->SendExperience();
}
void cClientHandle::SendSoundEffect(const AString & a_SoundName, int a_SrcX, int a_SrcY, int a_SrcZ, float a_Volume, float a_Pitch)
{
m_Protocol->SendSoundEffect(a_SoundName, a_SrcX, a_SrcY, a_SrcZ, a_Volume, a_Pitch);

View File

@ -120,6 +120,7 @@ public:
void SendPlayerPosition (void);
void SendPlayerSpawn (const cPlayer & a_Player);
void SendRespawn (void);
void SendExperience (void);
void SendSoundEffect (const AString & a_SoundName, int a_SrcX, int a_SrcY, int a_SrcZ, float a_Volume, float a_Pitch); // a_Src coords are Block * 8
void SendSoundParticleEffect (int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data);
void SendSpawnFallingBlock (const cFallingBlock & a_FallingBlock);

View File

@ -59,20 +59,20 @@ enum
enum eBlockFace
{
BLOCK_FACE_NONE = -1, // Interacting with no block face - swinging the item in the air
BLOCK_FACE_XM = 5, // Interacting with the X- face of the block
BLOCK_FACE_XP = 4, // Interacting with the X+ face of the block
BLOCK_FACE_XM = 4, // Interacting with the X- face of the block
BLOCK_FACE_XP = 5, // Interacting with the X+ face of the block
BLOCK_FACE_YM = 0, // Interacting with the Y- face of the block
BLOCK_FACE_YP = 1, // Interacting with the Y+ face of the block
BLOCK_FACE_ZM = 3, // Interacting with the Z- face of the block
BLOCK_FACE_ZP = 2, // Interacting with the Z+ face of the block
BLOCK_FACE_ZM = 2, // Interacting with the Z- face of the block
BLOCK_FACE_ZP = 3, // Interacting with the Z+ face of the block
// Synonyms using the (deprecated) world directions:
BLOCK_FACE_BOTTOM = BLOCK_FACE_YM, // Interacting with the bottom face of the block
BLOCK_FACE_TOP = BLOCK_FACE_YP, // Interacting with the top face of the block
BLOCK_FACE_NORTH = BLOCK_FACE_ZP, // Interacting with the northern face of the block
BLOCK_FACE_SOUTH = BLOCK_FACE_ZM, // Interacting with the southern face of the block
BLOCK_FACE_WEST = BLOCK_FACE_XP, // Interacting with the western face of the block
BLOCK_FACE_EAST = BLOCK_FACE_XM, // Interacting with the eastern face of the block
BLOCK_FACE_NORTH = BLOCK_FACE_ZM, // Interacting with the northern face of the block
BLOCK_FACE_SOUTH = BLOCK_FACE_ZP, // Interacting with the southern face of the block
BLOCK_FACE_WEST = BLOCK_FACE_XM, // Interacting with the western face of the block
BLOCK_FACE_EAST = BLOCK_FACE_XP, // Interacting with the eastern face of the block
} ;
@ -305,12 +305,12 @@ inline void AddFaceDirection(int & a_BlockX, int & a_BlockY, int & a_BlockZ, cha
{
switch (a_BlockFace)
{
case BLOCK_FACE_BOTTOM: a_BlockY--; break;
case BLOCK_FACE_TOP: a_BlockY++; break;
case BLOCK_FACE_EAST: a_BlockX++; break;
case BLOCK_FACE_WEST: a_BlockX--; break;
case BLOCK_FACE_NORTH: a_BlockZ--; break;
case BLOCK_FACE_SOUTH: a_BlockZ++; break;
case BLOCK_FACE_YP: a_BlockY++; break;
case BLOCK_FACE_YM: a_BlockY--; break;
case BLOCK_FACE_ZM: a_BlockZ--; break;
case BLOCK_FACE_ZP: a_BlockZ++; break;
case BLOCK_FACE_XP: a_BlockX++; break;
case BLOCK_FACE_XM: a_BlockX--; break;
default:
{
LOGWARNING("%s: Unknown face: %d", __FUNCTION__, a_BlockFace);
@ -323,12 +323,12 @@ inline void AddFaceDirection(int & a_BlockX, int & a_BlockY, int & a_BlockZ, cha
{
switch (a_BlockFace)
{
case BLOCK_FACE_BOTTOM: a_BlockY++; break;
case BLOCK_FACE_TOP: a_BlockY--; break;
case BLOCK_FACE_EAST: a_BlockX--; break;
case BLOCK_FACE_WEST: a_BlockX++; break;
case BLOCK_FACE_NORTH: a_BlockZ++; break;
case BLOCK_FACE_SOUTH: a_BlockZ--; break;
case BLOCK_FACE_YP: a_BlockY--; break;
case BLOCK_FACE_YM: a_BlockY++; break;
case BLOCK_FACE_ZM: a_BlockZ++; break;
case BLOCK_FACE_ZP: a_BlockZ--; break;
case BLOCK_FACE_XP: a_BlockX--; break;
case BLOCK_FACE_XM: a_BlockX++; break;
default:
{
LOGWARNING("%s: Unknown inv face: %d", __FUNCTION__, a_BlockFace);

View File

@ -66,7 +66,9 @@ cPlayer::cPlayer(cClientHandle* a_Client, const AString & a_PlayerName)
, m_EatingFinishTick(-1)
, m_IsChargingBow(false)
, m_BowCharge(0)
, m_XpTotal(0)
, m_CurrentXp(0)
, m_LifetimeTotalXp(0)
, m_bDirtyExperience(false)
{
LOGD("Created a player object for \"%s\" @ \"%s\" at %p, ID %d",
a_PlayerName.c_str(), a_Client->GetIPString().c_str(),
@ -222,6 +224,12 @@ void cPlayer::Tick(float a_Dt, cChunk & a_Chunk)
{
m_BowCharge += 1;
}
//handle updating experience
if (m_bDirtyExperience)
{
SendExperience();
}
if (m_bDirtyPosition)
{
@ -262,7 +270,7 @@ void cPlayer::Tick(float a_Dt, cChunk & a_Chunk)
int cPlayer::CalcLevelFromXp(int a_XpTotal)
short cPlayer::CalcLevelFromXp(short a_XpTotal)
{
//level 0 to 15
if(a_XpTotal <= XP_TO_LEVEL15)
@ -273,18 +281,18 @@ int cPlayer::CalcLevelFromXp(int a_XpTotal)
//level 30+
if(a_XpTotal > XP_TO_LEVEL30)
{
return (int) (151.5 + sqrt( 22952.25 - (14 * (2220 - a_XpTotal)))) / 7;
return (short) (151.5 + sqrt( 22952.25 - (14 * (2220 - a_XpTotal)))) / 7;
}
//level 16 to 30
return (int) ( 29.5 + sqrt( 870.25 - (6 * ( 360 - a_XpTotal )))) / 3;
return (short) ( 29.5 + sqrt( 870.25 - (6 * ( 360 - a_XpTotal )))) / 3;
}
int cPlayer::XpForLevel(int a_Level)
short cPlayer::XpForLevel(short a_Level)
{
//level 0 to 15
if(a_Level <= 15)
@ -295,46 +303,51 @@ int cPlayer::XpForLevel(int a_Level)
//level 30+
if(a_Level >= 31)
{
return (int) ( (3.5 * a_Level * a_Level) - (151.5 * a_Level) + 2220 );
return (short) ( (3.5 * a_Level * a_Level) - (151.5 * a_Level) + 2220 );
}
//level 16 to 30
return (int) ( (1.5 * a_Level * a_Level) - (29.5 * a_Level) + 360 );
return (short) ( (1.5 * a_Level * a_Level) - (29.5 * a_Level) + 360 );
}
int cPlayer::XpGetLevel()
short cPlayer::GetXpLevel()
{
return CalcLevelFromXp(m_XpTotal);
return CalcLevelFromXp(m_CurrentXp);
}
float cPlayer::XpGetPercentage()
float cPlayer::GetXpPercentage()
{
int currentLevel = CalcLevelFromXp(m_XpTotal);
short int currentLevel = CalcLevelFromXp(m_CurrentXp);
short int currentLevel_XpBase = XpForLevel(currentLevel);
return (float)m_XpTotal / (float)XpForLevel(1+currentLevel);
return (float)(m_CurrentXp - currentLevel_XpBase) /
(float)(XpForLevel(1+currentLevel) - currentLevel_XpBase);
}
bool cPlayer::SetExperience(int a_XpTotal)
bool cPlayer::SetCurrentExperience(short int a_CurrentXp)
{
if(!(a_XpTotal >= 0) || (a_XpTotal > (INT_MAX - m_XpTotal)))
if(!(a_CurrentXp >= 0) || (a_CurrentXp > (SHRT_MAX - m_LifetimeTotalXp)))
{
LOGWARNING("Tried to update experiece with an invalid Xp value: %d", a_XpTotal);
LOGWARNING("Tried to update experiece with an invalid Xp value: %d", a_CurrentXp);
return false; //oops, they gave us a dodgey number
}
m_XpTotal = a_XpTotal;
m_CurrentXp = a_CurrentXp;
// Set experience to be updated
m_bDirtyExperience = true;
return true;
}
@ -343,21 +356,37 @@ bool cPlayer::SetExperience(int a_XpTotal)
int cPlayer::AddExperience(int a_Xp_delta)
short cPlayer::DeltaExperience(short a_Xp_delta)
{
if(a_Xp_delta < 0)
if (a_Xp_delta > (SHRT_MAX - m_CurrentXp))
{
//value was negative, abort and report
LOGWARNING("Attempt was made to increment Xp by %d, must be positive",
// Value was bad, abort and report
LOGWARNING("Attempt was made to increment Xp by %d, which overflowed the short datatype. Ignoring.",
a_Xp_delta);
return -1; //should we instead just return the current Xp?
return -1; // Should we instead just return the current Xp?
}
LOGD("Player \"%s\" earnt %d experience", m_PlayerName.c_str(), a_Xp_delta);
m_XpTotal += a_Xp_delta;
m_CurrentXp += a_Xp_delta;
return m_XpTotal;
// Make sure they didn't subtract too much
if (m_CurrentXp < 0)
{
m_CurrentXp = 0;
}
// Update total for score calculation
if (a_Xp_delta > 0)
{
m_LifetimeTotalXp += a_Xp_delta;
}
LOGD("Player \"%s\" gained/lost %d experience, total is now: %d",
m_PlayerName.c_str(), a_Xp_delta, m_CurrentXp);
// Set experience to be updated
m_bDirtyExperience = true;
return m_CurrentXp;
}
@ -607,6 +636,19 @@ void cPlayer::SendHealth(void)
void cPlayer::SendExperience(void)
{
if (m_ClientHandle != NULL)
{
m_ClientHandle->SendExperience();
m_bDirtyExperience = false;
}
}
void cPlayer::ClearInventoryPaintSlots(void)
{
// Clear the list of slots that are being inventory-painted. Used by cWindow only
@ -759,6 +801,11 @@ void cPlayer::Respawn(void)
m_FoodLevel = MAX_FOOD_LEVEL;
m_FoodSaturationLevel = 5;
// Reset Experience
m_CurrentXp = 0;
m_LifetimeTotalXp = 0;
// ToDo: send score to client? How?
m_ClientHandle->SendRespawn();
// Extinguish the fire:
@ -1411,14 +1458,16 @@ bool cPlayer::LoadFromDisk()
SetRoll ((float)JSON_PlayerRotation[(unsigned int)2].asDouble());
}
m_Health = root.get("health", 0).asInt();
m_Health = root.get("health", 0).asInt();
m_AirLevel = root.get("air", MAX_AIR_LEVEL).asInt();
m_FoodLevel = root.get("food", MAX_FOOD_LEVEL).asInt();
m_FoodSaturationLevel = root.get("foodSaturation", MAX_FOOD_LEVEL).asDouble();
m_FoodTickTimer = root.get("foodTickTimer", 0).asInt();
m_FoodExhaustionLevel = root.get("foodExhaustion", 0).asDouble();
m_LifetimeTotalXp = (short) root.get("xpTotal", 0).asInt();
m_CurrentXp = (short) root.get("xpCurrent", 0).asInt();
SetExperience(root.get("experience", 0).asInt());
//SetExperience(root.get("experience", 0).asInt());
m_GameMode = (eGameMode) root.get("gamemode", eGameMode_NotSet).asInt();
@ -1460,7 +1509,8 @@ bool cPlayer::SaveToDisk()
root["rotation"] = JSON_PlayerRotation;
root["inventory"] = JSON_Inventory;
root["health"] = m_Health;
root["experience"] = m_XpTotal;
root["xpTotal"] = m_LifetimeTotalXp;
root["xpCurrent"] = m_CurrentXp;
root["air"] = m_AirLevel;
root["food"] = m_FoodLevel;
root["foodSaturation"] = m_FoodSaturationLevel;

View File

@ -71,21 +71,31 @@ public:
Returns true on success
"should" really only be called at init or player death, plugins excepted
*/
bool SetExperience(int a_XpTotal);
bool SetCurrentExperience(short a_XpTotal);
/* Adds Xp, "should" not inc more than MAX_EXPERIENCE_ORB_SIZE unless you're a plugin being funny, *cough* cheating
Returns the new total experience, -1 on error
/* changes Xp by Xp_delta, you "shouldn't" inc more than MAX_EXPERIENCE_ORB_SIZE
Wont't allow xp to go negative
Returns the new current experience, -1 on error
*/
int AddExperience(int a_Xp_delta);
short DeltaExperience(short a_Xp_delta);
/// Gets the experience total - XpTotal
inline int XpGetTotal(void) { return m_XpTotal; }
/// Gets the experience total - XpTotal for score on death
inline short GetXpLifetimeTotal(void) { return m_LifetimeTotalXp; }
/// Gets the currrent experience
inline short GetCurrentXp(void) { return m_CurrentXp; }
/// Gets the current level - XpLevel
int XpGetLevel(void);
short GetXpLevel(void);
/// Gets the experience bar percentage - XpP
float XpGetPercentage(void);
float GetXpPercentage(void);
/// Caculates the amount of XP needed for a given level, ref: http://minecraft.gamepedia.com/XP
static short XpForLevel(short int a_Level);
/// inverse of XpForLevel, ref: http://minecraft.gamepedia.com/XP values are as per this with pre-calculations
static short CalcLevelFromXp(short int a_CurrentXp);
// tolua_end
@ -269,6 +279,8 @@ public:
void UseEquippedItem(void);
void SendHealth(void);
void SendExperience(void);
// In UI windows, the item that the player is dragging:
bool IsDraggingItem(void) const { return !m_DraggingItem.IsEmpty(); }
@ -319,9 +331,7 @@ public:
virtual bool IsCrouched (void) const { return m_IsCrouched; }
virtual bool IsSprinting(void) const { return m_IsSprinting; }
virtual bool IsRclking (void) const { return IsEating(); }
protected:
typedef std::map< std::string, bool > PermissionMap;
PermissionMap m_ResolvedPermissions;
@ -413,17 +423,16 @@ protected:
Int64 m_EatingFinishTick;
/// Player Xp level
int m_XpTotal;
short int m_LifetimeTotalXp;
short int m_CurrentXp;
/// Caculates the Xp needed for a given level, ref: http://minecraft.gamepedia.com/XP
static int XpForLevel(int a_Level);
// flag saying we need to send a xp update to client
bool m_bDirtyExperience;
/// inverse of XpAtLevel, ref: http://minecraft.gamepedia.com/XP values are as per this with pre-calculations
static int CalcLevelFromXp(int a_XpTotal);
bool m_IsChargingBow;
int m_BowCharge;
virtual void Destroyed(void);
/// Filters out damage for creative mode

View File

@ -230,6 +230,8 @@ cProjectileEntity * cProjectileEntity::Create(eKind a_Kind, cEntity * a_Creator,
case pkSnowball: return new cThrownSnowballEntity (a_Creator, a_X, a_Y, a_Z, Speed);
case pkGhastFireball: return new cGhastFireballEntity (a_Creator, a_X, a_Y, a_Z, Speed);
case pkFireCharge: return new cFireChargeEntity (a_Creator, a_X, a_Y, a_Z, Speed);
case pkExpBottle: return new cExpBottleEntity (a_Creator, a_X, a_Y, a_Z, Speed);
case pkFirework: return new cFireworkEntity (a_Creator, a_X, a_Y, a_Z );
// TODO: the rest
}
@ -287,7 +289,11 @@ AString cProjectileEntity::GetMCAClassName(void) const
void cProjectileEntity::Tick(float a_Dt, cChunk & a_Chunk)
{
super::Tick(a_Dt, a_Chunk);
BroadcastMovementUpdate();
if (GetProjectileKind() != pkArrow) // See cArrow::Tick
{
BroadcastMovementUpdate();
}
}
@ -391,7 +397,8 @@ cArrowEntity::cArrowEntity(cEntity * a_Creator, double a_X, double a_Y, double a
m_IsCritical(false),
m_Timer(0),
m_bIsCollected(false),
m_HitBlockPos(Vector3i(0, 0, 0))
m_HitBlockPos(Vector3i(0, 0, 0)),
m_HitGroundTimer(0)
{
SetSpeed(a_Speed);
SetMass(0.1);
@ -414,7 +421,8 @@ cArrowEntity::cArrowEntity(cPlayer & a_Player, double a_Force) :
m_IsCritical((a_Force >= 1)),
m_Timer(0),
m_bIsCollected(false),
m_HitBlockPos(0, 0, 0)
m_HitBlockPos(0, 0, 0),
m_HitGroundTimer(0)
{
}
@ -440,37 +448,25 @@ bool cArrowEntity::CanPickup(const cPlayer & a_Player) const
void cArrowEntity::OnHitSolidBlock(const Vector3d & a_HitPos, char a_HitFace)
{
if (a_HitFace == BLOCK_FACE_NONE)
{
return;
}
if (a_HitFace == BLOCK_FACE_NONE) { return; }
super::OnHitSolidBlock(a_HitPos, a_HitFace);
int a_X = (int)a_HitPos.x, a_Y = (int)a_HitPos.y, a_Z = (int)a_HitPos.z;
if (a_HitFace != BLOCK_FACE_YP)
switch (a_HitFace)
{
AddFaceDirection(a_X, a_Y, a_Z, a_HitFace);
}
else if (a_HitFace == BLOCK_FACE_YP) // These conditions because xoft got a little confused on block face directions, so AddFace works with all but YP & YM
{
a_Y--;
}
else
{
a_Y++;
case BLOCK_FACE_XM: // Strangely, bounding boxes / block tracers return the actual block for these two directions, so AddFace not needed
case BLOCK_FACE_YM:
{
break;
}
default: AddFaceDirection(a_X, a_Y, a_Z, a_HitFace, true);
}
m_HitBlockPos = Vector3i(a_X, a_Y, a_Z);
// Broadcast arrow hit sound
m_World->BroadcastSoundEffect("random.bowhit", (int)GetPosX() * 8, (int)GetPosY() * 8, (int)GetPosZ() * 8, 0.5, (float)(0.75 + ((float)((GetUniqueID() * 23) % 32)) / 64));
// Broadcast the position and speed packets before teleporting:
BroadcastMovementUpdate();
// Teleport the entity to the exact hit coords:
m_World->BroadcastTeleportEntity(*this);
}
@ -542,6 +538,24 @@ void cArrowEntity::Tick(float a_Dt, cChunk & a_Chunk)
if (m_IsInGround)
{
// When an arrow hits, the client doesn't think its in the ground and keeps on moving, IF BroadcastMovementUpdate() and TeleportEntity was called during flight, AT ALL
// Fix is to simply not sync with the client and send a teleport to confirm pos after arrow has stabilised (around 1 sec after landing)
// We can afford to do this because xoft's algorithm for trajectory is near perfect, so things are pretty close anyway without sync
// Besides, this seems to be what the vanilla server does, note how arrows teleport half a second after they hit to the server position
if (m_HitGroundTimer != -1) // Sent a teleport already, don't do again
{
if (m_HitGroundTimer > 1000.f) // Send after a second, could be less, but just in case
{
m_World->BroadcastTeleportEntity(*this);
m_HitGroundTimer = -1;
}
else
{
m_HitGroundTimer += a_Dt;
}
}
int RelPosX = m_HitBlockPos.x - a_Chunk.GetPosX() * cChunkDef::Width;
int RelPosZ = m_HitBlockPos.z - a_Chunk.GetPosZ() * cChunkDef::Width;
cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(RelPosX, RelPosZ);
@ -650,6 +664,104 @@ void cThrownSnowballEntity::OnHitSolidBlock(const Vector3d & a_HitPos, char a_Hi
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cBottleOEnchantingEntity :
cExpBottleEntity::cExpBottleEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z, const Vector3d & a_Speed) :
super(pkExpBottle, a_Creator, a_X, a_Y, a_Z, 0.25, 0.25)
{
SetSpeed(a_Speed);
}
void cExpBottleEntity::OnHitSolidBlock(const Vector3d & a_HitPos, char a_HitFace)
{
// TODO: Spawn experience orbs
Destroy();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cFireworkEntity :
cFireworkEntity::cFireworkEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z) :
super(pkFirework, a_Creator, a_X, a_Y, a_Z, 0.25, 0.25)
{
}
void cFireworkEntity::OnHitSolidBlock(const Vector3d & a_HitPos, char a_HitFace)
{
if ((a_HitFace != BLOCK_FACE_BOTTOM) && (a_HitFace != BLOCK_FACE_NONE))
{
return;
}
SetSpeed(0, 0, 0);
SetPosition(GetPosX(), GetPosY() - 0.5, GetPosZ());
std::cout << a_HitPos.x << " " << a_HitPos.y << " " << a_HitPos.z << std::endl;
m_IsInGround = true;
BroadcastMovementUpdate();
}
void cFireworkEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk)
{
if (m_IsInGround)
{
if (a_Chunk.GetBlock((int)GetPosX(), (int)GetPosY() + 1, (int)GetPosZ()) == E_BLOCK_AIR)
{
m_IsInGround = false;
}
else
{
return;
}
}
Vector3d PerTickSpeed = GetSpeed() / 20;
Vector3d Pos = GetPosition();
// Trace the tick's worth of movement as a line:
Vector3d NextPos = Pos + PerTickSpeed;
cProjectileTracerCallback TracerCallback(this);
if (!cLineBlockTracer::Trace(*m_World, TracerCallback, Pos, NextPos))
{
// Something has been hit, abort all other processing
return;
}
// The tracer also checks the blocks for slowdown blocks - water and lava - and stores it for later in its SlowdownCoeff
// Update the position:
SetPosition(NextPos);
// Add slowdown and gravity effect to the speed:
Vector3d NewSpeed(GetSpeed());
NewSpeed.y += 2;
NewSpeed *= TracerCallback.GetSlowdownCoeff();
SetSpeed(NewSpeed);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cGhastFireballEntity :

View File

@ -34,6 +34,7 @@ public:
pkEnderPearl = 65,
pkExpBottle = 75,
pkSplashPotion = 73,
pkFirework = 76,
pkWitherSkull = 66,
pkFishingFloat = 90,
} ;
@ -83,7 +84,7 @@ protected:
/// True if the projectile has hit the ground and is stuck there
bool m_IsInGround;
// cEntity overrides:
virtual void Tick(float a_Dt, cChunk & a_Chunk) override;
virtual void HandlePhysics(float a_Dt, cChunk & a_Chunk) override;
@ -159,6 +160,9 @@ protected:
/// Timer for pickup collection animation or five minute timeout
float m_Timer;
/// Timer for client arrow position confirmation via TeleportEntity
float m_HitGroundTimer;
/// If true, the arrow is in the process of being collected - don't go to anyone else
bool m_bIsCollected;
@ -260,6 +264,59 @@ protected:
class cExpBottleEntity :
public cProjectileEntity
{
typedef cProjectileEntity super;
public:
// tolua_end
CLASS_PROTODEF(cExpBottleEntity);
cExpBottleEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z, const Vector3d & a_Speed);
protected:
// cProjectileEntity overrides:
virtual void OnHitSolidBlock(const Vector3d & a_HitPos, char a_HitFace) override;
// tolua_begin
};
class cFireworkEntity :
public cProjectileEntity
{
typedef cProjectileEntity super;
public:
// tolua_end
CLASS_PROTODEF(cFireworkEntity);
cFireworkEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z);
protected:
// cProjectileEntity overrides:
virtual void OnHitSolidBlock(const Vector3d & a_HitPos, char a_HitFace) override;
virtual void HandlePhysics(float a_Dt, cChunk & a_Chunk) override;
// tolua_begin
};
class cGhastFireballEntity :
public cProjectileEntity
{

View File

@ -55,7 +55,7 @@ struct cCaveDefPoint
int m_BlockY;
int m_BlockZ;
int m_Radius;
cCaveDefPoint(int a_BlockX, int a_BlockY, int a_BlockZ, int a_Radius) :
m_BlockX(a_BlockX),
m_BlockY(a_BlockY),
@ -78,22 +78,22 @@ class cCaveTunnel
int m_MinBlockX, m_MaxBlockX;
int m_MinBlockY, m_MaxBlockY;
int m_MinBlockZ, m_MaxBlockZ;
/// Generates the shaping defpoints for the ravine, based on the ravine block coords and noise
void Randomize(cNoise & a_Noise);
/// Refines (adds and smooths) defpoints from a_Src into a_Dst; returns false if no refinement possible (segments too short)
bool RefineDefPoints(const cCaveDefPoints & a_Src, cCaveDefPoints & a_Dst);
/// Does rounds of smoothing, two passes of RefineDefPoints(), as long as they return true
void Smooth(void);
/// Linearly interpolates the points so that the maximum distance between two neighbors is max 1 block
void FinishLinear(void);
/// Calculates the bounding box of the points present
void CalcBoundingBox(void);
public:
cCaveDefPoints m_Points;
@ -102,14 +102,14 @@ public:
int a_BlockEndX, int a_BlockEndY, int a_BlockEndZ, int a_EndRadius,
cNoise & a_Noise
);
/// Carves the tunnel into the chunk specified
void ProcessChunk(
int a_ChunkX, int a_ChunkZ,
cChunkDef::BlockTypes & a_BlockTypes,
int a_ChunkX, int a_ChunkZ,
cChunkDef::BlockTypes & a_BlockTypes,
cChunkDef::HeightMap & a_HeightMap
);
#ifdef _DEBUG
AString ExportAsSVG(int a_Color, int a_OffsetX, int a_OffsetZ) const;
#endif // _DEBUG
@ -128,17 +128,17 @@ public:
// The generating block position; is read directly in cStructGenWormNestCaves::GetCavesForChunk()
int m_BlockX;
int m_BlockZ;
cCaveSystem(int a_BlockX, int a_BlockZ, int a_MaxOffset, int a_Size, cNoise & a_Noise);
~cCaveSystem();
/// Carves the cave system into the chunk specified
void ProcessChunk(
int a_ChunkX, int a_ChunkZ,
cChunkDef::BlockTypes & a_BlockTypes,
int a_ChunkX, int a_ChunkZ,
cChunkDef::BlockTypes & a_BlockTypes,
cChunkDef::HeightMap & a_HeightMap
);
#ifdef _DEBUG
AString ExportAsSVG(int a_Color, int a_OffsetX, int a_OffsetZ) const;
#endif // _DEBUG
@ -146,15 +146,15 @@ public:
protected:
int m_Size;
cCaveTunnels m_Tunnels;
void Clear(void);
/// Generates a_Segment successive tunnels, with possible branches. Generates the same output for the same [x, y, z, a_Segments]
void GenerateTunnelsFromPoint(
int a_OriginX, int a_OriginY, int a_OriginZ,
int a_OriginX, int a_OriginY, int a_OriginZ,
cNoise & a_Noise, int a_Segments
);
/// Returns a radius based on the location provided.
int GetRadius(cNoise & a_Noise, int a_OriginX, int a_OriginY, int a_OriginZ);
} ;
@ -174,19 +174,19 @@ cCaveTunnel::cCaveTunnel(
{
m_Points.push_back(cCaveDefPoint(a_BlockStartX, a_BlockStartY, a_BlockStartZ, a_StartRadius));
m_Points.push_back(cCaveDefPoint(a_BlockEndX, a_BlockEndY, a_BlockEndZ, a_EndRadius));
if ((a_BlockStartY <= 0) && (a_BlockEndY <= 0))
{
// Don't bother detailing this cave, it's under the world anyway
return;
}
Randomize(a_Noise);
Smooth();
// We know that the linear finishing won't affect the bounding box, so let's calculate it now, as we have less data:
CalcBoundingBox();
FinishLinear();
}
@ -308,7 +308,7 @@ void cCaveTunnel::FinishLinear(void)
// For each segment, use Bresenham's 3D line algorithm to draw a "line" of defpoints
cCaveDefPoints Pts;
std::swap(Pts, m_Points);
m_Points.reserve(Pts.size() * 3);
int PrevX = Pts.front().m_BlockX;
int PrevY = Pts.front().m_BlockY;
@ -324,7 +324,6 @@ void cCaveTunnel::FinishLinear(void)
int sx = (PrevX < x1) ? 1 : -1;
int sy = (PrevY < y1) ? 1 : -1;
int sz = (PrevZ < z1) ? 1 : -1;
int err = dx - dz;
int R = itr->m_Radius;
if (dx >= std::max(dy, dz)) // x dominant
@ -418,7 +417,7 @@ void cCaveTunnel::FinishLinear(void)
PrevY += sy;
yd -= dz;
}
// move along z
PrevZ += sz;
xd += dx;
@ -453,8 +452,8 @@ void cCaveTunnel::CalcBoundingBox(void)
void cCaveTunnel::ProcessChunk(
int a_ChunkX, int a_ChunkZ,
cChunkDef::BlockTypes & a_BlockTypes,
int a_ChunkX, int a_ChunkZ,
cChunkDef::BlockTypes & a_BlockTypes,
cChunkDef::HeightMap & a_HeightMap
)
{
@ -462,7 +461,7 @@ void cCaveTunnel::ProcessChunk(
int BaseZ = a_ChunkZ * cChunkDef::Width;
if (
(BaseX > m_MaxBlockX) || (BaseX + cChunkDef::Width < m_MinBlockX) ||
(BaseX > m_MaxBlockX) || (BaseX + cChunkDef::Width < m_MinBlockX)
(BaseZ > m_MaxBlockZ) || (BaseZ + cChunkDef::Width < m_MinBlockZ)
)
{
// Tunnel does not intersect the chunk at all, bail out
@ -485,7 +484,7 @@ void cCaveTunnel::ProcessChunk(
// Cannot intersect, bail out early
continue;
}
// Carve out a sphere around the xyz point, m_Radius in diameter; skip 3/7 off the top and bottom:
int DifX = itr->m_BlockX - BlockStartX; // substitution for faster calc
int DifY = itr->m_BlockY;
@ -493,7 +492,7 @@ void cCaveTunnel::ProcessChunk(
int Bottom = std::max(itr->m_BlockY - 3 * itr->m_Radius / 7, 1);
int Top = std::min(itr->m_BlockY + 3 * itr->m_Radius / 7, (int)(cChunkDef::Height));
int SqRad = itr->m_Radius * itr->m_Radius;
for (int z = 0; z < cChunkDef::Width; z++) for (int x = 0; x < cChunkDef::Width; x++)
for (int z = 0; z < cChunkDef::Width; z++) for (int x = 0; x < cChunkDef::Width; x++)
{
for (int y = Bottom; y <= Top; y++)
{
@ -527,9 +526,9 @@ void cCaveTunnel::ProcessChunk(
} // for y
} // for x, z
} // for itr - m_Points[]
/*
#ifdef _DEBUG
#ifdef _DEBUG
// 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)
{
@ -587,7 +586,7 @@ cStructGenWormNestCaves::cCaveSystem::cCaveSystem(int a_BlockX, int a_BlockZ, in
int OriginX = a_BlockX + (a_Noise.IntNoise3DInt(13 * a_BlockX, 17 * a_BlockZ, 11 * i) / 19) % a_MaxOffset;
int OriginZ = a_BlockZ + (a_Noise.IntNoise3DInt(17 * a_BlockX, 13 * a_BlockZ, 11 * i) / 23) % a_MaxOffset;
int OriginY = 20 + (a_Noise.IntNoise3DInt(19 * a_BlockX, 13 * a_BlockZ, 11 * i) / 17) % 20;
// Generate three branches from the origin point:
// The tunnels generated depend on X, Y, Z and Branches,
// for the same set of numbers it generates the same offsets!
@ -613,8 +612,8 @@ cStructGenWormNestCaves::cCaveSystem::~cCaveSystem()
void cStructGenWormNestCaves::cCaveSystem::ProcessChunk(
int a_ChunkX, int a_ChunkZ,
cChunkDef::BlockTypes & a_BlockTypes,
int a_ChunkX, int a_ChunkZ,
cChunkDef::BlockTypes & a_BlockTypes,
cChunkDef::HeightMap & a_HeightMap
)
{
@ -645,14 +644,14 @@ AString cStructGenWormNestCaves::cCaveSystem::ExportAsSVG(int a_Color, int a_Off
AppendPrintf(SVG, "<path style=\"fill:none;stroke:#ff0000;stroke-width:1px;\"\nd=\"M %d,%d L %d,%d\"/>\n",
a_OffsetX + m_BlockX, a_OffsetZ + m_BlockZ - 5, a_OffsetX + m_BlockX, a_OffsetZ + m_BlockZ + 5
);
// A gray line from the base point to the first point of the ravine, for identification:
AppendPrintf(SVG, "<path style=\"fill:none;stroke:#cfcfcf;stroke-width:1px;\"\nd=\"M %d,%d L %d,%d\"/>\n",
a_OffsetX + m_BlockX, a_OffsetZ + m_BlockZ,
a_OffsetX + m_Tunnels.front()->m_Points.front().m_BlockX,
a_OffsetX + m_BlockX, a_OffsetZ + m_BlockZ,
a_OffsetX + m_Tunnels.front()->m_Points.front().m_BlockX,
a_OffsetZ + m_Tunnels.front()->m_Points.front().m_BlockZ
);
// Offset guides:
if (a_OffsetX > 0)
{
@ -666,7 +665,7 @@ AString cStructGenWormNestCaves::cCaveSystem::ExportAsSVG(int a_Color, int a_Off
a_OffsetZ, a_OffsetZ
);
}
return SVG;
}
#endif // _DEBUG
@ -689,7 +688,7 @@ void cStructGenWormNestCaves::cCaveSystem::Clear(void)
void cStructGenWormNestCaves::cCaveSystem::GenerateTunnelsFromPoint(
int a_OriginX, int a_OriginY, int a_OriginZ,
int a_OriginX, int a_OriginY, int a_OriginZ,
cNoise & a_Noise, int a_NumSegments
)
{
@ -727,7 +726,7 @@ int cStructGenWormNestCaves::cCaveSystem::GetRadius(cNoise & a_Noise, int a_Orig
// We want mapping 384 -> 3, 0 -> 19, 768 -> 19, so divide by 24 to get [0 .. 31] with center at 16, then use abs() to fold around the center
int res = 3 + abs((sum / 24) - 16);
*/
// Algorithm of choice: random value in the range of zero to random value - heavily towards zero
int res = MIN_RADIUS + (rnd >> 8) % ((rnd % (MAX_RADIUS - MIN_RADIUS)) + 1);
return res;
@ -815,7 +814,7 @@ void cStructGenWormNestCaves::GetCavesForChunk(int a_ChunkX, int a_ChunkZ, cStru
++itr;
}
} // for itr - m_Cache[]
for (int x = 0; x < NEIGHBORHOOD_SIZE; x++)
{
int RealX = (BaseX + x) * m_Grid;
@ -837,11 +836,11 @@ void cStructGenWormNestCaves::GetCavesForChunk(int a_ChunkX, int a_ChunkZ, cStru
}
}
}
// Copy a_Caves into m_Cache to the beginning:
cCaveSystems CavesCopy(a_Caves);
m_Cache.splice(m_Cache.begin(), CavesCopy, CavesCopy.begin(), CavesCopy.end());
// Trim the cache if it's too long:
if (m_Cache.size() > 100)
{
@ -855,7 +854,7 @@ void cStructGenWormNestCaves::GetCavesForChunk(int a_ChunkX, int a_ChunkZ, cStru
std::advance(itr, 100);
m_Cache.erase(itr, m_Cache.end());
}
/*
// Uncomment this block for debugging the caves' shapes in 2D using an SVG export
#ifdef _DEBUG
@ -869,7 +868,7 @@ void cStructGenWormNestCaves::GetCavesForChunk(int a_ChunkX, int a_ChunkZ, cStru
SVG.append((*itr)->ExportAsSVG(Color, 512, 512));
}
SVG.append("</svg>\n");
AString fnam;
Printf(fnam, "wnc\\%03d_%03d.svg", a_ChunkX, a_ChunkZ);
cFile File(fnam, cFile::fmWrite);
@ -905,13 +904,13 @@ static float GetMarbleNoise( float x, float y, float z, cNoise & a_Noise )
void cStructGenMarbleCaves::GenStructures(cChunkDesc & a_ChunkDesc)
{
cNoise Noise(m_Seed);
for (int z = 0; z < cChunkDef::Width; z++)
for (int z = 0; z < cChunkDef::Width; z++)
{
const float zz = (float)(a_ChunkDesc.GetChunkZ() * cChunkDef::Width + z);
for (int x = 0; x < cChunkDef::Width; x++)
{
const float xx = (float)(a_ChunkDesc.GetChunkX() * cChunkDef::Width + x);
int Top = a_ChunkDesc.GetHeight(x, z);
for (int y = 1; y < Top; ++y )
{
@ -940,18 +939,17 @@ void cStructGenMarbleCaves::GenStructures(cChunkDesc & a_ChunkDesc)
void cStructGenDualRidgeCaves::GenStructures(cChunkDesc & a_ChunkDesc)
{
for (int z = 0; z < cChunkDef::Width; z++)
for (int z = 0; z < cChunkDef::Width; z++)
{
const float zz = (float)(a_ChunkDesc.GetChunkZ() * cChunkDef::Width + z) / 10;
for (int x = 0; x < cChunkDef::Width; x++)
{
const float xx = (float)(a_ChunkDesc.GetChunkX() * cChunkDef::Width + x) / 10;
int Top = a_ChunkDesc.GetHeight(x, z);
for (int y = 1; y <= Top; ++y)
{
const float yy = (float)y / 10;
const float WaveNoise = 1;
float n1 = m_Noise1.CubicNoise3D(xx, yy, zz);
float n2 = m_Noise2.CubicNoise3D(xx, yy, zz);
float n3 = m_Noise1.CubicNoise3D(xx * 4, yy * 4, zz * 4) / 4;

View File

@ -271,7 +271,7 @@ void cChunkDesc::ReadBlockArea(cBlockArea & a_Dest, int a_MinRelX, int a_MaxRelX
a_MaxRelX += 1;
a_MaxRelY += 1;
a_MaxRelZ += 1;
// Check coords validity:
if (a_MinRelX < 0)
{
@ -314,7 +314,7 @@ void cChunkDesc::ReadBlockArea(cBlockArea & a_Dest, int a_MinRelX, int a_MaxRelX
LOGWARNING("%s: MaxRelY more than chunk height, adjusting to chunk height", __FUNCTION__);
a_MaxRelY = cChunkDef::Height - 1;
}
if (a_MinRelZ < 0)
{
LOGWARNING("%s: MinRelZ less than zero, adjusting to zero", __FUNCTION__);
@ -371,7 +371,7 @@ void cChunkDesc::ReadBlockArea(cBlockArea & a_Dest, int a_MinRelX, int a_MaxRelX
HEIGHTTYPE cChunkDesc::GetMaxHeight(void) const
{
HEIGHTTYPE MaxHeight = m_HeightMap[0];
for (int i = 1; i < ARRAYCOUNT(m_HeightMap); i++)
for (unsigned int i = 1; i < ARRAYCOUNT(m_HeightMap); i++)
{
if (m_HeightMap[i] > MaxHeight)
{
@ -398,7 +398,7 @@ void cChunkDesc::FillRelCuboid(
int MaxX = std::min(a_MaxX, cChunkDef::Width - 1);
int MaxY = std::min(a_MaxY, cChunkDef::Height - 1);
int MaxZ = std::min(a_MaxZ, cChunkDef::Width - 1);
for (int y = MinY; y <= MaxY; y++)
{
for (int z = MinZ; z <= MaxZ; z++)
@ -429,7 +429,7 @@ void cChunkDesc::ReplaceRelCuboid(
int MaxX = std::min(a_MaxX, cChunkDef::Width - 1);
int MaxY = std::min(a_MaxY, cChunkDef::Height - 1);
int MaxZ = std::min(a_MaxZ, cChunkDef::Width - 1);
for (int y = MinY; y <= MaxY; y++)
{
for (int z = MinZ; z <= MaxZ; z++)
@ -465,7 +465,7 @@ void cChunkDesc::FloorRelCuboid(
int MaxX = std::min(a_MaxX, cChunkDef::Width - 1);
int MaxY = std::min(a_MaxY, cChunkDef::Height - 1);
int MaxZ = std::min(a_MaxZ, cChunkDef::Width - 1);
for (int y = MinY; y <= MaxY; y++)
{
for (int z = MinZ; z <= MaxZ; z++)
@ -506,7 +506,7 @@ void cChunkDesc::RandomFillRelCuboid(
int MaxX = std::min(a_MaxX, cChunkDef::Width - 1);
int MaxY = std::min(a_MaxY, cChunkDef::Height - 1);
int MaxZ = std::min(a_MaxZ, cChunkDef::Width - 1);
for (int y = MinY; y <= MaxY; y++)
{
for (int z = MinZ; z <= MaxZ; z++)
@ -565,7 +565,7 @@ cBlockEntity * cChunkDesc::GetBlockEntity(int a_RelX, int a_RelY, int a_RelZ)
void cChunkDesc::CompressBlockMetas(cChunkDef::BlockNibbles & a_DestMetas)
{
const NIBBLETYPE * AreaMetas = m_BlockArea.GetBlockMetas();
for (int i = 0; i < ARRAYCOUNT(a_DestMetas); i++)
for (unsigned int i = 0; i < ARRAYCOUNT(a_DestMetas); i++)
{
a_DestMetas[i] = AreaMetas[2 * i] | (AreaMetas[2 * i + 1] << 4);
}

View File

@ -15,10 +15,10 @@
/// If the generation queue size exceeds this number, a warning will be output
const int QUEUE_WARNING_LIMIT = 1000;
const unsigned int QUEUE_WARNING_LIMIT = 1000;
/// If the generation queue size exceeds this number, chunks with no clients will be skipped
const int QUEUE_SKIP_LIMIT = 500;
const unsigned int QUEUE_SKIP_LIMIT = 500;
@ -53,7 +53,7 @@ bool cChunkGenerator::Start(cWorld * a_World, cIniFile & a_IniFile)
m_World = a_World;
m_Seed = a_IniFile.GetValueSetI("Seed", "Seed", rnd.randInt());
AString GeneratorName = a_IniFile.GetValueSet("Generator", "Generator", "Composable");
if (NoCaseCompare(GeneratorName, "Noise3D") == 0)
{
m_Generator = new cNoise3DGenerator(*this);
@ -72,9 +72,9 @@ bool cChunkGenerator::Start(cWorld * a_World, cIniFile & a_IniFile)
LOGERROR("Generator could not start, aborting the server");
return false;
}
m_Generator->Initialize(a_World, a_IniFile);
return super::Start();
}
@ -101,7 +101,7 @@ void cChunkGenerator::QueueGenerateChunk(int a_ChunkX, int a_ChunkY, int a_Chunk
{
{
cCSLock Lock(m_CS);
// Check if it is already in the queue:
for (cChunkCoordsList::iterator itr = m_Queue.begin(); itr != m_Queue.end(); ++itr)
{
@ -111,7 +111,7 @@ void cChunkGenerator::QueueGenerateChunk(int a_ChunkX, int a_ChunkY, int a_Chunk
return;
}
} // for itr - m_Queue[]
// Add to queue, issue a warning if too many:
if (m_Queue.size() >= QUEUE_WARNING_LIMIT)
{
@ -119,7 +119,7 @@ void cChunkGenerator::QueueGenerateChunk(int a_ChunkX, int a_ChunkY, int a_Chunk
}
m_Queue.push_back(cChunkCoords(a_ChunkX, a_ChunkY, a_ChunkZ));
}
m_Event.Set();
}
@ -196,7 +196,7 @@ void cChunkGenerator::Execute(void)
int NumChunksGenerated = 0; // Number of chunks generated since the queue was last empty
clock_t GenerationStart = clock(); // Clock tick when the queue started to fill
clock_t LastReportTick = clock(); // Clock tick of the last report made (so that performance isn't reported too often)
while (!m_ShouldTerminate)
{
cCSLock Lock(m_CS);
@ -219,7 +219,7 @@ void cChunkGenerator::Execute(void)
GenerationStart = clock();
LastReportTick = clock();
}
cChunkCoords coords = m_Queue.front(); // Get next coord from queue
m_Queue.erase( m_Queue.begin() ); // Remove coordinate from queue
bool SkipEnabled = (m_Queue.size() > QUEUE_SKIP_LIMIT);
@ -243,19 +243,19 @@ void cChunkGenerator::Execute(void)
// Already generated, ignore request
continue;
}
if (SkipEnabled && !m_World->HasChunkAnyClients(coords.m_ChunkX, coords.m_ChunkZ))
{
LOGWARNING("Chunk generator overloaded, skipping chunk [%d, %d]", coords.m_ChunkX, coords.m_ChunkZ);
continue;
}
LOGD("Generating chunk [%d, %d, %d]", coords.m_ChunkX, coords.m_ChunkY, coords.m_ChunkZ);
DoGenerate(coords.m_ChunkX, coords.m_ChunkY, coords.m_ChunkZ);
// Save the chunk right after generating, so that we don't have to generate it again on next run
m_World->GetStorage().QueueSaveChunk(coords.m_ChunkX, coords.m_ChunkY, coords.m_ChunkZ);
NumChunksGenerated++;
} // while (!bStop)
}
@ -269,17 +269,17 @@ void cChunkGenerator::DoGenerate(int a_ChunkX, int a_ChunkY, int a_ChunkZ)
cRoot::Get()->GetPluginManager()->CallHookChunkGenerating(m_World, a_ChunkX, a_ChunkZ, &ChunkDesc);
m_Generator->DoGenerate(a_ChunkX, a_ChunkZ, ChunkDesc);
cRoot::Get()->GetPluginManager()->CallHookChunkGenerated(m_World, a_ChunkX, a_ChunkZ, &ChunkDesc);
#ifdef _DEBUG
// Verify that the generator has produced valid data:
ChunkDesc.VerifyHeightmap();
#endif
cChunkDef::BlockNibbles BlockMetas;
ChunkDesc.CompressBlockMetas(BlockMetas);
m_World->SetChunkData(
a_ChunkX, a_ChunkZ,
a_ChunkX, a_ChunkZ,
ChunkDesc.GetBlockTypes(), BlockMetas,
NULL, NULL, // We don't have lighting, chunk will be lighted when needed
&ChunkDesc.GetHeightMap(), &ChunkDesc.GetBiomeMap(),

View File

@ -30,7 +30,7 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[biNumBiomes
/* biExtremeHills */ {16.0f, 16.0f},
/* biForest */ { 3.0f, 3.0f},
/* biTaiga */ { 1.5f, 1.5f},
/* biSwampland */ { 0.0f, 0.0f},
/* biRiver */ { 0.0f, 0.0f},
/* biNether */ { 0.0f, 0.0f}, // Unused, but must be here due to indexing
@ -81,7 +81,7 @@ void cDistortedHeightmap::Initialize(cIniFile & a_IniFile)
{
return;
}
// Read the params from the INI file:
m_SeaLevel = a_IniFile.GetValueSetI("Generator", "DistortedHeightmapSeaLevel", 62);
m_FrequencyX = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "DistortedHeightmapFrequencyX", 10);
@ -103,8 +103,8 @@ void cDistortedHeightmap::PrepareState(int a_ChunkX, int a_ChunkZ)
}
m_CurChunkX = a_ChunkX;
m_CurChunkZ = a_ChunkZ;
m_HeightGen.GenHeightMap(a_ChunkX, a_ChunkZ, m_CurChunkHeights);
UpdateDistortAmps();
GenerateHeightArray();
@ -126,13 +126,13 @@ void cDistortedHeightmap::GenerateHeightArray(void)
NOISE_DATATYPE EndY = ((NOISE_DATATYPE)(257)) / m_FrequencyY;
NOISE_DATATYPE StartZ = ((NOISE_DATATYPE)(m_CurChunkZ * cChunkDef::Width)) / m_FrequencyZ;
NOISE_DATATYPE EndZ = ((NOISE_DATATYPE)((m_CurChunkZ + 1) * cChunkDef::Width - 1)) / m_FrequencyZ;
m_NoiseDistortX.Generate3D(DistortNoiseX, DIM_X, DIM_Y, DIM_Z, StartX, EndX, StartY, EndY, StartZ, EndZ, Workspace);
m_NoiseDistortZ.Generate3D(DistortNoiseZ, DIM_X, DIM_Y, DIM_Z, StartX, EndX, StartY, EndY, StartZ, EndZ, Workspace);
// The distorted heightmap, before linear upscaling
NOISE_DATATYPE DistHei[DIM_X * DIM_Y * DIM_Z];
// Distort the heightmap using the distortion:
for (int z = 0; z < DIM_Z; z++)
{
@ -151,7 +151,7 @@ void cDistortedHeightmap::GenerateHeightArray(void)
}
}
}
// Upscale the distorted heightmap into full dimensions:
LinearUpscale3DArray(
DistHei, DIM_X, DIM_Y, DIM_Z,
@ -208,7 +208,7 @@ void cDistortedHeightmap::ComposeTerrain(cChunkDesc & a_ChunkDesc)
// Prepare the internal state for generating this chunk:
PrepareState(a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ());
// Compose:
a_ChunkDesc.FillBlocks(E_BLOCK_AIR, 0);
for (int z = 0; z < cChunkDef::Width; z++)
@ -348,7 +348,7 @@ int cDistortedHeightmap::GetHeightmapAt(NOISE_DATATYPE a_X, NOISE_DATATYPE a_Z)
{
return cChunkDef::GetHeight(m_CurChunkHeights, RelX, RelZ);
}
// Ask the cache:
HEIGHTTYPE res = 0;
if (m_HeightGen.GetHeightAt(ChunkX, ChunkZ, RelX, RelZ, res))
@ -356,7 +356,7 @@ int cDistortedHeightmap::GetHeightmapAt(NOISE_DATATYPE a_X, NOISE_DATATYPE a_Z)
// The height was in the cache
return res;
}
// The height is not in the cache, generate full heightmap and get it there:
cChunkDef::HeightMap Heightmap;
m_HeightGen.GenHeightMap(ChunkX, ChunkZ, Heightmap);
@ -385,7 +385,7 @@ void cDistortedHeightmap::UpdateDistortAmps(void)
GetDistortAmpsAt(Biomes, x * INTERPOL_X, z * INTERPOL_Z, m_DistortAmpX[x + DIM_X * z], m_DistortAmpZ[x + DIM_X * z]);
}
}
}
}
@ -430,7 +430,7 @@ void cDistortedHeightmap::GetDistortAmpsAt(BiomeNeighbors & a_Neighbors, int a_R
// For each biome type that has a nonzero count, calc its amps and add it:
NOISE_DATATYPE AmpX = 0;
NOISE_DATATYPE AmpZ = 0;
for (int i = 0; i < ARRAYCOUNT(BiomeCounts); i++)
for (unsigned int i = 0; i < ARRAYCOUNT(BiomeCounts); i++)
{
AmpX += BiomeCounts[i] * m_GenParam[i].m_DistortAmpX;
AmpZ += BiomeCounts[i] * m_GenParam[i].m_DistortAmpZ;

View File

@ -18,7 +18,7 @@ enum
INTERPOL_X = 4,
INTERPOL_Y = 4,
INTERPOL_Z = 4,
// Size of chunk data, downscaled before interpolation:
DIM_X = 16 / INTERPOL_X + 1,
DIM_Y = 256 / INTERPOL_Y + 1,
@ -59,7 +59,7 @@ void cEndGen::Initialize(cIniFile & a_IniFile)
m_FrequencyX = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "EndGenFrequencyX", m_FrequencyX);
m_FrequencyY = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "EndGenFrequencyY", m_FrequencyY);
m_FrequencyZ = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "EndGenFrequencyZ", m_FrequencyZ);
// Recalculate the min and max chunk coords of the island
m_MaxChunkX = (m_IslandSizeX + cChunkDef::Width - 1) / cChunkDef::Width;
m_MinChunkX = -m_MaxChunkX;
@ -75,15 +75,15 @@ void cEndGen::Initialize(cIniFile & a_IniFile)
void cEndGen::PrepareState(int a_ChunkX, int a_ChunkZ)
{
ASSERT(!IsChunkOutsideRange(a_ChunkX, a_ChunkZ)); // Should be filtered before calling this function
if ((m_LastChunkX == a_ChunkX) && (m_LastChunkZ == a_ChunkZ))
{
return;
}
m_LastChunkX = a_ChunkX;
m_LastChunkZ = a_ChunkZ;
GenerateNoiseArray();
}
@ -96,7 +96,7 @@ void cEndGen::GenerateNoiseArray(void)
{
NOISE_DATATYPE NoiseData[DIM_X * DIM_Y * DIM_Z]; // [x + DIM_X * z + DIM_X * DIM_Z * y]
NOISE_DATATYPE Workspace[DIM_X * DIM_Y * DIM_Z]; // [x + DIM_X * z + DIM_X * DIM_Z * y]
// Generate the downscaled noise:
NOISE_DATATYPE StartX = ((NOISE_DATATYPE)(m_LastChunkX * cChunkDef::Width)) / m_FrequencyX;
NOISE_DATATYPE EndX = ((NOISE_DATATYPE)((m_LastChunkX + 1) * cChunkDef::Width)) / m_FrequencyX;
@ -105,7 +105,7 @@ void cEndGen::GenerateNoiseArray(void)
NOISE_DATATYPE StartY = 0;
NOISE_DATATYPE EndY = ((NOISE_DATATYPE)257) / m_FrequencyY;
m_Perlin.Generate3D(NoiseData, DIM_X, DIM_Z, DIM_Y, StartX, EndX, StartZ, EndZ, StartY, EndY, Workspace);
// Add distance:
int idx = 0;
for (int y = 0; y < DIM_Y; y++)
@ -125,7 +125,7 @@ void cEndGen::GenerateNoiseArray(void)
} // for x
} // for z
} // for y
// Upscale into real chunk size:
LinearUpscale3DArray(NoiseData, DIM_X, DIM_Z, DIM_Y, m_NoiseArray, INTERPOL_X, INTERPOL_Z, INTERPOL_Y);
}
@ -133,14 +133,14 @@ void cEndGen::GenerateNoiseArray(void)
/// Returns true if the chunk is outside of the island's dimensions
bool cEndGen::IsChunkOutsideRange(int a_ChunkX, int a_ChunkZ)
{
return (
(a_ChunkX < m_MinChunkX) || (a_ChunkX > m_MaxChunkX) ||
(a_ChunkZ < m_MinChunkZ) || (a_ChunkZ > m_MaxChunkZ)
);
);
}
@ -151,15 +151,15 @@ void cEndGen::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_
{
if (IsChunkOutsideRange(a_ChunkX, a_ChunkZ))
{
for (int i = 0; i < ARRAYCOUNT(a_HeightMap); i++)
for (unsigned int i = 0; i < ARRAYCOUNT(a_HeightMap); i++)
{
a_HeightMap[i] = 0;
}
return;
}
PrepareState(a_ChunkX, a_ChunkZ);
int MaxY = std::min((int)(1.75 * m_IslandSizeY + 1), cChunkDef::Height - 1);
for (int z = 0; z < cChunkDef::Width; z++)
{
@ -189,9 +189,9 @@ void cEndGen::ComposeTerrain(cChunkDesc & a_ChunkDesc)
a_ChunkDesc.FillBlocks(E_BLOCK_AIR, 0);
return;
}
PrepareState(a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ());
int MaxY = std::min((int)(1.75 * m_IslandSizeY + 1), cChunkDef::Height - 1);
for (int z = 0; z < cChunkDef::Width; z++)
{

View File

@ -41,8 +41,8 @@ public:
mskCrossing,
mskStaircase,
} ;
enum eDirection
{
dirXP,
@ -50,8 +50,8 @@ public:
dirXM,
dirZM,
} ;
cStructGenMineShafts::cMineShaftSystem & m_ParentSystem;
eKind m_Kind;
cCuboid m_BoundingBox;
@ -62,25 +62,25 @@ public:
m_Kind(a_Kind)
{
}
cMineShaft(cStructGenMineShafts::cMineShaftSystem & a_ParentSystem, eKind a_Kind, const cCuboid & a_BoundingBox) :
m_ParentSystem(a_ParentSystem),
m_Kind(a_Kind),
m_BoundingBox(a_BoundingBox)
{
}
/// Returns true if this mineshaft intersects the specified cuboid
bool DoesIntersect(const cCuboid & a_Other)
{
return m_BoundingBox.DoesIntersect(a_Other);
}
/** If recursion level is not too large, appends more branches to the parent system,
using exit points specific to this class.
*/
virtual void AppendBranches(int a_RecursionLevel, cNoise & a_Noise) = 0;
/// Imprints this shape into the specified chunk's data
virtual void ProcessChunk(cChunkDesc & a_ChunkDesc) = 0;
} ;
@ -95,10 +95,10 @@ class cMineShaftDirtRoom :
public cMineShaft
{
typedef cMineShaft super;
public:
cMineShaftDirtRoom(cStructGenMineShafts::cMineShaftSystem & a_Parent, cNoise & a_Noise);
// cMineShaft overrides:
virtual void AppendBranches(int a_RecursionLevel, cNoise & a_Noise) override;
virtual void ProcessChunk(cChunkDesc & a_ChunkDesc) override;
@ -112,7 +112,7 @@ class cMineShaftCorridor :
public cMineShaft
{
typedef cMineShaft super;
public:
/** Creates a new Corridor attached to the specified pivot point and direction.
Checks all ParentSystem's objects and disallows intersecting. Initializes the new object to fit.
@ -123,36 +123,36 @@ public:
int a_PivotX, int a_PivotY, int a_PivotZ, eDirection a_Direction,
cNoise & a_Noise
);
protected:
static const int MAX_SEGMENTS = 5;
int m_NumSegments;
eDirection m_Direction;
bool m_HasFullBeam[MAX_SEGMENTS]; ///< If true, segment at that index has a full beam support (planks in the top center block)
int m_ChestPosition; ///< If <0, no chest; otherwise an offset from m_BoundingBox's p1.x or p1.z, depenging on m_Direction
int m_SpawnerPosition; ///< If <0, no spawner; otherwise an offset from m_BoundingBox's p1.x or p1.z, depenging on m_Direction
bool m_HasTracks; ///< If true, random tracks will be placed on the floor
cMineShaftCorridor(
cStructGenMineShafts::cMineShaftSystem & a_ParentSystem,
const cCuboid & a_BoundingBox, int a_NumSegments, eDirection a_Direction,
cNoise & a_Noise
);
// cMineShaft overrides:
virtual void AppendBranches(int a_RecursionLevel, cNoise & a_Noise) override;
virtual void ProcessChunk(cChunkDesc & a_ChunkDesc) override;
/// Places a chest, if the corridor has one
void PlaceChest(cChunkDesc & a_ChunkDesc);
/// If this corridor has tracks, places them randomly
void PlaceTracks(cChunkDesc & a_ChunkDesc);
/// If this corridor has a spawner, places the spawner
void PlaceSpawner(cChunkDesc & a_ChunkDesc);
/// Randomly places torches around the central beam block
void PlaceTorches(cChunkDesc & a_ChunkDesc);
} ;
@ -165,7 +165,7 @@ class cMineShaftCrossing :
public cMineShaft
{
typedef cMineShaft super;
public:
/** Creates a new Crossing attached to the specified pivot point and direction.
Checks all ParentSystem's objects and disallows intersecting. Initializes the new object to fit.
@ -176,10 +176,10 @@ public:
int a_PivotX, int a_PivotY, int a_PivotZ, eDirection a_Direction,
cNoise & a_Noise
);
protected:
cMineShaftCrossing(cStructGenMineShafts::cMineShaftSystem & a_ParentSystem, const cCuboid & a_BoundingBox);
// cMineShaft overrides:
virtual void AppendBranches(int a_RecursionLevel, cNoise & a_Noise) override;
virtual void ProcessChunk(cChunkDesc & a_ChunkDesc) override;
@ -193,14 +193,14 @@ class cMineShaftStaircase :
public cMineShaft
{
typedef cMineShaft super;
public:
enum eSlope
{
sUp,
sDown,
} ;
/** Creates a new Staircase attached to the specified pivot point and direction.
Checks all ParentSystem's objects and disallows intersecting. Initializes the new object to fit.
May return NULL if cannot fit.
@ -210,12 +210,12 @@ public:
int a_PivotX, int a_PivotY, int a_PivotZ, eDirection a_Direction,
cNoise & a_Noise
);
protected:
eDirection m_Direction;
eSlope m_Slope;
cMineShaftStaircase(
cStructGenMineShafts::cMineShaftSystem & a_ParentSystem,
const cCuboid & a_BoundingBox,
@ -257,7 +257,7 @@ public:
/// Carves the system into the chunk data
void ProcessChunk(cChunkDesc & a_Chunk);
/** Creates new cMineShaft descendant connected at the specified point, heading the specified direction,
if it fits, appends it to the list and calls its AppendBranches()
*/
@ -266,7 +266,7 @@ public:
cMineShaft::eDirection a_Direction, cNoise & a_Noise,
int a_RecursionLevel
);
/// Returns true if none of the objects in m_MineShafts intersect with the specified bounding box and the bounding box is valid
bool CanAppend(const cCuboid & a_BoundingBox);
} ;
@ -294,7 +294,7 @@ cStructGenMineShafts::cMineShaftSystem::cMineShaftSystem(
m_ChanceTorch(1000) // TODO: settable
{
m_MineShafts.reserve(100);
cMineShaft * Start = new cMineShaftDirtRoom(*this, a_Noise);
m_MineShafts.push_back(Start);
@ -302,9 +302,9 @@ cStructGenMineShafts::cMineShaftSystem::cMineShaftSystem(
Start->m_BoundingBox.p1.x - a_MaxSystemSize / 2, 2, Start->m_BoundingBox.p1.z - a_MaxSystemSize / 2,
Start->m_BoundingBox.p2.x + a_MaxSystemSize / 2, 50, Start->m_BoundingBox.p2.z + a_MaxSystemSize / 2
);
Start->AppendBranches(0, a_Noise);
for (cMineShafts::const_iterator itr = m_MineShafts.begin(), end = m_MineShafts.end(); itr != end; ++itr)
{
ASSERT((*itr)->m_BoundingBox.IsSorted());
@ -341,7 +341,7 @@ void cStructGenMineShafts::cMineShaftSystem::ProcessChunk(cChunkDesc & a_Chunk)
void cStructGenMineShafts::cMineShaftSystem::AppendBranch(
int a_PivotX, int a_PivotY, int a_PivotZ,
int a_PivotX, int a_PivotY, int a_PivotZ,
cMineShaft::eDirection a_Direction, cNoise & a_Noise,
int a_RecursionLevel
)
@ -350,7 +350,7 @@ void cStructGenMineShafts::cMineShaftSystem::AppendBranch(
{
return;
}
cMineShaft * Next = NULL;
int rnd = (a_Noise.IntNoise3DInt(a_PivotX, a_PivotY + a_RecursionLevel * 16, a_PivotZ) / 13) % m_ProbLevelStaircase;
if (rnd < m_ProbLevelCorridor)
@ -384,7 +384,7 @@ bool cStructGenMineShafts::cMineShaftSystem::CanAppend(const cCuboid & a_Boundin
// Too far away, or too low / too high
return false;
}
// Check intersections:
for (cMineShafts::const_iterator itr = m_MineShafts.begin(), end = m_MineShafts.end(); itr != end; ++itr)
{
@ -436,7 +436,7 @@ void cMineShaftDirtRoom::AppendBranches(int a_RecursionLevel, cNoise & a_Noise)
rnd >>= 4;
m_ParentSystem.AppendBranch(x, m_BoundingBox.p1.y + (rnd % Height), m_BoundingBox.p2.z + 1, dirZP, a_Noise, a_RecursionLevel);
}
for (int z = m_BoundingBox.p1.z + 1; z < m_BoundingBox.p2.z; z += 4)
{
int rnd = a_Noise.IntNoise3DInt(m_BoundingBox.p1.x, a_RecursionLevel, z) / 13;
@ -464,13 +464,13 @@ void cMineShaftDirtRoom::ProcessChunk(cChunkDesc & a_ChunkDesc)
// Early bailout - cannot intersect this chunk
return;
}
// Chunk-relative coords of the boundaries:
int MinX = std::max(BlockX, m_BoundingBox.p1.x) - BlockX;
int MaxX = std::min(BlockX + cChunkDef::Width, m_BoundingBox.p2.x + 1) - BlockX;
int MinZ = std::max(BlockZ, m_BoundingBox.p1.z) - BlockZ;
int MaxZ = std::min(BlockZ + cChunkDef::Width, m_BoundingBox.p2.z + 1) - BlockZ;
// Carve the room out:
for (int z = MinZ; z < MaxZ; z++)
{
@ -513,7 +513,7 @@ cMineShaftCorridor::cMineShaftCorridor(
rnd >>= 2;
}
m_HasTracks = ((rnd % 4) < 2); // 50 % chance of tracks
rnd = a_Noise.IntNoise3DInt(a_BoundingBox.p1.z, a_BoundingBox.p1.x, a_BoundingBox.p1.y) / 7;
int ChestCheck = rnd % 250;
rnd >>= 8;
@ -597,7 +597,7 @@ void cMineShaftCorridor::AppendBranches(int a_RecursionLevel, cNoise & a_Noise)
}
break;
}
case dirZM:
{
m_ParentSystem.AppendBranch(m_BoundingBox.p1.x + 1, Height, m_BoundingBox.p1.z - 1, dirZM, a_Noise, a_RecursionLevel);
@ -646,14 +646,14 @@ void cMineShaftCorridor::ProcessChunk(cChunkDesc & a_ChunkDesc)
Top.p2.y += 1;
Top.p1.y = Top.p2.y;
a_ChunkDesc.FillRelCuboid(RelBoundingBox, E_BLOCK_AIR, 0);
a_ChunkDesc.RandomFillRelCuboid(Top, E_BLOCK_AIR, 0, BlockX ^ BlockZ + BlockX, 8000);
a_ChunkDesc.RandomFillRelCuboid(Top, E_BLOCK_AIR, 0, (BlockX ^ (BlockZ + BlockX)), 8000);
if (m_SpawnerPosition >= 0)
{
// Cobwebs around the spider spawner
a_ChunkDesc.RandomFillRelCuboid(RelBoundingBox, E_BLOCK_COBWEB, 0, BlockX ^ BlockZ + BlockZ, 8000);
a_ChunkDesc.RandomFillRelCuboid(Top, E_BLOCK_COBWEB, 0, BlockX ^ BlockZ + BlockX, 5000);
a_ChunkDesc.RandomFillRelCuboid(RelBoundingBox, E_BLOCK_COBWEB, 0, (BlockX ^ (BlockZ + BlockZ)), 8000);
a_ChunkDesc.RandomFillRelCuboid(Top, E_BLOCK_COBWEB, 0, (BlockX ^ (BlockZ + BlockX)), 5000);
}
a_ChunkDesc.RandomFillRelCuboid(Top, E_BLOCK_COBWEB, 0, BlockX ^ BlockZ + BlockX + 10, 500);
a_ChunkDesc.RandomFillRelCuboid(Top, E_BLOCK_COBWEB, 0, (BlockX ^ (BlockZ + BlockX + 10)), 500);
RelBoundingBox.p1.y = m_BoundingBox.p1.y;
RelBoundingBox.p2.y = m_BoundingBox.p1.y;
a_ChunkDesc.FloorRelCuboid(RelBoundingBox, E_BLOCK_PLANKS, 0);
@ -693,7 +693,7 @@ void cMineShaftCorridor::ProcessChunk(cChunkDesc & a_ChunkDesc)
} // for i - NumSegments
break;
}
case dirZM:
case dirZP:
{
@ -729,7 +729,7 @@ void cMineShaftCorridor::ProcessChunk(cChunkDesc & a_ChunkDesc)
break;
} // case dirZ?
} // for i
PlaceChest(a_ChunkDesc);
PlaceTracks(a_ChunkDesc);
PlaceSpawner(a_ChunkDesc); // (must be after Tracks!)
@ -762,7 +762,7 @@ void cMineShaftCorridor::PlaceChest(cChunkDesc & a_ChunkDesc)
{
return;
}
int BlockX = a_ChunkDesc.GetChunkX() * cChunkDef::Width;
int BlockZ = a_ChunkDesc.GetChunkZ() * cChunkDef::Width;
int x, z;
@ -777,9 +777,10 @@ void cMineShaftCorridor::PlaceChest(cChunkDesc & a_ChunkDesc)
Meta = E_META_CHEST_FACING_ZP;
break;
}
case dirZM:
case dirZP:
default:
{
x = m_BoundingBox.p1.x - BlockX;
z = m_BoundingBox.p1.z + m_ChestPosition - BlockZ;
@ -829,7 +830,7 @@ void cMineShaftCorridor::PlaceTracks(cChunkDesc & a_ChunkDesc)
Meta = E_META_TRACKS_X;
break;
}
case dirZM:
case dirZP:
{
@ -921,7 +922,7 @@ void cMineShaftCorridor::PlaceTorches(cChunkDesc & a_ChunkDesc)
} // for i
break;
}
case dirZM:
case dirZP:
{
@ -1034,14 +1035,14 @@ void cMineShaftCrossing::AppendBranches(int a_RecursionLevel, cNoise & a_Noise)
{ 5, 5, 2, dirXP},
{ 2, 5, 5, dirZP},
} ;
for (int i = 0; i < ARRAYCOUNT(Exits); i++)
for (unsigned int i = 0; i < ARRAYCOUNT(Exits); i++)
{
if (m_BoundingBox.p1.y + Exits[i].y >= m_BoundingBox.p2.y)
{
// This exit is not available (two-level exit on a one-level crossing)
continue;
}
int Height = m_BoundingBox.p1.y + Exits[i].y;
m_ParentSystem.AppendBranch(m_BoundingBox.p1.x + Exits[i].x, Height, m_BoundingBox.p1.z + Exits[i].z, Exits[i].dir, a_Noise, a_RecursionLevel);
} // for i
@ -1089,7 +1090,7 @@ void cMineShaftCrossing::ProcessChunk(cChunkDesc & a_ChunkDesc)
a_ChunkDesc.FillRelCuboid(box.p1.x + 1, box.p2.x - 1, Mid, Ceil, box.p1.z, box.p1.z, E_BLOCK_AIR, 0);
a_ChunkDesc.FillRelCuboid(box.p1.x + 1, box.p2.x - 1, Mid, Ceil, box.p2.z, box.p2.z, E_BLOCK_AIR, 0);
}
// The floor, if needed:
box.p2.y = box.p1.y;
a_ChunkDesc.FloorRelCuboid(box, E_BLOCK_PLANKS, 0);
@ -1198,7 +1199,7 @@ void cMineShaftStaircase::ProcessChunk(cChunkDesc & a_ChunkDesc)
// No intersection between this staircase and this chunk
return;
}
int SFloor = RelB.p1.y + ((m_Slope == sDown) ? 5 : 1);
int DFloor = RelB.p1.y + ((m_Slope == sDown) ? 1 : 5);
int Add = (m_Slope == sDown) ? -1 : 1;
@ -1221,7 +1222,7 @@ void cMineShaftStaircase::ProcessChunk(cChunkDesc & a_ChunkDesc)
}
break;
}
case dirXP:
{
a_ChunkDesc.FillRelCuboid (RelB.p1.x, RelB.p1.x + 1, SFloor, SFloor + 2, RelB.p1.z, RelB.p2.z, E_BLOCK_AIR, 0);
@ -1253,7 +1254,7 @@ void cMineShaftStaircase::ProcessChunk(cChunkDesc & a_ChunkDesc)
}
break;
}
case dirZP:
{
a_ChunkDesc.FillRelCuboid (RelB.p1.x, RelB.p2.x, SFloor, SFloor + 2, RelB.p1.z, RelB.p1.z + 1, E_BLOCK_AIR, 0);
@ -1269,7 +1270,7 @@ void cMineShaftStaircase::ProcessChunk(cChunkDesc & a_ChunkDesc)
}
break;
}
} // switch (m_Direction)
}
@ -1359,7 +1360,7 @@ void cStructGenMineShafts::GetMineShaftSystemsForChunk(
++itr;
}
} // for itr - m_Cache[]
for (int x = 0; x < NEIGHBORHOOD_SIZE; x++)
{
int RealX = (BaseX + x) * m_GridSize;
@ -1381,11 +1382,11 @@ void cStructGenMineShafts::GetMineShaftSystemsForChunk(
}
} // for z
} // for x
// Copy a_MineShafts into m_Cache to the beginning:
cMineShaftSystems MineShaftsCopy(a_MineShafts);
m_Cache.splice(m_Cache.begin(), MineShaftsCopy, MineShaftsCopy.begin(), MineShaftsCopy.end());
// Trim the cache if it's too long:
if (m_Cache.size() > 100)
{

View File

@ -25,8 +25,8 @@ public:
DoTest1();
DoTest2();
}
void DoTest1(void)
{
float In[3 * 3 * 3];
@ -39,8 +39,8 @@ public:
LinearUpscale3DArray(In, 3, 3, 3, Out, 8, 16, 17);
Debug3DNoise(Out, 17, 33, 35, "Upscale3D test");
}
void DoTest2(void)
{
float In[3 * 3];
@ -53,7 +53,7 @@ public:
LinearUpscale2DArray(In, 3, 3, Out, 8, 16);
Debug2DNoise(Out, 17, 33, "Upscale2D test");
}
} gTest;
//*/
@ -72,7 +72,7 @@ cNoise3DGenerator::cNoise3DGenerator(cChunkGenerator & a_ChunkGenerator) :
m_Perlin.AddOctave(1, (NOISE_DATATYPE)0.5);
m_Perlin.AddOctave((NOISE_DATATYPE)0.5, 1);
m_Perlin.AddOctave((NOISE_DATATYPE)0.5, 2);
#if 0
// DEBUG: Test the noise generation:
// NOTE: In order to be able to run MCS with this code, you need to increase the default thread stack size
@ -84,7 +84,7 @@ cNoise3DGenerator::cNoise3DGenerator(cChunkGenerator & a_ChunkGenerator) :
m_FrequencyY = 4;
m_FrequencyZ = 4;
m_AirThreshold = 0.5;
const int NumChunks = 4;
NOISE_DATATYPE Noise[NumChunks][cChunkDef::Width * cChunkDef::Width * cChunkDef::Height];
for (int x = 0; x < NumChunks; x++)
@ -153,7 +153,7 @@ cNoise3DGenerator::~cNoise3DGenerator()
void cNoise3DGenerator::Initialize(cWorld * a_World, cIniFile & a_IniFile)
{
m_World = a_World;
// Params:
m_SeaLevel = a_IniFile.GetValueSetI("Generator", "Noise3DSeaLevel", 62);
m_HeightAmplification = (NOISE_DATATYPE)a_IniFile.GetValueSetF("Generator", "Noise3DHeightAmplification", 0);
@ -170,7 +170,7 @@ void cNoise3DGenerator::Initialize(cWorld * a_World, cIniFile & a_IniFile)
void cNoise3DGenerator::GenerateBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap)
{
for (int i = 0; i < ARRAYCOUNT(a_BiomeMap); i++)
for (unsigned int i = 0; i < ARRAYCOUNT(a_BiomeMap); i++)
{
a_BiomeMap[i] = biExtremeHills;
}
@ -184,7 +184,7 @@ void cNoise3DGenerator::DoGenerate(int a_ChunkX, int a_ChunkZ, cChunkDesc & a_Ch
{
NOISE_DATATYPE Noise[17 * 257 * 17];
GenerateNoiseArray(a_ChunkX, a_ChunkZ, Noise);
// Output noise into chunk:
for (int z = 0; z < cChunkDef::Width; z++)
{
@ -207,7 +207,7 @@ void cNoise3DGenerator::DoGenerate(int a_ChunkX, int a_ChunkZ, cChunkDesc & a_Ch
}
}
}
UpdateHeightmap(a_ChunkDesc);
ComposeTerrain (a_ChunkDesc);
}
@ -228,19 +228,19 @@ void cNoise3DGenerator::GenerateNoiseArray(int a_ChunkX, int a_ChunkZ, NOISE_DAT
NOISE_DATATYPE EndZ = ((NOISE_DATATYPE)((a_ChunkZ + 1) * cChunkDef::Width) - 1) / m_FrequencyZ;
NOISE_DATATYPE StartY = 0;
NOISE_DATATYPE EndY = ((NOISE_DATATYPE)256) / m_FrequencyY;
m_Perlin.Generate3D(NoiseO, DIM_X, DIM_Y, DIM_Z, StartX, EndX, StartY, EndY, StartZ, EndZ, NoiseW);
// DEBUG: Debug3DNoise(NoiseO, DIM_X, DIM_Y, DIM_Z, Printf("Chunk_%d_%d_orig", a_ChunkX, a_ChunkZ));
// Precalculate a "height" array:
NOISE_DATATYPE Height[DIM_X * DIM_Z]; // Output for the cubic noise heightmap ("source")
m_Cubic.Generate2D(Height, DIM_X, DIM_Z, StartX / 25, EndX / 25, StartZ / 25, EndZ / 25);
for (int i = 0; i < ARRAYCOUNT(Height); i++)
for (unsigned int i = 0; i < ARRAYCOUNT(Height); i++)
{
Height[i] = abs(Height[i]) * m_HeightAmplification + 1;
}
// Modify the noise by height data:
for (int y = 0; y < DIM_Y; y++)
{
@ -257,13 +257,13 @@ void cNoise3DGenerator::GenerateNoiseArray(int a_ChunkX, int a_ChunkZ, NOISE_DAT
}
// DEBUG: Debug3DNoise(NoiseO, DIM_X, DIM_Y, DIM_Z, Printf("Chunk_%d_%d_hei", a_ChunkX, a_ChunkZ));
// Upscale the Perlin noise into full-blown chunk dimensions:
LinearUpscale3DArray(
NoiseO, DIM_X, DIM_Y, DIM_Z,
a_OutNoise, UPSCALE_X, UPSCALE_Y, UPSCALE_Z
);
// DEBUG: Debug3DNoise(a_OutNoise, 17, 257, 17, Printf("Chunk_%d_%d_lerp", a_ChunkX, a_ChunkZ));
}
@ -383,15 +383,11 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ)
}
m_LastChunkX = a_ChunkX;
m_LastChunkZ = a_ChunkZ;
// Upscaling parameters:
const int UPSCALE_X = 8;
const int UPSCALE_Y = 4;
const int UPSCALE_Z = 8;
const int DIM_X = 1 + cChunkDef::Width / UPSCALE_X;
const int DIM_Y = 1 + cChunkDef::Height / UPSCALE_Y;
const int DIM_Z = 1 + cChunkDef::Width / UPSCALE_Z;
// Precalculate a "height" array:
NOISE_DATATYPE Height[17 * 17]; // x + 17 * z
@ -405,8 +401,7 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ)
Height[x + 17 * z] = val * val * val;
}
}
int idx = 0;
for (int y = 0; y < 257; y += UPSCALE_Y)
{
NOISE_DATATYPE NoiseY = ((NOISE_DATATYPE)y) / m_FrequencyY;
@ -419,7 +414,7 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ)
for (int x = 0; x < 17; x += UPSCALE_X)
{
NOISE_DATATYPE NoiseX = ((NOISE_DATATYPE)(a_ChunkX * cChunkDef::Width + x)) / m_FrequencyX;
CurFloor[x + 17 * z] =
CurFloor[x + 17 * z] =
m_Noise1.CubicNoise3D(NoiseX, NoiseY, NoiseZ) * (NOISE_DATATYPE)0.5 +
m_Noise2.CubicNoise3D(NoiseX / 2, NoiseY / 2, NoiseZ / 2) +
m_Noise3.CubicNoise3D(NoiseX / 4, NoiseY / 4, NoiseZ / 4) * 2 +
@ -429,7 +424,7 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ)
// Linear-interpolate this XZ floor:
LinearUpscale2DArrayInPlace(CurFloor, 17, 17, UPSCALE_X, UPSCALE_Z);
}
// Finish the 3D linear interpolation by interpolating between each XZ-floors on the Y axis
for (int y = 1; y < cChunkDef::Height; y++)
{
@ -455,7 +450,7 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ)
idx += 1; // Skipping one X column
}
}
// The noise array is now fully interpolated
/*
// DEBUG: Output two images of the array, sliced by XY and XZ:
@ -504,7 +499,7 @@ void cNoise3DComposable::GenerateNoiseArrayIfNeeded(int a_ChunkX, int a_ChunkZ)
void cNoise3DComposable::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap)
{
GenerateNoiseArrayIfNeeded(a_ChunkX, a_ChunkZ);
for (int z = 0; z < cChunkDef::Width; z++)
{
for (int x = 0; x < cChunkDef::Width; x++)
@ -529,9 +524,9 @@ void cNoise3DComposable::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::Hei
void cNoise3DComposable::ComposeTerrain(cChunkDesc & a_ChunkDesc)
{
GenerateNoiseArrayIfNeeded(a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ());
a_ChunkDesc.FillBlocks(E_BLOCK_AIR, 0);
// Make basic terrain composition:
for (int z = 0; z < cChunkDef::Width; z++)
{

View File

@ -2,7 +2,7 @@
#pragma once
#include "ItemHandler.h"
#include "../Simulator/RedstoneSimulator.h"
#include "../Blocks/BlockRedstoneRepeater.h"
@ -30,7 +30,7 @@ public:
) override
{
a_BlockType = E_BLOCK_INACTIVE_COMPARATOR;
a_BlockMeta = cRedstoneSimulator::RepeaterRotationToMetaData(a_Player->GetRotation());
a_BlockMeta = cBlockRedstoneRepeaterHandler::RepeaterRotationToMetaData(a_Player->GetRotation());
return true;
}
} ;

View File

@ -90,6 +90,7 @@ cItemHandler *cItemHandler::CreateItemHandler(int a_ItemType)
case E_BLOCK_WOOL: return new cItemClothHandler(a_ItemType);
case E_ITEM_BED: return new cItemBedHandler(a_ItemType);
case E_ITEM_BOAT: return new cItemBoatHandler(a_ItemType);
case E_ITEM_BOTTLE_O_ENCHANTING: return new cItemBottleOEnchantingHandler();
case E_ITEM_BOW: return new cItemBowHandler;
case E_ITEM_BREWING_STAND: return new cItemBrewingStandHandler(a_ItemType);
case E_ITEM_CAULDRON: return new cItemCauldronHandler(a_ItemType);
@ -97,6 +98,7 @@ cItemHandler *cItemHandler::CreateItemHandler(int a_ItemType)
case E_ITEM_DYE: return new cItemDyeHandler(a_ItemType);
case E_ITEM_EGG: return new cItemEggHandler();
case E_ITEM_ENDER_PEARL: return new cItemEnderPearlHandler();
case E_ITEM_FIREWORK_ROCKET: return new cItemFireworkHandler();
case E_ITEM_FLINT_AND_STEEL: return new cItemLighterHandler(a_ItemType);
case E_ITEM_FLOWER_POT: return new cItemFlowerPotHandler(a_ItemType);
case E_ITEM_REDSTONE_DUST: return new cItemRedstoneDustHandler(a_ItemType);

View File

@ -2,7 +2,7 @@
#pragma once
#include "ItemHandler.h"
#include "../Simulator/RedstoneSimulator.h"
#include "../Blocks/BlockRedstoneRepeater.h"
@ -30,7 +30,7 @@ public:
) override
{
a_BlockType = E_BLOCK_REDSTONE_REPEATER_OFF;
a_BlockMeta = cRedstoneSimulator::RepeaterRotationToMetaData(a_Player->GetRotation());
a_BlockMeta = cBlockRedstoneRepeaterHandler::RepeaterRotationToMetaData(a_Player->GetRotation());
return true;
}
} ;

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