chore: format Minecraft.Client

This commit is contained in:
Tropical 2026-03-13 17:10:10 -05:00
parent 33d0737d1d
commit e8424f2000
531 changed files with 67709 additions and 62690 deletions

View file

@ -1,4 +1,6 @@
#include "Platform/stdafx.h" #include "Platform/stdafx.h"
#include "ClientConstants.h" #include "ClientConstants.h"
const std::wstring ClientConstants::VERSION_STRING = std::wstring(L"Minecraft Xbox ") + VER_FILEVERSION_STR_W;//+ SharedConstants::VERSION_STRING; const std::wstring ClientConstants::VERSION_STRING =
std::wstring(L"Minecraft Xbox ") +
VER_FILEVERSION_STR_W; //+ SharedConstants::VERSION_STRING;

View file

@ -1,19 +1,16 @@
#pragma once #pragma once
class ClientConstants {
// This file holds global constants used by the client.
// The file should be replaced at compile-time with the
// proper settings for the given compilation. For example,
// release builds should replace this file with no-cheat
// settings.
class ClientConstants // INTERNAL DEVELOPMENT SETTINGS
{
// This file holds global constants used by the client.
// The file should be replaced at compile-time with the
// proper settings for the given compilation. For example,
// release builds should replace this file with no-cheat
// settings.
// INTERNAL DEVELOPMENT SETTINGS
public: public:
static const std::wstring VERSION_STRING; static const std::wstring VERSION_STRING;
static const bool DEADMAU5_CAMERA_CHEATS = false; static const bool DEADMAU5_CAMERA_CHEATS = false;
static const bool IS_DEMO_VERSION = false; static const bool IS_DEMO_VERSION = false;
}; };

View file

@ -9,82 +9,90 @@
#include "../../Minecraft.World/Headers/net.minecraft.world.level.dimension.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.dimension.h"
#include "TeleportCommand.h" #include "TeleportCommand.h"
EGameCommand TeleportCommand::getId() EGameCommand TeleportCommand::getId() { return eGameCommand_Teleport; }
{
return eGameCommand_Teleport; void TeleportCommand::execute(std::shared_ptr<CommandSender> source,
byteArray commandData) {
ByteArrayInputStream bais(commandData);
DataInputStream dis(&bais);
PlayerUID subjectID = dis.readPlayerUID();
PlayerUID destinationID = dis.readPlayerUID();
bais.reset();
PlayerList* players = MinecraftServer::getInstance()->getPlayerList();
std::shared_ptr<ServerPlayer> subject = players->getPlayer(subjectID);
std::shared_ptr<ServerPlayer> destination =
players->getPlayer(destinationID);
if (subject != NULL && destination != NULL &&
subject->level->dimension->id == destination->level->dimension->id &&
subject->isAlive()) {
subject->ride(nullptr);
subject->connection->teleport(destination->x, destination->y,
destination->z, destination->yRot,
destination->xRot);
// logAdminAction(source, "commands.tp.success", subject->getAName(),
// destination->getAName());
logAdminAction(source, ChatPacket::e_ChatCommandTeleportSuccess,
subject->getName(), eTYPE_SERVERPLAYER,
destination->getName());
if (subject == source) {
destination->sendMessage(subject->getName(),
ChatPacket::e_ChatCommandTeleportToMe);
} else {
subject->sendMessage(destination->getName(),
ChatPacket::e_ChatCommandTeleportMe);
}
}
// if (args.length >= 1) {
// MinecraftServer server = MinecraftServer.getInstance();
// ServerPlayer victim;
// if (args.length == 2 || args.length == 4) {
// victim = server.getPlayers().getPlayer(args[0]);
// if (victim == null) throw new PlayerNotFoundException();
// } else {
// victim = (ServerPlayer) convertSourceToPlayer(source);
// }
// if (args.length == 3 || args.length == 4) {
// if (victim.level != null) {
// int pos = args.length - 3;
// int maxPos = Level.MAX_LEVEL_SIZE;
// int x = convertArgToInt(source, args[pos++], -maxPos,
//maxPos); int y = convertArgToInt(source, args[pos++],
//Level.minBuildHeight, Level.maxBuildHeight); int z =
//convertArgToInt(source, args[pos++], -maxPos, maxPos);
// victim.teleportTo(x + 0.5f, y, z + 0.5f);
// logAdminAction(source, "commands.tp.coordinates",
//victim.getAName(), x, y, z);
// }
// } else if (args.length == 1 || args.length == 2) {
// ServerPlayer destination =
//server.getPlayers().getPlayer(args[args.length - 1]); if (destination ==
//null) throw new PlayerNotFoundException();
// victim.connection.teleport(destination.x, destination.y,
//destination.z, destination.yRot, destination.xRot); logAdminAction(source,
//"commands.tp.success", victim.getAName(), destination.getAName());
// }
//}
} }
void TeleportCommand::execute(std::shared_ptr<CommandSender> source, byteArray commandData) std::shared_ptr<GameCommandPacket> TeleportCommand::preparePacket(
{ PlayerUID subject, PlayerUID destination) {
ByteArrayInputStream bais(commandData); ByteArrayOutputStream baos;
DataInputStream dis(&bais); DataOutputStream dos(&baos);
PlayerUID subjectID = dis.readPlayerUID(); dos.writePlayerUID(subject);
PlayerUID destinationID = dis.readPlayerUID(); dos.writePlayerUID(destination);
bais.reset();
PlayerList *players = MinecraftServer::getInstance()->getPlayerList(); return std::shared_ptr<GameCommandPacket>(
new GameCommandPacket(eGameCommand_Teleport, baos.toByteArray()));
std::shared_ptr<ServerPlayer> subject = players->getPlayer(subjectID);
std::shared_ptr<ServerPlayer> destination = players->getPlayer(destinationID);
if(subject != NULL && destination != NULL && subject->level->dimension->id == destination->level->dimension->id && subject->isAlive() )
{
subject->ride(nullptr);
subject->connection->teleport(destination->x, destination->y, destination->z, destination->yRot, destination->xRot);
//logAdminAction(source, "commands.tp.success", subject->getAName(), destination->getAName());
logAdminAction(source, ChatPacket::e_ChatCommandTeleportSuccess, subject->getName(), eTYPE_SERVERPLAYER, destination->getName());
if(subject == source)
{
destination->sendMessage(subject->getName(), ChatPacket::e_ChatCommandTeleportToMe);
}
else
{
subject->sendMessage(destination->getName(), ChatPacket::e_ChatCommandTeleportMe);
}
}
//if (args.length >= 1) {
// MinecraftServer server = MinecraftServer.getInstance();
// ServerPlayer victim;
// if (args.length == 2 || args.length == 4) {
// victim = server.getPlayers().getPlayer(args[0]);
// if (victim == null) throw new PlayerNotFoundException();
// } else {
// victim = (ServerPlayer) convertSourceToPlayer(source);
// }
// if (args.length == 3 || args.length == 4) {
// if (victim.level != null) {
// int pos = args.length - 3;
// int maxPos = Level.MAX_LEVEL_SIZE;
// int x = convertArgToInt(source, args[pos++], -maxPos, maxPos);
// int y = convertArgToInt(source, args[pos++], Level.minBuildHeight, Level.maxBuildHeight);
// int z = convertArgToInt(source, args[pos++], -maxPos, maxPos);
// victim.teleportTo(x + 0.5f, y, z + 0.5f);
// logAdminAction(source, "commands.tp.coordinates", victim.getAName(), x, y, z);
// }
// } else if (args.length == 1 || args.length == 2) {
// ServerPlayer destination = server.getPlayers().getPlayer(args[args.length - 1]);
// if (destination == null) throw new PlayerNotFoundException();
// victim.connection.teleport(destination.x, destination.y, destination.z, destination.yRot, destination.xRot);
// logAdminAction(source, "commands.tp.success", victim.getAName(), destination.getAName());
// }
//}
}
std::shared_ptr<GameCommandPacket> TeleportCommand::preparePacket(PlayerUID subject, PlayerUID destination)
{
ByteArrayOutputStream baos;
DataOutputStream dos(&baos);
dos.writePlayerUID(subject);
dos.writePlayerUID(destination);
return std::shared_ptr<GameCommandPacket>( new GameCommandPacket(eGameCommand_Teleport, baos.toByteArray() ));
} }

View file

@ -2,11 +2,12 @@
#include "../../Minecraft.World/Commands/Command.h" #include "../../Minecraft.World/Commands/Command.h"
class TeleportCommand : public Command class TeleportCommand : public Command {
{
public: public:
virtual EGameCommand getId(); virtual EGameCommand getId();
virtual void execute(std::shared_ptr<CommandSender> source, byteArray commandData); virtual void execute(std::shared_ptr<CommandSender> source,
byteArray commandData);
static std::shared_ptr<GameCommandPacket> preparePacket(PlayerUID subject, PlayerUID destination); static std::shared_ptr<GameCommandPacket> preparePacket(
PlayerUID subject, PlayerUID destination);
}; };

View file

@ -10,121 +10,91 @@
#include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.h"
#include "../../Minecraft.World/Headers/net.minecraft.world.level.tile.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.tile.h"
CreativeMode::CreativeMode(Minecraft *minecraft) : GameMode(minecraft) CreativeMode::CreativeMode(Minecraft* minecraft) : GameMode(minecraft) {
{ destroyDelay = 0;
destroyDelay = 0; instaBuild = true;
instaBuild = true;
} }
void CreativeMode::init() void CreativeMode::init() {
{ // initPlayer();
// initPlayer();
} }
void CreativeMode::enableCreativeForPlayer(std::shared_ptr<Player> player) void CreativeMode::enableCreativeForPlayer(std::shared_ptr<Player> player) {
{ // please check ServerPlayerGameMode.java if you change these
// please check ServerPlayerGameMode.java if you change these player->abilities.mayfly = true;
player->abilities.mayfly = true; player->abilities.instabuild = true;
player->abilities.instabuild = true; player->abilities.invulnerable = true;
player->abilities.invulnerable = true;
} }
void CreativeMode::disableCreativeForPlayer(std::shared_ptr<Player> player) void CreativeMode::disableCreativeForPlayer(std::shared_ptr<Player> player) {
{ player->abilities.mayfly = false;
player->abilities.mayfly = false; player->abilities.flying = false;
player->abilities.flying = false; player->abilities.instabuild = false;
player->abilities.instabuild = false; player->abilities.invulnerable = false;
player->abilities.invulnerable = false;
} }
void CreativeMode::adjustPlayer(std::shared_ptr<Player> player) void CreativeMode::adjustPlayer(std::shared_ptr<Player> player) {
{ enableCreativeForPlayer(player);
enableCreativeForPlayer(player);
for (int i = 0; i < 9; i++) for (int i = 0; i < 9; i++) {
{ if (player->inventory->items[i] == NULL) {
if (player->inventory->items[i] == NULL) player->inventory->items[i] = std::shared_ptr<ItemInstance>(
{ new ItemInstance(User::allowedTiles[i]));
player->inventory->items[i] = std::shared_ptr<ItemInstance>( new ItemInstance(User::allowedTiles[i]) ); } else {
} // 4J-PB - this line is commented out in 1.0.1
else // player->inventory->items[i]->count = 1;
{
// 4J-PB - this line is commented out in 1.0.1
//player->inventory->items[i]->count = 1;
} }
} }
} }
void CreativeMode::creativeDestroyBlock(Minecraft *minecraft, GameMode *gameMode, int x, int y, int z, int face) void CreativeMode::creativeDestroyBlock(Minecraft* minecraft,
{ GameMode* gameMode, int x, int y, int z,
if(!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) int face) {
{ if (!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) {
gameMode->destroyBlock(x, y, z, face); gameMode->destroyBlock(x, y, z, face);
} }
} }
bool CreativeMode::useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, bool bTestUseOnOnly, bool *pbUsedItem) bool CreativeMode::useItemOn(std::shared_ptr<Player> player, Level* level,
{ std::shared_ptr<ItemInstance> item, int x, int y,
int t = level->getTile(x, y, z); int z, int face, bool bTestUseOnOnly,
if (t > 0) bool* pbUsedItem) {
{ int t = level->getTile(x, y, z);
if (Tile::tiles[t]->use(level, x, y, z, player)) return true; if (t > 0) {
} if (Tile::tiles[t]->use(level, x, y, z, player)) return true;
if (item == NULL) return false; }
int aux = item->getAuxValue(); if (item == NULL) return false;
int count = item->count; int aux = item->getAuxValue();
bool success = item->useOn(player, level, x, y, z, face); int count = item->count;
item->setAuxValue(aux); bool success = item->useOn(player, level, x, y, z, face);
item->count = count; item->setAuxValue(aux);
return success; item->count = count;
return success;
} }
void CreativeMode::startDestroyBlock(int x, int y, int z, int face) void CreativeMode::startDestroyBlock(int x, int y, int z, int face) {
{ creativeDestroyBlock(minecraft, this, x, y, z, face);
creativeDestroyBlock(minecraft, this, x, y, z, face); destroyDelay = 5;
destroyDelay = 5;
} }
void CreativeMode::continueDestroyBlock(int x, int y, int z, int face) void CreativeMode::continueDestroyBlock(int x, int y, int z, int face) {
{ destroyDelay--;
destroyDelay--; if (destroyDelay <= 0) {
if (destroyDelay <= 0) destroyDelay = 5;
{ creativeDestroyBlock(minecraft, this, x, y, z, face);
destroyDelay = 5; }
creativeDestroyBlock(minecraft, this, x, y, z, face);
}
} }
void CreativeMode::stopDestroyBlock() void CreativeMode::stopDestroyBlock() {}
{
}
bool CreativeMode::canHurtPlayer() bool CreativeMode::canHurtPlayer() { return false; }
{
return false;
}
void CreativeMode::initLevel(Level *level) void CreativeMode::initLevel(Level* level) { GameMode::initLevel(level); }
{
GameMode::initLevel(level);
}
float CreativeMode::getPickRange() float CreativeMode::getPickRange() { return 5.0f; }
{
return 5.0f;
}
bool CreativeMode::hasMissTime() bool CreativeMode::hasMissTime() { return false; }
{
return false;
}
bool CreativeMode::hasInfiniteItems() bool CreativeMode::hasInfiniteItems() { return true; }
{
return true;
}
bool CreativeMode::hasFarPickRange() bool CreativeMode::hasFarPickRange() { return true; }
{
return true;
}

View file

@ -1,26 +1,29 @@
#pragma once #pragma once
#include "GameMode.h" #include "GameMode.h"
class CreativeMode : public GameMode class CreativeMode : public GameMode {
{
private: private:
int destroyDelay; int destroyDelay;
public: public:
CreativeMode(Minecraft *minecraft); CreativeMode(Minecraft* minecraft);
virtual void init(); virtual void init();
static void enableCreativeForPlayer(std::shared_ptr<Player> player); static void enableCreativeForPlayer(std::shared_ptr<Player> player);
static void disableCreativeForPlayer(std::shared_ptr<Player> player); static void disableCreativeForPlayer(std::shared_ptr<Player> player);
virtual void adjustPlayer(std::shared_ptr<Player> player); virtual void adjustPlayer(std::shared_ptr<Player> player);
static void creativeDestroyBlock(Minecraft *minecraft, GameMode *gameMode, int x, int y, int z, int face); static void creativeDestroyBlock(Minecraft* minecraft, GameMode* gameMode,
virtual bool useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, bool bTestUseOnOnly=false, bool *pbUsedItem = NULL); int x, int y, int z, int face);
virtual void startDestroyBlock(int x, int y, int z, int face); virtual bool useItemOn(std::shared_ptr<Player> player, Level* level,
virtual void continueDestroyBlock(int x, int y, int z, int face); std::shared_ptr<ItemInstance> item, int x, int y,
virtual void stopDestroyBlock(); int z, int face, bool bTestUseOnOnly = false,
virtual bool canHurtPlayer(); bool* pbUsedItem = NULL);
virtual void initLevel(Level *level); virtual void startDestroyBlock(int x, int y, int z, int face);
virtual float getPickRange(); virtual void continueDestroyBlock(int x, int y, int z, int face);
virtual bool hasMissTime(); virtual void stopDestroyBlock();
virtual bool hasInfiniteItems(); virtual bool canHurtPlayer();
virtual bool hasFarPickRange(); virtual void initLevel(Level* level);
virtual float getPickRange();
virtual bool hasMissTime();
virtual bool hasInfiniteItems();
virtual bool hasFarPickRange();
}; };

View file

@ -2,111 +2,107 @@
#include "DemoMode.h" #include "DemoMode.h"
#include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.h"
DemoMode::DemoMode(Minecraft *minecraft) : SurvivalMode(minecraft) DemoMode::DemoMode(Minecraft* minecraft) : SurvivalMode(minecraft) {
{ demoHasEnded = false;
demoHasEnded = false;
demoEndedReminder = 0; demoEndedReminder = 0;
} }
void DemoMode::tick() void DemoMode::tick() {
{
SurvivalMode::tick(); SurvivalMode::tick();
/* 4J - TODO - seems unlikely we need this demo mode anyway /* 4J - TODO - seems unlikely we need this demo mode anyway
__int64 time = minecraft->level->getTime(); __int64 time = minecraft->level->getTime();
__int64 day = (time / Level::TICKS_PER_DAY) + 1; __int64 day = (time / Level::TICKS_PER_DAY) + 1;
demoHasEnded = (time > (500 + Level::TICKS_PER_DAY * DEMO_DAYS)); demoHasEnded = (time > (500 + Level::TICKS_PER_DAY * DEMO_DAYS));
if (demoHasEnded) if (demoHasEnded)
{ {
demoEndedReminder++; demoEndedReminder++;
} }
if ((time % Level::TICKS_PER_DAY) == 500) if ((time % Level::TICKS_PER_DAY) == 500)
{ {
if (day <= (DEMO_DAYS + 1)) if (day <= (DEMO_DAYS + 1))
{ {
minecraft->gui->displayClientMessage(L"demo.day." + _toString<__int64>(day)); minecraft->gui->displayClientMessage(L"demo.day." +
_toString<__int64>(day));
}
} }
} else if (day == 1)
else if (day == 1) {
{ Options *options = minecraft->options;
Options *options = minecraft->options; std::wstring message;
std::wstring message;
if (time == 100) { if (time == 100) {
minecraft.gui.addMessage("Seed: " + minecraft.level.getSeed()); minecraft.gui.addMessage("Seed: " + minecraft.level.getSeed());
message = language.getElement("demo.help.movement"); message = language.getElement("demo.help.movement");
message = String.format(message, Keyboard.getKeyName(options.keyUp.key), Keyboard.getKeyName(options.keyLeft.key), Keyboard.getKeyName(options.keyDown.key), message = String.format(message,
Keyboard.getKeyName(options.keyRight.key)); Keyboard.getKeyName(options.keyUp.key),
} else if (time == 175) { Keyboard.getKeyName(options.keyLeft.key),
message = language.getElement("demo.help.jump"); Keyboard.getKeyName(options.keyDown.key),
message = String.format(message, Keyboard.getKeyName(options.keyJump.key)); Keyboard.getKeyName(options.keyRight.key));
} else if (time == 250) { } else if (time == 175) {
message = language.getElement("demo.help.inventory"); message = language.getElement("demo.help.jump");
message = String.format(message, Keyboard.getKeyName(options.keyBuild.key)); message = String.format(message,
Keyboard.getKeyName(options.keyJump.key)); } else if (time == 250) {
message = language.getElement("demo.help.inventory");
message = String.format(message,
Keyboard.getKeyName(options.keyBuild.key));
}
if (message != null) {
minecraft.gui.addMessage(message);
}
} else if (day == DEMO_DAYS) {
if ((time % Level.TICKS_PER_DAY) == 22000) {
minecraft.gui.displayClientMessage("demo.day.warning");
}
} }
if (message != null) { */
minecraft.gui.addMessage(message);
}
} else if (day == DEMO_DAYS) {
if ((time % Level.TICKS_PER_DAY) == 22000) {
minecraft.gui.displayClientMessage("demo.day.warning");
}
}
*/
} }
void DemoMode::outputDemoReminder() void DemoMode::outputDemoReminder() {
{ /* 4J - TODO
/* 4J - TODO if (demoEndedReminder > 100) {
if (demoEndedReminder > 100) { minecraft.gui.displayClientMessage("demo.reminder");
minecraft.gui.displayClientMessage("demo.reminder"); demoEndedReminder = 0;
demoEndedReminder = 0; }
} */
*/
} }
void DemoMode::startDestroyBlock(int x, int y, int z, int face) void DemoMode::startDestroyBlock(int x, int y, int z, int face) {
{ if (demoHasEnded) {
if (demoHasEnded)
{
outputDemoReminder(); outputDemoReminder();
return; return;
} }
SurvivalMode::startDestroyBlock(x, y, z, face); SurvivalMode::startDestroyBlock(x, y, z, face);
} }
void DemoMode::continueDestroyBlock(int x, int y, int z, int face) void DemoMode::continueDestroyBlock(int x, int y, int z, int face) {
{ if (demoHasEnded) {
if (demoHasEnded)
{
return; return;
} }
SurvivalMode::continueDestroyBlock(x, y, z, face); SurvivalMode::continueDestroyBlock(x, y, z, face);
} }
bool DemoMode::destroyBlock(int x, int y, int z, int face) bool DemoMode::destroyBlock(int x, int y, int z, int face) {
{ if (demoHasEnded) {
if (demoHasEnded)
{
return false; return false;
} }
return SurvivalMode::destroyBlock(x, y, z, face); return SurvivalMode::destroyBlock(x, y, z, face);
} }
bool DemoMode::useItem(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item) bool DemoMode::useItem(std::shared_ptr<Player> player, Level* level,
{ std::shared_ptr<ItemInstance> item) {
if (demoHasEnded) if (demoHasEnded) {
{
outputDemoReminder(); outputDemoReminder();
return false; return false;
} }
return SurvivalMode::useItem(player, level, item); return SurvivalMode::useItem(player, level, item);
} }
bool DemoMode::useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face) bool DemoMode::useItemOn(std::shared_ptr<Player> player, Level* level,
{ std::shared_ptr<ItemInstance> item, int x, int y,
int z, int face) {
if (demoHasEnded) { if (demoHasEnded) {
outputDemoReminder(); outputDemoReminder();
return false; return false;
@ -114,10 +110,9 @@ bool DemoMode::useItemOn(std::shared_ptr<Player> player, Level *level, std::shar
return SurvivalMode::useItemOn(player, level, item, x, y, z, face); return SurvivalMode::useItemOn(player, level, item, x, y, z, face);
} }
void DemoMode::attack(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity) void DemoMode::attack(std::shared_ptr<Player> player,
{ std::shared_ptr<Entity> entity) {
if (demoHasEnded) if (demoHasEnded) {
{
outputDemoReminder(); outputDemoReminder();
return; return;
} }

View file

@ -1,27 +1,32 @@
#pragma once #pragma once
#include "SurvivalMode.h" #include "SurvivalMode.h"
class DemoMode : public SurvivalMode class DemoMode : public SurvivalMode {
{
private: private:
static const int DEMO_DAYS = 5; static const int DEMO_DAYS = 5;
bool demoHasEnded; bool demoHasEnded;
int demoEndedReminder; int demoEndedReminder;
public: public:
DemoMode(Minecraft *minecraft); DemoMode(Minecraft* minecraft);
virtual void tick(); virtual void tick();
private:
void outputDemoReminder();
public:
using GameMode::useItem;
using SurvivalMode::useItemOn;
virtual void startDestroyBlock(int x, int y, int z, int face); private:
void outputDemoReminder();
public:
using GameMode::useItem;
using SurvivalMode::useItemOn;
virtual void startDestroyBlock(int x, int y, int z, int face);
virtual void continueDestroyBlock(int x, int y, int z, int face); virtual void continueDestroyBlock(int x, int y, int z, int face);
virtual bool destroyBlock(int x, int y, int z, int face); virtual bool destroyBlock(int x, int y, int z, int face);
virtual bool useItem(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item); virtual bool useItem(std::shared_ptr<Player> player, Level* level,
virtual bool useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face); std::shared_ptr<ItemInstance> item);
virtual void attack(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity); virtual bool useItemOn(std::shared_ptr<Player> player, Level* level,
std::shared_ptr<ItemInstance> item, int x, int y,
int z, int face);
virtual void attack(std::shared_ptr<Player> player,
std::shared_ptr<Entity> entity);
}; };

View file

@ -1,6 +1,4 @@
#include "../Platform/stdafx.h" #include "../Platform/stdafx.h"
#include "DemoUser.h" #include "DemoUser.h"
DemoUser::DemoUser() : User(L"DemoUser", L"n/a") DemoUser::DemoUser() : User(L"DemoUser", L"n/a") {}
{
}

View file

@ -1,8 +1,7 @@
#pragma once #pragma once
#include "../Player/User.h" #include "../Player/User.h"
class DemoUser : public User class DemoUser : public User {
{
public: public:
DemoUser(); DemoUser();
}; };

View file

@ -11,60 +11,55 @@
#include "../../Minecraft.World/Headers/net.minecraft.world.entity.player.h" #include "../../Minecraft.World/Headers/net.minecraft.world.entity.player.h"
#include "../../Minecraft.World/Headers/net.minecraft.world.level.chunk.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.chunk.h"
GameMode::GameMode(Minecraft *minecraft) GameMode::GameMode(Minecraft* minecraft) {
{ instaBuild = false; // 4J - added
instaBuild = false; // 4J - added this->minecraft = minecraft;
this->minecraft = minecraft;
} }
void GameMode::initLevel(Level *level) void GameMode::initLevel(Level* level) {}
{
}
bool GameMode::destroyBlock(int x, int y, int z, int face) bool GameMode::destroyBlock(int x, int y, int z, int face) {
{ Level* level = minecraft->level;
Level *level = minecraft->level; Tile* oldTile = Tile::tiles[level->getTile(x, y, z)];
Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; if (oldTile == NULL) return false;
if (oldTile == NULL) return false;
// 4J - Let the rendering side of thing know we are about to destroy the tile, so we can synchronise collision with async render data upates. // 4J - Let the rendering side of thing know we are about to destroy the
minecraft->levelRenderer->destroyedTileManager->destroyingTileAt(level, x, y, z); // tile, so we can synchronise collision with async render data upates.
level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); minecraft->levelRenderer->destroyedTileManager->destroyingTileAt(level, x,
y, z);
level->levelEvent(
LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z,
oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT));
int data = level->getData(x, y, z); int data = level->getData(x, y, z);
// 4J - before we remove the tile, recalc the heightmap - setTile depends on this being valid to be able to do // 4J - before we remove the tile, recalc the heightmap - setTile depends on
// a quick update of skylighting when the block is removed, and there are cases with falling tiles where this can get out of sync // this being valid to be able to do a quick update of skylighting when the
level->getChunkAt(x,z)->recalcHeightmapOnly(); // block is removed, and there are cases with falling tiles where this can
// get out of sync
level->getChunkAt(x, z)->recalcHeightmapOnly();
bool changed = level->setTile(x, y, z, 0); bool changed = level->setTile(x, y, z, 0);
if (oldTile != NULL && changed) if (oldTile != NULL && changed) {
{
oldTile->destroy(level, x, y, z, data); oldTile->destroy(level, x, y, z, data);
} }
return changed; return changed;
} }
void GameMode::render(float a) void GameMode::render(float a) {}
{
bool GameMode::useItem(std::shared_ptr<Player> player, Level* level,
std::shared_ptr<ItemInstance> item, bool bTestUseOnly) {
return false;
} }
bool GameMode::useItem(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, bool bTestUseOnly) void GameMode::initPlayer(std::shared_ptr<Player> player) {}
{
return false;
}
void GameMode::initPlayer(std::shared_ptr<Player> player) void GameMode::tick() {}
{
}
void GameMode::tick() void GameMode::adjustPlayer(std::shared_ptr<Player> player) {}
{
}
void GameMode::adjustPlayer(std::shared_ptr<Player> player) // bool GameMode::useItemOn(std::shared_ptr<Player> player, Level *level,
{ // std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, bool
} // bTestUseOnOnly)
//bool GameMode::useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, bool bTestUseOnOnly)
//{ //{
// // 4J-PB - Adding a test only version to allow tooltips to be displayed // // 4J-PB - Adding a test only version to allow tooltips to be displayed
// int t = level->getTile(x, y, z); // int t = level->getTile(x, y, z);
@ -74,9 +69,10 @@ void GameMode::adjustPlayer(std::shared_ptr<Player> player)
// { // {
// switch(t) // switch(t)
// { // {
// case Tile::recordPlayer_Id: // case Tile::recordPlayer_Id:
// case Tile::bed_Id: // special case for a bed // case Tile::bed_Id: // special case for a bed
// if (Tile::tiles[t]->TestUse(level, x, y, z, player )) // if (Tile::tiles[t]->TestUse(level, x, y, z,
//player ))
// { // {
// return true; // return true;
// } // }
@ -91,94 +87,73 @@ void GameMode::adjustPlayer(std::shared_ptr<Player> player)
// break; // break;
// } // }
// } // }
// else // else
// { // {
// if (Tile::tiles[t]->use(level, x, y, z, player )) return true; // if (Tile::tiles[t]->use(level, x, y, z, player )) return
//true;
// } // }
// } // }
// //
// if (item == NULL) return false; // if (item == NULL) return false;
// return item->useOn(player, level, x, y, z, face, bTestUseOnOnly); // return item->useOn(player, level, x, y, z, face, bTestUseOnOnly);
//} // }
std::shared_ptr<Player> GameMode::createPlayer(Level* level) {
std::shared_ptr<Player> GameMode::createPlayer(Level *level) return std::shared_ptr<Player>(new LocalPlayer(
{ minecraft, level, minecraft->user, level->dimension->id));
return std::shared_ptr<Player>( new LocalPlayer(minecraft, level, minecraft->user, level->dimension->id) );
} }
bool GameMode::interact(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity) bool GameMode::interact(std::shared_ptr<Player> player,
{ std::shared_ptr<Entity> entity) {
return player->interact(entity); return player->interact(entity);
} }
void GameMode::attack(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity) void GameMode::attack(std::shared_ptr<Player> player,
{ std::shared_ptr<Entity> entity) {
player->attack(entity); player->attack(entity);
} }
std::shared_ptr<ItemInstance> GameMode::handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr<Player> player) std::shared_ptr<ItemInstance> GameMode::handleInventoryMouseClick(
{ int containerId, int slotNum, int buttonNum, bool quickKeyHeld,
return nullptr; std::shared_ptr<Player> player) {
return nullptr;
} }
void GameMode::handleCloseInventory(int containerId, std::shared_ptr<Player> player) void GameMode::handleCloseInventory(int containerId,
{ std::shared_ptr<Player> player) {
player->containerMenu->removed(player); player->containerMenu->removed(player);
delete player->containerMenu; delete player->containerMenu;
player->containerMenu = player->inventoryMenu; player->containerMenu = player->inventoryMenu;
} }
void GameMode::handleInventoryButtonClick(int containerId, int buttonId) void GameMode::handleInventoryButtonClick(int containerId, int buttonId) {}
{
bool GameMode::isCutScene() { return false; }
void GameMode::releaseUsingItem(std::shared_ptr<Player> player) {
player->releaseUsingItem();
} }
bool GameMode::isCutScene() bool GameMode::hasExperience() { return false; }
{
return false;
}
void GameMode::releaseUsingItem(std::shared_ptr<Player> player) bool GameMode::hasMissTime() { return true; }
{
player->releaseUsingItem();
}
bool GameMode::hasExperience() bool GameMode::hasInfiniteItems() { return false; }
{
return false;
}
bool GameMode::hasMissTime() bool GameMode::hasFarPickRange() { return false; }
{
return true;
}
bool GameMode::hasInfiniteItems() void GameMode::handleCreativeModeItemAdd(std::shared_ptr<ItemInstance> clicked,
{ int i) {}
return false;
}
bool GameMode::hasFarPickRange() void GameMode::handleCreativeModeItemDrop(
{ std::shared_ptr<ItemInstance> clicked) {}
return false;
}
void GameMode::handleCreativeModeItemAdd(std::shared_ptr<ItemInstance> clicked, int i) bool GameMode::handleCraftItem(int recipe, std::shared_ptr<Player> player) {
{ return true;
}
void GameMode::handleCreativeModeItemDrop(std::shared_ptr<ItemInstance> clicked)
{
}
bool GameMode::handleCraftItem(int recipe, std::shared_ptr<Player> player)
{
return true;
} }
// 4J-PB // 4J-PB
void GameMode::handleDebugOptions(unsigned int uiVal, std::shared_ptr<Player> player) void GameMode::handleDebugOptions(unsigned int uiVal,
{ std::shared_ptr<Player> player) {
player->SetDebugOptions(uiVal); player->SetDebugOptions(uiVal);
} }

View file

@ -8,17 +8,17 @@ class Entity;
class Tutorial; class Tutorial;
class GameMode class GameMode {
{
protected: protected:
Minecraft *minecraft; Minecraft* minecraft;
public: public:
bool instaBuild; bool instaBuild;
GameMode(Minecraft *minecraft); GameMode(Minecraft* minecraft);
virtual ~GameMode() {} virtual ~GameMode() {}
virtual void initLevel(Level *level) ; virtual void initLevel(Level* level);
virtual void startDestroyBlock(int x, int y, int z, int face) = 0; virtual void startDestroyBlock(int x, int y, int z, int face) = 0;
virtual bool destroyBlock(int x, int y, int z, int face); virtual bool destroyBlock(int x, int y, int z, int face);
virtual void continueDestroyBlock(int x, int y, int z, int face) = 0; virtual void continueDestroyBlock(int x, int y, int z, int face) = 0;
@ -29,31 +29,44 @@ public:
virtual void tick(); virtual void tick();
virtual bool canHurtPlayer() = 0; virtual bool canHurtPlayer() = 0;
virtual void adjustPlayer(std::shared_ptr<Player> player); virtual void adjustPlayer(std::shared_ptr<Player> player);
virtual bool useItem(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, bool bTestUseOnly=false); virtual bool useItem(std::shared_ptr<Player> player, Level* level,
virtual bool useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, bool bTestUseOnOnly=false, bool *pbUsedItem = NULL) = 0; std::shared_ptr<ItemInstance> item,
bool bTestUseOnly = false);
virtual bool useItemOn(std::shared_ptr<Player> player, Level* level,
std::shared_ptr<ItemInstance> item, int x, int y,
int z, int face, bool bTestUseOnOnly = false,
bool* pbUsedItem = NULL) = 0;
virtual std::shared_ptr<Player> createPlayer(Level *level); virtual std::shared_ptr<Player> createPlayer(Level* level);
virtual bool interact(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity); virtual bool interact(std::shared_ptr<Player> player,
virtual void attack(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity); std::shared_ptr<Entity> entity);
virtual std::shared_ptr<ItemInstance> handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr<Player> player); virtual void attack(std::shared_ptr<Player> player,
virtual void handleCloseInventory(int containerId, std::shared_ptr<Player> player); std::shared_ptr<Entity> entity);
virtual void handleInventoryButtonClick(int containerId, int buttonId); virtual std::shared_ptr<ItemInstance> handleInventoryMouseClick(
int containerId, int slotNum, int buttonNum, bool quickKeyHeld,
std::shared_ptr<Player> player);
virtual void handleCloseInventory(int containerId,
std::shared_ptr<Player> player);
virtual void handleInventoryButtonClick(int containerId, int buttonId);
virtual bool isCutScene(); virtual bool isCutScene();
virtual void releaseUsingItem(std::shared_ptr<Player> player); virtual void releaseUsingItem(std::shared_ptr<Player> player);
virtual bool hasExperience(); virtual bool hasExperience();
virtual bool hasMissTime(); virtual bool hasMissTime();
virtual bool hasInfiniteItems(); virtual bool hasInfiniteItems();
virtual bool hasFarPickRange(); virtual bool hasFarPickRange();
virtual void handleCreativeModeItemAdd(std::shared_ptr<ItemInstance> clicked, int i); virtual void handleCreativeModeItemAdd(
virtual void handleCreativeModeItemDrop(std::shared_ptr<ItemInstance> clicked); std::shared_ptr<ItemInstance> clicked, int i);
virtual void handleCreativeModeItemDrop(
std::shared_ptr<ItemInstance> clicked);
// 4J Stu - Added so we can send packets for this in the network game // 4J Stu - Added so we can send packets for this in the network game
virtual bool handleCraftItem(int recipe, std::shared_ptr<Player> player); virtual bool handleCraftItem(int recipe, std::shared_ptr<Player> player);
virtual void handleDebugOptions(unsigned int uiVal, std::shared_ptr<Player> player); virtual void handleDebugOptions(unsigned int uiVal,
std::shared_ptr<Player> player);
// 4J Stu - Added for tutorial checks // 4J Stu - Added for tutorial checks
virtual bool isInputAllowed(int mapping) { return true; } virtual bool isInputAllowed(int mapping) { return true; }
virtual bool isTutorial() { return false; } virtual bool isTutorial() { return false; }
virtual Tutorial *getTutorial() { return NULL; } virtual Tutorial* getTutorial() { return NULL; }
}; };

View file

@ -14,100 +14,90 @@
#include "../../Minecraft.World/IO/Streams/DataOutputStream.h" #include "../../Minecraft.World/IO/Streams/DataOutputStream.h"
#include "../../Minecraft.World/Util/StringHelpers.h" #include "../../Minecraft.World/Util/StringHelpers.h"
// 4J - the Option sub-class used to be an java enumerated type, trying to emulate that functionality here // 4J - the Option sub-class used to be an java enumerated type, trying to
const Options::Option Options::Option::options[17] = // emulate that functionality here
{ const Options::Option Options::Option::options[17] = {
Options::Option(L"options.music", true, false), Options::Option(L"options.music", true, false),
Options::Option(L"options.sound", true, false), Options::Option(L"options.sound", true, false),
Options::Option(L"options.invertMouse", false, true), Options::Option(L"options.invertMouse", false, true),
Options::Option(L"options.sensitivity", true, false), Options::Option(L"options.sensitivity", true, false),
Options::Option(L"options.renderDistance", false, false), Options::Option(L"options.renderDistance", false, false),
Options::Option(L"options.viewBobbing", false, true), Options::Option(L"options.viewBobbing", false, true),
Options::Option(L"options.anaglyph", false, true), Options::Option(L"options.anaglyph", false, true),
Options::Option(L"options.advancedOpengl", false, true), Options::Option(L"options.advancedOpengl", false, true),
Options::Option(L"options.framerateLimit", false, false), Options::Option(L"options.framerateLimit", false, false),
Options::Option(L"options.difficulty", false, false), Options::Option(L"options.difficulty", false, false),
Options::Option(L"options.graphics", false, false), Options::Option(L"options.graphics", false, false),
Options::Option(L"options.ao", false, true), Options::Option(L"options.ao", false, true),
Options::Option(L"options.guiScale", false, false), Options::Option(L"options.guiScale", false, false),
Options::Option(L"options.fov", true, false), Options::Option(L"options.fov", true, false),
Options::Option(L"options.gamma", true, false), Options::Option(L"options.gamma", true, false),
Options::Option(L"options.renderClouds",false, true), Options::Option(L"options.renderClouds", false, true),
Options::Option(L"options.particles", false, false), Options::Option(L"options.particles", false, false),
}; };
const Options::Option *Options::Option::MUSIC = &Options::Option::options[0]; const Options::Option* Options::Option::MUSIC = &Options::Option::options[0];
const Options::Option *Options::Option::SOUND = &Options::Option::options[1]; const Options::Option* Options::Option::SOUND = &Options::Option::options[1];
const Options::Option *Options::Option::INVERT_MOUSE = &Options::Option::options[2]; const Options::Option* Options::Option::INVERT_MOUSE =
const Options::Option *Options::Option::SENSITIVITY = &Options::Option::options[3]; &Options::Option::options[2];
const Options::Option *Options::Option::RENDER_DISTANCE = &Options::Option::options[4]; const Options::Option* Options::Option::SENSITIVITY =
const Options::Option *Options::Option::VIEW_BOBBING = &Options::Option::options[5]; &Options::Option::options[3];
const Options::Option *Options::Option::ANAGLYPH = &Options::Option::options[6]; const Options::Option* Options::Option::RENDER_DISTANCE =
const Options::Option *Options::Option::ADVANCED_OPENGL = &Options::Option::options[7]; &Options::Option::options[4];
const Options::Option *Options::Option::FRAMERATE_LIMIT = &Options::Option::options[8]; const Options::Option* Options::Option::VIEW_BOBBING =
const Options::Option *Options::Option::DIFFICULTY = &Options::Option::options[9]; &Options::Option::options[5];
const Options::Option *Options::Option::GRAPHICS = &Options::Option::options[10]; const Options::Option* Options::Option::ANAGLYPH = &Options::Option::options[6];
const Options::Option *Options::Option::AMBIENT_OCCLUSION = &Options::Option::options[11]; const Options::Option* Options::Option::ADVANCED_OPENGL =
const Options::Option *Options::Option::GUI_SCALE = &Options::Option::options[12]; &Options::Option::options[7];
const Options::Option *Options::Option::FOV = &Options::Option::options[13]; const Options::Option* Options::Option::FRAMERATE_LIMIT =
const Options::Option *Options::Option::GAMMA = &Options::Option::options[14]; &Options::Option::options[8];
const Options::Option *Options::Option::RENDER_CLOUDS = &Options::Option::options[15]; const Options::Option* Options::Option::DIFFICULTY =
const Options::Option *Options::Option::PARTICLES = &Options::Option::options[16]; &Options::Option::options[9];
const Options::Option* Options::Option::GRAPHICS =
&Options::Option::options[10];
const Options::Option* Options::Option::AMBIENT_OCCLUSION =
&Options::Option::options[11];
const Options::Option* Options::Option::GUI_SCALE =
&Options::Option::options[12];
const Options::Option* Options::Option::FOV = &Options::Option::options[13];
const Options::Option* Options::Option::GAMMA = &Options::Option::options[14];
const Options::Option* Options::Option::RENDER_CLOUDS =
&Options::Option::options[15];
const Options::Option* Options::Option::PARTICLES =
&Options::Option::options[16];
const Options::Option* Options::Option::getItem(int id) { return &options[id]; }
const Options::Option *Options::Option::getItem(int id) Options::Option::Option(const std::wstring& captionId, bool hasProgress,
{ bool isBoolean)
return &options[id]; : _isProgress(hasProgress), _isBoolean(isBoolean), captionId(captionId) {}
}
Options::Option::Option(const std::wstring& captionId, bool hasProgress, bool isBoolean) : _isProgress(hasProgress), _isBoolean(isBoolean), captionId(captionId) bool Options::Option::isProgress() const { return _isProgress; }
{
}
bool Options::Option::isProgress() const bool Options::Option::isBoolean() const { return _isBoolean; }
{
return _isProgress;
}
bool Options::Option::isBoolean() const int Options::Option::getId() const { return (int)(this - options); }
{
return _isBoolean;
}
int Options::Option::getId() const std::wstring Options::Option::getCaptionId() const { return captionId; }
{
return (int)(this-options);
}
std::wstring Options::Option::getCaptionId() const const std::wstring Options::RENDER_DISTANCE_NAMES[] = {
{ L"options.renderDistance.far", L"options.renderDistance.normal",
return captionId; L"options.renderDistance.short", L"options.renderDistance.tiny"};
} const std::wstring Options::DIFFICULTY_NAMES[] = {
L"options.difficulty.peaceful", L"options.difficulty.easy",
L"options.difficulty.normal", L"options.difficulty.hard"};
const std::wstring Options::GUI_SCALE[] = {
L"options.guiScale.auto", L"options.guiScale.small",
L"options.guiScale.normal", L"options.guiScale.large"};
const std::wstring Options::FRAMERATE_LIMITS[] = {
L"performance.max", L"performance.balanced", L"performance.powersaver"};
const std::wstring Options::RENDER_DISTANCE_NAMES[] = const std::wstring Options::PARTICLES[] = {L"options.particles.all",
{ L"options.particles.decreased",
L"options.renderDistance.far", L"options.renderDistance.normal", L"options.renderDistance.short", L"options.renderDistance.tiny" L"options.particles.minimal"};
};
const std::wstring Options::DIFFICULTY_NAMES[] =
{
L"options.difficulty.peaceful", L"options.difficulty.easy", L"options.difficulty.normal", L"options.difficulty.hard"
};
const std::wstring Options::GUI_SCALE[] =
{
L"options.guiScale.auto", L"options.guiScale.small", L"options.guiScale.normal", L"options.guiScale.large"
};
const std::wstring Options::FRAMERATE_LIMITS[] =
{
L"performance.max", L"performance.balanced", L"performance.powersaver"
};
const std::wstring Options::PARTICLES[] = {
L"options.particles.all", L"options.particles.decreased", L"options.particles.minimal"
};
// 4J added // 4J added
void Options::init() void Options::init() {
{
music = 1; music = 1;
sound = 1; sound = 1;
sensitivity = 0.5f; sensitivity = 0.5f;
@ -116,16 +106,16 @@ void Options::init()
bobView = true; bobView = true;
anaglyph3d = false; anaglyph3d = false;
advancedOpengl = false; advancedOpengl = false;
//4JCRAFT V-Sync / VSync // 4JCRAFT V-Sync / VSync
#ifdef ENABLE_VSYNC #ifdef ENABLE_VSYNC
framerateLimit = 2; framerateLimit = 2;
#else #else
framerateLimit = 3; framerateLimit = 3;
#endif #endif
fancyGraphics = true; fancyGraphics = true;
ambientOcclusion = true; ambientOcclusion = true;
renderClouds = true; renderClouds = true;
skin = L"Default"; skin = L"Default";
keyUp = new KeyMapping(L"key.forward", Keyboard::KEY_W); keyUp = new KeyMapping(L"key.forward", Keyboard::KEY_W);
@ -137,395 +127,348 @@ void Options::init()
keyDrop = new KeyMapping(L"key.drop", Keyboard::KEY_Q); keyDrop = new KeyMapping(L"key.drop", Keyboard::KEY_Q);
keyChat = new KeyMapping(L"key.chat", Keyboard::KEY_T); keyChat = new KeyMapping(L"key.chat", Keyboard::KEY_T);
keySneak = new KeyMapping(L"key.sneak", Keyboard::KEY_LSHIFT); keySneak = new KeyMapping(L"key.sneak", Keyboard::KEY_LSHIFT);
keyAttack = new KeyMapping(L"key.attack", -100 + 0); keyAttack = new KeyMapping(L"key.attack", -100 + 0);
keyUse = new KeyMapping(L"key.use", -100 + 1); keyUse = new KeyMapping(L"key.use", -100 + 1);
keyPlayerList = new KeyMapping(L"key.playerlist", Keyboard::KEY_TAB); keyPlayerList = new KeyMapping(L"key.playerlist", Keyboard::KEY_TAB);
keyPickItem = new KeyMapping(L"key.pickItem", -100 + 2); keyPickItem = new KeyMapping(L"key.pickItem", -100 + 2);
keyToggleFog = new KeyMapping(L"key.fog", Keyboard::KEY_F); keyToggleFog = new KeyMapping(L"key.fog", Keyboard::KEY_F);
keyMappings[0] = keyAttack; keyMappings[0] = keyAttack;
keyMappings[1] = keyUse; keyMappings[1] = keyUse;
keyMappings[2] = keyUp; keyMappings[2] = keyUp;
keyMappings[3] = keyLeft; keyMappings[3] = keyLeft;
keyMappings[4] = keyDown; keyMappings[4] = keyDown;
keyMappings[5] = keyRight; keyMappings[5] = keyRight;
keyMappings[6] = keyJump; keyMappings[6] = keyJump;
keyMappings[7] = keySneak; keyMappings[7] = keySneak;
keyMappings[8] = keyDrop; keyMappings[8] = keyDrop;
keyMappings[9] = keyBuild; keyMappings[9] = keyBuild;
keyMappings[10] = keyChat; keyMappings[10] = keyChat;
keyMappings[11] = keyPlayerList; keyMappings[11] = keyPlayerList;
keyMappings[12] = keyPickItem; keyMappings[12] = keyPickItem;
keyMappings[13] = keyToggleFog; keyMappings[13] = keyToggleFog;
minecraft = NULL; minecraft = NULL;
//optionsFile = NULL; // optionsFile = NULL;
difficulty = 2; difficulty = 2;
hideGui = false; hideGui = false;
thirdPersonView = false; thirdPersonView = false;
renderDebug = false; renderDebug = false;
lastMpIp = L""; lastMpIp = L"";
isFlying = false; isFlying = false;
smoothCamera = false; smoothCamera = false;
fixedCamera = false; fixedCamera = false;
flySpeed = 1; flySpeed = 1;
cameraSpeed = 1; cameraSpeed = 1;
guiScale = 0; guiScale = 0;
particles = 0; particles = 0;
fov = 0; fov = 0;
gamma = 0; gamma = 0;
} }
Options::Options(Minecraft *minecraft, File workingDirectory) Options::Options(Minecraft* minecraft, File workingDirectory) {
{ init();
init(); this->minecraft = minecraft;
this->minecraft = minecraft; optionsFile = File(workingDirectory, L"options.txt");
optionsFile = File(workingDirectory, L"options.txt");
} }
Options::Options() Options::Options() { init(); }
{
init();
}
std::wstring Options::getKeyDescription(int i) std::wstring Options::getKeyDescription(int i) {
{ Language* language = Language::getInstance();
Language *language = Language::getInstance();
return language->getElement(keyMappings[i]->name); return language->getElement(keyMappings[i]->name);
} }
std::wstring Options::getKeyMessage(int i) std::wstring Options::getKeyMessage(int i) {
{ int key = keyMappings[i]->key;
int key = keyMappings[i]->key; if (key < 0) {
if (key < 0) { return I18n::get(L"key.mouseButton", key + 101);
return I18n::get(L"key.mouseButton", key + 101); } else {
} else { return Keyboard::getKeyName(keyMappings[i]->key);
return Keyboard::getKeyName(keyMappings[i]->key); }
}
} }
void Options::setKey(int i, int key) void Options::setKey(int i, int key) {
{
keyMappings[i]->key = key; keyMappings[i]->key = key;
save(); save();
} }
void Options::set(const Options::Option *item, float fVal) void Options::set(const Options::Option* item, float fVal) {
{ if (item == Option::MUSIC) {
if (item == Option::MUSIC)
{
music = fVal; music = fVal;
#ifdef _XBOX #ifdef _XBOX
minecraft->soundEngine->updateMusicVolume(fVal*2.0f); minecraft->soundEngine->updateMusicVolume(fVal * 2.0f);
#else #else
minecraft->soundEngine->updateMusicVolume(fVal); minecraft->soundEngine->updateMusicVolume(fVal);
#endif #endif
} }
if (item == Option::SOUND) if (item == Option::SOUND) {
{
sound = fVal; sound = fVal;
#ifdef _XBOX #ifdef _XBOX
minecraft->soundEngine->updateSoundEffectVolume(fVal*2.0f); minecraft->soundEngine->updateSoundEffectVolume(fVal * 2.0f);
#else #else
minecraft->soundEngine->updateSoundEffectVolume(fVal); minecraft->soundEngine->updateSoundEffectVolume(fVal);
#endif #endif
} }
if (item == Option::SENSITIVITY) if (item == Option::SENSITIVITY) {
{
sensitivity = fVal; sensitivity = fVal;
} }
if (item == Option::FOV) if (item == Option::FOV) {
{ fov = fVal;
fov = fVal; }
} if (item == Option::GAMMA) {
if (item == Option::GAMMA) gamma = fVal;
{ }
gamma = fVal;
}
} }
void Options::toggle(const Options::Option *option, int dir) void Options::toggle(const Options::Option* option, int dir) {
{
if (option == Option::INVERT_MOUSE) invertYMouse = !invertYMouse; if (option == Option::INVERT_MOUSE) invertYMouse = !invertYMouse;
if (option == Option::RENDER_DISTANCE) viewDistance = (viewDistance + dir) & 3; if (option == Option::RENDER_DISTANCE)
viewDistance = (viewDistance + dir) & 3;
if (option == Option::GUI_SCALE) guiScale = (guiScale + dir) & 3; if (option == Option::GUI_SCALE) guiScale = (guiScale + dir) & 3;
if (option == Option::PARTICLES) particles = (particles + dir) % 3; if (option == Option::PARTICLES) particles = (particles + dir) % 3;
// 4J-PB - changing // 4J-PB - changing
//if (option == Option::VIEW_BOBBING) bobView = !bobView; // if (option == Option::VIEW_BOBBING) bobView = !bobView;
if (option == Option::VIEW_BOBBING) ((dir==0)?bobView=false: bobView=true); if (option == Option::VIEW_BOBBING)
if (option == Option::RENDER_CLOUDS) renderClouds = !renderClouds; ((dir == 0) ? bobView = false : bobView = true);
if (option == Option::ADVANCED_OPENGL) if (option == Option::RENDER_CLOUDS) renderClouds = !renderClouds;
{ if (option == Option::ADVANCED_OPENGL) {
advancedOpengl = !advancedOpengl; advancedOpengl = !advancedOpengl;
minecraft->levelRenderer->allChanged(); minecraft->levelRenderer->allChanged();
} }
if (option == Option::ANAGLYPH) if (option == Option::ANAGLYPH) {
{
anaglyph3d = !anaglyph3d; anaglyph3d = !anaglyph3d;
minecraft->textures->reloadAll(); minecraft->textures->reloadAll();
} }
if (option == Option::FRAMERATE_LIMIT) framerateLimit = (framerateLimit + dir + 3) % 3; if (option == Option::FRAMERATE_LIMIT)
framerateLimit = (framerateLimit + dir + 3) % 3;
// 4J-PB - Change for Xbox // 4J-PB - Change for Xbox
//if (option == Option::DIFFICULTY) difficulty = (difficulty + dir) & 3; // if (option == Option::DIFFICULTY) difficulty = (difficulty + dir) & 3;
if (option == Option::DIFFICULTY) difficulty = (dir) & 3; if (option == Option::DIFFICULTY) difficulty = (dir) & 3;
app.DebugPrintf("Option::DIFFICULTY = %d",difficulty); app.DebugPrintf("Option::DIFFICULTY = %d", difficulty);
if (option == Option::GRAPHICS) if (option == Option::GRAPHICS) {
{
fancyGraphics = !fancyGraphics; fancyGraphics = !fancyGraphics;
minecraft->levelRenderer->allChanged(); minecraft->levelRenderer->allChanged();
} }
if (option == Option::AMBIENT_OCCLUSION) if (option == Option::AMBIENT_OCCLUSION) {
{
ambientOcclusion = !ambientOcclusion; ambientOcclusion = !ambientOcclusion;
minecraft->levelRenderer->allChanged(); minecraft->levelRenderer->allChanged();
} }
// 4J-PB - don't do the file save on the xbox // 4J-PB - don't do the file save on the xbox
// save(); // save();
} }
float Options::getProgressValue(const Options::Option *item) float Options::getProgressValue(const Options::Option* item) {
{ if (item == Option::FOV) return fov;
if (item == Option::FOV) return fov; if (item == Option::GAMMA) return gamma;
if (item == Option::GAMMA) return gamma;
if (item == Option::MUSIC) return music; if (item == Option::MUSIC) return music;
if (item == Option::SOUND) return sound; if (item == Option::SOUND) return sound;
if (item == Option::SENSITIVITY) return sensitivity; if (item == Option::SENSITIVITY) return sensitivity;
return 0; return 0;
} }
bool Options::getBooleanValue(const Options::Option *item) bool Options::getBooleanValue(const Options::Option* item) {
{ // 4J - was a switch statement which we can't do with our Option:: pointer
// 4J - was a switch statement which we can't do with our Option:: pointer types // types
if( item == Option::INVERT_MOUSE) return invertYMouse; if (item == Option::INVERT_MOUSE) return invertYMouse;
if( item == Option::VIEW_BOBBING) return bobView; if (item == Option::VIEW_BOBBING) return bobView;
if( item == Option::ANAGLYPH) return anaglyph3d; if (item == Option::ANAGLYPH) return anaglyph3d;
if( item == Option::ADVANCED_OPENGL) return advancedOpengl; if (item == Option::ADVANCED_OPENGL) return advancedOpengl;
if( item == Option::AMBIENT_OCCLUSION) return ambientOcclusion; if (item == Option::AMBIENT_OCCLUSION) return ambientOcclusion;
if( item == Option::RENDER_CLOUDS) return renderClouds; if (item == Option::RENDER_CLOUDS) return renderClouds;
return false; return false;
} }
std::wstring Options::getMessage(const Options::Option *item) std::wstring Options::getMessage(const Options::Option* item) {
{ // 4J TODO, should these std::wstrings append rather than add?
// 4J TODO, should these std::wstrings append rather than add?
Language *language = Language::getInstance(); Language* language = Language::getInstance();
std::wstring caption = language->getElement(item->getCaptionId()) + L": "; std::wstring caption = language->getElement(item->getCaptionId()) + L": ";
if (item->isProgress()) if (item->isProgress()) {
{
float progressValue = getProgressValue(item); float progressValue = getProgressValue(item);
if (item == Option::SENSITIVITY) if (item == Option::SENSITIVITY) {
{ if (progressValue == 0) {
if (progressValue == 0) return caption +
{ language->getElement(L"options.sensitivity.min");
return caption + language->getElement(L"options.sensitivity.min");
} }
if (progressValue == 1) if (progressValue == 1) {
{ return caption +
return caption + language->getElement(L"options.sensitivity.max"); language->getElement(L"options.sensitivity.max");
} }
return caption + _toString<int>((int) (progressValue * 200)) + L"%"; return caption + _toString<int>((int)(progressValue * 200)) + L"%";
} else if (item == Option::FOV) } else if (item == Option::FOV) {
{ if (progressValue == 0) {
if (progressValue == 0) return caption + language->getElement(L"options.fov.min");
{ }
return caption + language->getElement(L"options.fov.min"); if (progressValue == 1) {
} return caption + language->getElement(L"options.fov.max");
if (progressValue == 1) }
{ return caption + _toString<int>((int)(70 + progressValue * 40));
return caption + language->getElement(L"options.fov.max"); } else if (item == Option::GAMMA) {
} if (progressValue == 0) {
return caption + _toString<int>((int) (70 + progressValue * 40)); return caption + language->getElement(L"options.gamma.min");
} else if (item == Option::GAMMA) }
{ if (progressValue == 1) {
if (progressValue == 0) return caption + language->getElement(L"options.gamma.max");
{ }
return caption + language->getElement(L"options.gamma.min"); return caption + L"+" + _toString<int>((int)(progressValue * 100)) +
} L"%";
if (progressValue == 1) } else {
{ if (progressValue == 0) {
return caption + language->getElement(L"options.gamma.max");
}
return caption + L"+" + _toString<int>((int) (progressValue * 100)) + L"%";
}
else
{
if (progressValue == 0)
{
return caption + language->getElement(L"options.off"); return caption + language->getElement(L"options.off");
} }
return caption + _toString<int>((int) (progressValue * 100)) + L"%"; return caption + _toString<int>((int)(progressValue * 100)) + L"%";
} }
} else if (item->isBoolean()) } else if (item->isBoolean()) {
{
bool booleanValue = getBooleanValue(item); bool booleanValue = getBooleanValue(item);
if (booleanValue) if (booleanValue) {
{
return caption + language->getElement(L"options.on"); return caption + language->getElement(L"options.on");
} }
return caption + language->getElement(L"options.off"); return caption + language->getElement(L"options.off");
} } else if (item == Option::RENDER_DISTANCE) {
else if (item == Option::RENDER_DISTANCE) return caption +
{ language->getElement(RENDER_DISTANCE_NAMES[viewDistance]);
return caption + language->getElement(RENDER_DISTANCE_NAMES[viewDistance]); } else if (item == Option::DIFFICULTY) {
}
else if (item == Option::DIFFICULTY)
{
return caption + language->getElement(DIFFICULTY_NAMES[difficulty]); return caption + language->getElement(DIFFICULTY_NAMES[difficulty]);
} } else if (item == Option::GUI_SCALE) {
else if (item == Option::GUI_SCALE)
{
return caption + language->getElement(GUI_SCALE[guiScale]); return caption + language->getElement(GUI_SCALE[guiScale]);
} } else if (item == Option::PARTICLES) {
else if (item == Option::PARTICLES) return caption + language->getElement(PARTICLES[particles]);
{ } else if (item == Option::FRAMERATE_LIMIT) {
return caption + language->getElement(PARTICLES[particles]);
}
else if (item == Option::FRAMERATE_LIMIT)
{
return caption + I18n::get(FRAMERATE_LIMITS[framerateLimit]); return caption + I18n::get(FRAMERATE_LIMITS[framerateLimit]);
} } else if (item == Option::GRAPHICS) {
else if (item == Option::GRAPHICS) if (fancyGraphics) {
{
if (fancyGraphics)
{
return caption + language->getElement(L"options.graphics.fancy"); return caption + language->getElement(L"options.graphics.fancy");
} }
return caption + language->getElement(L"options.graphics.fast"); return caption + language->getElement(L"options.graphics.fast");
} }
return caption; return caption;
} }
void Options::load() void Options::load() {
{ // 4J - removed try/catch
// 4J - removed try/catch // try {
// try { if (!optionsFile.exists()) return;
if (!optionsFile.exists()) return; // 4J - was new BufferedReader(new FileReader(optionsFile));
// 4J - was new BufferedReader(new FileReader(optionsFile)); BufferedReader* br = new BufferedReader(
BufferedReader *br = new BufferedReader(new InputStreamReader( new FileInputStream( optionsFile ) ) ); new InputStreamReader(new FileInputStream(optionsFile)));
std::wstring line = L"";
while ((line = br->readLine()) != L"") // 4J - was check against NULL - do we need to distinguish between empty lines and a fail here?
{
// 4J - removed try/catch
// try {
std::wstring cmds[2];
int splitpos = (int)line.find(L":");
if( splitpos == std::wstring::npos )
{
cmds[0] = line;
cmds[1] = L"";
}
else
{
cmds[0] = line.substr(0,splitpos);
cmds[1] = line.substr(splitpos,line.length()-splitpos);
}
if (cmds[0] == L"music") music = readFloat(cmds[1]); std::wstring line = L"";
if (cmds[0] == L"sound") sound = readFloat(cmds[1]); while ((line = br->readLine()) !=
if (cmds[0] == L"mouseSensitivity") sensitivity = readFloat(cmds[1]); L"") // 4J - was check against NULL - do we need to distinguish
if (cmds[0] == L"fov") fov = readFloat(cmds[1]); // between empty lines and a fail here?
if (cmds[0] == L"gamma") gamma = readFloat(cmds[1]); {
if (cmds[0] == L"invertYMouse") invertYMouse = cmds[1]==L"true"; // 4J - removed try/catch
if (cmds[0] == L"viewDistance") viewDistance = _fromString<int>(cmds[1]); // try {
if (cmds[0] == L"guiScale") guiScale =_fromString<int>(cmds[1]); std::wstring cmds[2];
if (cmds[0] == L"particles") particles = _fromString<int>(cmds[1]); int splitpos = (int)line.find(L":");
if (cmds[0] == L"bobView") bobView = cmds[1]==L"true"; if (splitpos == std::wstring::npos) {
if (cmds[0] == L"anaglyph3d") anaglyph3d = cmds[1]==L"true"; cmds[0] = line;
if (cmds[0] == L"advancedOpengl") advancedOpengl = cmds[1]==L"true"; cmds[1] = L"";
if (cmds[0] == L"fpsLimit") framerateLimit = _fromString<int>(cmds[1]); } else {
if (cmds[0] == L"difficulty") difficulty = _fromString<int>(cmds[1]); cmds[0] = line.substr(0, splitpos);
if (cmds[0] == L"fancyGraphics") fancyGraphics = cmds[1]==L"true"; cmds[1] = line.substr(splitpos, line.length() - splitpos);
if (cmds[0] == L"ao") ambientOcclusion = cmds[1]==L"true";
if (cmds[0] == L"clouds") renderClouds = cmds[1]==L"true";
if (cmds[0] == L"skin") skin = cmds[1];
if (cmds[0] == L"lastServer") lastMpIp = cmds[1];
for (int i = 0; i < keyMappings_length; i++)
{
if (cmds[0] == (L"key_" + keyMappings[i]->name))
{
keyMappings[i]->key = _fromString<int>(cmds[1]);
}
}
// } catch (Exception e) {
// System.out.println("Skipping bad option: " + line);
// }
} }
//KeyMapping.resetMapping(); // 4J Not implemented
br->close();
// } catch (Exception e) {
// System.out.println("Failed to load options");
// e.printStackTrace();
// }
if (cmds[0] == L"music") music = readFloat(cmds[1]);
if (cmds[0] == L"sound") sound = readFloat(cmds[1]);
if (cmds[0] == L"mouseSensitivity") sensitivity = readFloat(cmds[1]);
if (cmds[0] == L"fov") fov = readFloat(cmds[1]);
if (cmds[0] == L"gamma") gamma = readFloat(cmds[1]);
if (cmds[0] == L"invertYMouse") invertYMouse = cmds[1] == L"true";
if (cmds[0] == L"viewDistance")
viewDistance = _fromString<int>(cmds[1]);
if (cmds[0] == L"guiScale") guiScale = _fromString<int>(cmds[1]);
if (cmds[0] == L"particles") particles = _fromString<int>(cmds[1]);
if (cmds[0] == L"bobView") bobView = cmds[1] == L"true";
if (cmds[0] == L"anaglyph3d") anaglyph3d = cmds[1] == L"true";
if (cmds[0] == L"advancedOpengl") advancedOpengl = cmds[1] == L"true";
if (cmds[0] == L"fpsLimit") framerateLimit = _fromString<int>(cmds[1]);
if (cmds[0] == L"difficulty") difficulty = _fromString<int>(cmds[1]);
if (cmds[0] == L"fancyGraphics") fancyGraphics = cmds[1] == L"true";
if (cmds[0] == L"ao") ambientOcclusion = cmds[1] == L"true";
if (cmds[0] == L"clouds") renderClouds = cmds[1] == L"true";
if (cmds[0] == L"skin") skin = cmds[1];
if (cmds[0] == L"lastServer") lastMpIp = cmds[1];
for (int i = 0; i < keyMappings_length; i++) {
if (cmds[0] == (L"key_" + keyMappings[i]->name)) {
keyMappings[i]->key = _fromString<int>(cmds[1]);
}
}
// } catch (Exception e) {
// System.out.println("Skipping bad option: " + line);
// }
}
// KeyMapping.resetMapping(); // 4J Not implemented
br->close();
// } catch (Exception e) {
// System.out.println("Failed to load options");
// e.printStackTrace();
// }
} }
float Options::readFloat(std::wstring string) float Options::readFloat(std::wstring string) {
{
if (string == L"true") return 1; if (string == L"true") return 1;
if (string == L"false") return 0; if (string == L"false") return 0;
return _fromString<float>(string); return _fromString<float>(string);
} }
void Options::save() void Options::save() {
{ // 4J - try/catch removed
// 4J - try/catch removed // try {
// try {
// 4J - original used a PrintWriter & FileWriter, but seems a bit much implementing these just to do this // 4J - original used a PrintWriter & FileWriter, but seems a bit much
FileOutputStream fos = FileOutputStream(optionsFile); // implementing these just to do this
DataOutputStream dos = DataOutputStream(&fos); FileOutputStream fos = FileOutputStream(optionsFile);
// PrintWriter pw = new PrintWriter(new FileWriter(optionsFile)); DataOutputStream dos = DataOutputStream(&fos);
// PrintWriter pw = new PrintWriter(new FileWriter(optionsFile));
dos.writeChars(L"music:" + _toString<float>(music) + L"\n"); dos.writeChars(L"music:" + _toString<float>(music) + L"\n");
dos.writeChars(L"sound:" + _toString<float>(sound) + L"\n"); dos.writeChars(L"sound:" + _toString<float>(sound) + L"\n");
dos.writeChars(L"invertYMouse:" + std::wstring(invertYMouse ? L"true" : L"false") + L"\n"); dos.writeChars(L"invertYMouse:" +
dos.writeChars(L"mouseSensitivity:" + _toString<float>(sensitivity)); std::wstring(invertYMouse ? L"true" : L"false") + L"\n");
dos.writeChars(L"fov:" + _toString<float>(fov)); dos.writeChars(L"mouseSensitivity:" + _toString<float>(sensitivity));
dos.writeChars(L"gamma:" + _toString<float>(gamma)); dos.writeChars(L"fov:" + _toString<float>(fov));
dos.writeChars(L"viewDistance:" + _toString<int>(viewDistance)); dos.writeChars(L"gamma:" + _toString<float>(gamma));
dos.writeChars(L"guiScale:" + _toString<int>(guiScale)); dos.writeChars(L"viewDistance:" + _toString<int>(viewDistance));
dos.writeChars(L"particles:" + _toString<int>(particles)); dos.writeChars(L"guiScale:" + _toString<int>(guiScale));
dos.writeChars(L"bobView:" + std::wstring(bobView ? L"true" : L"false")); dos.writeChars(L"particles:" + _toString<int>(particles));
dos.writeChars(L"anaglyph3d:" + std::wstring(anaglyph3d ? L"true" : L"false")); dos.writeChars(L"bobView:" + std::wstring(bobView ? L"true" : L"false"));
dos.writeChars(L"advancedOpengl:" + std::wstring(advancedOpengl ? L"true" : L"false")); dos.writeChars(L"anaglyph3d:" +
dos.writeChars(L"fpsLimit:" + _toString<int>(framerateLimit)); std::wstring(anaglyph3d ? L"true" : L"false"));
dos.writeChars(L"difficulty:" + _toString<int>(difficulty)); dos.writeChars(L"advancedOpengl:" +
dos.writeChars(L"fancyGraphics:" + std::wstring(fancyGraphics ? L"true" : L"false")); std::wstring(advancedOpengl ? L"true" : L"false"));
dos.writeChars(L"ao:" + std::wstring(ambientOcclusion ? L"true" : L"false")); dos.writeChars(L"fpsLimit:" + _toString<int>(framerateLimit));
dos.writeChars(L"clouds:" + _toString<bool>(renderClouds)); dos.writeChars(L"difficulty:" + _toString<int>(difficulty));
dos.writeChars(L"skin:" + skin); dos.writeChars(L"fancyGraphics:" +
dos.writeChars(L"lastServer:" + lastMpIp); std::wstring(fancyGraphics ? L"true" : L"false"));
dos.writeChars(L"ao:" +
std::wstring(ambientOcclusion ? L"true" : L"false"));
dos.writeChars(L"clouds:" + _toString<bool>(renderClouds));
dos.writeChars(L"skin:" + skin);
dos.writeChars(L"lastServer:" + lastMpIp);
for (int i = 0; i < keyMappings_length; i++) for (int i = 0; i < keyMappings_length; i++) {
{ dos.writeChars(L"key_" + keyMappings[i]->name + L":" +
dos.writeChars(L"key_" + keyMappings[i]->name + L":" + _toString<int>(keyMappings[i]->key)); _toString<int>(keyMappings[i]->key));
} }
dos.close();
// } catch (Exception e) {
// System.out.println("Failed to save options");
// e.printStackTrace();
// }
dos.close();
// } catch (Exception e) {
// System.out.println("Failed to save options");
// e.printStackTrace();
// }
} }
bool Options::isCloudsOn() bool Options::isCloudsOn() { return viewDistance < 2 && renderClouds; }
{
return viewDistance < 2 && renderClouds;
}

View file

@ -4,60 +4,58 @@ class Minecraft;
class KeyMapping; class KeyMapping;
#include "../../Minecraft.World/IO/Files/File.h" #include "../../Minecraft.World/IO/Files/File.h"
class Options class Options {
{
public: public:
static const int AO_OFF = 0; static const int AO_OFF = 0;
static const int AO_MIN = 1; static const int AO_MIN = 1;
static const int AO_MAX = 2; static const int AO_MAX = 2;
// 4J - this used to be an enum // 4J - this used to be an enum
class Option class Option {
{ public:
public: static const Option options[17];
static const Option options[17]; static const Option* MUSIC;
static const Option *MUSIC; static const Option* SOUND;
static const Option *SOUND; static const Option* INVERT_MOUSE;
static const Option *INVERT_MOUSE; static const Option* SENSITIVITY;
static const Option *SENSITIVITY; static const Option* RENDER_DISTANCE;
static const Option *RENDER_DISTANCE; static const Option* VIEW_BOBBING;
static const Option *VIEW_BOBBING; static const Option* ANAGLYPH;
static const Option *ANAGLYPH; static const Option* ADVANCED_OPENGL;
static const Option *ADVANCED_OPENGL; static const Option* FRAMERATE_LIMIT;
static const Option *FRAMERATE_LIMIT; static const Option* DIFFICULTY;
static const Option *DIFFICULTY; static const Option* GRAPHICS;
static const Option *GRAPHICS; static const Option* AMBIENT_OCCLUSION;
static const Option *AMBIENT_OCCLUSION; static const Option* GUI_SCALE;
static const Option *GUI_SCALE; static const Option* FOV;
static const Option *FOV; static const Option* GAMMA;
static const Option *GAMMA; static const Option* RENDER_CLOUDS;
static const Option *RENDER_CLOUDS; static const Option* PARTICLES;
static const Option *PARTICLES;
private: private:
const bool _isProgress; const bool _isProgress;
const bool _isBoolean; const bool _isBoolean;
const std::wstring captionId; const std::wstring captionId;
public: public:
static const Option *getItem(int id); static const Option* getItem(int id);
Option(const std::wstring& captionId, bool hasProgress, bool isBoolean); Option(const std::wstring& captionId, bool hasProgress, bool isBoolean);
bool isProgress() const; bool isProgress() const;
bool isBoolean() const; bool isBoolean() const;
int getId() const; int getId() const;
std::wstring getCaptionId() const; std::wstring getCaptionId() const;
}; };
private: private:
static const std::wstring RENDER_DISTANCE_NAMES[]; static const std::wstring RENDER_DISTANCE_NAMES[];
static const std::wstring DIFFICULTY_NAMES[]; static const std::wstring DIFFICULTY_NAMES[];
static const std::wstring GUI_SCALE[]; static const std::wstring GUI_SCALE[];
static const std::wstring FRAMERATE_LIMITS[]; static const std::wstring FRAMERATE_LIMITS[];
static const std::wstring PARTICLES[]; static const std::wstring PARTICLES[];
public: public:
float music; float music;
float sound; float sound;
float sensitivity; float sensitivity;
bool invertYMouse; bool invertYMouse;
@ -68,34 +66,35 @@ public:
int framerateLimit; int framerateLimit;
bool fancyGraphics; bool fancyGraphics;
bool ambientOcclusion; bool ambientOcclusion;
bool renderClouds; bool renderClouds;
std::wstring skin; std::wstring skin;
KeyMapping *keyUp; KeyMapping* keyUp;
KeyMapping *keyLeft; KeyMapping* keyLeft;
KeyMapping *keyDown; KeyMapping* keyDown;
KeyMapping *keyRight; KeyMapping* keyRight;
KeyMapping *keyJump; KeyMapping* keyJump;
KeyMapping *keyBuild; KeyMapping* keyBuild;
KeyMapping *keyDrop; KeyMapping* keyDrop;
KeyMapping *keyChat; KeyMapping* keyChat;
KeyMapping *keySneak; KeyMapping* keySneak;
KeyMapping *keyAttack; KeyMapping* keyAttack;
KeyMapping *keyUse; KeyMapping* keyUse;
KeyMapping *keyPlayerList; KeyMapping* keyPlayerList;
KeyMapping *keyPickItem; KeyMapping* keyPickItem;
KeyMapping *keyToggleFog; KeyMapping* keyToggleFog;
static const int keyMappings_length = 14; static const int keyMappings_length = 14;
KeyMapping *keyMappings[keyMappings_length]; KeyMapping* keyMappings[keyMappings_length];
protected: protected:
Minecraft *minecraft; Minecraft* minecraft;
private: private:
File optionsFile; File optionsFile;
public: public:
int difficulty; int difficulty;
bool hideGui; bool hideGui;
bool thirdPersonView; bool thirdPersonView;
bool renderDebug; bool renderDebug;
@ -107,26 +106,28 @@ public:
float flySpeed; float flySpeed;
float cameraSpeed; float cameraSpeed;
int guiScale; int guiScale;
int particles; // 0 is all, 1 is decreased and 2 is minimal int particles; // 0 is all, 1 is decreased and 2 is minimal
float fov; float fov;
float gamma; float gamma;
void init(); // 4J added void init(); // 4J added
Options(Minecraft *minecraft, File workingDirectory); Options(Minecraft* minecraft, File workingDirectory);
Options(); Options();
std::wstring getKeyDescription(int i); std::wstring getKeyDescription(int i);
std::wstring getKeyMessage(int i); std::wstring getKeyMessage(int i);
void setKey(int i, int key); void setKey(int i, int key);
void set(const Options::Option *item, float value); void set(const Options::Option* item, float value);
void toggle(const Options::Option *option, int dir); void toggle(const Options::Option* option, int dir);
float getProgressValue(const Options::Option *item); float getProgressValue(const Options::Option* item);
bool getBooleanValue(const Options::Option *item); bool getBooleanValue(const Options::Option* item);
std::wstring getMessage(const Options::Option *item); std::wstring getMessage(const Options::Option* item);
void load(); void load();
private:
float readFloat(std::wstring string);
public:
void save();
bool isCloudsOn(); private:
float readFloat(std::wstring string);
public:
void save();
bool isCloudsOn();
}; };

View file

@ -3,53 +3,41 @@
#include "../../Minecraft.World/Util/StringHelpers.h" #include "../../Minecraft.World/Util/StringHelpers.h"
// 4J - TODO - serialise/deserialise from file // 4J - TODO - serialise/deserialise from file
Settings::Settings(File *file) Settings::Settings(File* file) {}
{
void Settings::generateNewProperties() {}
void Settings::saveProperties() {}
std::wstring Settings::getString(const std::wstring& key,
const std::wstring& defaultValue) {
if (properties.find(key) == properties.end()) {
properties[key] = defaultValue;
saveProperties();
}
return properties[key];
} }
void Settings::generateNewProperties() int Settings::getInt(const std::wstring& key, int defaultValue) {
{ if (properties.find(key) == properties.end()) {
properties[key] = _toString<int>(defaultValue);
saveProperties();
}
return _fromString<int>(properties[key]);
} }
void Settings::saveProperties() bool Settings::getBoolean(const std::wstring& key, bool defaultValue) {
{ if (properties.find(key) == properties.end()) {
properties[key] = _toString<bool>(defaultValue);
saveProperties();
}
MemSect(35);
bool retval = _fromString<bool>(properties[key]);
MemSect(0);
return retval;
} }
std::wstring Settings::getString(const std::wstring& key, const std::wstring& defaultValue) void Settings::setBooleanAndSave(const std::wstring& key, bool value) {
{ properties[key] = _toString<bool>(value);
if(properties.find(key) == properties.end()) saveProperties();
{
properties[key] = defaultValue;
saveProperties();
}
return properties[key];
}
int Settings::getInt(const std::wstring& key, int defaultValue)
{
if(properties.find(key) == properties.end())
{
properties[key] = _toString<int>(defaultValue);
saveProperties();
}
return _fromString<int>(properties[key]);
}
bool Settings::getBoolean(const std::wstring& key, bool defaultValue)
{
if(properties.find(key) == properties.end())
{
properties[key] = _toString<bool>(defaultValue);
saveProperties();
}
MemSect(35);
bool retval = _fromString<bool>(properties[key]);
MemSect(0);
return retval;
}
void Settings::setBooleanAndSave(const std::wstring& key, bool value)
{
properties[key] = _toString<bool>(value);
saveProperties();
} }

View file

@ -1,20 +1,21 @@
#pragma once #pragma once
class File; class File;
class Settings {
class Settings // public static Logger logger = Logger.getLogger("Minecraft");
{ // private Properties properties = new Properties();
// public static Logger logger = Logger.getLogger("Minecraft");
// private Properties properties = new Properties();
private: private:
std::unordered_map<std::wstring,std::wstring> properties; // 4J - TODO was Properties type, will need to implement something we can serialise/deserialise too std::unordered_map<std::wstring, std::wstring>
//File *file; properties; // 4J - TODO was Properties type, will need to implement
// something we can serialise/deserialise too
// File *file;
public: public:
Settings(File *file); Settings(File* file);
void generateNewProperties(); void generateNewProperties();
void saveProperties(); void saveProperties();
std::wstring getString(const std::wstring& key, const std::wstring& defaultValue); std::wstring getString(const std::wstring& key,
const std::wstring& defaultValue);
int getInt(const std::wstring& key, int defaultValue); int getInt(const std::wstring& key, int defaultValue);
bool getBoolean(const std::wstring& key, bool defaultValue); bool getBoolean(const std::wstring& key, bool defaultValue);
void setBooleanAndSave(const std::wstring& key, bool value); void setBooleanAndSave(const std::wstring& key, bool value);

File diff suppressed because it is too large Load diff

View file

@ -5,100 +5,96 @@ class Achievement;
class StatsSyncher; class StatsSyncher;
class User; class User;
class StatsCounter {
class StatsCounter
{
private: private:
enum eDifficulty {
eDifficulty_Peaceful = 0,
eDifficulty_Easy,
eDifficulty_Normal,
eDifficulty_Hard,
eDifficulty_Max
};
enum eDifficulty struct StatContainer {
{ unsigned int stats[eDifficulty_Max];
eDifficulty_Peaceful=0,
eDifficulty_Easy,
eDifficulty_Normal,
eDifficulty_Hard,
eDifficulty_Max
};
struct StatContainer StatContainer() {
{ stats[eDifficulty_Peaceful] = stats[eDifficulty_Easy] =
unsigned int stats[eDifficulty_Max]; stats[eDifficulty_Normal] = stats[eDifficulty_Hard] = 0;
}
};
StatContainer() typedef std::unordered_map<Stat*, StatContainer> StatsMap;
{
stats[eDifficulty_Peaceful] = stats[eDifficulty_Easy] = stats[eDifficulty_Normal] = stats[eDifficulty_Hard] = 0;
}
};
typedef std::unordered_map<Stat*, StatContainer> StatsMap;
//static const int STAT_DATA_OFFSET = 32; // static const int STAT_DATA_OFFSET = 32;
static const int LARGE_STATS_COUNT = 8; static const int LARGE_STATS_COUNT = 8;
static Stat** LARGE_STATS[LARGE_STATS_COUNT]; static Stat** LARGE_STATS[LARGE_STATS_COUNT];
static const int SAVE_DELAY = 30*60; static const int SAVE_DELAY = 30 * 60;
static const int FLUSH_DELAY = 30*60*5; static const int FLUSH_DELAY = 30 * 60 * 5;
typedef enum { typedef enum {
LEADERBOARD_KILLS_PEACEFUL = 0x00000001, LEADERBOARD_KILLS_PEACEFUL = 0x00000001,
LEADERBOARD_KILLS_EASY = 0x00000002, LEADERBOARD_KILLS_EASY = 0x00000002,
LEADERBOARD_KILLS_NORMAL = 0x00000004, LEADERBOARD_KILLS_NORMAL = 0x00000004,
LEADERBOARD_KILLS_HARD = 0x00000008, LEADERBOARD_KILLS_HARD = 0x00000008,
LEADERBOARD_MININGBLOCKS_PEACEFUL = 0x00000010, LEADERBOARD_MININGBLOCKS_PEACEFUL = 0x00000010,
LEADERBOARD_MININGBLOCKS_EASY = 0x00000020, LEADERBOARD_MININGBLOCKS_EASY = 0x00000020,
LEADERBOARD_MININGBLOCKS_NORMAL = 0x00000040, LEADERBOARD_MININGBLOCKS_NORMAL = 0x00000040,
LEADERBOARD_MININGBLOCKS_HARD = 0x00000080, LEADERBOARD_MININGBLOCKS_HARD = 0x00000080,
LEADERBOARD_MININGORE_PEACEFUL = 0x00000100, LEADERBOARD_MININGORE_PEACEFUL = 0x00000100,
LEADERBOARD_MININGORE_EASY = 0x00000200, LEADERBOARD_MININGORE_EASY = 0x00000200,
LEADERBOARD_MININGORE_NORMAL = 0x00000400, LEADERBOARD_MININGORE_NORMAL = 0x00000400,
LEADERBOARD_MININGORE_HARD = 0x00000800, LEADERBOARD_MININGORE_HARD = 0x00000800,
LEADERBOARD_FARMING_PEACEFUL = 0x00001000, LEADERBOARD_FARMING_PEACEFUL = 0x00001000,
LEADERBOARD_FARMING_EASY = 0x00002000, LEADERBOARD_FARMING_EASY = 0x00002000,
LEADERBOARD_FARMING_NORMAL = 0x00004000, LEADERBOARD_FARMING_NORMAL = 0x00004000,
LEADERBOARD_FARMING_HARD = 0x00008000, LEADERBOARD_FARMING_HARD = 0x00008000,
LEADERBOARD_TRAVELLING_PEACEFUL = 0x00010000, LEADERBOARD_TRAVELLING_PEACEFUL = 0x00010000,
LEADERBOARD_TRAVELLING_EASY = 0x00020000, LEADERBOARD_TRAVELLING_EASY = 0x00020000,
LEADERBOARD_TRAVELLING_NORMAL = 0x00040000, LEADERBOARD_TRAVELLING_NORMAL = 0x00040000,
LEADERBOARD_TRAVELLING_HARD = 0x00080000, LEADERBOARD_TRAVELLING_HARD = 0x00080000,
LEADERBOARD_NETHER_PEACEFUL = 0x00100000, LEADERBOARD_NETHER_PEACEFUL = 0x00100000,
LEADERBOARD_NETHER_EASY = 0x00200000, LEADERBOARD_NETHER_EASY = 0x00200000,
LEADERBOARD_NETHER_NORMAL = 0x00400000, LEADERBOARD_NETHER_NORMAL = 0x00400000,
LEADERBOARD_NETHER_HARD = 0x00800000, LEADERBOARD_NETHER_HARD = 0x00800000,
LEADERBOARD_TRAVELLING_TOTAL = 0x01000000 LEADERBOARD_TRAVELLING_TOTAL = 0x01000000
} LEADERBOARD_FLAG; } LEADERBOARD_FLAG;
StatsMap stats; StatsMap stats;
bool requiresSave; bool requiresSave;
int saveCounter; int saveCounter;
int modifiedBoards; int modifiedBoards;
static std::unordered_map<Stat*, int> statBoards; static std::unordered_map<Stat*, int> statBoards;
int flushCounter; int flushCounter;
public: public:
StatsCounter(); StatsCounter();
void award(Stat *stat, unsigned int difficulty, unsigned int count); void award(Stat* stat, unsigned int difficulty, unsigned int count);
bool hasTaken(Achievement *ach); bool hasTaken(Achievement* ach);
bool canTake(Achievement *ach); bool canTake(Achievement* ach);
unsigned int getValue(Stat *stat, unsigned int difficulty); unsigned int getValue(Stat* stat, unsigned int difficulty);
unsigned int getTotalValue(Stat *stat); unsigned int getTotalValue(Stat* stat);
void tick(int player); void tick(int player);
void parse(void* data); void parse(void* data);
void clear(); void clear();
void save(int player, bool force=false); void save(int player, bool force = false);
void flushLeaderboards(); void flushLeaderboards();
void saveLeaderboards(); void saveLeaderboards();
static void setupStatBoards(); static void setupStatBoards();
#ifdef _DEBUG #ifdef _DEBUG
void WipeLeaderboards(); void WipeLeaderboards();
#endif #endif
private: private:
bool isLargeStat(Stat* stat); bool isLargeStat(Stat* stat);
void dumpStatsToTTY(); void dumpStatsToTTY();
#ifdef _XBOX #ifdef _XBOX
static void setLeaderboardProperty(XUSER_PROPERTY* prop, std::uint32_t id, unsigned int value); static void setLeaderboardProperty(XUSER_PROPERTY* prop, std::uint32_t id,
static void setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value); unsigned int value);
static void setLeaderboardRating(XUSER_PROPERTY* prop, LONGLONG value);
#endif #endif
void writeStats(); void writeStats();
}; };

View file

@ -5,42 +5,46 @@ class User;
class File; class File;
class Stat; class Stat;
class StatsSyncher {
class StatsSyncher
{
private: private:
static const int SAVE_INTERVAL = 20 * 5; static const int SAVE_INTERVAL = 20 * 5;
static const int SEND_INTERVAL = 20 * 60; static const int SEND_INTERVAL = 20 * 60;
volatile bool busy; volatile bool busy;
volatile std::unordered_map<Stat *, int> *serverStats; volatile std::unordered_map<Stat*, int>* serverStats;
volatile std::unordered_map<Stat *, int> *failedSentStats; volatile std::unordered_map<Stat*, int>* failedSentStats;
StatsCounter *statsCounter; StatsCounter* statsCounter;
File *unsentFile, *lastServerFile; File *unsentFile, *lastServerFile;
File *unsentFileTmp, *lastServerFileTmp; File *unsentFileTmp, *lastServerFileTmp;
File *unsentFileOld, *lastServerFileOld; File *unsentFileOld, *lastServerFileOld;
User *user; User* user;
int noSaveIn, noSendIn; int noSaveIn, noSendIn;
public: public:
StatsSyncher(User *user, StatsCounter *statsCounter, File *dir); StatsSyncher(User* user, StatsCounter* statsCounter, File* dir);
private: private:
void attemptRename(File *dir, const std::wstring& name, File *to); void attemptRename(File* dir, const std::wstring& name, File* to);
std::unordered_map<Stat *, int> *loadStatsFromDisk(File *file, File *tmp, File *old); std::unordered_map<Stat*, int>* loadStatsFromDisk(File* file, File* tmp,
std::unordered_map<Stat *, int> *loadStatsFromDisk(File *file); File* old);
void doSend(std::unordered_map<Stat *, int> *stats); std::unordered_map<Stat*, int>* loadStatsFromDisk(File* file);
void doSave(std::unordered_map<Stat *, int> *stats, File *file, File *tmp, File *old); void doSend(std::unordered_map<Stat*, int>* stats);
void doSave(std::unordered_map<Stat*, int>* stats, File* file, File* tmp,
File* old);
protected: protected:
std::unordered_map<Stat *, int> *doGetStats(); std::unordered_map<Stat*, int>* doGetStats();
public: public:
void getStatsFromServer(); void getStatsFromServer();
void saveUnsent(std::unordered_map<Stat *, int> *stats); void saveUnsent(std::unordered_map<Stat*, int>* stats);
void sendUnsent(std::unordered_map<Stat *, int> *stats, std::unordered_map<Stat *, int> *fullStats); void sendUnsent(std::unordered_map<Stat*, int>* stats,
void forceSendUnsent(std::unordered_map<Stat *, int> *stats); std::unordered_map<Stat*, int>* fullStats);
void forceSaveUnsent(std::unordered_map<Stat *, int> *stats); void forceSendUnsent(std::unordered_map<Stat*, int>* stats);
void forceSaveUnsent(std::unordered_map<Stat*, int>* stats);
bool maySave(); bool maySave();
bool maySend(); bool maySend();
void tick(); void tick();

View file

@ -11,10 +11,9 @@
#include "../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../../Minecraft.World/Headers/net.minecraft.world.item.h"
#include "../ClientConstants.h" #include "../ClientConstants.h"
SurvivalMode::SurvivalMode(Minecraft *minecraft) : GameMode(minecraft) SurvivalMode::SurvivalMode(Minecraft* minecraft) : GameMode(minecraft) {
{ // 4J - added initialisers
// 4J - added initialisers xDestroyBlock = -1;
xDestroyBlock = -1;
yDestroyBlock = -1; yDestroyBlock = -1;
zDestroyBlock = -1; zDestroyBlock = -1;
destroyProgress = 0; destroyProgress = 0;
@ -22,122 +21,103 @@ SurvivalMode::SurvivalMode(Minecraft *minecraft) : GameMode(minecraft)
destroyTicks = 0; destroyTicks = 0;
destroyDelay = 0; destroyDelay = 0;
if (ClientConstants::IS_DEMO_VERSION) if (ClientConstants::IS_DEMO_VERSION) {
{ if (dynamic_cast<DemoMode*>(this) == NULL) {
if( dynamic_cast<DemoMode *>(this) == NULL ) assert(false);
{ // throw new IllegalStateException("Invalid game mode");
assert(false); // // 4J - removed
// throw new IllegalStateException("Invalid game mode"); // 4J - removed
} }
} }
} }
// 4J Stu - Added this ctor so we can exit the tutorial and replace it with a standard // 4J Stu - Added this ctor so we can exit the tutorial and replace it with a
// survival mode // standard survival mode
SurvivalMode::SurvivalMode(SurvivalMode *copy) : GameMode( copy->minecraft ) SurvivalMode::SurvivalMode(SurvivalMode* copy) : GameMode(copy->minecraft) {
{ xDestroyBlock = copy->xDestroyBlock;
xDestroyBlock = copy->xDestroyBlock; yDestroyBlock = copy->yDestroyBlock;
yDestroyBlock = copy->yDestroyBlock; zDestroyBlock = copy->zDestroyBlock;
zDestroyBlock = copy->zDestroyBlock; destroyProgress = copy->destroyProgress;
destroyProgress = copy->destroyProgress; oDestroyProgress = copy->oDestroyProgress;
oDestroyProgress = copy->oDestroyProgress; destroyTicks = copy->destroyTicks;
destroyTicks = copy->destroyTicks;
destroyDelay = copy->destroyDelay; destroyDelay = copy->destroyDelay;
} }
void SurvivalMode::initPlayer(std::shared_ptr<Player> player) void SurvivalMode::initPlayer(std::shared_ptr<Player> player) {
{ player->yRot = -180;
player->yRot = -180;
} }
void SurvivalMode::init() void SurvivalMode::init() {}
{
}
bool SurvivalMode::canHurtPlayer() bool SurvivalMode::canHurtPlayer() { return true; }
{
return true;
}
bool SurvivalMode::destroyBlock(int x, int y, int z, int face) bool SurvivalMode::destroyBlock(int x, int y, int z, int face) {
{
int t = minecraft->level->getTile(x, y, z); int t = minecraft->level->getTile(x, y, z);
int data = minecraft->level->getData(x, y, z); int data = minecraft->level->getData(x, y, z);
bool changed = GameMode::destroyBlock(x, y, z, face); bool changed = GameMode::destroyBlock(x, y, z, face);
std::shared_ptr<ItemInstance> item = minecraft->player->getSelectedItem(); std::shared_ptr<ItemInstance> item = minecraft->player->getSelectedItem();
bool couldDestroy = minecraft->player->canDestroy(Tile::tiles[t]); bool couldDestroy = minecraft->player->canDestroy(Tile::tiles[t]);
if (item != NULL) if (item != NULL) {
{
item->mineBlock(minecraft->level, t, x, y, z, minecraft->player); item->mineBlock(minecraft->level, t, x, y, z, minecraft->player);
if (item->count == 0) if (item->count == 0) {
{
minecraft->player->removeSelectedItem(); minecraft->player->removeSelectedItem();
} }
} }
if (changed && couldDestroy) if (changed && couldDestroy) {
{ Tile::tiles[t]->playerDestroy(minecraft->level, minecraft->player, x, y,
Tile::tiles[t]->playerDestroy(minecraft->level, minecraft->player, x, y, z, data); z, data);
} }
return changed; return changed;
} }
void SurvivalMode::startDestroyBlock(int x, int y, int z, int face) void SurvivalMode::startDestroyBlock(int x, int y, int z, int face) {
{ if (!minecraft->player->mayBuild(x, y, z)) return;
if (!minecraft->player->mayBuild(x, y, z)) return;
minecraft->level->extinguishFire(minecraft->player, x, y, z, face); minecraft->level->extinguishFire(minecraft->player, x, y, z, face);
int t = minecraft->level->getTile(x, y, z); int t = minecraft->level->getTile(x, y, z);
if (t > 0 && destroyProgress == 0) Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player); if (t > 0 && destroyProgress == 0)
if (t > 0 && Tile::tiles[t]->getDestroyProgress(minecraft->player) >= 1) Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player);
{ if (t > 0 && Tile::tiles[t]->getDestroyProgress(minecraft->player) >= 1) {
destroyBlock(x, y, z, face); destroyBlock(x, y, z, face);
} }
} }
void SurvivalMode::stopDestroyBlock() void SurvivalMode::stopDestroyBlock() {
{
destroyProgress = 0; destroyProgress = 0;
destroyDelay = 0; destroyDelay = 0;
} }
void SurvivalMode::continueDestroyBlock(int x, int y, int z, int face) void SurvivalMode::continueDestroyBlock(int x, int y, int z, int face) {
{ if (destroyDelay > 0) {
if (destroyDelay > 0)
{
destroyDelay--; destroyDelay--;
return; return;
} }
if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) {
{
int t = minecraft->level->getTile(x, y, z); int t = minecraft->level->getTile(x, y, z);
if (!minecraft->player->mayBuild(x, y, z)) return; if (!minecraft->player->mayBuild(x, y, z)) return;
if (t == 0) return; if (t == 0) return;
Tile *tile = Tile::tiles[t]; Tile* tile = Tile::tiles[t];
destroyProgress += tile->getDestroyProgress(minecraft->player); destroyProgress += tile->getDestroyProgress(minecraft->player);
if (destroyTicks % 4 == 0) if (destroyTicks % 4 == 0) {
{ if (tile != NULL) {
if (tile != NULL) minecraft->soundEngine->play(
{ tile->soundType->getStepSound(), x + 0.5f, y + 0.5f,
minecraft->soundEngine->play(tile->soundType->getStepSound(), x + 0.5f, y + 0.5f, z + 0.5f, (tile->soundType->getVolume() + 1) / 8, tile->soundType->getPitch() * 0.5f); z + 0.5f, (tile->soundType->getVolume() + 1) / 8,
tile->soundType->getPitch() * 0.5f);
} }
} }
destroyTicks++; destroyTicks++;
if (destroyProgress >= 1) if (destroyProgress >= 1) {
{
destroyBlock(x, y, z, face); destroyBlock(x, y, z, face);
destroyProgress = 0; destroyProgress = 0;
oDestroyProgress = 0; oDestroyProgress = 0;
destroyTicks = 0; destroyTicks = 0;
destroyDelay = 5; destroyDelay = 5;
} }
} } else {
else
{
destroyProgress = 0; destroyProgress = 0;
oDestroyProgress = 0; oDestroyProgress = 0;
destroyTicks = 0; destroyTicks = 0;
@ -145,64 +125,49 @@ void SurvivalMode::continueDestroyBlock(int x, int y, int z, int face)
yDestroyBlock = y; yDestroyBlock = y;
zDestroyBlock = z; zDestroyBlock = z;
} }
} }
void SurvivalMode::render(float a) void SurvivalMode::render(float a) {
{ if (destroyProgress <= 0) {
if (destroyProgress <= 0)
{
minecraft->gui->progress = 0; minecraft->gui->progress = 0;
minecraft->levelRenderer->destroyProgress = 0; minecraft->levelRenderer->destroyProgress = 0;
} } else {
else
{
float dp = oDestroyProgress + (destroyProgress - oDestroyProgress) * a; float dp = oDestroyProgress + (destroyProgress - oDestroyProgress) * a;
minecraft->gui->progress = dp; minecraft->gui->progress = dp;
minecraft->levelRenderer->destroyProgress = dp; minecraft->levelRenderer->destroyProgress = dp;
} }
} }
float SurvivalMode::getPickRange() float SurvivalMode::getPickRange() { return 4.0f; }
{
return 4.0f; void SurvivalMode::initLevel(Level* level) { GameMode::initLevel(level); }
std::shared_ptr<Player> SurvivalMode::createPlayer(Level* level) {
std::shared_ptr<Player> player = GameMode::createPlayer(level);
// player.inventory.add(new ItemInstance(Item.pickAxe_diamond));
// player.inventory.add(new ItemInstance(Item.hatchet_diamond));
// player.inventory.add(new ItemInstance(Tile.torch, 64));
// player.inventory.add(new ItemInstance(Item.porkChop_cooked, 4));
// player.inventory.add(new ItemInstance(Item.bow, 1));
// player.inventory.add(new ItemInstance(Item.arrow, 64));
return player;
} }
void SurvivalMode::initLevel(Level *level) void SurvivalMode::tick() {
{
GameMode::initLevel(level);
}
std::shared_ptr<Player> SurvivalMode::createPlayer(Level *level)
{
std::shared_ptr<Player> player = GameMode::createPlayer(level);
// player.inventory.add(new ItemInstance(Item.pickAxe_diamond));
// player.inventory.add(new ItemInstance(Item.hatchet_diamond));
// player.inventory.add(new ItemInstance(Tile.torch, 64));
// player.inventory.add(new ItemInstance(Item.porkChop_cooked, 4));
// player.inventory.add(new ItemInstance(Item.bow, 1));
// player.inventory.add(new ItemInstance(Item.arrow, 64));
return player;
}
void SurvivalMode::tick()
{
oDestroyProgress = destroyProgress; oDestroyProgress = destroyProgress;
//minecraft->soundEngine->playMusicTick(); // minecraft->soundEngine->playMusicTick();
} }
bool SurvivalMode::useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, bool bTestUseOnOnly, bool *pbUsedItem) bool SurvivalMode::useItemOn(std::shared_ptr<Player> player, Level* level,
{ std::shared_ptr<ItemInstance> item, int x, int y,
int t = level->getTile(x, y, z); int z, int face, bool bTestUseOnOnly,
if (t > 0) bool* pbUsedItem) {
{ int t = level->getTile(x, y, z);
if (Tile::tiles[t]->use(level, x, y, z, player)) return true; if (t > 0) {
} if (Tile::tiles[t]->use(level, x, y, z, player)) return true;
if (item == NULL) return false; }
return item->useOn(player, level, x, y, z, face); if (item == NULL) return false;
return item->useOn(player, level, x, y, z, face);
} }
bool SurvivalMode::hasExperience() bool SurvivalMode::hasExperience() { return true; }
{
return true;
}

View file

@ -1,32 +1,34 @@
#pragma once #pragma once
#include "GameMode.h" #include "GameMode.h"
class SurvivalMode : public GameMode class SurvivalMode : public GameMode {
{
private: private:
int xDestroyBlock; int xDestroyBlock;
int yDestroyBlock; int yDestroyBlock;
int zDestroyBlock; int zDestroyBlock;
float destroyProgress; float destroyProgress;
float oDestroyProgress; float oDestroyProgress;
int destroyTicks; // 4J was float but doesn't seem to need to be int destroyTicks; // 4J was float but doesn't seem to need to be
int destroyDelay; int destroyDelay;
public: public:
SurvivalMode(Minecraft *minecraft); SurvivalMode(Minecraft* minecraft);
SurvivalMode(SurvivalMode *copy); SurvivalMode(SurvivalMode* copy);
virtual void initPlayer(std::shared_ptr<Player> player); virtual void initPlayer(std::shared_ptr<Player> player);
virtual void init(); virtual void init();
virtual bool canHurtPlayer(); virtual bool canHurtPlayer();
virtual bool destroyBlock(int x, int y, int z, int face); virtual bool destroyBlock(int x, int y, int z, int face);
virtual void startDestroyBlock(int x, int y, int z, int face); virtual void startDestroyBlock(int x, int y, int z, int face);
virtual void stopDestroyBlock(); virtual void stopDestroyBlock();
virtual void continueDestroyBlock(int x, int y, int z, int face); virtual void continueDestroyBlock(int x, int y, int z, int face);
virtual void render(float a); virtual void render(float a);
virtual float getPickRange(); virtual float getPickRange();
virtual void initLevel(Level *level); virtual void initLevel(Level* level);
virtual std::shared_ptr<Player> createPlayer(Level *level); virtual std::shared_ptr<Player> createPlayer(Level* level);
virtual void tick(); virtual void tick();
virtual bool useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, bool bTestUseOnOnly=false, bool *pbUsedItem=NULL); virtual bool useItemOn(std::shared_ptr<Player> player, Level* level,
virtual bool hasExperience(); std::shared_ptr<ItemInstance> item, int x, int y,
int z, int face, bool bTestUseOnOnly = false,
bool* pbUsedItem = NULL);
virtual bool hasExperience();
}; };

View file

@ -1,8 +1,8 @@
#include "../Platform/stdafx.h" #include "../Platform/stdafx.h"
#include "ConsoleInput.h" #include "ConsoleInput.h"
ConsoleInput::ConsoleInput(const std::wstring& msg, ConsoleInputSource *source) ConsoleInput::ConsoleInput(const std::wstring& msg,
{ ConsoleInputSource* source) {
this->msg = msg; this->msg = msg;
this->source = source; this->source = source;
} }

View file

@ -1,12 +1,10 @@
#pragma once #pragma once
#include "ConsoleInputSource.h" #include "ConsoleInputSource.h"
class ConsoleInput {
class ConsoleInput
{
public: public:
std::wstring msg; std::wstring msg;
ConsoleInputSource *source; ConsoleInputSource* source;
ConsoleInput(const std::wstring& msg, ConsoleInputSource *source); ConsoleInput(const std::wstring& msg, ConsoleInputSource* source);
}; };

View file

@ -1,10 +1,9 @@
#pragma once #pragma once
class ConsoleInputSource class ConsoleInputSource {
{
public: public:
virtual ~ConsoleInputSource(){} virtual ~ConsoleInputSource() {}
virtual void info(const std::wstring& string) = 0; virtual void info(const std::wstring& string) = 0;
virtual void warn(const std::wstring& string) = 0; virtual void warn(const std::wstring& string) = 0;
virtual std::wstring getConsoleName() = 0; virtual std::wstring getConsoleName() = 0;
}; };

View file

@ -8,108 +8,123 @@
#include "../Player/LocalPlayer.h" #include "../Player/LocalPlayer.h"
#include "../GameState/Options.h" #include "../GameState/Options.h"
Input::Input() Input::Input() {
{ xa = 0;
xa = 0; ya = 0;
ya = 0; wasJumping = false;
wasJumping = false; jumping = false;
jumping = false; sneaking = false;
sneaking = false; sprintKey = false;
sprintKey = false;
lReset = false; lReset = false;
rReset = false; rReset = false;
} }
void Input::tick(LocalPlayer *player) void Input::tick(LocalPlayer* player) {
{ // 4J Stu - Assume that we only need one input class, even though the java
// 4J Stu - Assume that we only need one input class, even though the java has subclasses for keyboard/controller // has subclasses for keyboard/controller This function is based on the
// This function is based on the ControllerInput class in the Java, and will probably need changed // ControllerInput class in the Java, and will probably need changed
//OutputDebugString("INPUT: Beginning input tick\n"); // OutputDebugString("INPUT: Beginning input tick\n");
Minecraft *pMinecraft=Minecraft::GetInstance(); Minecraft* pMinecraft = Minecraft::GetInstance();
int iPad=player->GetXboxPad(); int iPad = player->GetXboxPad();
// 4J-PB minecraft movement seems to be the wrong way round, so invert x! // 4J-PB minecraft movement seems to be the wrong way round, so invert x!
if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LEFT) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_RIGHT) ) if (pMinecraft->localgameModes[iPad]->isInputAllowed(
xa = -InputManager.GetJoypadStick_LX(iPad); MINECRAFT_ACTION_LEFT) ||
else pMinecraft->localgameModes[iPad]->isInputAllowed(
xa = 0.0f; MINECRAFT_ACTION_RIGHT))
xa = -InputManager.GetJoypadStick_LX(iPad);
if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_FORWARD) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_BACKWARD) ) else
ya = InputManager.GetJoypadStick_LY(iPad); xa = 0.0f;
else
ya = 0.0f; if (pMinecraft->localgameModes[iPad]->isInputAllowed(
MINECRAFT_ACTION_FORWARD) ||
pMinecraft->localgameModes[iPad]->isInputAllowed(
MINECRAFT_ACTION_BACKWARD))
ya = InputManager.GetJoypadStick_LY(iPad);
else
ya = 0.0f;
#ifndef _CONTENT_PACKAGE #ifndef _CONTENT_PACKAGE
if (app.GetFreezePlayers()) if (app.GetFreezePlayers()) {
{ xa = ya = 0.0f;
xa = ya = 0.0f; player->abilities.flying = true;
player->abilities.flying = true; }
}
#endif #endif
if (!lReset) if (!lReset) {
{ if (xa * xa + ya * ya == 0.0f) {
if (xa*xa+ya*ya==0.0f)
{
lReset = true; lReset = true;
} }
xa = ya = 0.0f; xa = ya = 0.0f;
} }
// 4J - in flying mode, don't actually toggle sneaking // 4J - in flying mode, don't actually toggle sneaking
if(!player->abilities.flying) if (!player->abilities.flying) {
{ if ((player->ullButtonsPressed &
if((player->ullButtonsPressed&(1LL<<MINECRAFT_ACTION_SNEAK_TOGGLE)) && pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_SNEAK_TOGGLE)) (1LL << MINECRAFT_ACTION_SNEAK_TOGGLE)) &&
{ pMinecraft->localgameModes[iPad]->isInputAllowed(
sneaking=!sneaking; MINECRAFT_ACTION_SNEAK_TOGGLE)) {
} sneaking = !sneaking;
} }
}
if(sneaking) if (sneaking) {
{ xa *= 0.3f;
xa*=0.3f; ya *= 0.3f;
ya*=0.3f; }
}
float turnSpeed = 50.0f; float turnSpeed = 50.0f;
float tx = 0.0f; float tx = 0.0f;
float ty = 0.0f; float ty = 0.0f;
if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_LEFT) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_RIGHT) ) if (pMinecraft->localgameModes[iPad]->isInputAllowed(
tx = InputManager.GetJoypadStick_RX(iPad)*(((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look MINECRAFT_ACTION_LOOK_LEFT) ||
if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_UP) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_LOOK_DOWN) ) pMinecraft->localgameModes[iPad]->isInputAllowed(
ty = InputManager.GetJoypadStick_RY(iPad)*(((float)app.GetGameSettings(iPad,eGameSetting_Sensitivity_InGame))/100.0f); // apply sensitivity to look MINECRAFT_ACTION_LOOK_RIGHT))
tx = InputManager.GetJoypadStick_RX(iPad) *
(((float)app.GetGameSettings(iPad,
eGameSetting_Sensitivity_InGame)) /
100.0f); // apply sensitivity to look
if (pMinecraft->localgameModes[iPad]->isInputAllowed(
MINECRAFT_ACTION_LOOK_UP) ||
pMinecraft->localgameModes[iPad]->isInputAllowed(
MINECRAFT_ACTION_LOOK_DOWN))
ty = InputManager.GetJoypadStick_RY(iPad) *
(((float)app.GetGameSettings(iPad,
eGameSetting_Sensitivity_InGame)) /
100.0f); // apply sensitivity to look
#ifndef _CONTENT_PACKAGE #ifndef _CONTENT_PACKAGE
if (app.GetFreezePlayers()) tx = ty = 0.0f; if (app.GetFreezePlayers()) tx = ty = 0.0f;
#endif #endif
// 4J: WESTY : Invert look Y if required. // 4J: WESTY : Invert look Y if required.
if ( app.GetGameSettings(iPad,eGameSetting_ControlInvertLook) ) if (app.GetGameSettings(iPad, eGameSetting_ControlInvertLook)) {
{ ty = -ty;
ty = -ty; }
}
if (!rReset) if (!rReset) {
{ if (tx * tx + ty * ty == 0.0f) {
if (tx*tx+ty*ty==0.0f)
{
rReset = true; rReset = true;
} }
tx = ty = 0.0f; tx = ty = 0.0f;
} }
player->interpolateTurn(tx * abs(tx) * turnSpeed, ty * abs(ty) * turnSpeed); player->interpolateTurn(tx * abs(tx) * turnSpeed, ty * abs(ty) * turnSpeed);
//jumping = controller.isButtonPressed(0);
sprintKey = InputManager.GetValue(iPad, MINECRAFT_ACTION_SPRINT) && pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_SPRINT); // jumping = controller.isButtonPressed(0);
jumping = InputManager.GetValue(iPad, MINECRAFT_ACTION_JUMP) && pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_JUMP);
sprintKey = InputManager.GetValue(iPad, MINECRAFT_ACTION_SPRINT) &&
pMinecraft->localgameModes[iPad]->isInputAllowed(
MINECRAFT_ACTION_SPRINT);
jumping =
InputManager.GetValue(iPad, MINECRAFT_ACTION_JUMP) &&
pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_JUMP);
#ifndef _CONTENT_PACKAGE #ifndef _CONTENT_PACKAGE
if (app.GetFreezePlayers()) jumping = false; if (app.GetFreezePlayers()) jumping = false;
#endif #endif
//OutputDebugString("INPUT: End input tick\n"); // OutputDebugString("INPUT: End input tick\n");
} }

View file

@ -1,24 +1,22 @@
#pragma once #pragma once
class Player; class Player;
class Input class Input {
{
public: public:
float xa; float xa;
float ya; float ya;
bool wasJumping; bool wasJumping;
bool jumping; bool jumping;
bool sneaking; bool sneaking;
bool sprintKey; bool sprintKey;
Input(); // 4J - added
virtual ~Input(){}
virtual void tick(LocalPlayer *player); Input(); // 4J - added
virtual ~Input() {}
virtual void tick(LocalPlayer* player);
private: private:
bool lReset; bool lReset;
bool rReset; bool rReset;
}; };

View file

@ -1,8 +1,7 @@
#include "../Platform/stdafx.h" #include "../Platform/stdafx.h"
#include "KeyMapping.h" #include "KeyMapping.h"
KeyMapping::KeyMapping(const std::wstring& name, int key) KeyMapping::KeyMapping(const std::wstring& name, int key) {
{ this->name = name;
this->name = name; this->key = key;
this->key = key;
} }

View file

@ -1,10 +1,9 @@
#pragma once #pragma once
// 4J Stu - Not updated to 1.8.2 as we don't use this // 4J Stu - Not updated to 1.8.2 as we don't use this
class KeyMapping class KeyMapping {
{
public: public:
std::wstring name; std::wstring name;
int key; int key;
KeyMapping(const std::wstring& name, int key); KeyMapping(const std::wstring& name, int key);
}; };

View file

@ -2,24 +2,17 @@
#include "DemoLevel.h" #include "DemoLevel.h"
#include "../../Minecraft.World/Headers/net.minecraft.world.level.storage.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.storage.h"
LevelSettings DemoLevel::DEMO_LEVEL_SETTINGS = LevelSettings( LevelSettings DemoLevel::DEMO_LEVEL_SETTINGS =
DemoLevel::DEMO_LEVEL_SEED, LevelSettings(DemoLevel::DEMO_LEVEL_SEED, GameType::SURVIVAL, false, false,
GameType::SURVIVAL, false, LevelType::lvl_normal_1_1, LEVEL_MAX_WIDTH, 1.0);
false,
false,
false, LevelType::lvl_normal_1_1, LEVEL_MAX_WIDTH,
1.0
);
DemoLevel::DemoLevel(std::shared_ptr<LevelStorage> levelStorage, const std::wstring& levelName) : Level(levelStorage, levelName, &DEMO_LEVEL_SETTINGS) DemoLevel::DemoLevel(std::shared_ptr<LevelStorage> levelStorage,
{ const std::wstring& levelName)
} : Level(levelStorage, levelName, &DEMO_LEVEL_SETTINGS) {}
DemoLevel::DemoLevel(Level *level, Dimension *dimension): Level(level, dimension) DemoLevel::DemoLevel(Level* level, Dimension* dimension)
{ : Level(level, dimension) {}
}
void DemoLevel::setInitialSpawn() void DemoLevel::setInitialSpawn() {
{ levelData->setSpawn(DEMO_SPAWN_X, DEMO_SPAWN_Y, DEMO_SPAWN_Z);
levelData->setSpawn(DEMO_SPAWN_X, DEMO_SPAWN_Y, DEMO_SPAWN_Z);
} }

View file

@ -1,17 +1,20 @@
#pragma once #pragma once
#include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.h"
class DemoLevel : public Level class DemoLevel : public Level {
{
private: private:
static const __int64 DEMO_LEVEL_SEED = 0; // 4J - TODO - was "Don't Look Back".hashCode(); static const __int64 DEMO_LEVEL_SEED =
0; // 4J - TODO - was "Don't Look Back".hashCode();
static const int DEMO_SPAWN_X = 796; static const int DEMO_SPAWN_X = 796;
static const int DEMO_SPAWN_Y = 72; static const int DEMO_SPAWN_Y = 72;
static const int DEMO_SPAWN_Z = -731; static const int DEMO_SPAWN_Z = -731;
static LevelSettings DEMO_LEVEL_SETTINGS; static LevelSettings DEMO_LEVEL_SETTINGS;
public: public:
DemoLevel(std::shared_ptr<LevelStorage> levelStorage, const std::wstring& levelName); DemoLevel(std::shared_ptr<LevelStorage> levelStorage,
DemoLevel(Level *level, Dimension *dimension); const std::wstring& levelName);
DemoLevel(Level* level, Dimension* dimension);
protected: protected:
virtual void setInitialSpawn(); virtual void setInitialSpawn();
}; };

View file

@ -3,27 +3,28 @@
#include "../../Minecraft.World/Level/Storage/SavedDataStorage.h" #include "../../Minecraft.World/Level/Storage/SavedDataStorage.h"
#include "../../Minecraft.World/Level/DerivedLevelData.h" #include "../../Minecraft.World/Level/DerivedLevelData.h"
DerivedServerLevel::DerivedServerLevel(MinecraftServer *server, std::shared_ptr<LevelStorage> levelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings, ServerLevel *wrapped) DerivedServerLevel::DerivedServerLevel(
: ServerLevel(server, levelStorage, levelName, dimension, levelSettings) MinecraftServer* server, std::shared_ptr<LevelStorage> levelStorage,
{ const std::wstring& levelName, int dimension, LevelSettings* levelSettings,
// 4J-PB - we're going to override the savedDataStorage, so we need to delete the current one ServerLevel* wrapped)
if(this->savedDataStorage) : ServerLevel(server, levelStorage, levelName, dimension, levelSettings) {
{ // 4J-PB - we're going to override the savedDataStorage, so we need to
delete this->savedDataStorage; // delete the current one
this->savedDataStorage=NULL; if (this->savedDataStorage) {
} delete this->savedDataStorage;
this->savedDataStorage = wrapped->savedDataStorage; this->savedDataStorage = NULL;
levelData = new DerivedLevelData(wrapped->getLevelData()); }
this->savedDataStorage = wrapped->savedDataStorage;
levelData = new DerivedLevelData(wrapped->getLevelData());
} }
DerivedServerLevel::~DerivedServerLevel() DerivedServerLevel::~DerivedServerLevel() {
{ // we didn't allocate savedDataStorage here, so we don't want the level
// we didn't allocate savedDataStorage here, so we don't want the level destructor to delete it // destructor to delete it
this->savedDataStorage=NULL; this->savedDataStorage = NULL;
} }
void DerivedServerLevel::saveLevelData() void DerivedServerLevel::saveLevelData() {
{ // Do nothing?
// Do nothing? // Do nothing!
// Do nothing!
} }

View file

@ -1,12 +1,14 @@
#pragma once #pragma once
#include "ServerLevel.h" #include "ServerLevel.h"
class DerivedServerLevel : public ServerLevel class DerivedServerLevel : public ServerLevel {
{
public: public:
DerivedServerLevel(MinecraftServer *server, std::shared_ptr<LevelStorage>levelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings, ServerLevel *wrapped); DerivedServerLevel(MinecraftServer* server,
~DerivedServerLevel(); std::shared_ptr<LevelStorage> levelStorage,
const std::wstring& levelName, int dimension,
LevelSettings* levelSettings, ServerLevel* wrapped);
~DerivedServerLevel();
protected: protected:
void saveLevelData(); void saveLevelData();
}; };

File diff suppressed because it is too large Load diff

View file

@ -8,95 +8,111 @@
class ClientConnection; class ClientConnection;
class MultiPlayerChunkCache; class MultiPlayerChunkCache;
class MultiPlayerLevel : public Level {
class MultiPlayerLevel : public Level
{
private: private:
static const int TICKS_BEFORE_RESET = 20 * 4; static const int TICKS_BEFORE_RESET = 20 * 4;
class ResetInfo class ResetInfo {
{ public:
public:
int x, y, z, ticks, tile, data; int x, y, z, ticks, tile, data;
ResetInfo(int x, int y, int z, int tile, int data); ResetInfo(int x, int y, int z, int tile, int data);
}; };
std::vector<ResetInfo> updatesToReset; // 4J - was linked list but vector seems more appropriate std::vector<ResetInfo> updatesToReset; // 4J - was linked list but vector
bool m_bEnableResetChanges; // 4J Added // seems more appropriate
bool m_bEnableResetChanges; // 4J Added
public: public:
void unshareChunkAt(int x, int z); // 4J - added void unshareChunkAt(int x, int z); // 4J - added
void shareChunkAt(int x, int z); // 4J - added void shareChunkAt(int x, int z); // 4J - added
void enableResetChanges(bool enable) { m_bEnableResetChanges = enable; } // 4J Added void enableResetChanges(bool enable) {
m_bEnableResetChanges = enable;
} // 4J Added
private: private:
int unshareCheckX; // 4J - added int unshareCheckX; // 4J - added
int unshareCheckZ; // 4J - added int unshareCheckZ; // 4J - added
int compressCheckX; // 4J - added int compressCheckX; // 4J - added
int compressCheckZ; // 4J - added int compressCheckZ; // 4J - added
std::vector<ClientConnection *> connections; // 4J Stu - Made this a vector as we can have more than one local connection std::vector<ClientConnection*>
MultiPlayerChunkCache *chunkCache; connections; // 4J Stu - Made this a vector as we can have more than
Minecraft *minecraft; // one local connection
MultiPlayerChunkCache* chunkCache;
Minecraft* minecraft;
public: public:
MultiPlayerLevel(ClientConnection *connection, LevelSettings *levelSettings, int dimension, int difficulty); MultiPlayerLevel(ClientConnection* connection, LevelSettings* levelSettings,
virtual ~MultiPlayerLevel(); int dimension, int difficulty);
virtual void tick() ; virtual ~MultiPlayerLevel();
virtual void tick();
void clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1);
void clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1);
protected: protected:
ChunkSource *createChunkSource(); // 4J - was virtual, but was called from parent ctor ChunkSource*
createChunkSource(); // 4J - was virtual, but was called from parent ctor
public: public:
virtual void validateSpawn(); virtual void validateSpawn();
protected: protected:
virtual void tickTiles(); virtual void tickTiles();
public: public:
void setChunkVisible(int x, int z, bool visible); void setChunkVisible(int x, int z, bool visible);
private: private:
std::unordered_map<int, std::shared_ptr<Entity>, IntKeyHash2, IntKeyEq> entitiesById; // 4J - was IntHashMap std::unordered_map<int, std::shared_ptr<Entity>, IntKeyHash2, IntKeyEq>
entitiesById; // 4J - was IntHashMap
std::unordered_set<std::shared_ptr<Entity> > forced; std::unordered_set<std::shared_ptr<Entity> > forced;
std::unordered_set<std::shared_ptr<Entity> > reEntries; std::unordered_set<std::shared_ptr<Entity> > reEntries;
public: public:
virtual bool addEntity(std::shared_ptr<Entity> e); virtual bool addEntity(std::shared_ptr<Entity> e);
virtual void removeEntity(std::shared_ptr<Entity> e); virtual void removeEntity(std::shared_ptr<Entity> e);
protected: protected:
virtual void entityAdded(std::shared_ptr<Entity> e); virtual void entityAdded(std::shared_ptr<Entity> e);
virtual void entityRemoved(std::shared_ptr<Entity> e); virtual void entityRemoved(std::shared_ptr<Entity> e);
public: public:
void putEntity(int id, std::shared_ptr<Entity> e); void putEntity(int id, std::shared_ptr<Entity> e);
std::shared_ptr<Entity> getEntity(int id); std::shared_ptr<Entity> getEntity(int id);
std::shared_ptr<Entity> removeEntity(int id); std::shared_ptr<Entity> removeEntity(int id);
virtual void removeEntities(std::vector<std::shared_ptr<Entity> > *list); // 4J Added override virtual void removeEntities(
std::vector<std::shared_ptr<Entity> >* list); // 4J Added override
virtual bool setDataNoUpdate(int x, int y, int z, int data); virtual bool setDataNoUpdate(int x, int y, int z, int data);
virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile, int data); virtual bool setTileAndDataNoUpdate(int x, int y, int z, int tile,
int data);
virtual bool setTileNoUpdate(int x, int y, int z, int tile); virtual bool setTileNoUpdate(int x, int y, int z, int tile);
bool doSetTileAndData(int x, int y, int z, int tile, int data); bool doSetTileAndData(int x, int y, int z, int tile, int data);
virtual void disconnect(bool sendDisconnect = true); virtual void disconnect(bool sendDisconnect = true);
void animateTick(int xt, int yt, int zt); void animateTick(int xt, int yt, int zt);
protected: protected:
virtual void tickWeather(); virtual void tickWeather();
static const int ANIMATE_TICK_MAX_PARTICLES = 500; static const int ANIMATE_TICK_MAX_PARTICLES = 500;
public: public:
void animateTickDoWork(); // 4J added void animateTickDoWork(); // 4J added
std::unordered_set<int> chunksToAnimate; // 4J added std::unordered_set<int> chunksToAnimate; // 4J added
public: public:
void removeAllPendingEntityRemovals(); void removeAllPendingEntityRemovals();
virtual void playSound(std::shared_ptr<Entity> entity, int iSound, float volume, float pitch); virtual void playSound(std::shared_ptr<Entity> entity, int iSound,
float volume, float pitch);
virtual void playLocalSound(double x, double y, double z, int iSound, float volume, float pitch, float fClipSoundDist=16.0f); virtual void playLocalSound(double x, double y, double z, int iSound,
float volume, float pitch,
float fClipSoundDist = 16.0f);
// 4J Stu - Added so we can have multiple local connections // 4J Stu - Added so we can have multiple local connections
void addClientConnection(ClientConnection *c) { connections.push_back( c ); } void addClientConnection(ClientConnection* c) { connections.push_back(c); }
void removeClientConnection(ClientConnection *c, bool sendDisconnect); void removeClientConnection(ClientConnection* c, bool sendDisconnect);
void tickAllConnections(); void tickAllConnections();
void dataReceivedForChunk(int x, int z); // 4J added void dataReceivedForChunk(int x, int z); // 4J added
void removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1); // 4J added void removeUnusedTileEntitiesInRegion(int x0, int y0, int z0, int x1,
int y1, int z1); // 4J added
}; };

File diff suppressed because it is too large Load diff

View file

@ -7,165 +7,193 @@ class Node;
class EntityTracker; class EntityTracker;
class PlayerChunkMap; class PlayerChunkMap;
class ServerLevel : public Level {
class ServerLevel : public Level
{
private: private:
static const int EMPTY_TIME_NO_TICK = SharedConstants::TICKS_PER_SECOND * 3; static const int EMPTY_TIME_NO_TICK = SharedConstants::TICKS_PER_SECOND * 3;
MinecraftServer *server; MinecraftServer* server;
EntityTracker *tracker; EntityTracker* tracker;
PlayerChunkMap *chunkMap; PlayerChunkMap* chunkMap;
CRITICAL_SECTION m_tickNextTickCS; // 4J added CRITICAL_SECTION m_tickNextTickCS; // 4J added
std::set<TickNextTickData, TickNextTickDataKeyCompare> tickNextTickList; // 4J Was TreeSet std::set<TickNextTickData, TickNextTickDataKeyCompare>
std::unordered_set<TickNextTickData, TickNextTickDataKeyHash, TickNextTickDataKeyEq> tickNextTickSet; // 4J Was HashSet tickNextTickList; // 4J Was TreeSet
std::unordered_set<TickNextTickData, TickNextTickDataKeyHash,
TickNextTickDataKeyEq>
tickNextTickSet; // 4J Was HashSet
std::vector<Pos *> m_queuedSendTileUpdates; // 4J added std::vector<Pos*> m_queuedSendTileUpdates; // 4J added
CRITICAL_SECTION m_csQueueSendTileUpdates; CRITICAL_SECTION m_csQueueSendTileUpdates;
protected: protected:
int saveInterval; int saveInterval;
public: public:
ServerChunkCache *cache; ServerChunkCache* cache;
bool canEditSpawn; bool canEditSpawn;
bool noSave; bool noSave;
private:
bool allPlayersSleeping;
int emptyTime;
bool m_bAtLeastOnePlayerSleeping; // 4J Added
static WeighedTreasureArray RANDOM_BONUS_ITEMS; // 4J - brought forward from 1.3.2
std::vector<TileEventData> tileEvents[2];
int activeTileEventsList;
public:
static void staticCtor();
ServerLevel(MinecraftServer *server, std::shared_ptr<LevelStorage>levelStorage, const std::wstring& levelName, int dimension, LevelSettings *levelSettings);
~ServerLevel();
void tick();
Biome::MobSpawnerData *getRandomMobSpawnAt(MobCategory *mobCategory, int x, int y, int z);
void updateSleepingPlayerList();
protected:
void awakenAllPlayers();
private: private:
void stopWeather(); bool allPlayersSleeping;
int emptyTime;
bool m_bAtLeastOnePlayerSleeping; // 4J Added
static WeighedTreasureArray
RANDOM_BONUS_ITEMS; // 4J - brought forward from 1.3.2
std::vector<TileEventData> tileEvents[2];
int activeTileEventsList;
public: public:
bool allPlayersAreSleeping(); static void staticCtor();
void validateSpawn(); ServerLevel(MinecraftServer* server,
std::shared_ptr<LevelStorage> levelStorage,
const std::wstring& levelName, int dimension,
LevelSettings* levelSettings);
~ServerLevel();
void tick();
Biome::MobSpawnerData* getRandomMobSpawnAt(MobCategory* mobCategory, int x,
int y, int z);
void updateSleepingPlayerList();
protected: protected:
void tickTiles(); void awakenAllPlayers();
private:
void stopWeather();
public: public:
void addToTickNextTick(int x, int y, int z, int tileId, int tickDelay); bool allPlayersAreSleeping();
void forceAddTileTick(int x, int y, int z, int tileId, int tickDelay); void validateSpawn();
void tickEntities();
bool tickPendingTicks(bool force); protected:
std::vector<TickNextTickData> *fetchTicksInChunk(LevelChunk *chunk, bool remove); void tickTiles();
public:
void addToTickNextTick(int x, int y, int z, int tileId, int tickDelay);
void forceAddTileTick(int x, int y, int z, int tileId, int tickDelay);
void tickEntities();
bool tickPendingTicks(bool force);
std::vector<TickNextTickData>* fetchTicksInChunk(LevelChunk* chunk,
bool remove);
virtual void tick(std::shared_ptr<Entity> e, bool actual); virtual void tick(std::shared_ptr<Entity> e, bool actual);
void forceTick(std::shared_ptr<Entity> e, bool actual); void forceTick(std::shared_ptr<Entity> e, bool actual);
bool AllPlayersAreSleeping() { return allPlayersSleeping;} // 4J added for a message to other players bool AllPlayersAreSleeping() {
bool isAtLeastOnePlayerSleeping() { return m_bAtLeastOnePlayerSleeping;} return allPlayersSleeping;
} // 4J added for a message to other players
bool isAtLeastOnePlayerSleeping() { return m_bAtLeastOnePlayerSleeping; }
protected: protected:
ChunkSource *createChunkSource(); // 4J - was virtual, but was called from parent ctor ChunkSource*
createChunkSource(); // 4J - was virtual, but was called from parent ctor
public: public:
std::vector<std::shared_ptr<TileEntity> > *getTileEntitiesInRegion(int x0, int y0, int z0, int x1, int y1, int z1); std::vector<std::shared_ptr<TileEntity> >* getTileEntitiesInRegion(
virtual bool mayInteract(std::shared_ptr<Player> player, int xt, int yt, int zt, int id); int x0, int y0, int z0, int x1, int y1, int z1);
virtual bool mayInteract(std::shared_ptr<Player> player, int xt, int yt,
int zt, int id);
protected: protected:
virtual void initializeLevel(LevelSettings *settings); virtual void initializeLevel(LevelSettings* settings);
virtual void setInitialSpawn(LevelSettings *settings); virtual void setInitialSpawn(LevelSettings* settings);
void generateBonusItemsNearSpawn(); // 4J - brought forward from 1.3.2 void generateBonusItemsNearSpawn(); // 4J - brought forward from 1.3.2
public: public:
Pos *getDimensionSpecificSpawn(); Pos* getDimensionSpecificSpawn();
void Suspend(); // 4j Added for XboxOne PLM void Suspend(); // 4j Added for XboxOne PLM
void save(bool force, ProgressListener *progressListener, bool bAutosave=false); void save(bool force, ProgressListener* progressListener,
void saveToDisc(ProgressListener *progressListener, bool autosave); // 4J Added bool bAutosave = false);
void saveToDisc(ProgressListener* progressListener,
bool autosave); // 4J Added
private: private:
void saveLevelData(); void saveLevelData();
typedef std::unordered_map<int, std::shared_ptr<Entity> , IntKeyHash2, IntKeyEq> intEntityMap; typedef std::unordered_map<int, std::shared_ptr<Entity>, IntKeyHash2,
intEntityMap entitiesById; // 4J - was IntHashMap, using same hashing function as this uses IntKeyEq>
intEntityMap;
intEntityMap entitiesById; // 4J - was IntHashMap, using same hashing
// function as this uses
protected: protected:
virtual void entityAdded(std::shared_ptr<Entity> e); virtual void entityAdded(std::shared_ptr<Entity> e);
virtual void entityRemoved(std::shared_ptr<Entity> e); virtual void entityRemoved(std::shared_ptr<Entity> e);
public: public:
std::shared_ptr<Entity> getEntity(int id); std::shared_ptr<Entity> getEntity(int id);
virtual bool addGlobalEntity(std::shared_ptr<Entity> e); virtual bool addGlobalEntity(std::shared_ptr<Entity> e);
void broadcastEntityEvent(std::shared_ptr<Entity> e, uint8_t event); void broadcastEntityEvent(std::shared_ptr<Entity> e, uint8_t event);
virtual std::shared_ptr<Explosion> explode(std::shared_ptr<Entity> source, double x, double y, double z, float r, bool fire, bool destroyBlocks); virtual std::shared_ptr<Explosion> explode(std::shared_ptr<Entity> source,
double x, double y, double z,
float r, bool fire,
bool destroyBlocks);
virtual void tileEvent(int x, int y, int z, int tile, int b0, int b1); virtual void tileEvent(int x, int y, int z, int tile, int b0, int b1);
private: private:
void runTileEvents(); void runTileEvents();
bool doTileEvent(TileEventData *te); bool doTileEvent(TileEventData* te);
public: public:
void closeLevelStorage(); void closeLevelStorage();
protected: protected:
virtual void tickWeather(); virtual void tickWeather();
public: public:
MinecraftServer *getServer(); MinecraftServer* getServer();
EntityTracker *getTracker(); EntityTracker* getTracker();
void setTimeAndAdjustTileTicks(__int64 newTime); void setTimeAndAdjustTileTicks(__int64 newTime);
PlayerChunkMap *getChunkMap(); PlayerChunkMap* getChunkMap();
void queueSendTileUpdate(int x, int y, int z); // 4J Added void queueSendTileUpdate(int x, int y, int z); // 4J Added
private: private:
void runQueuedSendTileUpdates();// 4J Added void runQueuedSendTileUpdates(); // 4J Added
// 4J - added for implementation of finite limit to number of item entities, tnt and falling block entities // 4J - added for implementation of finite limit to number of item entities,
// tnt and falling block entities
public: public:
static const int MAX_HANGING_ENTITIES = 400;
static const int MAX_ITEM_ENTITIES = 200;
static const int MAX_ARROW_ENTITIES = 200;
static const int MAX_EXPERIENCEORB_ENTITIES = 50;
static const int MAX_PRIMED_TNT = 20;
static const int MAX_FALLING_TILE = 20;
static const int MAX_HANGING_ENTITIES = 400; int m_primedTntCount;
static const int MAX_ITEM_ENTITIES = 200; int m_fallingTileCount;
static const int MAX_ARROW_ENTITIES = 200; CRITICAL_SECTION m_limiterCS;
static const int MAX_EXPERIENCEORB_ENTITIES = 50; std::list<std::shared_ptr<Entity> > m_itemEntities;
static const int MAX_PRIMED_TNT = 20; std::list<std::shared_ptr<Entity> > m_hangingEntities;
static const int MAX_FALLING_TILE = 20; std::list<std::shared_ptr<Entity> > m_arrowEntities;
std::list<std::shared_ptr<Entity> > m_experienceOrbEntities;
int m_primedTntCount; virtual bool addEntity(std::shared_ptr<Entity> e);
int m_fallingTileCount; void entityAddedExtra(std::shared_ptr<Entity> e);
CRITICAL_SECTION m_limiterCS; void entityRemovedExtra(std::shared_ptr<Entity> e);
std::list< std::shared_ptr<Entity> > m_itemEntities;
std::list< std::shared_ptr<Entity> > m_hangingEntities;
std::list< std::shared_ptr<Entity> > m_arrowEntities;
std::list< std::shared_ptr<Entity> > m_experienceOrbEntities;
virtual bool addEntity(std::shared_ptr<Entity> e); virtual bool newPrimedTntAllowed();
void entityAddedExtra(std::shared_ptr<Entity> e); virtual bool newFallingTileAllowed();
void entityRemovedExtra(std::shared_ptr<Entity> e);
virtual bool newPrimedTntAllowed();
virtual bool newFallingTileAllowed();
void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added void flagEntitiesToBeRemoved(unsigned int* flags,
bool* removedFound); // 4J added
// 4J added // 4J added
static const int MAX_UPDATES = 256; static const int MAX_UPDATES = 256;
// Each of these need to be duplicated for each level in the current game. As we currently only have 2 (over/nether), making this constant // Each of these need to be duplicated for each level in the current game.
static Level *m_level[3]; // As we currently only have 2 (over/nether), making this constant
static int m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; static Level* m_level[3];
static int m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX]; static int m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX];
static int m_updateChunkCount[3]; static int m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX];
static int m_updateTileX[3][MAX_UPDATES]; static int m_updateChunkCount[3];
static int m_updateTileY[3][MAX_UPDATES]; static int m_updateTileX[3][MAX_UPDATES];
static int m_updateTileZ[3][MAX_UPDATES]; static int m_updateTileY[3][MAX_UPDATES];
static int m_updateTileCount[3]; static int m_updateTileZ[3][MAX_UPDATES];
static int m_randValue[3]; static int m_updateTileCount[3];
static int m_randValue[3];
static C4JThread::EventArray* m_updateTrigger; static C4JThread::EventArray* m_updateTrigger;
static CRITICAL_SECTION m_updateCS[3]; static CRITICAL_SECTION m_updateCS[3];
static C4JThread* m_updateThread;
static int runUpdate(void* lpParam);
static C4JThread* m_updateThread;
static int runUpdate(void* lpParam);
}; };

View file

@ -11,116 +11,120 @@
#include "../../Minecraft.World/Headers/net.minecraft.network.packet.h" #include "../../Minecraft.World/Headers/net.minecraft.network.packet.h"
#include "../../Minecraft.World/Level/LevelData.h" #include "../../Minecraft.World/Level/LevelData.h"
ServerLevelListener::ServerLevelListener(MinecraftServer* server,
ServerLevelListener::ServerLevelListener(MinecraftServer *server, ServerLevel *level) ServerLevel* level) {
{ this->server = server;
this->server = server; this->level = level;
this->level = level;
} }
// 4J removed - // 4J removed -
/* /*
void ServerLevelListener::addParticle(const std::wstring& name, double x, double y, double z, double xa, double ya, double za) void ServerLevelListener::addParticle(const std::wstring& name, double x, double
y, double z, double xa, double ya, double za)
{ {
} }
*/ */
void ServerLevelListener::addParticle(ePARTICLE_TYPE name, double x, double y, double z, double xa, double ya, double za) void ServerLevelListener::addParticle(ePARTICLE_TYPE name, double x, double y,
{ double z, double xa, double ya,
double za) {}
void ServerLevelListener::allChanged() {}
void ServerLevelListener::entityAdded(std::shared_ptr<Entity> entity) {
MemSect(10);
level->getTracker()->addEntity(entity);
MemSect(0);
} }
void ServerLevelListener::allChanged() void ServerLevelListener::entityRemoved(std::shared_ptr<Entity> entity) {
{ level->getTracker()->removeEntity(entity);
}
void ServerLevelListener::entityAdded(std::shared_ptr<Entity> entity)
{
MemSect(10);
level->getTracker()->addEntity(entity);
MemSect(0);
}
void ServerLevelListener::entityRemoved(std::shared_ptr<Entity> entity)
{
level->getTracker()->removeEntity(entity);
} }
// 4J added // 4J added
void ServerLevelListener::playerRemoved(std::shared_ptr<Entity> entity) void ServerLevelListener::playerRemoved(std::shared_ptr<Entity> entity) {
{ std::shared_ptr<ServerPlayer> player =
std::shared_ptr<ServerPlayer> player = std::dynamic_pointer_cast<ServerPlayer>(entity); std::dynamic_pointer_cast<ServerPlayer>(entity);
player->getLevel()->getTracker()->removePlayer(entity); player->getLevel()->getTracker()->removePlayer(entity);
} }
void ServerLevelListener::playSound(int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist) void ServerLevelListener::playSound(int iSound, double x, double y, double z,
{ float volume, float pitch,
if(iSound < 0) float fClipSoundDist) {
{ if (iSound < 0) {
app.DebugPrintf("ServerLevelListener received request for sound less than 0, so ignoring\n"); app.DebugPrintf(
} "ServerLevelListener received request for sound less than 0, so "
else "ignoring\n");
{ } else {
// 4J-PB - I don't want to broadcast player sounds to my local machine, since we're already playing these in the LevelRenderer::playSound. // 4J-PB - I don't want to broadcast player sounds to my local machine,
// The PC version does seem to do this and the result is I can stop walking , and then I'll hear my footstep sound with a delay // since we're already playing these in the LevelRenderer::playSound.
server->getPlayers()->broadcast(x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, std::shared_ptr<LevelSoundPacket>(new LevelSoundPacket(iSound, x, y, z, volume, pitch))); // The PC version does seem to do this and the result is I can stop
} // walking , and then I'll hear my footstep sound with a delay
server->getPlayers()->broadcast(
x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id,
std::shared_ptr<LevelSoundPacket>(
new LevelSoundPacket(iSound, x, y, z, volume, pitch)));
}
} }
void ServerLevelListener::playSound(std::shared_ptr<Entity> entity,int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist) void ServerLevelListener::playSound(std::shared_ptr<Entity> entity, int iSound,
{ double x, double y, double z, float volume,
if(iSound < 0) float pitch, float fClipSoundDist) {
{ if (iSound < 0) {
app.DebugPrintf("ServerLevelListener received request for sound less than 0, so ignoring\n"); app.DebugPrintf(
} "ServerLevelListener received request for sound less than 0, so "
else "ignoring\n");
{ } else {
// 4J-PB - I don't want to broadcast player sounds to my local machine, since we're already playing these in the LevelRenderer::playSound. // 4J-PB - I don't want to broadcast player sounds to my local machine,
// The PC version does seem to do this and the result is I can stop walking , and then I'll hear my footstep sound with a delay // since we're already playing these in the LevelRenderer::playSound.
std::shared_ptr<Player> player= std::dynamic_pointer_cast<Player>(entity); // The PC version does seem to do this and the result is I can stop
server->getPlayers()->broadcast(player,x, y, z, volume > 1 ? 16 * volume : 16, level->dimension->id, std::shared_ptr<LevelSoundPacket>(new LevelSoundPacket(iSound, x, y, z, volume, pitch))); // walking , and then I'll hear my footstep sound with a delay
} std::shared_ptr<Player> player =
std::dynamic_pointer_cast<Player>(entity);
server->getPlayers()->broadcast(
player, x, y, z, volume > 1 ? 16 * volume : 16,
level->dimension->id,
std::shared_ptr<LevelSoundPacket>(
new LevelSoundPacket(iSound, x, y, z, volume, pitch)));
}
} }
void ServerLevelListener::setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level) void ServerLevelListener::setTilesDirty(int x0, int y0, int z0, int x1, int y1,
{ int z1, Level* level) {}
void ServerLevelListener::skyColorChanged() {}
void ServerLevelListener::tileChanged(int x, int y, int z) {
level->getChunkMap()->tileChanged(x, y, z);
} }
void ServerLevelListener::skyColorChanged() void ServerLevelListener::tileLightChanged(int x, int y, int z) {}
{
void ServerLevelListener::playStreamingMusic(const std::wstring& name, int x,
int y, int z) {}
void ServerLevelListener::levelEvent(std::shared_ptr<Player> source, int type,
int x, int y, int z, int data) {
server->getPlayers()->broadcast(
source, x, y, z, 64, level->dimension->id,
std::shared_ptr<LevelEventPacket>(
new LevelEventPacket(type, x, y, z, data)));
} }
void ServerLevelListener::tileChanged(int x, int y, int z) void ServerLevelListener::destroyTileProgress(int id, int x, int y, int z,
{ int progress) {
level->getChunkMap()->tileChanged(x, y, z); // for (ServerPlayer p : server->getPlayers()->players)
} for (AUTO_VAR(it, server->getPlayers()->players.begin());
it != server->getPlayers()->players.end(); ++it) {
std::shared_ptr<ServerPlayer> p = *it;
if (p == NULL || p->level != level || p->entityId == id) continue;
double xd = (double)x - p->x;
double yd = (double)y - p->y;
double zd = (double)z - p->z;
void ServerLevelListener::tileLightChanged(int x, int y, int z) if (xd * xd + yd * yd + zd * zd < 32 * 32) {
{ p->connection->send(std::shared_ptr<TileDestructionPacket>(
} new TileDestructionPacket(id, x, y, z, progress)));
}
void ServerLevelListener::playStreamingMusic(const std::wstring& name, int x, int y, int z) }
{
}
void ServerLevelListener::levelEvent(std::shared_ptr<Player> source, int type, int x, int y, int z, int data)
{
server->getPlayers()->broadcast(source, x, y, z, 64, level->dimension->id, std::shared_ptr<LevelEventPacket>( new LevelEventPacket(type, x, y, z, data) ) );
}
void ServerLevelListener::destroyTileProgress(int id, int x, int y, int z, int progress)
{
//for (ServerPlayer p : server->getPlayers()->players)
for(AUTO_VAR(it, server->getPlayers()->players.begin()); it != server->getPlayers()->players.end(); ++it)
{
std::shared_ptr<ServerPlayer> p = *it;
if (p == NULL || p->level != level || p->entityId == id) continue;
double xd = (double) x - p->x;
double yd = (double) y - p->y;
double zd = (double) z - p->z;
if (xd * xd + yd * yd + zd * zd < 32 * 32)
{
p->connection->send(std::shared_ptr<TileDestructionPacket>(new TileDestructionPacket(id, x, y, z, progress)));
}
}
} }

View file

@ -7,27 +7,37 @@ class MinecraftServer;
class ServerLevel; class ServerLevel;
// 4J - renamed class to ServerLevelListener to avoid clash with LevelListener // 4J - renamed class to ServerLevelListener to avoid clash with LevelListener
class ServerLevelListener : public LevelListener class ServerLevelListener : public LevelListener {
{
private: private:
MinecraftServer *server; MinecraftServer* server;
ServerLevel *level; ServerLevel* level;
public: public:
ServerLevelListener(MinecraftServer *server, ServerLevel *level); ServerLevelListener(MinecraftServer* server, ServerLevel* level);
// 4J removed - virtual void addParticle(const std::wstring& name, double x, double y, double z, double xa, double ya, double za); // 4J removed - virtual void addParticle(const std::wstring& name, double x,
virtual void addParticle(ePARTICLE_TYPE name, double x, double y, double z, double xa, double ya, double za); // 4J added // double y, double z, double xa, double ya, double za);
virtual void addParticle(ePARTICLE_TYPE name, double x, double y, double z,
double xa, double ya, double za); // 4J added
virtual void allChanged(); virtual void allChanged();
virtual void entityAdded(std::shared_ptr<Entity> entity); virtual void entityAdded(std::shared_ptr<Entity> entity);
virtual void entityRemoved(std::shared_ptr<Entity> entity); virtual void entityRemoved(std::shared_ptr<Entity> entity);
virtual void playerRemoved(std::shared_ptr<Entity> entity); // 4J added - for when a player is removed from the level's player array, not just the entity storage virtual void playerRemoved(
virtual void playSound(int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist); std::shared_ptr<Entity>
virtual void playSound(std::shared_ptr<Entity> entity,int iSound, double x, double y, double z, float volume, float pitch, float fClipSoundDist); entity); // 4J added - for when a player is removed from the
virtual void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1, Level *level); // 4J - added level param // level's player array, not just the entity storage
virtual void playSound(int iSound, double x, double y, double z,
float volume, float pitch, float fClipSoundDist);
virtual void playSound(std::shared_ptr<Entity> entity, int iSound, double x,
double y, double z, float volume, float pitch,
float fClipSoundDist);
virtual void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1,
Level* level); // 4J - added level param
virtual void skyColorChanged(); virtual void skyColorChanged();
virtual void tileChanged(int x, int y, int z); virtual void tileChanged(int x, int y, int z);
virtual void tileLightChanged(int x, int y, int z); virtual void tileLightChanged(int x, int y, int z);
virtual void playStreamingMusic(const std::wstring& name, int x, int y, int z); virtual void playStreamingMusic(const std::wstring& name, int x, int y,
virtual void levelEvent(std::shared_ptr<Player> source, int type, int x, int y, int z, int data); int z);
virtual void destroyTileProgress(int id, int x, int y, int z, int progress); virtual void levelEvent(std::shared_ptr<Player> source, int type, int x,
int y, int z, int data);
virtual void destroyTileProgress(int id, int x, int y, int z, int progress);
}; };

View file

@ -9,31 +9,31 @@ class FloatBuffer;
class IntBuffer; class IntBuffer;
class ByteBuffer; class ByteBuffer;
void glGenTextures(IntBuffer *); void glGenTextures(IntBuffer*);
int glGenTextures(); int glGenTextures();
void glDeleteTextures(IntBuffer *); void glDeleteTextures(IntBuffer*);
void glLight(int, int, FloatBuffer *); void glLight(int, int, FloatBuffer*);
void glLightModel(int, FloatBuffer *); void glLightModel(int, FloatBuffer*);
void glGetFloat(int a, FloatBuffer *b); void glGetFloat(int a, FloatBuffer* b);
void glTexCoordPointer(int, int, int, int); void glTexCoordPointer(int, int, int, int);
void glTexCoordPointer(int, int, FloatBuffer *); void glTexCoordPointer(int, int, FloatBuffer*);
void glNormalPointer(int, int, int); void glNormalPointer(int, int, int);
void glNormalPointer(int, ByteBuffer *); void glNormalPointer(int, ByteBuffer*);
void glColorPointer(int, bool, int, ByteBuffer *); void glColorPointer(int, bool, int, ByteBuffer*);
void glColorPointer(int, int, int, int); void glColorPointer(int, int, int, int);
void glVertexPointer(int, int, int, int); void glVertexPointer(int, int, int, int);
void glVertexPointer(int, int, FloatBuffer *); void glVertexPointer(int, int, FloatBuffer*);
void glNewList(int, int); void glNewList(int, int);
void glEndList(int vertexCount = 0); void glEndList(int vertexCount = 0);
void glTexImage2D(int, int, int, int, int, int, int, int, ByteBuffer *); void glTexImage2D(int, int, int, int, int, int, int, int, ByteBuffer*);
void glCallLists(IntBuffer *); void glCallLists(IntBuffer*);
void glGenQueriesARB(IntBuffer *); void glGenQueriesARB(IntBuffer*);
void glBeginQueryARB(int, int); void glBeginQueryARB(int, int);
void glEndQueryARB(int); void glEndQueryARB(int);
void glGetQueryObjectuARB(int, int, IntBuffer *); void glGetQueryObjectuARB(int, int, IntBuffer*);
void glFog(int, FloatBuffer *); void glFog(int, FloatBuffer*);
void glTexGen(int, int, FloatBuffer *); void glTexGen(int, int, FloatBuffer*);
void glReadPixels(int, int, int, int, int, int, ByteBuffer *); void glReadPixels(int, int, int, int, int, int, ByteBuffer*);
void glTexGeni(int, int, int); void glTexGeni(int, int, int);
void glMultiTexCoord2f(int, float, float); void glMultiTexCoord2f(int, float, float);
void glClientActiveTexture(int); void glClientActiveTexture(int);

File diff suppressed because it is too large Load diff

View file

@ -46,299 +46,349 @@ class PsPlusUpsellWrapper;
#undef linux #undef linux
#endif #endif
class Minecraft {
class Minecraft
{
public: public:
static const std::wstring VERSION_STRING; static const std::wstring VERSION_STRING;
Minecraft(Component *mouseComponent, Canvas *parent, MinecraftApplet *minecraftApplet, int width, int height, bool fullscreen); Minecraft(Component* mouseComponent, Canvas* parent,
void init(); MinecraftApplet* minecraftApplet, int width, int height,
bool fullscreen);
void init();
// 4J - removed // 4J - removed
// void crash(CrashReport crash); // void crash(CrashReport crash);
// public abstract void onCrash(CrashReport crash); // public abstract void onCrash(CrashReport crash);
private: private:
static Minecraft *m_instance; static Minecraft* m_instance;
public: public:
MultiPlayerGameMode *gameMode; MultiPlayerGameMode* gameMode;
private: private:
bool fullscreen; bool fullscreen;
bool hasCrashed; bool hasCrashed;
C4JThread::EventQueue* levelTickEventQueue; C4JThread::EventQueue* levelTickEventQueue;
static void levelTickUpdateFunc(void* pParam); static void levelTickUpdateFunc(void* pParam);
static void levelTickThreadInitFunc(); static void levelTickThreadInitFunc();
public: public:
int width, height; int width, height;
int width_phys, height_phys; // 4J - added int width_phys, height_phys; // 4J - added
// private OpenGLCapabilities openGLCapabilities; // private OpenGLCapabilities openGLCapabilities;
private: private:
Timer *timer; Timer* timer;
bool reloadTextures; bool reloadTextures;
public: public:
Level *oldLevel; // 4J Stu added to keep a handle on an old level so we can delete it Level* oldLevel; // 4J Stu added to keep a handle on an old level so we can
//HANDLE m_hPlayerRespawned; // 4J Added so we can wait in menus until it is done (for async in multiplayer) // delete it
// HANDLE m_hPlayerRespawned; // 4J Added so we can wait in menus until it
// is done (for async in multiplayer)
public: public:
MultiPlayerLevel* level;
LevelRenderer* levelRenderer;
std::shared_ptr<MultiplayerLocalPlayer> player;
MultiPlayerLevel *level; MultiPlayerLevelArray levels;
LevelRenderer *levelRenderer;
std::shared_ptr<MultiplayerLocalPlayer> player;
MultiPlayerLevelArray levels; std::shared_ptr<MultiplayerLocalPlayer> localplayers[XUSER_MAX_COUNT];
MultiPlayerGameMode* localgameModes[XUSER_MAX_COUNT];
int localPlayerIdx;
ItemInHandRenderer* localitemInHandRenderers[XUSER_MAX_COUNT];
// 4J-PB - so we can have debugoptions in the server
unsigned int uiDebugOptionsA[XUSER_MAX_COUNT];
std::shared_ptr<MultiplayerLocalPlayer> localplayers[XUSER_MAX_COUNT]; // 4J Stu - Added these so that we can show a Xui scene while connecting
MultiPlayerGameMode *localgameModes[XUSER_MAX_COUNT]; bool m_connectionFailed[XUSER_MAX_COUNT];
int localPlayerIdx; DisconnectPacket::eDisconnectReason
ItemInHandRenderer *localitemInHandRenderers[XUSER_MAX_COUNT]; m_connectionFailedReason[XUSER_MAX_COUNT];
// 4J-PB - so we can have debugoptions in the server ClientConnection* m_pendingLocalConnections[XUSER_MAX_COUNT];
unsigned int uiDebugOptionsA[XUSER_MAX_COUNT];
// 4J Stu - Added these so that we can show a Xui scene while connecting bool addLocalPlayer(
bool m_connectionFailed[XUSER_MAX_COUNT]; int idx); // Re-arrange the screen and start the connection
DisconnectPacket::eDisconnectReason m_connectionFailedReason[XUSER_MAX_COUNT]; void addPendingLocalConnection(int idx, ClientConnection* connection);
ClientConnection *m_pendingLocalConnections[XUSER_MAX_COUNT]; void connectionDisconnected(int idx,
DisconnectPacket::eDisconnectReason reason) {
m_connectionFailed[idx] = true;
m_connectionFailedReason[idx] = reason;
}
bool addLocalPlayer(int idx); // Re-arrange the screen and start the connection std::shared_ptr<MultiplayerLocalPlayer> createExtraLocalPlayer(
void addPendingLocalConnection(int idx, ClientConnection *connection); int idx, const std::wstring& name, int pad, int iDimension,
void connectionDisconnected(int idx, DisconnectPacket::eDisconnectReason reason) { m_connectionFailed[idx] = true; m_connectionFailedReason[idx] = reason; } ClientConnection* clientConnection = NULL,
MultiPlayerLevel* levelpassedin = NULL);
void createPrimaryLocalPlayer(int iPad);
bool setLocalPlayerIdx(int idx);
int getLocalPlayerIdx();
void removeLocalPlayerIdx(int idx);
void storeExtraLocalPlayer(int idx);
void updatePlayerViewportAssignments();
int unoccupiedQuadrant; // 4J - added
std::shared_ptr<MultiplayerLocalPlayer> createExtraLocalPlayer(int idx, const std::wstring& name, int pad, int iDimension, ClientConnection *clientConnection = NULL,MultiPlayerLevel *levelpassedin=NULL); std::shared_ptr<Mob> cameraTargetPlayer;
void createPrimaryLocalPlayer(int iPad); ParticleEngine* particleEngine;
bool setLocalPlayerIdx(int idx); User* user;
int getLocalPlayerIdx(); std::wstring serverDomain;
void removeLocalPlayerIdx(int idx); Canvas* parent;
void storeExtraLocalPlayer(int idx); bool appletMode;
void updatePlayerViewportAssignments();
int unoccupiedQuadrant; // 4J - added
std::shared_ptr<Mob> cameraTargetPlayer; // 4J - per player ?
ParticleEngine *particleEngine; volatile bool pause;
User *user;
std::wstring serverDomain;
Canvas *parent;
bool appletMode;
// 4J - per player ? Textures* textures;
volatile bool pause; Font *font, *altFont;
Screen* screen;
ProgressRenderer* progressRenderer;
GameRenderer* gameRenderer;
Textures *textures;
Font *font, *altFont;
Screen *screen;
ProgressRenderer *progressRenderer;
GameRenderer *gameRenderer;
private: private:
BackgroundDownloader *bgLoader; BackgroundDownloader* bgLoader;
int ticks; int ticks;
// 4J-PB - moved to per player // 4J-PB - moved to per player
//int missTime; // int missTime;
int orgWidth, orgHeight;
int orgWidth, orgHeight;
public: public:
AchievementPopup *achievementPopup; AchievementPopup* achievementPopup;
public:
Gui *gui; public:
// 4J - move to the per player structure? Gui* gui;
bool noRender; // 4J - move to the per player structure?
bool noRender;
HumanoidModel* humanoidModel;
HitResult* hitResult;
Options* options;
HumanoidModel *humanoidModel;
HitResult *hitResult;
Options *options;
protected: protected:
MinecraftApplet *minecraftApplet; MinecraftApplet* minecraftApplet;
public:
SoundEngine *soundEngine;
MouseHandler *mouseHandler;
public:
TexturePackRepository *skins;
File workingDirectory;
private:
LevelStorageSource *levelSource;
public:
static const int frameTimes_length = 512;
static __int64 frameTimes[frameTimes_length];
static const int tickTimes_length = 512;
static __int64 tickTimes[tickTimes_length];
static int frameTimePos;
static __int64 warezTime;
private:
int rightClickDelay;
public:
// 4J- this should really be in localplayer
StatsCounter* stats[4];
private:
std::wstring connectToIp;
int connectToPort;
public: public:
void clearConnectionFailed(); SoundEngine* soundEngine;
void connectTo(const std::wstring& server, int port); MouseHandler* mouseHandler;
private:
void renderLoadingScreen();
public: public:
void blit(int x, int y, int sx, int sy, int w, int h); TexturePackRepository* skins;
File workingDirectory;
private: private:
static File workDir; LevelStorageSource* levelSource;
public: public:
static File getWorkingDirectory(); static const int frameTimes_length = 512;
static File getWorkingDirectory(const std::wstring& applicationName); static __int64 frameTimes[frameTimes_length];
public: static const int tickTimes_length = 512;
LevelStorageSource *getLevelSource(); static __int64 tickTimes[tickTimes_length];
void setScreen(Screen *screen); static int frameTimePos;
static __int64 warezTime;
private: private:
void checkGlError(const std::wstring& string); int rightClickDelay;
public:
// 4J- this should really be in localplayer
StatsCounter* stats[4];
private:
std::wstring connectToIp;
int connectToPort;
public:
void clearConnectionFailed();
void connectTo(const std::wstring& server, int port);
private:
void renderLoadingScreen();
public:
void blit(int x, int y, int sx, int sy, int w, int h);
private:
static File workDir;
public:
static File getWorkingDirectory();
static File getWorkingDirectory(const std::wstring& applicationName);
public:
LevelStorageSource* getLevelSource();
void setScreen(Screen* screen);
private:
void checkGlError(const std::wstring& string);
#ifdef __ORBIS__ #ifdef __ORBIS__
PsPlusUpsellWrapper *m_pPsPlusUpsell; PsPlusUpsellWrapper* m_pPsPlusUpsell;
#endif #endif
public: public:
void destroy(); void destroy();
volatile bool running; volatile bool running;
std::wstring fpsString; std::wstring fpsString;
void run(); void run();
// 4J-PB - split the run into 3 parts so we can run it from our xbox game loop // 4J-PB - split the run into 3 parts so we can run it from our xbox game
static Minecraft *GetInstance(); // loop
void run_middle(); static Minecraft* GetInstance();
void run_end(); void run_middle();
void run_end();
void emergencySave(); void emergencySave();
// 4J - removed // 4J - removed
//bool wasDown ; // bool wasDown ;
private: private:
// void checkScreenshot(); // 4J - removed // void checkScreenshot(); // 4J - removed
// String grabHugeScreenshot(File workDir2, int width, int height, int ssWidth, int ssHeight); // 4J - removed // String grabHugeScreenshot(File workDir2, int width, int height, int
// ssWidth, int ssHeight); // 4J - removed
// 4J - per player thing? // 4J - per player thing?
__int64 lastTimer; __int64 lastTimer;
void renderFpsMeter(__int64 tickTime); void renderFpsMeter(__int64 tickTime);
public:
void stop();
// 4J removed
// bool mouseGrabbed;
// void grabMouse();
// void releaseMouse();
// 4J-PB - moved these into localplayer
//void handleMouseDown(int button, bool down);
//void handleMouseClick(int button);
void pauseGame();
// void toggleFullScreen(); // 4J - removed
private:
void resize(int width, int height);
public: public:
// 4J - Moved to per player void stop();
//bool isRaining ; // 4J removed
// bool mouseGrabbed;
// 4J - Moved to per player // void grabMouse();
//__int64 lastTickTime; // void releaseMouse();
// 4J-PB - moved these into localplayer
// void handleMouseDown(int button, bool down);
// void handleMouseClick(int button);
void pauseGame();
// void toggleFullScreen(); // 4J - removed
private: private:
// 4J- per player? void resize(int width, int height);
int recheckPlayerIn;
void verify();
public: public:
// 4J - added bFirst parameter, which is true for the first active viewport in splitscreen // 4J - Moved to per player
// 4J - added bUpdateTextures, which is true if the actual renderer textures are to be updated - this will be true for the last time this tick runs with bFirst true // bool isRaining ;
void tick(bool bFirst, bool bUpdateTextures);
// 4J - Moved to per player
//__int64 lastTickTime;
private: private:
void reloadSound(); // 4J- per player?
int recheckPlayerIn;
void verify();
public: public:
bool isClientSide(); // 4J - added bFirst parameter, which is true for the first active viewport
void selectLevel(ConsoleSaveFile *saveFile, const std::wstring& levelId, const std::wstring& levelName, LevelSettings *levelSettings); // in splitscreen 4J - added bUpdateTextures, which is true if the actual
//void toggleDimension(int targetDimension); // renderer textures are to be updated - this will be true for the last time
bool saveSlot(int slot, const std::wstring& name); // this tick runs with bFirst true
bool loadSlot(const std::wstring& userName, int slot); void tick(bool bFirst, bool bUpdateTextures);
void releaseLevel(int message);
// 4J Stu - Added the doForceStatsSave param
//void setLevel(Level *level, bool doForceStatsSave = true);
//void setLevel(Level *level, const std::wstring& message, bool doForceStatsSave = true);
void setLevel(MultiPlayerLevel *level, int message = -1, std::shared_ptr<Player> forceInsertPlayer = nullptr, bool doForceStatsSave = true,bool bPrimaryPlayerSignedOut=false);
// 4J-PB - added to force in the 'other' level when the main player creates the level at game load time
void forceaddLevel(MultiPlayerLevel *level);
void prepareLevel(int title); // 4J - changed to public
void fileDownloaded(const std::wstring& name, File *file);
// OpenGLCapabilities getOpenGLCapabilities(); // 4J - removed
std::wstring gatherStats1(); private:
std::wstring gatherStats2(); void reloadSound();
std::wstring gatherStats3();
std::wstring gatherStats4();
void respawnPlayer(int iPad,int dimension,int newEntityId); public:
static void start(const std::wstring& name, const std::wstring& sid); bool isClientSide();
static void startAndConnectTo(const std::wstring& name, const std::wstring& sid, const std::wstring& url); void selectLevel(ConsoleSaveFile* saveFile, const std::wstring& levelId,
ClientConnection *getConnection(int iPad); // 4J Stu added iPad param const std::wstring& levelName,
static void main(); LevelSettings* levelSettings);
static bool renderNames(); // void toggleDimension(int targetDimension);
static bool useFancyGraphics(); bool saveSlot(int slot, const std::wstring& name);
static bool useAmbientOcclusion(); bool loadSlot(const std::wstring& userName, int slot);
static bool renderDebug(); void releaseLevel(int message);
bool handleClientSideCommand(const std::wstring& chatMessage); // 4J Stu - Added the doForceStatsSave param
// void setLevel(Level *level, bool doForceStatsSave = true);
// void setLevel(Level *level, const std::wstring& message, bool
// doForceStatsSave = true);
void setLevel(MultiPlayerLevel* level, int message = -1,
std::shared_ptr<Player> forceInsertPlayer = nullptr,
bool doForceStatsSave = true,
bool bPrimaryPlayerSignedOut = false);
// 4J-PB - added to force in the 'other' level when the main player creates
// the level at game load time
void forceaddLevel(MultiPlayerLevel* level);
void prepareLevel(int title); // 4J - changed to public
void fileDownloaded(const std::wstring& name, File* file);
// OpenGLCapabilities getOpenGLCapabilities(); // 4J - removed
static int maxSupportedTextureSize(); std::wstring gatherStats1();
void delayTextureReload(); std::wstring gatherStats2();
static __int64 currentTimeMillis(); std::wstring gatherStats3();
std::wstring gatherStats4();
void respawnPlayer(int iPad, int dimension, int newEntityId);
static void start(const std::wstring& name, const std::wstring& sid);
static void startAndConnectTo(const std::wstring& name,
const std::wstring& sid,
const std::wstring& url);
ClientConnection* getConnection(int iPad); // 4J Stu added iPad param
static void main();
static bool renderNames();
static bool useFancyGraphics();
static bool useAmbientOcclusion();
static bool renderDebug();
bool handleClientSideCommand(const std::wstring& chatMessage);
static int maxSupportedTextureSize();
void delayTextureReload();
static __int64 currentTimeMillis();
#ifdef _DURANGO #ifdef _DURANGO
static void inGameSignInCheckAllPrivilegesCallback(void *lpParam, bool hasPrivileges, int iPad); static void inGameSignInCheckAllPrivilegesCallback(void* lpParam,
bool hasPrivileges,
int iPad);
#endif #endif
static int InGame_SignInReturned(void *pParam,bool bContinue, int iPad); static int InGame_SignInReturned(void* pParam, bool bContinue, int iPad);
// 4J-PB // 4J-PB
Screen * getScreen(); Screen* getScreen();
// 4J Stu // 4J Stu
void forceStatsSave(int idx); void forceStatsSave(int idx);
CRITICAL_SECTION m_setLevelCS;
CRITICAL_SECTION m_setLevelCS;
private: private:
// A bit field that store whether a particular quadrant is in the full tutorial or not // A bit field that store whether a particular quadrant is in the full
std::uint8_t m_inFullTutorialBits; // tutorial or not
std::uint8_t m_inFullTutorialBits;
public: public:
bool isTutorial(); bool isTutorial();
void playerStartedTutorial(int iPad); void playerStartedTutorial(int iPad);
void playerLeftTutorial(int iPad); void playerLeftTutorial(int iPad);
// 4J Added // 4J Added
MultiPlayerLevel *getLevel(int dimension); MultiPlayerLevel* getLevel(int dimension);
void tickAllConnections(); void tickAllConnections();
Level *animateTickLevel; // 4J added Level* animateTickLevel; // 4J added
// 4J - When a client requests a texture, it should add it to here while we are waiting for it // 4J - When a client requests a texture, it should add it to here while we
std::vector<std::wstring> m_pendingTextureRequests; // are waiting for it
std::vector<std::wstring> m_pendingGeometryRequests; // additional skin box geometry std::vector<std::wstring> m_pendingTextureRequests;
std::vector<std::wstring>
m_pendingGeometryRequests; // additional skin box geometry
// 4J Added // 4J Added
bool addPendingClientTextureRequest(const std::wstring &textureName); bool addPendingClientTextureRequest(const std::wstring& textureName);
void handleClientTextureReceived(const std::wstring &textureName); void handleClientTextureReceived(const std::wstring& textureName);
void clearPendingClientTextureRequests() { m_pendingTextureRequests.clear(); } void clearPendingClientTextureRequests() {
bool addPendingClientGeometryRequest(const std::wstring &textureName); m_pendingTextureRequests.clear();
void handleClientGeometryReceived(const std::wstring &textureName); }
void clearPendingClientGeometryRequests() { m_pendingGeometryRequests.clear(); } bool addPendingClientGeometryRequest(const std::wstring& textureName);
void handleClientGeometryReceived(const std::wstring& textureName);
void clearPendingClientGeometryRequests() {
m_pendingGeometryRequests.clear();
}
unsigned int getCurrentTexturePackId(); unsigned int getCurrentTexturePackId();
ColourTable *getColourTable(); ColourTable* getColourTable();
#if defined __ORBIS__ #if defined __ORBIS__
static int MustSignInReturnedPSN(void *pParam, int iPad, C4JStorage::EMessageResult result); static int MustSignInReturnedPSN(void* pParam, int iPad,
C4JStorage::EMessageResult result);
#endif #endif
}; };

File diff suppressed because it is too large Load diff

View file

@ -22,226 +22,265 @@ class CommandDispatcher;
#define MINECRAFT_SERVER_SLOW_QUEUE_DELAY 250 #define MINECRAFT_SERVER_SLOW_QUEUE_DELAY 250
typedef struct _LoadSaveDataThreadParam typedef struct _LoadSaveDataThreadParam {
{ void* data;
void *data; __int64 fileSize;
__int64 fileSize; const std::wstring saveName;
const std::wstring saveName; _LoadSaveDataThreadParam(void* data, __int64 filesize,
_LoadSaveDataThreadParam(void *data, __int64 filesize, const std::wstring &saveName) : data( data ), fileSize( filesize ), saveName( saveName ) {} const std::wstring& saveName)
: data(data), fileSize(filesize), saveName(saveName) {}
} LoadSaveDataThreadParam; } LoadSaveDataThreadParam;
typedef struct _NetworkGameInitData typedef struct _NetworkGameInitData {
{ __int64 seed;
__int64 seed; LoadSaveDataThreadParam* saveData;
LoadSaveDataThreadParam *saveData; std::uint32_t settings;
std::uint32_t settings; LevelGenerationOptions* levelGen;
LevelGenerationOptions *levelGen; std::uint32_t texturePackId;
std::uint32_t texturePackId; bool findSeed;
bool findSeed; unsigned int xzSize;
unsigned int xzSize; unsigned char hellScale;
unsigned char hellScale; ESavePlatform savePlatform;
ESavePlatform savePlatform;
_NetworkGameInitData() _NetworkGameInitData() {
{ seed = 0;
seed = 0; saveData = NULL;
saveData = NULL; settings = 0;
settings = 0; levelGen = NULL;
levelGen = NULL; texturePackId = 0;
texturePackId = 0; findSeed = false;
findSeed = false; xzSize = LEVEL_LEGACY_WIDTH;
xzSize = LEVEL_LEGACY_WIDTH; hellScale = HELL_LEVEL_LEGACY_SCALE;
hellScale = HELL_LEVEL_LEGACY_SCALE; savePlatform = SAVE_FILE_PLATFORM_LOCAL;
savePlatform = SAVE_FILE_PLATFORM_LOCAL; }
}
} NetworkGameInitData; } NetworkGameInitData;
// 4J Stu - 1.0.1 updates the server to implement the ServerInterface class, but
// I don't think we will use any of the functions that defines so not
// 4J Stu - 1.0.1 updates the server to implement the ServerInterface class, but I don't think we will use any of the functions that defines so not implementing here // implementing here
class MinecraftServer : public ConsoleInputSource class MinecraftServer : public ConsoleInputSource {
{
public: public:
static const std::wstring VERSION; static const std::wstring VERSION;
static const int TICK_STATS_SPAN = SharedConstants::TICKS_PER_SECOND * 5; static const int TICK_STATS_SPAN = SharedConstants::TICKS_PER_SECOND * 5;
// static Logger logger = Logger.getLogger("Minecraft"); // static Logger logger = Logger.getLogger("Minecraft");
static std::unordered_map<std::wstring, int> ironTimers; static std::unordered_map<std::wstring, int> ironTimers;
private: private:
static const int DEFAULT_MINECRAFT_PORT = 25565; static const int DEFAULT_MINECRAFT_PORT = 25565;
static const int MS_PER_TICK = 1000 / SharedConstants::TICKS_PER_SECOND; static const int MS_PER_TICK = 1000 / SharedConstants::TICKS_PER_SECOND;
// 4J Stu - Added 1.0.1, Not needed // 4J Stu - Added 1.0.1, Not needed
//std::wstring localIp; // std::wstring localIp;
//int port; // int port;
public: public:
ServerConnection *connection; ServerConnection* connection;
Settings *settings; Settings* settings;
ServerLevelArray levels; ServerLevelArray levels;
private: private:
PlayerList *players; PlayerList* players;
// 4J Stu - Added 1.0.1, Not needed // 4J Stu - Added 1.0.1, Not needed
//long[] tickTimes = new long[TICK_STATS_SPAN]; // long[] tickTimes = new long[TICK_STATS_SPAN];
//long[][] levelTickTimes; // long[][] levelTickTimes;
private: private:
ConsoleCommands *commands; ConsoleCommands* commands;
bool running; bool running;
bool m_bLoaded; bool m_bLoaded;
public: public:
bool stopped; bool stopped;
int tickCount; int tickCount;
public: public:
std::wstring progressStatus; std::wstring progressStatus;
int progress; int progress;
private: private:
// std::vector<Tickable *> tickables = new ArrayList<Tickable>(); // 4J - removed // std::vector<Tickable *> tickables = new ArrayList<Tickable>(); // 4J -
CommandDispatcher *commandDispatcher; //removed
std::vector<ConsoleInput *> consoleInput; // 4J - was synchronizedList - TODO - investigate CommandDispatcher* commandDispatcher;
std::vector<ConsoleInput*>
consoleInput; // 4J - was synchronizedList - TODO - investigate
public: public:
bool onlineMode; bool onlineMode;
bool animals; bool animals;
bool npcs; bool npcs;
bool pvp; bool pvp;
bool allowFlight; bool allowFlight;
std::wstring motd; std::wstring motd;
int maxBuildHeight; int maxBuildHeight;
private: private:
// 4J Added // 4J Added
//int m_lastSentDifficulty; // int m_lastSentDifficulty;
public: public:
// 4J Stu - This value should be incremented every time the list of players with friends-only UGC settings changes // 4J Stu - This value should be incremented every time the list of players
// It is sent with PreLoginPacket and compared when it comes back in the LoginPacket // with friends-only UGC settings changes It is sent with PreLoginPacket and
std::uint32_t m_ugcPlayersVersion; // compared when it comes back in the LoginPacket
std::uint32_t m_ugcPlayersVersion;
// This value is used to store the texture pack id for the currently loaded world // This value is used to store the texture pack id for the currently loaded
std::uint32_t m_texturePackId; // world
std::uint32_t m_texturePackId;
public: public:
MinecraftServer(); MinecraftServer();
~MinecraftServer(); ~MinecraftServer();
private: private:
// 4J Added - LoadSaveDataThreadParam // 4J Added - LoadSaveDataThreadParam
bool initServer(__int64 seed, NetworkGameInitData *initData, std::uint32_t initSettings, bool findSeed); bool initServer(__int64 seed, NetworkGameInitData* initData,
void postProcessTerminate(ProgressRenderer *mcprogress); std::uint32_t initSettings, bool findSeed);
bool loadLevel(LevelStorageSource *storageSource, const std::wstring& name, __int64 levelSeed, LevelType *pLevelType, NetworkGameInitData *initData); void postProcessTerminate(ProgressRenderer* mcprogress);
bool loadLevel(LevelStorageSource* storageSource, const std::wstring& name,
__int64 levelSeed, LevelType* pLevelType,
NetworkGameInitData* initData);
void setProgress(const std::wstring& status, int progress); void setProgress(const std::wstring& status, int progress);
void endProgress(); void endProgress();
void saveAllChunks(); void saveAllChunks();
void saveGameRules(); void saveGameRules();
void stopServer(); void stopServer();
public: public:
void setMaxBuildHeight(int maxBuildHeight); void setMaxBuildHeight(int maxBuildHeight);
int getMaxBuildHeight(); int getMaxBuildHeight();
PlayerList *getPlayers(); PlayerList* getPlayers();
void setPlayers(PlayerList *players); void setPlayers(PlayerList* players);
ServerConnection *getConnection(); ServerConnection* getConnection();
bool isAnimals(); bool isAnimals();
void setAnimals(bool animals); void setAnimals(bool animals);
bool isNpcsEnabled(); bool isNpcsEnabled();
void setNpcsEnabled(bool npcs); void setNpcsEnabled(bool npcs);
bool isPvpAllowed(); bool isPvpAllowed();
void setPvpAllowed(bool pvp); void setPvpAllowed(bool pvp);
bool isFlightAllowed(); bool isFlightAllowed();
void setFlightAllowed(bool allowFlight); void setFlightAllowed(bool allowFlight);
bool isNetherEnabled(); bool isNetherEnabled();
bool isHardcore(); bool isHardcore();
CommandDispatcher *getCommandDispatcher(); CommandDispatcher* getCommandDispatcher();
public: public:
void halt(); void halt();
void run(__int64 seed, void *lpParameter); void run(__int64 seed, void* lpParameter);
void broadcastStartSavingPacket(); void broadcastStartSavingPacket();
void broadcastStopSavingPacket(); void broadcastStopSavingPacket();
private: private:
void tick(); void tick();
public:
void handleConsoleInput(const std::wstring& msg, ConsoleInputSource *source);
void handleConsoleInputs();
// void addTickable(Tickable tickable); // 4J removed
static void main(__int64 seed, void *lpParameter);
static void HaltServer(bool bPrimaryPlayerSignedOut=false);
File *getFile(const std::wstring& name); public:
void handleConsoleInput(const std::wstring& msg,
ConsoleInputSource* source);
void handleConsoleInputs();
// void addTickable(Tickable tickable); // 4J removed
static void main(__int64 seed, void* lpParameter);
static void HaltServer(bool bPrimaryPlayerSignedOut = false);
File* getFile(const std::wstring& name);
void info(const std::wstring& string); void info(const std::wstring& string);
void warn(const std::wstring& string); void warn(const std::wstring& string);
std::wstring getConsoleName(); std::wstring getConsoleName();
ServerLevel *getLevel(int dimension); ServerLevel* getLevel(int dimension);
void setLevel(int dimension, ServerLevel *level); // 4J added void setLevel(int dimension, ServerLevel* level); // 4J added
static MinecraftServer *getInstance() { return server; } // 4J added static MinecraftServer* getInstance() { return server; } // 4J added
static bool serverHalted() { return s_bServerHalted; } static bool serverHalted() { return s_bServerHalted; }
static bool saveOnExitAnswered() { return s_bSaveOnExitAnswered; } static bool saveOnExitAnswered() { return s_bSaveOnExitAnswered; }
static void resetFlags() { s_bServerHalted = false; s_bSaveOnExitAnswered = false; } static void resetFlags() {
s_bServerHalted = false;
s_bSaveOnExitAnswered = false;
}
bool flagEntitiesToBeRemoved(unsigned int *flags); // 4J added bool flagEntitiesToBeRemoved(unsigned int* flags); // 4J added
private: private:
//4J Added // 4J Added
static MinecraftServer *server; static MinecraftServer* server;
static bool setTimeOfDayAtEndOfTick; static bool setTimeOfDayAtEndOfTick;
static __int64 setTimeOfDay; static __int64 setTimeOfDay;
static bool setTimeAtEndOfTick; static bool setTimeAtEndOfTick;
static __int64 setTime; static __int64 setTime;
static bool m_bPrimaryPlayerSignedOut; // 4J-PB added to tell the stopserver not to save the game - another player may have signed in in their place, so ProfileManager.IsSignedIn isn't enough static bool
static bool s_bServerHalted; // 4J Stu Added so that we can halt the server even before it's been created properly m_bPrimaryPlayerSignedOut; // 4J-PB added to tell the stopserver not to
static bool s_bSaveOnExitAnswered; // 4J Stu Added so that we only ask this question once when we exit // save the game - another player may have
// signed in in their place, so
// ProfileManager.IsSignedIn isn't enough
static bool s_bServerHalted; // 4J Stu Added so that we can halt the server
// even before it's been created properly
static bool s_bSaveOnExitAnswered; // 4J Stu Added so that we only ask this
// question once when we exit
// 4J - added so that we can have a separate thread for post processing chunks on level creation // 4J - added so that we can have a separate thread for post processing
static int runPostUpdate(void* lpParam); // chunks on level creation
C4JThread* m_postUpdateThread; static int runPostUpdate(void* lpParam);
bool m_postUpdateTerminate; C4JThread* m_postUpdateThread;
class postProcessRequest bool m_postUpdateTerminate;
{ class postProcessRequest {
public: public:
int x, z; int x, z;
ChunkSource *chunkSource; ChunkSource* chunkSource;
postProcessRequest(int x, int z, ChunkSource *chunkSource) : x(x), z(z), chunkSource(chunkSource) {} postProcessRequest(int x, int z, ChunkSource* chunkSource)
}; : x(x), z(z), chunkSource(chunkSource) {}
std::vector<postProcessRequest> m_postProcessRequests; };
CRITICAL_SECTION m_postProcessCS; std::vector<postProcessRequest> m_postProcessRequests;
public: CRITICAL_SECTION m_postProcessCS;
void addPostProcessRequest(ChunkSource *chunkSource, int x, int z);
public: public:
static PlayerList *getPlayerList() { if( server != NULL ) return server->players; else return NULL; } void addPostProcessRequest(ChunkSource* chunkSource, int x, int z);
static void SetTimeOfDay(__int64 time) { setTimeOfDayAtEndOfTick = true; setTimeOfDay = time; }
static void SetTime(__int64 time) { setTimeAtEndOfTick = true; setTime = time; }
C4JThread::Event* m_serverPausedEvent;
private:
// 4J Added
bool m_isServerPaused;
// 4J Added - A static that stores the QNet index of the player that is next allowed to send a packet in the slow queue
static int s_slowQueuePlayerIndex;
static int s_slowQueueLastTime;
public: public:
static bool s_slowQueuePacketSent; static PlayerList* getPlayerList() {
if (server != NULL)
return server->players;
else
return NULL;
}
static void SetTimeOfDay(__int64 time) {
setTimeOfDayAtEndOfTick = true;
setTimeOfDay = time;
}
static void SetTime(__int64 time) {
setTimeAtEndOfTick = true;
setTime = time;
}
bool IsServerPaused() { return m_isServerPaused; } C4JThread::Event* m_serverPausedEvent;
private: private:
// 4J Added // 4J Added
bool m_saveOnExit; bool m_isServerPaused;
bool m_suspending;
// 4J Added - A static that stores the QNet index of the player that is next
// allowed to send a packet in the slow queue
static int s_slowQueuePlayerIndex;
static int s_slowQueueLastTime;
public: public:
//static int getSlowQueueIndex() { return s_slowQueuePlayerIndex; } static bool s_slowQueuePacketSent;
static bool canSendOnSlowQueue(INetworkPlayer *player);
static void cycleSlowQueueIndex();
void setSaveOnExit(bool save) { m_saveOnExit = save; s_bSaveOnExitAnswered = true; } bool IsServerPaused() { return m_isServerPaused; }
void Suspend();
bool IsSuspending();
// 4J Stu - A load of functions were all added in 1.0.1 in the ServerInterface, but I don't think we need any of them private:
// 4J Added
bool m_saveOnExit;
bool m_suspending;
public:
// static int getSlowQueueIndex() { return s_slowQueuePlayerIndex; }
static bool canSendOnSlowQueue(INetworkPlayer* player);
static void cycleSlowQueueIndex();
void setSaveOnExit(bool save) {
m_saveOnExit = save;
s_bSaveOnExitAnswered = true;
}
void Suspend();
bool IsSuspending();
// 4J Stu - A load of functions were all added in 1.0.1 in the
// ServerInterface, but I don't think we need any of them
}; };

File diff suppressed because it is too large Load diff

View file

@ -6,81 +6,97 @@ class SavedDataStorage;
class Socket; class Socket;
class MultiplayerLocalPlayer; class MultiplayerLocalPlayer;
class ClientConnection : public PacketListener class ClientConnection : public PacketListener {
{
private: private:
enum eClientConnectionConnectingState enum eClientConnectionConnectingState {
{ eCCPreLoginSent = 0,
eCCPreLoginSent = 0, eCCPreLoginReceived,
eCCPreLoginReceived, eCCLoginSent,
eCCLoginSent, eCCLoginReceived,
eCCLoginReceived, eCCConnected
eCCConnected };
};
private: private:
bool done; bool done;
Connection *connection; Connection* connection;
public: public:
std::wstring message; std::wstring message;
bool createdOk; // 4J added bool createdOk; // 4J added
private: private:
Minecraft *minecraft; Minecraft* minecraft;
MultiPlayerLevel *level; MultiPlayerLevel* level;
bool started; bool started;
// 4J Stu - I don't think we are interested in the PlayerInfo data, so I'm not going to use it at the moment // 4J Stu - I don't think we are interested in the PlayerInfo data, so I'm
//Map<String, PlayerInfo> playerInfoMap = new HashMap<String, PlayerInfo>(); // not going to use it at the moment
// Map<String, PlayerInfo> playerInfoMap = new HashMap<String,
// PlayerInfo>();
public: public:
//List<PlayerInfo> playerInfos = new ArrayList<PlayerInfo>(); // List<PlayerInfo> playerInfos = new ArrayList<PlayerInfo>();
int maxPlayers; int maxPlayers;
public: public:
bool isStarted() { return started; } // 4J Added bool isStarted() { return started; } // 4J Added
bool isClosed() { return done; } // 4J Added bool isClosed() { return done; } // 4J Added
Socket *getSocket() { return connection->getSocket(); } // 4J Added Socket* getSocket() { return connection->getSocket(); } // 4J Added
private: private:
int m_userIndex; // 4J Added int m_userIndex; // 4J Added
public: public:
SavedDataStorage *savedDataStorage; SavedDataStorage* savedDataStorage;
ClientConnection(Minecraft *minecraft, const std::wstring& ip, int port); ClientConnection(Minecraft* minecraft, const std::wstring& ip, int port);
ClientConnection(Minecraft *minecraft, Socket *socket, int iUserIndex = -1); ClientConnection(Minecraft* minecraft, Socket* socket, int iUserIndex = -1);
~ClientConnection(); ~ClientConnection();
void tick(); void tick();
INetworkPlayer *getNetworkPlayer(); INetworkPlayer* getNetworkPlayer();
virtual void handleLogin(std::shared_ptr<LoginPacket> packet); virtual void handleLogin(std::shared_ptr<LoginPacket> packet);
virtual void handleAddEntity(std::shared_ptr<AddEntityPacket> packet); virtual void handleAddEntity(std::shared_ptr<AddEntityPacket> packet);
virtual void handleAddExperienceOrb(std::shared_ptr<AddExperienceOrbPacket> packet); virtual void handleAddExperienceOrb(
virtual void handleAddGlobalEntity(std::shared_ptr<AddGlobalEntityPacket> packet); std::shared_ptr<AddExperienceOrbPacket> packet);
virtual void handleAddGlobalEntity(
std::shared_ptr<AddGlobalEntityPacket> packet);
virtual void handleAddPainting(std::shared_ptr<AddPaintingPacket> packet); virtual void handleAddPainting(std::shared_ptr<AddPaintingPacket> packet);
virtual void handleSetEntityMotion(std::shared_ptr<SetEntityMotionPacket> packet); virtual void handleSetEntityMotion(
virtual void handleSetEntityData(std::shared_ptr<SetEntityDataPacket> packet); std::shared_ptr<SetEntityMotionPacket> packet);
virtual void handleSetEntityData(
std::shared_ptr<SetEntityDataPacket> packet);
virtual void handleAddPlayer(std::shared_ptr<AddPlayerPacket> packet); virtual void handleAddPlayer(std::shared_ptr<AddPlayerPacket> packet);
virtual void handleTeleportEntity(std::shared_ptr<TeleportEntityPacket> packet); virtual void handleTeleportEntity(
std::shared_ptr<TeleportEntityPacket> packet);
virtual void handleMoveEntity(std::shared_ptr<MoveEntityPacket> packet); virtual void handleMoveEntity(std::shared_ptr<MoveEntityPacket> packet);
virtual void handleRotateMob(std::shared_ptr<RotateHeadPacket> packet); virtual void handleRotateMob(std::shared_ptr<RotateHeadPacket> packet);
virtual void handleMoveEntitySmall(std::shared_ptr<MoveEntityPacketSmall> packet); virtual void handleMoveEntitySmall(
virtual void handleRemoveEntity(std::shared_ptr<RemoveEntitiesPacket> packet); std::shared_ptr<MoveEntityPacketSmall> packet);
virtual void handleMovePlayer(std::shared_ptr<MovePlayerPacket> packet); virtual void handleRemoveEntity(
std::shared_ptr<RemoveEntitiesPacket> packet);
virtual void handleMovePlayer(std::shared_ptr<MovePlayerPacket> packet);
Random *random; Random* random;
// 4J Added
virtual void handleChunkVisibilityArea(std::shared_ptr<ChunkVisibilityAreaPacket> packet);
virtual void handleChunkVisibility(std::shared_ptr<ChunkVisibilityPacket> packet); // 4J Added
virtual void handleChunkTilesUpdate(std::shared_ptr<ChunkTilesUpdatePacket> packet); virtual void handleChunkVisibilityArea(
virtual void handleBlockRegionUpdate(std::shared_ptr<BlockRegionUpdatePacket> packet); std::shared_ptr<ChunkVisibilityAreaPacket> packet);
virtual void handleChunkVisibility(
std::shared_ptr<ChunkVisibilityPacket> packet);
virtual void handleChunkTilesUpdate(
std::shared_ptr<ChunkTilesUpdatePacket> packet);
virtual void handleBlockRegionUpdate(
std::shared_ptr<BlockRegionUpdatePacket> packet);
virtual void handleTileUpdate(std::shared_ptr<TileUpdatePacket> packet); virtual void handleTileUpdate(std::shared_ptr<TileUpdatePacket> packet);
virtual void handleDisconnect(std::shared_ptr<DisconnectPacket> packet); virtual void handleDisconnect(std::shared_ptr<DisconnectPacket> packet);
virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason,
void* reasonObjects);
void sendAndDisconnect(std::shared_ptr<Packet> packet); void sendAndDisconnect(std::shared_ptr<Packet> packet);
void send(std::shared_ptr<Packet> packet); void send(std::shared_ptr<Packet> packet);
virtual void handleTakeItemEntity(std::shared_ptr<TakeItemEntityPacket> packet); virtual void handleTakeItemEntity(
std::shared_ptr<TakeItemEntityPacket> packet);
virtual void handleChat(std::shared_ptr<ChatPacket> packet); virtual void handleChat(std::shared_ptr<ChatPacket> packet);
virtual void handleAnimate(std::shared_ptr<AnimatePacket> packet); virtual void handleAnimate(std::shared_ptr<AnimatePacket> packet);
virtual void handleEntityActionAtPosition(std::shared_ptr<EntityActionAtPositionPacket> packet); virtual void handleEntityActionAtPosition(
std::shared_ptr<EntityActionAtPositionPacket> packet);
virtual void handlePreLogin(std::shared_ptr<PreLoginPacket> packet); virtual void handlePreLogin(std::shared_ptr<PreLoginPacket> packet);
void close(); void close();
virtual void handleAddMob(std::shared_ptr<AddMobPacket> packet); virtual void handleAddMob(std::shared_ptr<AddMobPacket> packet);
@ -88,53 +104,79 @@ public:
virtual void handleSetSpawn(std::shared_ptr<SetSpawnPositionPacket> packet); virtual void handleSetSpawn(std::shared_ptr<SetSpawnPositionPacket> packet);
virtual void handleRidePacket(std::shared_ptr<SetRidingPacket> packet); virtual void handleRidePacket(std::shared_ptr<SetRidingPacket> packet);
virtual void handleEntityEvent(std::shared_ptr<EntityEventPacket> packet); virtual void handleEntityEvent(std::shared_ptr<EntityEventPacket> packet);
private: private:
std::shared_ptr<Entity> getEntity(int entityId); std::shared_ptr<Entity> getEntity(int entityId);
std::wstring GetDisplayNameByGamertag(std::wstring gamertag); std::wstring GetDisplayNameByGamertag(std::wstring gamertag);
public: public:
virtual void handleSetHealth(std::shared_ptr<SetHealthPacket> packet); virtual void handleSetHealth(std::shared_ptr<SetHealthPacket> packet);
virtual void handleSetExperience(std::shared_ptr<SetExperiencePacket> packet); virtual void handleSetExperience(
std::shared_ptr<SetExperiencePacket> packet);
virtual void handleRespawn(std::shared_ptr<RespawnPacket> packet); virtual void handleRespawn(std::shared_ptr<RespawnPacket> packet);
virtual void handleExplosion(std::shared_ptr<ExplodePacket> packet); virtual void handleExplosion(std::shared_ptr<ExplodePacket> packet);
virtual void handleContainerOpen(std::shared_ptr<ContainerOpenPacket> packet); virtual void handleContainerOpen(
virtual void handleContainerSetSlot(std::shared_ptr<ContainerSetSlotPacket> packet); std::shared_ptr<ContainerOpenPacket> packet);
virtual void handleContainerSetSlot(
std::shared_ptr<ContainerSetSlotPacket> packet);
virtual void handleContainerAck(std::shared_ptr<ContainerAckPacket> packet); virtual void handleContainerAck(std::shared_ptr<ContainerAckPacket> packet);
virtual void handleContainerContent(std::shared_ptr<ContainerSetContentPacket> packet); virtual void handleContainerContent(
std::shared_ptr<ContainerSetContentPacket> packet);
virtual void handleSignUpdate(std::shared_ptr<SignUpdatePacket> packet); virtual void handleSignUpdate(std::shared_ptr<SignUpdatePacket> packet);
virtual void handleTileEntityData(std::shared_ptr<TileEntityDataPacket> packet); virtual void handleTileEntityData(
virtual void handleContainerSetData(std::shared_ptr<ContainerSetDataPacket> packet); std::shared_ptr<TileEntityDataPacket> packet);
virtual void handleSetEquippedItem(std::shared_ptr<SetEquippedItemPacket> packet); virtual void handleContainerSetData(
virtual void handleContainerClose(std::shared_ptr<ContainerClosePacket> packet); std::shared_ptr<ContainerSetDataPacket> packet);
virtual void handleSetEquippedItem(
std::shared_ptr<SetEquippedItemPacket> packet);
virtual void handleContainerClose(
std::shared_ptr<ContainerClosePacket> packet);
virtual void handleTileEvent(std::shared_ptr<TileEventPacket> packet); virtual void handleTileEvent(std::shared_ptr<TileEventPacket> packet);
virtual void handleTileDestruction(std::shared_ptr<TileDestructionPacket> packet); virtual void handleTileDestruction(
virtual bool canHandleAsyncPackets(); std::shared_ptr<TileDestructionPacket> packet);
virtual void handleGameEvent(std::shared_ptr<GameEventPacket> gameEventPacket); virtual bool canHandleAsyncPackets();
virtual void handleComplexItemData(std::shared_ptr<ComplexItemDataPacket> packet); virtual void handleGameEvent(
std::shared_ptr<GameEventPacket> gameEventPacket);
virtual void handleComplexItemData(
std::shared_ptr<ComplexItemDataPacket> packet);
virtual void handleLevelEvent(std::shared_ptr<LevelEventPacket> packet); virtual void handleLevelEvent(std::shared_ptr<LevelEventPacket> packet);
virtual void handleAwardStat(std::shared_ptr<AwardStatPacket> packet); virtual void handleAwardStat(std::shared_ptr<AwardStatPacket> packet);
virtual void handleUpdateMobEffect(std::shared_ptr<UpdateMobEffectPacket> packet); virtual void handleUpdateMobEffect(
virtual void handleRemoveMobEffect(std::shared_ptr<RemoveMobEffectPacket> packet); std::shared_ptr<UpdateMobEffectPacket> packet);
virtual bool isServerPacketListener(); virtual void handleRemoveMobEffect(
virtual void handlePlayerInfo(std::shared_ptr<PlayerInfoPacket> packet); std::shared_ptr<RemoveMobEffectPacket> packet);
virtual void handleKeepAlive(std::shared_ptr<KeepAlivePacket> packet); virtual bool isServerPacketListener();
virtual void handlePlayerAbilities(std::shared_ptr<PlayerAbilitiesPacket> playerAbilitiesPacket); virtual void handlePlayerInfo(std::shared_ptr<PlayerInfoPacket> packet);
virtual void handleSoundEvent(std::shared_ptr<LevelSoundPacket> packet); virtual void handleKeepAlive(std::shared_ptr<KeepAlivePacket> packet);
virtual void handleCustomPayload(std::shared_ptr<CustomPayloadPacket> customPayloadPacket); virtual void handlePlayerAbilities(
virtual Connection *getConnection(); std::shared_ptr<PlayerAbilitiesPacket> playerAbilitiesPacket);
virtual void handleSoundEvent(std::shared_ptr<LevelSoundPacket> packet);
virtual void handleCustomPayload(
std::shared_ptr<CustomPayloadPacket> customPayloadPacket);
virtual Connection* getConnection();
// 4J Added // 4J Added
virtual void handleServerSettingsChanged(std::shared_ptr<ServerSettingsChangedPacket> packet); virtual void handleServerSettingsChanged(
virtual void handleTexture(std::shared_ptr<TexturePacket> packet); std::shared_ptr<ServerSettingsChangedPacket> packet);
virtual void handleTextureAndGeometry(std::shared_ptr<TextureAndGeometryPacket> packet); virtual void handleTexture(std::shared_ptr<TexturePacket> packet);
virtual void handleUpdateProgress(std::shared_ptr<UpdateProgressPacket> packet); virtual void handleTextureAndGeometry(
std::shared_ptr<TextureAndGeometryPacket> packet);
virtual void handleUpdateProgress(
std::shared_ptr<UpdateProgressPacket> packet);
// 4J Added // 4J Added
static int HostDisconnectReturned(void *pParam,int iPad,C4JStorage::EMessageResult result); static int HostDisconnectReturned(void* pParam, int iPad,
static int ExitGameAndSaveReturned(void *pParam,int iPad,C4JStorage::EMessageResult result); C4JStorage::EMessageResult result);
virtual void handleTextureChange(std::shared_ptr<TextureChangePacket> packet); static int ExitGameAndSaveReturned(void* pParam, int iPad,
virtual void handleTextureAndGeometryChange(std::shared_ptr<TextureAndGeometryChangePacket> packet); C4JStorage::EMessageResult result);
virtual void handleUpdateGameRuleProgressPacket(std::shared_ptr<UpdateGameRuleProgressPacket> packet); virtual void handleTextureChange(
virtual void handleXZ(std::shared_ptr<XZPacket> packet); std::shared_ptr<TextureChangePacket> packet);
virtual void handleTextureAndGeometryChange(
std::shared_ptr<TextureAndGeometryChangePacket> packet);
virtual void handleUpdateGameRuleProgressPacket(
std::shared_ptr<UpdateGameRuleProgressPacket> packet);
virtual void handleXZ(std::shared_ptr<XZPacket> packet);
void displayPrivilegeChanges(std::shared_ptr<MultiplayerLocalPlayer> player, unsigned int oldPrivileges); void displayPrivilegeChanges(std::shared_ptr<MultiplayerLocalPlayer> player,
unsigned int oldPrivileges);
}; };

View file

@ -10,297 +10,287 @@
#include "../../Minecraft.World/Blocks/Tile.h" #include "../../Minecraft.World/Blocks/Tile.h"
#include "../../Minecraft.World/Level/WaterLevelChunk.h" #include "../../Minecraft.World/Level/WaterLevelChunk.h"
MultiPlayerChunkCache::MultiPlayerChunkCache(Level *level) MultiPlayerChunkCache::MultiPlayerChunkCache(Level* level) {
{ XZSIZE = level->dimension->getXZSize(); // 4J Added
XZSIZE = level->dimension->getXZSize(); // 4J Added XZOFFSET = XZSIZE / 2; // 4J Added
XZOFFSET = XZSIZE/2; // 4J Added m_XZSize = XZSIZE;
m_XZSize = XZSIZE; hasData = new bool[XZSIZE * XZSIZE];
hasData = new bool[XZSIZE * XZSIZE]; memset(hasData, 0, sizeof(bool) * XZSIZE * XZSIZE);
memset(hasData, 0, sizeof(bool) * XZSIZE * XZSIZE);
emptyChunk = new EmptyLevelChunk(level, byteArray(16 * 16 * Level::maxBuildHeight), 0, 0); emptyChunk = new EmptyLevelChunk(
level, byteArray(16 * 16 * Level::maxBuildHeight), 0, 0);
// For normal world dimension, create a chunk that can be used to create the illusion of infinite water at the edge of the world // For normal world dimension, create a chunk that can be used to create the
if( level->dimension->id == 0 ) // illusion of infinite water at the edge of the world
{ if (level->dimension->id == 0) {
byteArray bytes = byteArray(16 * 16 * 128); byteArray bytes = byteArray(16 * 16 * 128);
// Superflat.... make grass, not water... // Superflat.... make grass, not water...
if(level->getLevelData()->getGenerator() == LevelType::lvl_flat) if (level->getLevelData()->getGenerator() == LevelType::lvl_flat) {
{ for (int x = 0; x < 16; x++)
for( int x = 0; x < 16; x++ ) for (int y = 0; y < 128; y++)
for( int y = 0; y < 128; y++ ) for (int z = 0; z < 16; z++) {
for( int z = 0; z < 16; z++ ) unsigned char tileId = 0;
{ if (y == 3)
unsigned char tileId = 0; tileId = Tile::grass_Id;
if( y == 3 ) tileId = Tile::grass_Id; else if (y <= 2)
else if( y <= 2 ) tileId = Tile::dirt_Id; tileId = Tile::dirt_Id;
bytes[x << 11 | z << 7 | y] = tileId; bytes[x << 11 | z << 7 | y] = tileId;
} }
} } else {
else for (int x = 0; x < 16; x++)
{ for (int y = 0; y < 128; y++)
for( int x = 0; x < 16; x++ ) for (int z = 0; z < 16; z++) {
for( int y = 0; y < 128; y++ ) unsigned char tileId = 0;
for( int z = 0; z < 16; z++ ) if (y <= (level->getSeaLevel() - 10))
{ tileId = Tile::rock_Id;
unsigned char tileId = 0; else if (y < level->getSeaLevel())
if( y <= ( level->getSeaLevel() - 10 ) ) tileId = Tile::rock_Id; tileId = Tile::calmWater_Id;
else if( y < level->getSeaLevel() ) tileId = Tile::calmWater_Id;
bytes[x << 11 | z << 7 | y] = tileId; bytes[x << 11 | z << 7 | y] = tileId;
} }
} }
waterChunk = new WaterLevelChunk(level, bytes, 0, 0); waterChunk = new WaterLevelChunk(level, bytes, 0, 0);
delete[] bytes.data; delete[] bytes.data;
if(level->getLevelData()->getGenerator() == LevelType::lvl_flat) if (level->getLevelData()->getGenerator() == LevelType::lvl_flat) {
{ for (int x = 0; x < 16; x++)
for( int x = 0; x < 16; x++ ) for (int y = 0; y < 128; y++)
for( int y = 0; y < 128; y++ ) for (int z = 0; z < 16; z++) {
for( int z = 0; z < 16; z++ ) if (y >= 3) {
{ ((WaterLevelChunk*)waterChunk)
if( y >= 3 ) ->setLevelChunkBrightness(LightLayer::Sky, x, y,
{ z, 15);
((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); }
} }
} } else {
} for (int x = 0; x < 16; x++)
else for (int y = 0; y < 128; y++)
{ for (int z = 0; z < 16; z++) {
for( int x = 0; x < 16; x++ ) if (y >= (level->getSeaLevel() - 1)) {
for( int y = 0; y < 128; y++ ) ((WaterLevelChunk*)waterChunk)
for( int z = 0; z < 16; z++ ) ->setLevelChunkBrightness(LightLayer::Sky, x, y,
{ z, 15);
if( y >= ( level->getSeaLevel() - 1 ) ) } else {
{ ((WaterLevelChunk*)waterChunk)
((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,15); ->setLevelChunkBrightness(LightLayer::Sky, x, y,
} z, 2);
else }
{ }
((WaterLevelChunk *)waterChunk)->setLevelChunkBrightness(LightLayer::Sky,x,y,z,2); }
} } else {
} waterChunk = NULL;
} }
}
else
{
waterChunk = NULL;
}
this->level = level; this->level = level;
this->cache = new LevelChunk *[XZSIZE * XZSIZE]; this->cache = new LevelChunk*[XZSIZE * XZSIZE];
memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk *)); memset(this->cache, 0, XZSIZE * XZSIZE * sizeof(LevelChunk*));
InitializeCriticalSectionAndSpinCount(&m_csLoadCreate,4000); InitializeCriticalSectionAndSpinCount(&m_csLoadCreate, 4000);
} }
MultiPlayerChunkCache::~MultiPlayerChunkCache() MultiPlayerChunkCache::~MultiPlayerChunkCache() {
{ delete emptyChunk;
delete emptyChunk; delete waterChunk;
delete waterChunk; delete cache;
delete cache; delete hasData;
delete hasData;
AUTO_VAR(itEnd, loadedChunkList.end()); AUTO_VAR(itEnd, loadedChunkList.end());
for (AUTO_VAR(it, loadedChunkList.begin()); it != itEnd; it++) for (AUTO_VAR(it, loadedChunkList.begin()); it != itEnd; it++) delete *it;
delete *it;
DeleteCriticalSection(&m_csLoadCreate); DeleteCriticalSection(&m_csLoadCreate);
} }
bool MultiPlayerChunkCache::hasChunk(int x, int z) {
bool MultiPlayerChunkCache::hasChunk(int x, int z) // This cache always claims to have chunks, although it might actually just
{ // return empty data if it doesn't have anything
// This cache always claims to have chunks, although it might actually just return empty data if it doesn't have anything return true;
return true;
} }
// 4J added - find out if we actually really do have a chunk in our cache // 4J added - find out if we actually really do have a chunk in our cache
bool MultiPlayerChunkCache::reallyHasChunk(int x, int z) bool MultiPlayerChunkCache::reallyHasChunk(int x, int z) {
{ int ix = x + XZOFFSET;
int ix = x + XZOFFSET; int iz = z + XZOFFSET;
int iz = z + XZOFFSET; // Check we're in range of the stored level - if we aren't, then consider
// Check we're in range of the stored level - if we aren't, then consider that we do have that chunk as we'll be able to use the water chunk there // that we do have that chunk as we'll be able to use the water chunk there
if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return true; if ((ix < 0) || (ix >= XZSIZE)) return true;
if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return true; if ((iz < 0) || (iz >= XZSIZE)) return true;
int idx = ix * XZSIZE + iz; int idx = ix * XZSIZE + iz;
LevelChunk *chunk = cache[idx]; LevelChunk* chunk = cache[idx];
if( chunk == NULL ) if (chunk == NULL) {
{ return false;
return false; }
} return hasData[idx];
return hasData[idx];
} }
void MultiPlayerChunkCache::drop(int x, int z) void MultiPlayerChunkCache::drop(int x, int z) {
{ // 4J Stu - We do want to drop any entities in the chunks, especially for
// 4J Stu - We do want to drop any entities in the chunks, especially for the case when a player is dead as they will // the case when a player is dead as they will not get the RemoveEntity
// not get the RemoveEntity packet if an entity is removed. // packet if an entity is removed.
LevelChunk *chunk = getChunk(x, z); LevelChunk* chunk = getChunk(x, z);
if (!chunk->isEmpty()) if (!chunk->isEmpty()) {
{ // Added parameter here specifies that we don't want to delete tile
// Added parameter here specifies that we don't want to delete tile entities, as they won't get recreated unless they've got update packets // entities, as they won't get recreated unless they've got update
// The tile entities are in general only created on the client by virtue of the chunk rebuild // packets The tile entities are in general only created on the client
chunk->unload(false); // by virtue of the chunk rebuild
chunk->unload(false);
// 4J - We just want to clear out the entities in the chunk, but everything else should be valid // 4J - We just want to clear out the entities in the chunk, but
chunk->loaded = true; // everything else should be valid
chunk->loaded = true;
} }
} }
LevelChunk *MultiPlayerChunkCache::create(int x, int z) LevelChunk* MultiPlayerChunkCache::create(int x, int z) {
{ int ix = x + XZOFFSET;
int ix = x + XZOFFSET; int iz = z + XZOFFSET;
int iz = z + XZOFFSET; // Check we're in range of the stored level
// Check we're in range of the stored level if ((ix < 0) || (ix >= XZSIZE))
if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); return (waterChunk ? waterChunk : emptyChunk);
if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); if ((iz < 0) || (iz >= XZSIZE))
int idx = ix * XZSIZE + iz; return (waterChunk ? waterChunk : emptyChunk);
LevelChunk *chunk = cache[idx]; int idx = ix * XZSIZE + iz;
LevelChunk *lastChunk = chunk; LevelChunk* chunk = cache[idx];
LevelChunk* lastChunk = chunk;
if( chunk == NULL ) if (chunk == NULL) {
{ EnterCriticalSection(&m_csLoadCreate);
EnterCriticalSection(&m_csLoadCreate);
//LevelChunk *chunk; // LevelChunk *chunk;
if( g_NetworkManager.IsHost() ) // force here to disable sharing of data if (g_NetworkManager.IsHost()) // force here to disable sharing of data
{ {
// 4J-JEV: We are about to use shared data, abort if the server is stopped and the data is deleted. // 4J-JEV: We are about to use shared data, abort if the server is
if (MinecraftServer::getInstance()->serverHalted()) return NULL; // stopped and the data is deleted.
if (MinecraftServer::getInstance()->serverHalted()) return NULL;
// If we're the host, then don't create the chunk, share data from the server's copy // If we're the host, then don't create the chunk, share data from
// the server's copy
#ifdef _LARGE_WORLDS #ifdef _LARGE_WORLDS
LevelChunk *serverChunk = MinecraftServer::getInstance()->getLevel(level->dimension->id)->cache->getChunkLoadedOrUnloaded(x,z); LevelChunk* serverChunk =
MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunkLoadedOrUnloaded(x, z);
#else #else
LevelChunk *serverChunk = MinecraftServer::getInstance()->getLevel(level->dimension->id)->cache->getChunk(x,z); LevelChunk* serverChunk = MinecraftServer::getInstance()
->getLevel(level->dimension->id)
->cache->getChunk(x, z);
#endif #endif
chunk = new LevelChunk(level, x, z, serverChunk); chunk = new LevelChunk(level, x, z, serverChunk);
// Let renderer know that this chunk has been created - it might have made render data from the EmptyChunk if it got to a chunk before the server sent it // Let renderer know that this chunk has been created - it might
level->setTilesDirty( x * 16 , 0 , z * 16 , x * 16 + 15, 127, z * 16 + 15); // have made render data from the EmptyChunk if it got to a chunk
hasData[idx] = true; // before the server sent it
} level->setTilesDirty(x * 16, 0, z * 16, x * 16 + 15, 127,
else z * 16 + 15);
{ hasData[idx] = true;
// Passing an empty array into the LevelChunk ctor, which it now detects and sets up the chunk as compressed & empty } else {
byteArray bytes; // Passing an empty array into the LevelChunk ctor, which it now
// detects and sets up the chunk as compressed & empty
byteArray bytes;
chunk = new LevelChunk(level, bytes, x, z); chunk = new LevelChunk(level, bytes, x, z);
// 4J - changed to use new methods for lighting // 4J - changed to use new methods for lighting
chunk->setSkyLightDataAllBright(); chunk->setSkyLightDataAllBright();
// Arrays::fill(chunk->skyLight->data, (uint8_t) 255); // Arrays::fill(chunk->skyLight->data, (uint8_t)
} //255);
}
chunk->loaded = true;
LeaveCriticalSection(&m_csLoadCreate); chunk->loaded = true;
#if ( defined _WIN64 || defined __LP64__ ) LeaveCriticalSection(&m_csLoadCreate);
if( InterlockedCompareExchangeRelease64((LONG64 *)&cache[idx],(LONG64)chunk,(LONG64)lastChunk) == (LONG64)lastChunk )
#if (defined _WIN64 || defined __LP64__)
if (InterlockedCompareExchangeRelease64(
(LONG64*)&cache[idx], (LONG64)chunk, (LONG64)lastChunk) ==
(LONG64)lastChunk)
#else #else
if( InterlockedCompareExchangeRelease((LONG *)&cache[idx],(LONG)chunk,(LONG)lastChunk) == (LONG)lastChunk ) if (InterlockedCompareExchangeRelease((LONG*)&cache[idx], (LONG)chunk,
#endif // _DURANGO (LONG)lastChunk) ==
{ (LONG)lastChunk)
// If we're sharing with the server, we'll need to calculate our heightmap now, which isn't shared. If we aren't sharing with the server, #endif // _DURANGO
// then this will be calculated when the chunk data arrives. {
if( g_NetworkManager.IsHost() ) // If we're sharing with the server, we'll need to calculate our
{ // heightmap now, which isn't shared. If we aren't sharing with the
chunk->recalcHeightmapOnly(); // server, then this will be calculated when the chunk data arrives.
} if (g_NetworkManager.IsHost()) {
chunk->recalcHeightmapOnly();
}
// Successfully updated the cache // Successfully updated the cache
EnterCriticalSection(&m_csLoadCreate); EnterCriticalSection(&m_csLoadCreate);
loadedChunkList.push_back(chunk); loadedChunkList.push_back(chunk);
LeaveCriticalSection(&m_csLoadCreate); LeaveCriticalSection(&m_csLoadCreate);
} } else {
else // Something else must have updated the cache. Return that chunk and
{ // discard this one. This really shouldn't be happening in
// Something else must have updated the cache. Return that chunk and discard this one. This really shouldn't be happening // multiplayer
// in multiplayer delete chunk;
delete chunk; return cache[idx];
return cache[idx]; }
}
} } else {
else chunk->load();
{ }
chunk->load();
}
return chunk; return chunk;
} }
LevelChunk *MultiPlayerChunkCache::getChunk(int x, int z) LevelChunk* MultiPlayerChunkCache::getChunk(int x, int z) {
{ int ix = x + XZOFFSET;
int ix = x + XZOFFSET; int iz = z + XZOFFSET;
int iz = z + XZOFFSET; // Check we're in range of the stored level
// Check we're in range of the stored level if ((ix < 0) || (ix >= XZSIZE))
if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); return (waterChunk ? waterChunk : emptyChunk);
if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return ( waterChunk ? waterChunk : emptyChunk ); if ((iz < 0) || (iz >= XZSIZE))
int idx = ix * XZSIZE + iz; return (waterChunk ? waterChunk : emptyChunk);
int idx = ix * XZSIZE + iz;
LevelChunk *chunk = cache[idx]; LevelChunk* chunk = cache[idx];
if( chunk == NULL ) if (chunk == NULL) {
{ return emptyChunk;
return emptyChunk; } else {
} return chunk;
else }
{
return chunk;
}
} }
bool MultiPlayerChunkCache::save(bool force, ProgressListener *progressListener) bool MultiPlayerChunkCache::save(bool force,
{ ProgressListener* progressListener) {
return true; return true;
} }
bool MultiPlayerChunkCache::tick() bool MultiPlayerChunkCache::tick() { return false; }
{
return false; bool MultiPlayerChunkCache::shouldSave() { return false; }
void MultiPlayerChunkCache::postProcess(ChunkSource* parent, int x, int z) {}
std::vector<Biome::MobSpawnerData*>* MultiPlayerChunkCache::getMobsAt(
MobCategory* mobCategory, int x, int y, int z) {
return NULL;
} }
bool MultiPlayerChunkCache::shouldSave() TilePos* MultiPlayerChunkCache::findNearestMapFeature(
{ Level* level, const std::wstring& featureName, int x, int y, int z) {
return false; return NULL;
} }
void MultiPlayerChunkCache::postProcess(ChunkSource *parent, int x, int z) std::wstring MultiPlayerChunkCache::gatherStats() {
{ EnterCriticalSection(&m_csLoadCreate);
int size = (int)loadedChunkList.size();
LeaveCriticalSection(&m_csLoadCreate);
return L"MultiplayerChunkCache: " + _toString<int>(size);
} }
std::vector<Biome::MobSpawnerData *> *MultiPlayerChunkCache::getMobsAt(MobCategory *mobCategory, int x, int y, int z) void MultiPlayerChunkCache::dataReceived(int x, int z) {
{ int ix = x + XZOFFSET;
return NULL; int iz = z + XZOFFSET;
} // Check we're in range of the stored level
if ((ix < 0) || (ix >= XZSIZE)) return;
TilePos *MultiPlayerChunkCache::findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z) if ((iz < 0) || (iz >= XZSIZE)) return;
{ int idx = ix * XZSIZE + iz;
return NULL; hasData[idx] = true;
}
std::wstring MultiPlayerChunkCache::gatherStats()
{
EnterCriticalSection(&m_csLoadCreate);
int size = (int)loadedChunkList.size();
LeaveCriticalSection(&m_csLoadCreate);
return L"MultiplayerChunkCache: " + _toString<int>(size);
}
void MultiPlayerChunkCache::dataReceived(int x, int z)
{
int ix = x + XZOFFSET;
int iz = z + XZOFFSET;
// Check we're in range of the stored level
if( ( ix < 0 ) || ( ix >= XZSIZE ) ) return;
if( ( iz < 0 ) || ( iz >= XZSIZE ) ) return;
int idx = ix * XZSIZE + iz;
hasData[idx] = true;
} }

View file

@ -3,45 +3,48 @@
#include "../../Minecraft.World/Headers/net.minecraft.world.level.chunk.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.chunk.h"
#include "../../Minecraft.World/Level/RandomLevelSource.h" #include "../../Minecraft.World/Level/RandomLevelSource.h"
class ServerChunkCache; class ServerChunkCache;
// 4J - various alterations here to make this thread safe, and operate as a fixed sized cache // 4J - various alterations here to make this thread safe, and operate as a
class MultiPlayerChunkCache : public ChunkSource // fixed sized cache
{ class MultiPlayerChunkCache : public ChunkSource {
friend class LevelRenderer; friend class LevelRenderer;
private: private:
LevelChunk *emptyChunk; LevelChunk* emptyChunk;
LevelChunk *waterChunk; LevelChunk* waterChunk;
std::vector<LevelChunk *> loadedChunkList; std::vector<LevelChunk*> loadedChunkList;
LevelChunk **cache; LevelChunk** cache;
// 4J - added for multithreaded support // 4J - added for multithreaded support
CRITICAL_SECTION m_csLoadCreate; CRITICAL_SECTION m_csLoadCreate;
// 4J - size of cache is defined by size of one side - must be even // 4J - size of cache is defined by size of one side - must be even
int XZSIZE; int XZSIZE;
int XZOFFSET; int XZOFFSET;
bool *hasData; bool* hasData;
Level *level; Level* level;
public: public:
MultiPlayerChunkCache(Level *level); MultiPlayerChunkCache(Level* level);
~MultiPlayerChunkCache(); ~MultiPlayerChunkCache();
virtual bool hasChunk(int x, int z); virtual bool hasChunk(int x, int z);
virtual bool reallyHasChunk(int x, int z); virtual bool reallyHasChunk(int x, int z);
virtual void drop(int x, int z); virtual void drop(int x, int z);
virtual LevelChunk *create(int x, int z); virtual LevelChunk* create(int x, int z);
virtual LevelChunk *getChunk(int x, int z); virtual LevelChunk* getChunk(int x, int z);
virtual bool save(bool force, ProgressListener *progressListener); virtual bool save(bool force, ProgressListener* progressListener);
virtual bool tick(); virtual bool tick();
virtual bool shouldSave(); virtual bool shouldSave();
virtual void postProcess(ChunkSource *parent, int x, int z); virtual void postProcess(ChunkSource* parent, int x, int z);
virtual std::wstring gatherStats(); virtual std::wstring gatherStats();
virtual std::vector<Biome::MobSpawnerData *> *getMobsAt(MobCategory *mobCategory, int x, int y, int z); virtual std::vector<Biome::MobSpawnerData*>* getMobsAt(
virtual TilePos *findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z); MobCategory* mobCategory, int x, int y, int z);
virtual void dataReceived(int x, int z); // 4J added virtual TilePos* findNearestMapFeature(Level* level,
const std::wstring& featureName,
int x, int y, int z);
virtual void dataReceived(int x, int z); // 4J added
virtual LevelChunk **getCache() { return cache; } // 4J added virtual LevelChunk** getCache() { return cache; } // 4J added
}; };

View file

@ -19,112 +19,108 @@
// #include "PS3/Network/NetworkPlayerSony.h" // #include "PS3/Network/NetworkPlayerSony.h"
// #endif // #endif
Random *PendingConnection::random = new Random(); Random* PendingConnection::random = new Random();
PendingConnection::PendingConnection(MinecraftServer *server, Socket *socket, const std::wstring& id) PendingConnection::PendingConnection(MinecraftServer* server, Socket* socket,
{ const std::wstring& id) {
// 4J - added initialisers // 4J - added initialisers
done = false; done = false;
_tick = 0; _tick = 0;
name = L""; name = L"";
acceptedLogin = nullptr; acceptedLogin = nullptr;
loginKey = L""; loginKey = L"";
this->server = server; this->server = server;
connection = new Connection(socket, id, this); connection = new Connection(socket, id, this);
connection->fakeLag = FAKE_LAG; connection->fakeLag = FAKE_LAG;
} }
PendingConnection::~PendingConnection() PendingConnection::~PendingConnection() { delete connection; }
{
delete connection;
}
void PendingConnection::tick() void PendingConnection::tick() {
{ if (acceptedLogin != NULL) {
if (acceptedLogin != NULL)
{
this->handleAcceptedLogin(acceptedLogin); this->handleAcceptedLogin(acceptedLogin);
acceptedLogin = nullptr; acceptedLogin = nullptr;
} }
if (_tick++ == MAX_TICKS_BEFORE_LOGIN) if (_tick++ == MAX_TICKS_BEFORE_LOGIN) {
{
disconnect(DisconnectPacket::eDisconnect_LoginTooLong); disconnect(DisconnectPacket::eDisconnect_LoginTooLong);
} } else {
else
{
connection->tick(); connection->tick();
} }
} }
void PendingConnection::disconnect(DisconnectPacket::eDisconnectReason reason) void PendingConnection::disconnect(DisconnectPacket::eDisconnectReason reason) {
{ // try { // 4J - removed try/catch
// try { // 4J - removed try/catch // logger.info("Disconnecting " + getName() + ": " + reason);
// logger.info("Disconnecting " + getName() + ": " + reason); fprintf(stderr, "[PENDING] disconnect called with reason=%d at tick=%d\n",
fprintf(stderr, "[PENDING] disconnect called with reason=%d at tick=%d\n", reason, _tick); reason, _tick);
app.DebugPrintf("Pending connection disconnect: %d\n", reason ); app.DebugPrintf("Pending connection disconnect: %d\n", reason);
connection->send( std::shared_ptr<DisconnectPacket>( new DisconnectPacket(reason) ) ); connection->send(
connection->sendAndQuit(); std::shared_ptr<DisconnectPacket>(new DisconnectPacket(reason)));
done = true; connection->sendAndQuit();
// } catch (Exception e) { done = true;
// e.printStackTrace(); // } catch (Exception e) {
// } // e.printStackTrace();
// }
} }
void PendingConnection::handlePreLogin(std::shared_ptr<PreLoginPacket> packet) void PendingConnection::handlePreLogin(std::shared_ptr<PreLoginPacket> packet) {
{ if (packet->m_netcodeVersion != MINECRAFT_NET_VERSION) {
if (packet->m_netcodeVersion != MINECRAFT_NET_VERSION) app.DebugPrintf("Netcode version is %d not equal to %d\n",
{ packet->m_netcodeVersion, MINECRAFT_NET_VERSION);
app.DebugPrintf("Netcode version is %d not equal to %d\n", packet->m_netcodeVersion, MINECRAFT_NET_VERSION); if (packet->m_netcodeVersion > MINECRAFT_NET_VERSION) {
if (packet->m_netcodeVersion > MINECRAFT_NET_VERSION)
{
disconnect(DisconnectPacket::eDisconnect_OutdatedServer); disconnect(DisconnectPacket::eDisconnect_OutdatedServer);
} } else {
else
{
disconnect(DisconnectPacket::eDisconnect_OutdatedClient); disconnect(DisconnectPacket::eDisconnect_OutdatedClient);
} }
return; return;
} }
// printf("Server: handlePreLogin\n"); // printf("Server: handlePreLogin\n");
name = packet->loginKey; // 4J Stu - Change from the login packet as we know better on client end during the pre-login packet name =
sendPreLoginResponse(); packet->loginKey; // 4J Stu - Change from the login packet as we know
// better on client end during the pre-login packet
sendPreLoginResponse();
} }
void PendingConnection::sendPreLoginResponse() void PendingConnection::sendPreLoginResponse() {
{ // 4J Stu - Calculate the players with UGC privileges set
// 4J Stu - Calculate the players with UGC privileges set PlayerUID* ugcXuids = new PlayerUID[MINECRAFT_NET_MAX_PLAYERS];
PlayerUID *ugcXuids = new PlayerUID[MINECRAFT_NET_MAX_PLAYERS]; std::uint8_t ugcXuidCount = 0;
std::uint8_t ugcXuidCount = 0; std::uint8_t hostIndex = 0;
std::uint8_t hostIndex = 0; std::uint8_t ugcFriendsOnlyBits = 0;
std::uint8_t ugcFriendsOnlyBits = 0; char szUniqueMapName[14];
char szUniqueMapName[14];
StorageManager.GetSaveUniqueFilename(szUniqueMapName); StorageManager.GetSaveUniqueFilename(szUniqueMapName);
PlayerList *playerList = MinecraftServer::getInstance()->getPlayers(); PlayerList* playerList = MinecraftServer::getInstance()->getPlayers();
for(AUTO_VAR(it, playerList->players.begin()); it != playerList->players.end(); ++it) for (AUTO_VAR(it, playerList->players.begin());
{ it != playerList->players.end(); ++it) {
std::shared_ptr<ServerPlayer> player = *it; std::shared_ptr<ServerPlayer> player = *it;
// If the offline Xuid is invalid but the online one is not then that's guest which we should ignore // If the offline Xuid is invalid but the online one is not then that's
// If the online Xuid is invalid but the offline one is not then we are definitely an offline game so dont care about UGC // guest which we should ignore If the online Xuid is invalid but the
// offline one is not then we are definitely an offline game so dont
// PADDY - this is failing when a local player with chat restrictions joins an online game // care about UGC
if( player != NULL && player->connection->m_offlineXUID != INVALID_XUID && player->connection->m_onlineXUID != INVALID_XUID ) // PADDY - this is failing when a local player with chat restrictions
{ // joins an online game
if( player->connection->m_friendsOnlyUGC )
{
ugcFriendsOnlyBits |= (1<<ugcXuidCount);
}
// Need to use the online XUID otherwise friend checks will fail on the client
ugcXuids[ugcXuidCount] = player->connection->m_onlineXUID;
if( player->connection->getNetworkPlayer() != NULL && player->connection->getNetworkPlayer()->IsHost() ) hostIndex = ugcXuidCount; if (player != NULL &&
player->connection->m_offlineXUID != INVALID_XUID &&
player->connection->m_onlineXUID != INVALID_XUID) {
if (player->connection->m_friendsOnlyUGC) {
ugcFriendsOnlyBits |= (1 << ugcXuidCount);
}
// Need to use the online XUID otherwise friend checks will fail on
// the client
ugcXuids[ugcXuidCount] = player->connection->m_onlineXUID;
++ugcXuidCount; if (player->connection->getNetworkPlayer() != NULL &&
} player->connection->getNetworkPlayer()->IsHost())
} hostIndex = ugcXuidCount;
++ugcXuidCount;
}
}
#if 0 #if 0
if (false)// server->onlineMode) // 4J - removed if (false)// server->onlineMode) // 4J - removed
@ -134,47 +130,44 @@ void PendingConnection::sendPreLoginResponse()
} }
else else
#endif #endif
{ {
connection->send( std::shared_ptr<PreLoginPacket>( new PreLoginPacket(L"-", ugcXuids, ugcXuidCount, ugcFriendsOnlyBits, server->m_ugcPlayersVersion,szUniqueMapName,app.GetGameHostOption(eGameHostOption_All),hostIndex, server->m_texturePackId) ) ); connection->send(std::shared_ptr<PreLoginPacket>(
new PreLoginPacket(L"-", ugcXuids, ugcXuidCount, ugcFriendsOnlyBits,
server->m_ugcPlayersVersion, szUniqueMapName,
app.GetGameHostOption(eGameHostOption_All),
hostIndex, server->m_texturePackId)));
} }
} }
void PendingConnection::handleLogin(std::shared_ptr<LoginPacket> packet) void PendingConnection::handleLogin(std::shared_ptr<LoginPacket> packet) {
{ fprintf(stderr, "[LOGIN-SRV] handleLogin called! clientVersion=%d\n",
fprintf(stderr, "[LOGIN-SRV] handleLogin called! clientVersion=%d\n", packet->clientVersion); packet->clientVersion);
//name = packet->userName; // name = packet->userName;
if (packet->clientVersion != SharedConstants::NETWORK_PROTOCOL_VERSION) if (packet->clientVersion != SharedConstants::NETWORK_PROTOCOL_VERSION) {
{ app.DebugPrintf("Client version is %d not equal to %d\n",
app.DebugPrintf("Client version is %d not equal to %d\n", packet->clientVersion, SharedConstants::NETWORK_PROTOCOL_VERSION); packet->clientVersion,
if (packet->clientVersion > SharedConstants::NETWORK_PROTOCOL_VERSION) SharedConstants::NETWORK_PROTOCOL_VERSION);
{ if (packet->clientVersion > SharedConstants::NETWORK_PROTOCOL_VERSION) {
disconnect(DisconnectPacket::eDisconnect_OutdatedServer); disconnect(DisconnectPacket::eDisconnect_OutdatedServer);
} } else {
else
{
disconnect(DisconnectPacket::eDisconnect_OutdatedClient); disconnect(DisconnectPacket::eDisconnect_OutdatedClient);
} }
return; return;
} }
//if (true)// 4J removed !server->onlineMode) // if (true)// 4J removed !server->onlineMode)
bool sentDisconnect = false; bool sentDisconnect = false;
if( sentDisconnect ) if (sentDisconnect) {
{ // Do nothing
// Do nothing } else if (server->getPlayers()->isXuidBanned(packet->m_onlineXuid)) {
} disconnect(DisconnectPacket::eDisconnect_Banned);
else if( server->getPlayers()->isXuidBanned( packet->m_onlineXuid ) ) } else {
{
disconnect(DisconnectPacket::eDisconnect_Banned);
}
else
{
handleAcceptedLogin(packet); handleAcceptedLogin(packet);
} }
//else // else
{ {
//4J - removed // 4J - removed
#if 0 #if 0
new Thread() { new Thread() {
public void run() { public void run() {
@ -197,75 +190,71 @@ void PendingConnection::handleLogin(std::shared_ptr<LoginPacket> packet)
}.start(); }.start();
#endif #endif
} }
} }
void PendingConnection::handleAcceptedLogin(std::shared_ptr<LoginPacket> packet) void PendingConnection::handleAcceptedLogin(
{ std::shared_ptr<LoginPacket> packet) {
if(packet->m_ugcPlayersVersion != server->m_ugcPlayersVersion) if (packet->m_ugcPlayersVersion != server->m_ugcPlayersVersion) {
{ // Send the pre-login packet again with the new list of players
// Send the pre-login packet again with the new list of players sendPreLoginResponse();
sendPreLoginResponse(); return;
return; }
}
// Guests use the online xuid, everyone else uses the offline one // Guests use the online xuid, everyone else uses the offline one
PlayerUID playerXuid = packet->m_offlineXuid; PlayerUID playerXuid = packet->m_offlineXuid;
if(playerXuid == INVALID_XUID) playerXuid = packet->m_onlineXuid; if (playerXuid == INVALID_XUID) playerXuid = packet->m_onlineXuid;
std::shared_ptr<ServerPlayer> playerEntity = server->getPlayers()->getPlayerForLogin(this, name, playerXuid,packet->m_onlineXuid); std::shared_ptr<ServerPlayer> playerEntity =
if (playerEntity != NULL) server->getPlayers()->getPlayerForLogin(this, name, playerXuid,
{ packet->m_onlineXuid);
if (playerEntity != NULL) {
server->getPlayers()->placeNewPlayer(connection, playerEntity, packet); server->getPlayers()->placeNewPlayer(connection, playerEntity, packet);
connection = NULL; // We've moved responsibility for this over to the new PlayerConnection, NULL so we don't delete our reference to it here in our dtor connection = NULL; // We've moved responsibility for this over to the
// new PlayerConnection, NULL so we don't delete our
// reference to it here in our dtor
} }
done = true; done = true;
} }
void PendingConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects) void PendingConnection::onDisconnect(DisconnectPacket::eDisconnectReason reason,
{ void* reasonObjects) {
// logger.info(getName() + " lost connection"); // logger.info(getName() + " lost connection");
done = true; done = true;
} }
void PendingConnection::handleGetInfo(std::shared_ptr<GetInfoPacket> packet) void PendingConnection::handleGetInfo(std::shared_ptr<GetInfoPacket> packet) {
{ // try {
//try { // String message = server->motd + "§" + server->players->getPlayerCount() +
//String message = server->motd + "§" + server->players->getPlayerCount() + "§" + server->players->getMaxPlayers(); // "§" + server->players->getMaxPlayers(); connection->send(new
//connection->send(new DisconnectPacket(message)); // DisconnectPacket(message));
connection->send(std::shared_ptr<DisconnectPacket>(new DisconnectPacket(DisconnectPacket::eDisconnect_ServerFull) ) ); connection->send(std::shared_ptr<DisconnectPacket>(
connection->sendAndQuit(); new DisconnectPacket(DisconnectPacket::eDisconnect_ServerFull)));
server->connection->removeSpamProtection(connection->getSocket()); connection->sendAndQuit();
done = true; server->connection->removeSpamProtection(connection->getSocket());
//} catch (Exception e) { done = true;
// e.printStackTrace(); //} catch (Exception e) {
//} // e.printStackTrace();
//}
} }
void PendingConnection::handleKeepAlive(std::shared_ptr<KeepAlivePacket> packet) void PendingConnection::handleKeepAlive(
{ std::shared_ptr<KeepAlivePacket> packet) {
// Ignore // Ignore
} }
void PendingConnection::onUnhandledPacket(std::shared_ptr<Packet> packet) void PendingConnection::onUnhandledPacket(std::shared_ptr<Packet> packet) {
{ disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket);
disconnect(DisconnectPacket::eDisconnect_UnexpectedPacket);
} }
void PendingConnection::send(std::shared_ptr<Packet> packet) void PendingConnection::send(std::shared_ptr<Packet> packet) {
{ connection->send(packet);
connection->send(packet);
} }
std::wstring PendingConnection::getName() std::wstring PendingConnection::getName() {
{ return L"Unimplemented";
return L"Unimplemented"; // if (name != null) return name + " [" +
// if (name != null) return name + " [" + connection.getRemoteAddress().toString() + "]"; // connection.getRemoteAddress().toString() + "]"; return
// return connection.getRemoteAddress().toString(); // connection.getRemoteAddress().toString();
} }
bool PendingConnection::isServerPacketListener() bool PendingConnection::isServerPacketListener() { return true; }
{
return true;
}

View file

@ -6,43 +6,47 @@ class LoginPacket;
class Connection; class Connection;
class Random; class Random;
class PendingConnection : public PacketListener {
class PendingConnection : public PacketListener
{
private: private:
static const int FAKE_LAG = 0; static const int FAKE_LAG = 0;
static const int MAX_TICKS_BEFORE_LOGIN = 20 * 30 * 10; // 10 minutes instead of 20 sec for Linux theres just no login yet static const int MAX_TICKS_BEFORE_LOGIN =
20 * 30 *
10; // 10 minutes instead of 20 sec for Linux theres just no login yet
// public static Logger logger = Logger.getLogger("Minecraft"); // public static Logger logger = Logger.getLogger("Minecraft");
static Random *random; static Random* random;
public: public:
Connection *connection; Connection* connection;
public: public:
bool done; bool done;
private: private:
MinecraftServer *server; MinecraftServer* server;
int _tick; int _tick;
std::wstring name; std::wstring name;
std::shared_ptr<LoginPacket> acceptedLogin; std::shared_ptr<LoginPacket> acceptedLogin;
std::wstring loginKey; std::wstring loginKey;
public: public:
PendingConnection(MinecraftServer *server, Socket *socket, const std::wstring& id); PendingConnection(MinecraftServer* server, Socket* socket,
~PendingConnection(); const std::wstring& id);
~PendingConnection();
void tick(); void tick();
void disconnect(DisconnectPacket::eDisconnectReason reason); void disconnect(DisconnectPacket::eDisconnectReason reason);
virtual void handlePreLogin(std::shared_ptr<PreLoginPacket> packet); virtual void handlePreLogin(std::shared_ptr<PreLoginPacket> packet);
virtual void handleLogin(std::shared_ptr<LoginPacket> packet); virtual void handleLogin(std::shared_ptr<LoginPacket> packet);
virtual void handleAcceptedLogin(std::shared_ptr<LoginPacket> packet); virtual void handleAcceptedLogin(std::shared_ptr<LoginPacket> packet);
virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason,
virtual void handleGetInfo(std::shared_ptr<GetInfoPacket> packet); void* reasonObjects);
virtual void handleKeepAlive(std::shared_ptr<KeepAlivePacket> packet); virtual void handleGetInfo(std::shared_ptr<GetInfoPacket> packet);
virtual void handleKeepAlive(std::shared_ptr<KeepAlivePacket> packet);
virtual void onUnhandledPacket(std::shared_ptr<Packet> packet); virtual void onUnhandledPacket(std::shared_ptr<Packet> packet);
void send(std::shared_ptr<Packet> packet); void send(std::shared_ptr<Packet> packet);
std::wstring getName(); std::wstring getName();
virtual bool isServerPacketListener(); virtual bool isServerPacketListener();
private: private:
void sendPreLoginResponse(); void sendPreLoginResponse();
}; };

File diff suppressed because it is too large Load diff

View file

@ -7,35 +7,34 @@ class MinecraftServer;
class Packet; class Packet;
class TileEntity; class TileEntity;
class PlayerChunkMap {
class PlayerChunkMap
{
public: public:
#ifdef _LARGE_WORLDS #ifdef _LARGE_WORLDS
static const int MAX_VIEW_DISTANCE = 30; static const int MAX_VIEW_DISTANCE = 30;
#else #else
static const int MAX_VIEW_DISTANCE = 15; static const int MAX_VIEW_DISTANCE = 15;
#endif #endif
static const int MIN_VIEW_DISTANCE = 3; static const int MIN_VIEW_DISTANCE = 3;
static const int MAX_CHANGES_BEFORE_RESEND = 10; static const int MAX_CHANGES_BEFORE_RESEND = 10;
static const int MIN_TICKS_BETWEEN_REGION_UPDATE = 10; static const int MIN_TICKS_BETWEEN_REGION_UPDATE = 10;
// 4J - added // 4J - added
class PlayerChunkAddRequest class PlayerChunkAddRequest {
{ public:
public: int x, z;
int x,z; std::shared_ptr<ServerPlayer> player;
std::shared_ptr<ServerPlayer> player; PlayerChunkAddRequest(int x, int z,
PlayerChunkAddRequest(int x, int z, std::shared_ptr<ServerPlayer> player ) : x(x), z(z), player(player) {} std::shared_ptr<ServerPlayer> player)
}; : x(x), z(z), player(player) {}
};
class PlayerChunk class PlayerChunk {
{ friend class PlayerChunkMap;
friend class PlayerChunkMap;
private: private:
PlayerChunkMap *parent; // 4J added PlayerChunkMap* parent; // 4J added
std::vector<std::shared_ptr<ServerPlayer> > players; std::vector<std::shared_ptr<ServerPlayer> > players;
//int x, z; // int x, z;
ChunkPos pos; ChunkPos pos;
shortArray changedTiles; shortArray changedTiles;
@ -43,63 +42,73 @@ public:
int xChangeMin, xChangeMax; int xChangeMin, xChangeMax;
int yChangeMin, yChangeMax; int yChangeMin, yChangeMax;
int zChangeMin, zChangeMax; int zChangeMin, zChangeMax;
int ticksToNextRegionUpdate; // 4J added int ticksToNextRegionUpdate; // 4J added
bool prioritised; // 4J added bool prioritised; // 4J added
public: public:
PlayerChunk(int x, int z, PlayerChunkMap *pcm); PlayerChunk(int x, int z, PlayerChunkMap* pcm);
~PlayerChunk(); ~PlayerChunk();
// 4J Added sendPacket param so we can aggregate the initial send into one much smaller packet // 4J Added sendPacket param so we can aggregate the initial send into
// one much smaller packet
void add(std::shared_ptr<ServerPlayer> player, bool sendPacket = true); void add(std::shared_ptr<ServerPlayer> player, bool sendPacket = true);
void remove(std::shared_ptr<ServerPlayer> player); void remove(std::shared_ptr<ServerPlayer> player);
void tileChanged(int x, int y, int z); void tileChanged(int x, int y, int z);
void prioritiseTileChanges(); // 4J added void prioritiseTileChanges(); // 4J added
void broadcast(std::shared_ptr<Packet> packet); void broadcast(std::shared_ptr<Packet> packet);
bool broadcastChanges(bool allowRegionUpdate); // 4J - added parm bool broadcastChanges(bool allowRegionUpdate); // 4J - added parm
private: private:
void broadcast(std::shared_ptr<TileEntity> te); void broadcast(std::shared_ptr<TileEntity> te);
}; };
public: public:
std::vector<std::shared_ptr<ServerPlayer> > players; std::vector<std::shared_ptr<ServerPlayer> > players;
void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added void flagEntitiesToBeRemoved(unsigned int* flags,
bool* removedFound); // 4J added
private: private:
std::unordered_map<__int64,PlayerChunk *,LongKeyHash,LongKeyEq> chunks; // 4J - was LongHashMap std::unordered_map<__int64, PlayerChunk*, LongKeyHash, LongKeyEq>
std::vector<PlayerChunk *> changedChunks; chunks; // 4J - was LongHashMap
std::vector<PlayerChunkAddRequest> addRequests; // 4J added std::vector<PlayerChunk*> changedChunks;
void tickAddRequests(std::shared_ptr<ServerPlayer> player); // 4J added std::vector<PlayerChunkAddRequest> addRequests; // 4J added
void tickAddRequests(std::shared_ptr<ServerPlayer> player); // 4J added
ServerLevel *level; ServerLevel* level;
int radius; int radius;
int dimension; int dimension;
public: public:
PlayerChunkMap(ServerLevel *level, int dimension, int radius); PlayerChunkMap(ServerLevel* level, int dimension, int radius);
~PlayerChunkMap(); ~PlayerChunkMap();
ServerLevel *getLevel(); ServerLevel* getLevel();
void tick(); void tick();
bool hasChunk(int x, int z); bool hasChunk(int x, int z);
private: private:
PlayerChunk *getChunk(int x, int z, bool create); PlayerChunk* getChunk(int x, int z, bool create);
void getChunkAndAddPlayer(int x, int z, std::shared_ptr<ServerPlayer> player); // 4J added void getChunkAndAddPlayer(
void getChunkAndRemovePlayer(int x, int z, std::shared_ptr<ServerPlayer> player); // 4J added int x, int z, std::shared_ptr<ServerPlayer> player); // 4J added
void getChunkAndRemovePlayer(
int x, int z, std::shared_ptr<ServerPlayer> player); // 4J added
public: public:
void broadcastTileUpdate(std::shared_ptr<Packet> packet, int x, int y, int z); void broadcastTileUpdate(std::shared_ptr<Packet> packet, int x, int y,
int z);
void tileChanged(int x, int y, int z); void tileChanged(int x, int y, int z);
bool isTrackingTile(int x, int y, int z); // 4J added bool isTrackingTile(int x, int y, int z); // 4J added
void prioritiseTileChanges(int x, int y, int z); // 4J added void prioritiseTileChanges(int x, int y, int z); // 4J added
void add(std::shared_ptr<ServerPlayer> player); void add(std::shared_ptr<ServerPlayer> player);
void remove(std::shared_ptr<ServerPlayer> player); void remove(std::shared_ptr<ServerPlayer> player);
private:
bool chunkInRange(int x, int z, int xc, int zc);
public:
void move(std::shared_ptr<ServerPlayer> player);
int getMaxRange();
bool isPlayerIn(std::shared_ptr<ServerPlayer> player, int xChunk, int zChunk);
static int convertChunkRangeToBlock(int radius);
// AP added for Vita private:
void setRadius(int newRadius); bool chunkInRange(int x, int z, int xc, int zc);
public:
void move(std::shared_ptr<ServerPlayer> player);
int getMaxRange();
bool isPlayerIn(std::shared_ptr<ServerPlayer> player, int xChunk,
int zChunk);
static int convertChunkRangeToBlock(int radius);
// AP added for Vita
void setRadius(int newRadius);
}; };

File diff suppressed because it is too large Load diff

View file

@ -8,132 +8,152 @@ class Connection;
class ServerPlayer; class ServerPlayer;
class INetworkPlayer; class INetworkPlayer;
class PlayerConnection : public PacketListener, public ConsoleInputSource {
// public static Logger logger = Logger.getLogger("Minecraft");
class PlayerConnection : public PacketListener, public ConsoleInputSource
{
// public static Logger logger = Logger.getLogger("Minecraft");
public: public:
Connection *connection; Connection* connection;
bool done; bool done;
CRITICAL_SECTION done_cs; CRITICAL_SECTION done_cs;
// 4J Stu - Added this so that we can manage UGC privileges // 4J Stu - Added this so that we can manage UGC privileges
PlayerUID m_offlineXUID, m_onlineXUID; PlayerUID m_offlineXUID, m_onlineXUID;
bool m_friendsOnlyUGC; bool m_friendsOnlyUGC;
private: private:
MinecraftServer *server; MinecraftServer* server;
std::shared_ptr<ServerPlayer> player; std::shared_ptr<ServerPlayer> player;
int tickCount; int tickCount;
int aboveGroundTickCount; int aboveGroundTickCount;
bool didTick; bool didTick;
int lastKeepAliveId; int lastKeepAliveId;
__int64 lastKeepAliveTime; __int64 lastKeepAliveTime;
static Random random; static Random random;
__int64 lastKeepAliveTick; __int64 lastKeepAliveTick;
int chatSpamTickCount; int chatSpamTickCount;
int dropSpamTickCount; int dropSpamTickCount;
bool m_bHasClientTickedOnce; bool m_bHasClientTickedOnce;
public: public:
PlayerConnection(MinecraftServer *server, Connection *connection, std::shared_ptr<ServerPlayer> player); PlayerConnection(MinecraftServer* server, Connection* connection,
~PlayerConnection(); std::shared_ptr<ServerPlayer> player);
~PlayerConnection();
void tick(); void tick();
void disconnect(DisconnectPacket::eDisconnectReason reason); void disconnect(DisconnectPacket::eDisconnectReason reason);
private: private:
double xLastOk, yLastOk, zLastOk; double xLastOk, yLastOk, zLastOk;
bool synched; bool synched;
public: public:
virtual void handlePlayerInput(std::shared_ptr<PlayerInputPacket> packet); virtual void handlePlayerInput(std::shared_ptr<PlayerInputPacket> packet);
virtual void handleMovePlayer(std::shared_ptr<MovePlayerPacket> packet); virtual void handleMovePlayer(std::shared_ptr<MovePlayerPacket> packet);
void teleport(double x, double y, double z, float yRot, float xRot, bool sendPacket = true); // 4J Added sendPacket param void teleport(double x, double y, double z, float yRot, float xRot,
bool sendPacket = true); // 4J Added sendPacket param
virtual void handlePlayerAction(std::shared_ptr<PlayerActionPacket> packet); virtual void handlePlayerAction(std::shared_ptr<PlayerActionPacket> packet);
virtual void handleUseItem(std::shared_ptr<UseItemPacket> packet); virtual void handleUseItem(std::shared_ptr<UseItemPacket> packet);
virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason, void *reasonObjects); virtual void onDisconnect(DisconnectPacket::eDisconnectReason reason,
void* reasonObjects);
virtual void onUnhandledPacket(std::shared_ptr<Packet> packet); virtual void onUnhandledPacket(std::shared_ptr<Packet> packet);
void send(std::shared_ptr<Packet> packet); void send(std::shared_ptr<Packet> packet);
void queueSend(std::shared_ptr<Packet> packet); // 4J Added void queueSend(std::shared_ptr<Packet> packet); // 4J Added
virtual void handleSetCarriedItem(std::shared_ptr<SetCarriedItemPacket> packet); virtual void handleSetCarriedItem(
std::shared_ptr<SetCarriedItemPacket> packet);
virtual void handleChat(std::shared_ptr<ChatPacket> packet); virtual void handleChat(std::shared_ptr<ChatPacket> packet);
private: private:
void handleCommand(const std::wstring& message); void handleCommand(const std::wstring& message);
public: public:
virtual void handleAnimate(std::shared_ptr<AnimatePacket> packet); virtual void handleAnimate(std::shared_ptr<AnimatePacket> packet);
virtual void handlePlayerCommand(std::shared_ptr<PlayerCommandPacket> packet); virtual void handlePlayerCommand(
std::shared_ptr<PlayerCommandPacket> packet);
virtual void handleDisconnect(std::shared_ptr<DisconnectPacket> packet); virtual void handleDisconnect(std::shared_ptr<DisconnectPacket> packet);
int countDelayedPackets(); int countDelayedPackets();
virtual void info(const std::wstring& string); virtual void info(const std::wstring& string);
virtual void warn(const std::wstring& string); virtual void warn(const std::wstring& string);
virtual std::wstring getConsoleName(); virtual std::wstring getConsoleName();
virtual void handleInteract(std::shared_ptr<InteractPacket> packet); virtual void handleInteract(std::shared_ptr<InteractPacket> packet);
bool canHandleAsyncPackets(); bool canHandleAsyncPackets();
virtual void handleClientCommand(std::shared_ptr<ClientCommandPacket> packet); virtual void handleClientCommand(
std::shared_ptr<ClientCommandPacket> packet);
virtual void handleRespawn(std::shared_ptr<RespawnPacket> packet); virtual void handleRespawn(std::shared_ptr<RespawnPacket> packet);
virtual void handleContainerClose(std::shared_ptr<ContainerClosePacket> packet); virtual void handleContainerClose(
std::shared_ptr<ContainerClosePacket> packet);
private: private:
std::unordered_map<int, short, IntKeyHash, IntKeyEq> expectedAcks; std::unordered_map<int, short, IntKeyHash, IntKeyEq> expectedAcks;
public: public:
// 4J Stu - Handlers only valid in debug mode // 4J Stu - Handlers only valid in debug mode
#ifndef _CONTENT_PACKAGE #ifndef _CONTENT_PACKAGE
virtual void handleContainerSetSlot(std::shared_ptr<ContainerSetSlotPacket> packet); virtual void handleContainerSetSlot(
std::shared_ptr<ContainerSetSlotPacket> packet);
#endif #endif
virtual void handleContainerClick(std::shared_ptr<ContainerClickPacket> packet); virtual void handleContainerClick(
virtual void handleContainerButtonClick(std::shared_ptr<ContainerButtonClickPacket> packet); std::shared_ptr<ContainerClickPacket> packet);
virtual void handleSetCreativeModeSlot(std::shared_ptr<SetCreativeModeSlotPacket> packet); virtual void handleContainerButtonClick(
std::shared_ptr<ContainerButtonClickPacket> packet);
virtual void handleSetCreativeModeSlot(
std::shared_ptr<SetCreativeModeSlotPacket> packet);
virtual void handleContainerAck(std::shared_ptr<ContainerAckPacket> packet); virtual void handleContainerAck(std::shared_ptr<ContainerAckPacket> packet);
virtual void handleSignUpdate(std::shared_ptr<SignUpdatePacket> packet); virtual void handleSignUpdate(std::shared_ptr<SignUpdatePacket> packet);
virtual void handleKeepAlive(std::shared_ptr<KeepAlivePacket> packet); virtual void handleKeepAlive(std::shared_ptr<KeepAlivePacket> packet);
virtual void handlePlayerInfo(std::shared_ptr<PlayerInfoPacket> packet); // 4J Added virtual void handlePlayerInfo(
std::shared_ptr<PlayerInfoPacket> packet); // 4J Added
virtual bool isServerPacketListener(); virtual bool isServerPacketListener();
virtual void handlePlayerAbilities(std::shared_ptr<PlayerAbilitiesPacket> playerAbilitiesPacket); virtual void handlePlayerAbilities(
virtual void handleCustomPayload(std::shared_ptr<CustomPayloadPacket> customPayloadPacket); std::shared_ptr<PlayerAbilitiesPacket> playerAbilitiesPacket);
virtual void handleCustomPayload(
std::shared_ptr<CustomPayloadPacket> customPayloadPacket);
// 4J Added // 4J Added
virtual void handleCraftItem(std::shared_ptr<CraftItemPacket> packet); virtual void handleCraftItem(std::shared_ptr<CraftItemPacket> packet);
virtual void handleTradeItem(std::shared_ptr<TradeItemPacket> packet); virtual void handleTradeItem(std::shared_ptr<TradeItemPacket> packet);
virtual void handleDebugOptions(std::shared_ptr<DebugOptionsPacket> packet); virtual void handleDebugOptions(std::shared_ptr<DebugOptionsPacket> packet);
virtual void handleTexture(std::shared_ptr<TexturePacket> packet); virtual void handleTexture(std::shared_ptr<TexturePacket> packet);
virtual void handleTextureAndGeometry(std::shared_ptr<TextureAndGeometryPacket> packet); virtual void handleTextureAndGeometry(
virtual void handleTextureChange(std::shared_ptr<TextureChangePacket> packet); std::shared_ptr<TextureAndGeometryPacket> packet);
virtual void handleTextureAndGeometryChange(std::shared_ptr<TextureAndGeometryChangePacket> packet); virtual void handleTextureChange(
virtual void handleServerSettingsChanged(std::shared_ptr<ServerSettingsChangedPacket> packet); std::shared_ptr<TextureChangePacket> packet);
virtual void handleKickPlayer(std::shared_ptr<KickPlayerPacket> packet); virtual void handleTextureAndGeometryChange(
virtual void handleGameCommand(std::shared_ptr<GameCommandPacket> packet); std::shared_ptr<TextureAndGeometryChangePacket> packet);
virtual void handleServerSettingsChanged(
std::shared_ptr<ServerSettingsChangedPacket> packet);
virtual void handleKickPlayer(std::shared_ptr<KickPlayerPacket> packet);
virtual void handleGameCommand(std::shared_ptr<GameCommandPacket> packet);
INetworkPlayer *getNetworkPlayer(); INetworkPlayer* getNetworkPlayer();
bool isLocal(); bool isLocal();
bool isGuest(); bool isGuest();
// 4J Added as we need to set this from outside sometimes // 4J Added as we need to set this from outside sometimes
void setPlayer(std::shared_ptr<ServerPlayer> player) { this->player = player; } void setPlayer(std::shared_ptr<ServerPlayer> player) {
std::shared_ptr<ServerPlayer> getPlayer() { return player; } this->player = player;
}
std::shared_ptr<ServerPlayer> getPlayer() { return player; }
// 4J Added to signal a disconnect from another thread // 4J Added to signal a disconnect from another thread
void closeOnTick() { m_bCloseOnTick = true; } void closeOnTick() { m_bCloseOnTick = true; }
// 4J Added so that we can send on textures that get received after this connection requested them // 4J Added so that we can send on textures that get received after this
void handleTextureReceived(const std::wstring &textureName); // connection requested them
void handleTextureAndGeometryReceived(const std::wstring &textureName); void handleTextureReceived(const std::wstring& textureName);
void handleTextureAndGeometryReceived(const std::wstring& textureName);
void setShowOnMaps(bool bVal); void setShowOnMaps(bool bVal);
void setWasKicked() { m_bWasKicked = true; } void setWasKicked() { m_bWasKicked = true; }
bool getWasKicked() { return m_bWasKicked; } bool getWasKicked() { return m_bWasKicked; }
// 4J Added // 4J Added
bool hasClientTickedOnce() { return m_bHasClientTickedOnce; } bool hasClientTickedOnce() { return m_bHasClientTickedOnce; }
private: private:
bool m_bCloseOnTick; bool m_bCloseOnTick;
std::vector<std::wstring> m_texturesRequested; std::vector<std::wstring> m_texturesRequested;
bool m_bWasKicked; bool m_bWasKicked;
}; };

View file

@ -1,15 +1,12 @@
#pragma once #pragma once
class PlayerInfo {
class PlayerInfo
{
public: public:
std::wstring name; std::wstring name;
int latency; int latency;
PlayerInfo(const std::wstring &name) PlayerInfo(const std::wstring& name) {
{ this->name = name;
this->name = name; latency = 0;
latency = 0; }
}
}; };

File diff suppressed because it is too large Load diff

View file

@ -15,114 +15,136 @@ class ProgressListener;
class GameType; class GameType;
class LoginPacket; class LoginPacket;
class PlayerList {
class PlayerList
{
private: private:
static const int SEND_PLAYER_INFO_INTERVAL = 20 * 10; // 4J - brought forward from 1.2.3 static const int SEND_PLAYER_INFO_INTERVAL =
// public static Logger logger = Logger.getLogger("Minecraft"); 20 * 10; // 4J - brought forward from 1.2.3
// public static Logger logger = Logger.getLogger("Minecraft");
public: public:
std::vector<std::shared_ptr<ServerPlayer> > players; std::vector<std::shared_ptr<ServerPlayer> > players;
private: private:
MinecraftServer *server; MinecraftServer* server;
unsigned int maxPlayers; unsigned int maxPlayers;
// 4J Added // 4J Added
std::vector<PlayerUID> m_bannedXuids; std::vector<PlayerUID> m_bannedXuids;
std::deque<std::uint8_t> m_smallIdsToKick; std::deque<std::uint8_t> m_smallIdsToKick;
CRITICAL_SECTION m_kickPlayersCS; CRITICAL_SECTION m_kickPlayersCS;
std::deque<std::uint8_t> m_smallIdsToClose; std::deque<std::uint8_t> m_smallIdsToClose;
CRITICAL_SECTION m_closePlayersCS; CRITICAL_SECTION m_closePlayersCS;
/* 4J - removed /* 4J - removed
Set<String> bans = new HashSet<String>(); Set<String> bans = new HashSet<String>();
Set<String> ipBans = new HashSet<String>(); Set<String> ipBans = new HashSet<String>();
Set<String> ops = new HashSet<String>(); Set<String> ops = new HashSet<String>();
Set<String> whitelist = new HashSet<String>(); Set<String> whitelist = new HashSet<String>();
File banFile, ipBanFile, opFile, whiteListFile; File banFile, ipBanFile, opFile, whiteListFile;
*/ */
PlayerIO *playerIo; PlayerIO* playerIo;
bool doWhiteList; bool doWhiteList;
GameType *overrideGameMode; GameType* overrideGameMode;
bool allowCheatsForAllPlayers; bool allowCheatsForAllPlayers;
int viewDistance; int viewDistance;
int sendAllPlayerInfoIn; int sendAllPlayerInfoIn;
// 4J Added to maintain which players in which dimensions can receive all
// packet types
std::vector<std::shared_ptr<ServerPlayer> > receiveAllPlayers[3];
// 4J Added to maintain which players in which dimensions can receive all packet types
std::vector<std::shared_ptr<ServerPlayer> > receiveAllPlayers[3];
private: private:
std::shared_ptr<ServerPlayer> findAlivePlayerOnSystem(std::shared_ptr<ServerPlayer> currentPlayer); std::shared_ptr<ServerPlayer> findAlivePlayerOnSystem(
std::shared_ptr<ServerPlayer> currentPlayer);
public: public:
void removePlayerFromReceiving(std::shared_ptr<ServerPlayer> player, bool usePlayerDimension = true, int dimension = 0); void removePlayerFromReceiving(std::shared_ptr<ServerPlayer> player,
void addPlayerToReceiving(std::shared_ptr<ServerPlayer> player); bool usePlayerDimension = true,
bool canReceiveAllPackets(std::shared_ptr<ServerPlayer> player); int dimension = 0);
void addPlayerToReceiving(std::shared_ptr<ServerPlayer> player);
bool canReceiveAllPackets(std::shared_ptr<ServerPlayer> player);
public: public:
PlayerList(MinecraftServer *server); PlayerList(MinecraftServer* server);
~PlayerList(); ~PlayerList();
void placeNewPlayer(Connection *connection, std::shared_ptr<ServerPlayer> player, std::shared_ptr<LoginPacket> packet); void placeNewPlayer(Connection* connection,
std::shared_ptr<ServerPlayer> player,
std::shared_ptr<LoginPacket> packet);
void setLevel(ServerLevelArray levels); void setLevel(ServerLevelArray levels);
void changeDimension(std::shared_ptr<ServerPlayer> player, ServerLevel *from); void changeDimension(std::shared_ptr<ServerPlayer> player,
ServerLevel* from);
int getMaxRange(); int getMaxRange();
bool load(std::shared_ptr<ServerPlayer> player); // 4J Changed return val to bool to check if new player or loaded player bool load(std::shared_ptr<ServerPlayer>
player); // 4J Changed return val to bool to check if new
// player or loaded player
protected: protected:
void save(std::shared_ptr<ServerPlayer> player); void save(std::shared_ptr<ServerPlayer> player);
public: public:
void validatePlayerSpawnPosition(std::shared_ptr<ServerPlayer> player); // 4J Added void validatePlayerSpawnPosition(
std::shared_ptr<ServerPlayer> player); // 4J Added
void add(std::shared_ptr<ServerPlayer> player); void add(std::shared_ptr<ServerPlayer> player);
void move(std::shared_ptr<ServerPlayer> player); void move(std::shared_ptr<ServerPlayer> player);
void remove(std::shared_ptr<ServerPlayer> player); void remove(std::shared_ptr<ServerPlayer> player);
std::shared_ptr<ServerPlayer> getPlayerForLogin(PendingConnection *pendingConnection, const std::wstring& userName, PlayerUID xuid, PlayerUID OnlineXuid); std::shared_ptr<ServerPlayer> getPlayerForLogin(
std::shared_ptr<ServerPlayer> respawn(std::shared_ptr<ServerPlayer> serverPlayer, int targetDimension, bool keepAllPlayerData); PendingConnection* pendingConnection, const std::wstring& userName,
void toggleDimension(std::shared_ptr<ServerPlayer> player, int targetDimension); PlayerUID xuid, PlayerUID OnlineXuid);
std::shared_ptr<ServerPlayer> respawn(
std::shared_ptr<ServerPlayer> serverPlayer, int targetDimension,
bool keepAllPlayerData);
void toggleDimension(std::shared_ptr<ServerPlayer> player,
int targetDimension);
void tick(); void tick();
bool isTrackingTile(int x, int y, int z, int dimension); // 4J added bool isTrackingTile(int x, int y, int z, int dimension); // 4J added
void prioritiseTileChanges(int x, int y, int z, int dimension); // 4J added void prioritiseTileChanges(int x, int y, int z, int dimension); // 4J added
void broadcastAll(std::shared_ptr<Packet> packet); void broadcastAll(std::shared_ptr<Packet> packet);
void broadcastAll(std::shared_ptr<Packet> packet, int dimension); void broadcastAll(std::shared_ptr<Packet> packet, int dimension);
std::wstring getPlayerNames(); std::wstring getPlayerNames();
public: public:
bool isWhiteListed(const std::wstring& name); bool isWhiteListed(const std::wstring& name);
bool isOp(const std::wstring& name); bool isOp(const std::wstring& name);
bool isOp(std::shared_ptr<ServerPlayer> player); // 4J Added bool isOp(std::shared_ptr<ServerPlayer> player); // 4J Added
std::shared_ptr<ServerPlayer> getPlayer(const std::wstring& name); std::shared_ptr<ServerPlayer> getPlayer(const std::wstring& name);
std::shared_ptr<ServerPlayer> getPlayer(PlayerUID uid); std::shared_ptr<ServerPlayer> getPlayer(PlayerUID uid);
void sendMessage(const std::wstring& name, const std::wstring& message); void sendMessage(const std::wstring& name, const std::wstring& message);
void broadcast(double x, double y, double z, double range, int dimension, std::shared_ptr<Packet> packet); void broadcast(double x, double y, double z, double range, int dimension,
void broadcast(std::shared_ptr<Player> except, double x, double y, double z, double range, int dimension, std::shared_ptr<Packet> packet); std::shared_ptr<Packet> packet);
void broadcast(std::shared_ptr<Player> except, double x, double y, double z,
double range, int dimension, std::shared_ptr<Packet> packet);
void broadcastToAllOps(const std::wstring& message); void broadcastToAllOps(const std::wstring& message);
bool sendTo(const std::wstring& name, std::shared_ptr<Packet> packet); bool sendTo(const std::wstring& name, std::shared_ptr<Packet> packet);
// 4J Added ProgressListener *progressListener param and bDeleteGuestMaps param // 4J Added ProgressListener *progressListener param and bDeleteGuestMaps
void saveAll(ProgressListener *progressListener, bool bDeleteGuestMaps = false); // param
void saveAll(ProgressListener* progressListener,
bool bDeleteGuestMaps = false);
void whiteList(const std::wstring& playerName); void whiteList(const std::wstring& playerName);
void blackList(const std::wstring& playerName); void blackList(const std::wstring& playerName);
// Set<String> getWhiteList(); / 4J removed // Set<String> getWhiteList(); / 4J removed
void reloadWhitelist(); void reloadWhitelist();
void sendLevelInfo(std::shared_ptr<ServerPlayer> player, ServerLevel *level); void sendLevelInfo(std::shared_ptr<ServerPlayer> player,
ServerLevel* level);
void sendAllPlayerInfo(std::shared_ptr<ServerPlayer> player); void sendAllPlayerInfo(std::shared_ptr<ServerPlayer> player);
int getPlayerCount(); int getPlayerCount();
int getPlayerCount(ServerLevel *level); // 4J Added int getPlayerCount(ServerLevel* level); // 4J Added
int getMaxPlayers(); int getMaxPlayers();
MinecraftServer *getServer(); MinecraftServer* getServer();
int getViewDistance(); int getViewDistance();
void setOverrideGameMode(GameType *gameMode); void setOverrideGameMode(GameType* gameMode);
private: private:
void updatePlayerGameMode(std::shared_ptr<ServerPlayer> newPlayer, std::shared_ptr<ServerPlayer> oldPlayer, Level *level); void updatePlayerGameMode(std::shared_ptr<ServerPlayer> newPlayer,
std::shared_ptr<ServerPlayer> oldPlayer,
Level* level);
public: public:
void setAllowCheatsForAllPlayers(bool allowCommands); void setAllowCheatsForAllPlayers(bool allowCommands);
// 4J Added // 4J Added
void kickPlayerByShortId(std::uint8_t networkSmallId); void kickPlayerByShortId(std::uint8_t networkSmallId);
void closePlayerConnectionBySmallId(std::uint8_t networkSmallId); void closePlayerConnectionBySmallId(std::uint8_t networkSmallId);
bool isXuidBanned(PlayerUID xuid); bool isXuidBanned(PlayerUID xuid);
// AP added for Vita so the range can be increased once the level starts // AP added for Vita so the range can be increased once the level starts
void setViewDistance(int newViewDistance); void setViewDistance(int newViewDistance);
}; };

File diff suppressed because it is too large Load diff

View file

@ -8,94 +8,99 @@
class ServerLevel; class ServerLevel;
class ServerChunkCache : public ChunkSource class ServerChunkCache : public ChunkSource {
{ private:
// std::unordered_set<int,IntKeyHash, IntKeyEq> toDrop;
private:
LevelChunk* emptyChunk;
ChunkSource* source;
ChunkStorage* storage;
public:
bool autoCreate;
private: private:
// std::unordered_set<int,IntKeyHash, IntKeyEq> toDrop; LevelChunk** cache;
private: std::vector<LevelChunk*> m_loadedChunkList;
LevelChunk *emptyChunk; ServerLevel* level;
ChunkSource *source;
ChunkStorage *storage;
public:
bool autoCreate;
private:
LevelChunk **cache;
std::vector<LevelChunk *> m_loadedChunkList;
ServerLevel *level;
#ifdef _LARGE_WORLDS #ifdef _LARGE_WORLDS
std::deque<LevelChunk *> m_toDrop; std::deque<LevelChunk*> m_toDrop;
LevelChunk **m_unloadedCache; LevelChunk** m_unloadedCache;
#endif #endif
// 4J - added for multithreaded support // 4J - added for multithreaded support
CRITICAL_SECTION m_csLoadCreate; CRITICAL_SECTION m_csLoadCreate;
// 4J - size of cache is defined by size of one side - must be even // 4J - size of cache is defined by size of one side - must be even
int XZSIZE; int XZSIZE;
int XZOFFSET; int XZOFFSET;
public: public:
ServerChunkCache(ServerLevel *level, ChunkStorage *storage, ChunkSource *source); ServerChunkCache(ServerLevel* level, ChunkStorage* storage,
virtual ~ServerChunkCache(); ChunkSource* source);
virtual ~ServerChunkCache();
virtual bool hasChunk(int x, int z); virtual bool hasChunk(int x, int z);
std::vector<LevelChunk *> *getLoadedChunkList(); std::vector<LevelChunk*>* getLoadedChunkList();
void drop(int x, int z); void drop(int x, int z);
void dropAll(); void dropAll();
virtual LevelChunk *create(int x, int z); virtual LevelChunk* create(int x, int z);
LevelChunk *create(int x, int z, bool asyncPostProcess ); // 4J added LevelChunk* create(int x, int z, bool asyncPostProcess); // 4J added
virtual LevelChunk *getChunk(int x, int z); virtual LevelChunk* getChunk(int x, int z);
#ifdef _LARGE_WORLDS #ifdef _LARGE_WORLDS
LevelChunk *getChunkLoadedOrUnloaded(int x, int z); // 4J added LevelChunk* getChunkLoadedOrUnloaded(int x, int z); // 4J added
#endif #endif
virtual LevelChunk **getCache() { return cache; } // 4J added virtual LevelChunk** getCache() { return cache; } // 4J added
// 4J-JEV Added; Remove chunk from the toDrop queue. // 4J-JEV Added; Remove chunk from the toDrop queue.
#ifdef _LARGE_WORLDS #ifdef _LARGE_WORLDS
void dontDrop(int x, int z); void dontDrop(int x, int z);
#endif #endif
private: private:
LevelChunk *load(int x, int z); LevelChunk* load(int x, int z);
void saveEntities(LevelChunk *levelChunk); void saveEntities(LevelChunk* levelChunk);
void save(LevelChunk *levelChunk); void save(LevelChunk* levelChunk);
void updatePostProcessFlag(short flag, int x, int z, int xo, int zo, LevelChunk *lc); // 4J added void updatePostProcessFlag(short flag, int x, int z, int xo, int zo,
void updatePostProcessFlags(int x, int z); // 4J added LevelChunk* lc); // 4J added
void flagPostProcessComplete(short flag, int x, int z); // 4J added void updatePostProcessFlags(int x, int z); // 4J added
void flagPostProcessComplete(short flag, int x, int z); // 4J added
public: public:
virtual void postProcess(ChunkSource *parent, int x, int z); virtual void postProcess(ChunkSource* parent, int x, int z);
private: private:
#ifdef _LARGE_WORLDS #ifdef _LARGE_WORLDS
static const int MAX_SAVES = 20; static const int MAX_SAVES = 20;
#else #else
// 4J Stu - Was 24, but lowering it drastically so that we can trickle save chunks // 4J Stu - Was 24, but lowering it drastically so that we can trickle save
static const int MAX_SAVES = 1; // chunks
static const int MAX_SAVES = 1;
#endif #endif
public: public:
virtual bool saveAllEntities(); virtual bool saveAllEntities();
virtual bool save(bool force, ProgressListener *progressListener); virtual bool save(bool force, ProgressListener* progressListener);
virtual bool tick(); virtual bool tick();
virtual bool shouldSave(); virtual bool shouldSave();
virtual std::wstring gatherStats(); virtual std::wstring gatherStats();
virtual std::vector<Biome::MobSpawnerData *> *getMobsAt(MobCategory *mobCategory, int x, int y, int z); virtual std::vector<Biome::MobSpawnerData*>* getMobsAt(
virtual TilePos *findNearestMapFeature(Level *level, const std::wstring &featureName, int x, int y, int z); MobCategory* mobCategory, int x, int y, int z);
virtual TilePos* findNearestMapFeature(Level* level,
const std::wstring& featureName,
int x, int y, int z);
private: private:
typedef struct _SaveThreadData typedef struct _SaveThreadData {
{ ServerChunkCache* cache;
ServerChunkCache *cache; LevelChunk* chunkToSave;
LevelChunk *chunkToSave; bool saveEntities;
bool saveEntities; bool useSharedThreadStorage;
bool useSharedThreadStorage; C4JThread::Event* notificationEvent;
C4JThread::Event *notificationEvent; C4JThread::Event* wakeEvent; // This is a handle to the one fired by
C4JThread::Event *wakeEvent; // This is a handle to the one fired by the producer thread // the producer thread
} SaveThreadData; } SaveThreadData;
public: public:
static int runSaveThreadProc(void *lpParam); static int runSaveThreadProc(void* lpParam);
}; };

View file

@ -7,69 +7,72 @@
#include "../Commands/TeleportCommand.h" #include "../Commands/TeleportCommand.h"
#include "ServerCommandDispatcher.h" #include "ServerCommandDispatcher.h"
ServerCommandDispatcher::ServerCommandDispatcher() ServerCommandDispatcher::ServerCommandDispatcher() {
{ addCommand(new TimeCommand());
addCommand(new TimeCommand()); addCommand(new GameModeCommand());
addCommand(new GameModeCommand()); addCommand(new DefaultGameModeCommand());
addCommand(new DefaultGameModeCommand()); addCommand(new KillCommand());
addCommand(new KillCommand()); addCommand(new ToggleDownfallCommand());
addCommand(new ToggleDownfallCommand()); addCommand(new ExperienceCommand());
addCommand(new ExperienceCommand()); addCommand(new TeleportCommand());
addCommand(new TeleportCommand()); addCommand(new GiveItemCommand());
addCommand(new GiveItemCommand()); addCommand(new EnchantItemCommand());
addCommand(new EnchantItemCommand()); // addCommand(new EmoteCommand());
//addCommand(new EmoteCommand()); // addCommand(new ShowSeedCommand());
//addCommand(new ShowSeedCommand()); // addCommand(new HelpCommand());
//addCommand(new HelpCommand()); // addCommand(new DebugCommand());
//addCommand(new DebugCommand()); // addCommand(new MessageCommand());
//addCommand(new MessageCommand());
//if (MinecraftServer::getInstance()->isDedicatedServer()) // if (MinecraftServer::getInstance()->isDedicatedServer())
//{ //{
// addCommand(new OpCommand()); // addCommand(new OpCommand());
// addCommand(new DeOpCommand()); // addCommand(new DeOpCommand());
// addCommand(new StopCommand()); // addCommand(new StopCommand());
// addCommand(new SaveAllCommand()); // addCommand(new SaveAllCommand());
// addCommand(new SaveOffCommand()); // addCommand(new SaveOffCommand());
// addCommand(new SaveOnCommand()); // addCommand(new SaveOnCommand());
// addCommand(new BanIpCommand()); // addCommand(new BanIpCommand());
// addCommand(new PardonIpCommand()); // addCommand(new PardonIpCommand());
// addCommand(new BanPlayerCommand()); // addCommand(new BanPlayerCommand());
// addCommand(new ListBansCommand()); // addCommand(new ListBansCommand());
// addCommand(new PardonPlayerCommand()); // addCommand(new PardonPlayerCommand());
// addCommand(new KickCommand()); // addCommand(new KickCommand());
// addCommand(new ListPlayersCommand()); // addCommand(new ListPlayersCommand());
// addCommand(new BroadcastCommand()); // addCommand(new BroadcastCommand());
// addCommand(new WhitelistCommand()); // addCommand(new WhitelistCommand());
//} // }
//else // else
//{ //{
// addCommand(new PublishLocalServerCommand()); // addCommand(new PublishLocalServerCommand());
//} // }
// addCommand(new ServerTempDebugCommand()); // addCommand(new ServerTempDebugCommand());
Command::setLogger(this); Command::setLogger(this);
} }
void ServerCommandDispatcher::logAdminCommand(std::shared_ptr<CommandSender> source, int type, ChatPacket::EChatPacketMessage messageType, const std::wstring& message, int customData, const std::wstring& additionalMessage) void ServerCommandDispatcher::logAdminCommand(
{ std::shared_ptr<CommandSender> source, int type,
PlayerList *playerList = MinecraftServer::getInstance()->getPlayers(); ChatPacket::EChatPacketMessage messageType, const std::wstring& message,
//for (Player player : MinecraftServer.getInstance().getPlayers().players) int customData, const std::wstring& additionalMessage) {
for(AUTO_VAR(it, playerList->players.begin()); it != playerList->players.end(); ++it) PlayerList* playerList = MinecraftServer::getInstance()->getPlayers();
{ // for (Player player : MinecraftServer.getInstance().getPlayers().players)
std::shared_ptr<ServerPlayer> player = *it; for (AUTO_VAR(it, playerList->players.begin());
if (player != source && playerList->isOp(player)) it != playerList->players.end(); ++it) {
{ std::shared_ptr<ServerPlayer> player = *it;
// TODO: Change chat packet to be able to send more bits of data if (player != source && playerList->isOp(player)) {
// 4J Stu - Take this out until we can add the name of the player performing the action. Also if the target is a mod then maybe don't need the message? // TODO: Change chat packet to be able to send more bits of data
//player->sendMessage(message, messageType, customData, additionalMessage); // 4J Stu - Take this out until we can add the name of the player
//player->sendMessage("\u00A77\u00A7o[" + source.getName() + ": " + player.localize(message, args) + "]"); // performing the action. Also if the target is a mod then maybe
} // don't need the message?
} // player->sendMessage(message, messageType, customData,
// additionalMessage); player->sendMessage("\u00A77\u00A7o[" +
// source.getName() + ": " + player.localize(message, args) + "]");
}
}
if ((type & LOGTYPE_DONT_SHOW_TO_SELF) != LOGTYPE_DONT_SHOW_TO_SELF) if ((type & LOGTYPE_DONT_SHOW_TO_SELF) != LOGTYPE_DONT_SHOW_TO_SELF) {
{ source->sendMessage(message, messageType, customData,
source->sendMessage(message, messageType, customData, additionalMessage); additionalMessage);
} }
} }

View file

@ -3,9 +3,12 @@
#include "../../Minecraft.World/Commands/CommandDispatcher.h" #include "../../Minecraft.World/Commands/CommandDispatcher.h"
#include "../../Minecraft.World/Commands/AdminLogCommand.h" #include "../../Minecraft.World/Commands/AdminLogCommand.h"
class ServerCommandDispatcher : public CommandDispatcher, public AdminLogCommand class ServerCommandDispatcher : public CommandDispatcher,
{ public AdminLogCommand {
public: public:
ServerCommandDispatcher(); ServerCommandDispatcher();
void logAdminCommand(std::shared_ptr<CommandSender> source, int type, ChatPacket::EChatPacketMessage messageType, const std::wstring& message = L"", int customData = -1, const std::wstring& additionalMessage = L""); void logAdminCommand(std::shared_ptr<CommandSender> source, int type,
ChatPacket::EChatPacketMessage messageType,
const std::wstring& message = L"", int customData = -1,
const std::wstring& additionalMessage = L"");
}; };

View file

@ -9,196 +9,187 @@
#include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.h"
#include "../Level/MultiPlayerLevel.h" #include "../Level/MultiPlayerLevel.h"
ServerConnection::ServerConnection(MinecraftServer *server) ServerConnection::ServerConnection(MinecraftServer* server) {
{ // 4J - added initialiser
// 4J - added initialiser connectionCounter = 0;
connectionCounter = 0; InitializeCriticalSection(&pending_cs);
InitializeCriticalSection(&pending_cs);
this->server = server; this->server = server;
} }
ServerConnection::~ServerConnection() ServerConnection::~ServerConnection() { DeleteCriticalSection(&pending_cs); }
{
DeleteCriticalSection(&pending_cs); // 4J - added to handle incoming connections, to replace thread that original
// used to have
void ServerConnection::NewIncomingSocket(Socket* socket) {
std::shared_ptr<PendingConnection> unconnectedClient =
std::shared_ptr<PendingConnection>(new PendingConnection(
server, socket,
L"Connection #" + _toString<int>(connectionCounter++)));
handleConnection(unconnectedClient);
} }
// 4J - added to handle incoming connections, to replace thread that original used to have void ServerConnection::addPlayerConnection(
void ServerConnection::NewIncomingSocket(Socket *socket) std::shared_ptr<PlayerConnection> uc) {
{ players.push_back(uc);
std::shared_ptr<PendingConnection> unconnectedClient = std::shared_ptr<PendingConnection>(new PendingConnection(server, socket, L"Connection #" + _toString<int>(connectionCounter++)));
handleConnection(unconnectedClient);
} }
void ServerConnection::addPlayerConnection(std::shared_ptr<PlayerConnection> uc) void ServerConnection::handleConnection(std::shared_ptr<PendingConnection> uc) {
{ EnterCriticalSection(&pending_cs);
players.push_back(uc); pending.push_back(uc);
LeaveCriticalSection(&pending_cs);
} }
void ServerConnection::handleConnection(std::shared_ptr<PendingConnection> uc) void ServerConnection::stop() {
{ EnterCriticalSection(&pending_cs);
EnterCriticalSection(&pending_cs); for (unsigned int i = 0; i < pending.size(); i++) {
pending.push_back(uc);
LeaveCriticalSection(&pending_cs);
}
void ServerConnection::stop()
{
EnterCriticalSection(&pending_cs);
for (unsigned int i = 0; i < pending.size(); i++)
{
std::shared_ptr<PendingConnection> uc = pending[i]; std::shared_ptr<PendingConnection> uc = pending[i];
uc->connection->close(DisconnectPacket::eDisconnect_Closed); uc->connection->close(DisconnectPacket::eDisconnect_Closed);
} }
LeaveCriticalSection(&pending_cs); LeaveCriticalSection(&pending_cs);
for (unsigned int i = 0; i < players.size(); i++) for (unsigned int i = 0; i < players.size(); i++) {
{
std::shared_ptr<PlayerConnection> player = players[i]; std::shared_ptr<PlayerConnection> player = players[i];
player->connection->close(DisconnectPacket::eDisconnect_Closed); player->connection->close(DisconnectPacket::eDisconnect_Closed);
} }
} }
void ServerConnection::tick() void ServerConnection::tick() {
{ {
{ // MGH - changed this so that the the CS lock doesn't cover the tick
// MGH - changed this so that the the CS lock doesn't cover the tick (was causing a lockup when 2 players tried to join) // (was causing a lockup when 2 players tried to join)
EnterCriticalSection(&pending_cs); EnterCriticalSection(&pending_cs);
std::vector< std::shared_ptr<PendingConnection> > tempPending = pending; std::vector<std::shared_ptr<PendingConnection> > tempPending = pending;
LeaveCriticalSection(&pending_cs); LeaveCriticalSection(&pending_cs);
for (unsigned int i = 0; i < tempPending.size(); i++) for (unsigned int i = 0; i < tempPending.size(); i++) {
{ std::shared_ptr<PendingConnection> uc = tempPending[i];
std::shared_ptr<PendingConnection> uc = tempPending[i]; // try { // 4J - removed try/catch
// try { // 4J - removed try/catch uc->tick();
uc->tick(); // } catch (Exception e) {
// } catch (Exception e) { // uc.disconnect("Internal server error");
// uc.disconnect("Internal server error"); // logger.log(Level.WARNING, "Failed to handle packet: "
// logger.log(Level.WARNING, "Failed to handle packet: " + e, e); // + e, e);
// } // }
if(uc->connection != NULL) uc->connection->flush(); if (uc->connection != NULL) uc->connection->flush();
} }
} }
// now remove from the pending list // now remove from the pending list
EnterCriticalSection(&pending_cs); EnterCriticalSection(&pending_cs);
for (unsigned int i = 0; i < pending.size(); i++) for (unsigned int i = 0; i < pending.size(); i++)
if (pending[i]->done) if (pending[i]->done) {
{ pending.erase(pending.begin() + i);
pending.erase(pending.begin()+i); i--;
i--; }
} LeaveCriticalSection(&pending_cs);
LeaveCriticalSection(&pending_cs);
for (unsigned int i = 0; i < players.size(); i++) for (unsigned int i = 0; i < players.size(); i++) {
{
std::shared_ptr<PlayerConnection> player = players[i]; std::shared_ptr<PlayerConnection> player = players[i];
std::shared_ptr<ServerPlayer> serverPlayer = player->getPlayer(); std::shared_ptr<ServerPlayer> serverPlayer = player->getPlayer();
if( serverPlayer ) if (serverPlayer) {
{ serverPlayer->doChunkSendingTick(false);
serverPlayer->doChunkSendingTick(false); }
} // try { // 4J - removed try/catch
// try { // 4J - removed try/catch player->tick();
player->tick(); // } catch (Exception e) {
// } catch (Exception e) { // logger.log(Level.WARNING, "Failed to handle packet: " + e,
// logger.log(Level.WARNING, "Failed to handle packet: " + e, e); // e); player.disconnect("Internal server error");
// player.disconnect("Internal server error"); // }
// } if (player->done) {
if (player->done) players.erase(players.begin() + i);
{ i--;
players.erase(players.begin()+i);
i--;
} }
player->connection->flush(); player->connection->flush();
} }
} }
bool ServerConnection::addPendingTextureRequest(const std::wstring &textureName) bool ServerConnection::addPendingTextureRequest(
{ const std::wstring& textureName) {
AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); AUTO_VAR(it, find(m_pendingTextureRequests.begin(),
if( it == m_pendingTextureRequests.end() ) m_pendingTextureRequests.end(), textureName));
{ if (it == m_pendingTextureRequests.end()) {
m_pendingTextureRequests.push_back(textureName); m_pendingTextureRequests.push_back(textureName);
return true; return true;
} }
// 4J Stu - We want to request this texture from everyone, if we have a duplicate it's most likely because the first person we asked for it didn't have it // 4J Stu - We want to request this texture from everyone, if we have a
// eg They selected a skin then deleted the skin pack. The side effect of this change is that in certain cases we can send a few more requests, and receive // duplicate it's most likely because the first person we asked for it
// a few more responses if people join with the same skin in a short space of time // didn't have it eg They selected a skin then deleted the skin pack. The
return true; // side effect of this change is that in certain cases we can send a few
// more requests, and receive a few more responses if people join with the
// same skin in a short space of time
return true;
} }
void ServerConnection::handleTextureReceived(const std::wstring &textureName) void ServerConnection::handleTextureReceived(const std::wstring& textureName) {
{ AUTO_VAR(it, find(m_pendingTextureRequests.begin(),
AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); m_pendingTextureRequests.end(), textureName));
if( it != m_pendingTextureRequests.end() ) if (it != m_pendingTextureRequests.end()) {
{ m_pendingTextureRequests.erase(it);
m_pendingTextureRequests.erase(it); }
} for (unsigned int i = 0; i < players.size(); i++) {
for (unsigned int i = 0; i < players.size(); i++)
{
std::shared_ptr<PlayerConnection> player = players[i]; std::shared_ptr<PlayerConnection> player = players[i];
if (!player->done) if (!player->done) {
{ player->handleTextureReceived(textureName);
player->handleTextureReceived(textureName);
} }
} }
} }
void ServerConnection::handleTextureAndGeometryReceived(const std::wstring &textureName) void ServerConnection::handleTextureAndGeometryReceived(
{ const std::wstring& textureName) {
AUTO_VAR(it, find( m_pendingTextureRequests.begin(), m_pendingTextureRequests.end(), textureName)); AUTO_VAR(it, find(m_pendingTextureRequests.begin(),
if( it != m_pendingTextureRequests.end() ) m_pendingTextureRequests.end(), textureName));
{ if (it != m_pendingTextureRequests.end()) {
m_pendingTextureRequests.erase(it); m_pendingTextureRequests.erase(it);
} }
for (unsigned int i = 0; i < players.size(); i++) for (unsigned int i = 0; i < players.size(); i++) {
{ std::shared_ptr<PlayerConnection> player = players[i];
std::shared_ptr<PlayerConnection> player = players[i]; if (!player->done) {
if (!player->done) player->handleTextureAndGeometryReceived(textureName);
{ }
player->handleTextureAndGeometryReceived(textureName); }
}
}
} }
void ServerConnection::handleServerSettingsChanged(std::shared_ptr<ServerSettingsChangedPacket> packet) void ServerConnection::handleServerSettingsChanged(
{ std::shared_ptr<ServerSettingsChangedPacket> packet) {
Minecraft *pMinecraft = Minecraft::GetInstance(); Minecraft* pMinecraft = Minecraft::GetInstance();
if(packet->action==ServerSettingsChangedPacket::HOST_DIFFICULTY) if (packet->action == ServerSettingsChangedPacket::HOST_DIFFICULTY) {
{ for (unsigned int i = 0; i < pMinecraft->levels.length; ++i) {
for(unsigned int i = 0; i < pMinecraft->levels.length; ++i) if (pMinecraft->levels[i] != NULL) {
{ app.DebugPrintf(
if( pMinecraft->levels[i] != NULL ) "ClientConnection::handleServerSettingsChanged - "
{ "Difficulty = %d",
app.DebugPrintf("ClientConnection::handleServerSettingsChanged - Difficulty = %d",packet->data); packet->data);
pMinecraft->levels[i]->difficulty = packet->data; pMinecraft->levels[i]->difficulty = packet->data;
} }
} }
} }
// else if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS)// options // else
// { // if(packet->action==ServerSettingsChangedPacket::HOST_IN_GAME_SETTINGS)//
// app.SetGameHostOption(eGameHostOption_All,packet->m_serverSettings) // options
// } // {
// else // app.SetGameHostOption(eGameHostOption_All,packet->m_serverSettings)
// { // }
// unsigned char ucData=(unsigned char)packet->data; // else
// if(ucData&1) // {
// { // unsigned char ucData=(unsigned char)packet->data;
// // hide gamertags // if(ucData&1)
// pMinecraft->options->SetGamertagSetting(true); // {
// } // // hide gamertags
// else // pMinecraft->options->SetGamertagSetting(true);
// { // }
// pMinecraft->options->SetGamertagSetting(false); // else
// } // {
// // pMinecraft->options->SetGamertagSetting(false);
// for (unsigned int i = 0; i < players.size(); i++) // }
// { //
// std::shared_ptr<PlayerConnection> playerconnection = players[i]; // for (unsigned int i = 0; i < players.size(); i++)
// playerconnection->setShowOnMaps(pMinecraft->options->GetGamertagSetting()); // {
// } // std::shared_ptr<PlayerConnection> playerconnection =
// } // players[i];
// playerconnection->setShowOnMaps(pMinecraft->options->GetGamertagSetting());
// }
// }
} }

View file

@ -5,45 +5,52 @@ class MinecraftServer;
class Socket; class Socket;
class ServerSettingsChangedPacket; class ServerSettingsChangedPacket;
class ServerConnection {
// public static Logger logger = Logger.getLogger("Minecraft");
class ServerConnection
{
// public static Logger logger = Logger.getLogger("Minecraft");
private: private:
// ServerSocket serverSocket; // ServerSocket serverSocket;
// private Thread listenThread; // private Thread listenThread;
public: public:
volatile bool running; volatile bool running;
private: private:
int connectionCounter; int connectionCounter;
private: private:
CRITICAL_SECTION pending_cs; // 4J added CRITICAL_SECTION pending_cs; // 4J added
std::vector< std::shared_ptr<PendingConnection> > pending; std::vector<std::shared_ptr<PendingConnection> > pending;
std::vector< std::shared_ptr<PlayerConnection> > players; std::vector<std::shared_ptr<PlayerConnection> > players;
// 4J - When the server requests a texture, it should add it to here while we are waiting for it // 4J - When the server requests a texture, it should add it to here while
std::vector<std::wstring> m_pendingTextureRequests; // we are waiting for it
public: std::vector<std::wstring> m_pendingTextureRequests;
MinecraftServer *server;
public: public:
ServerConnection(MinecraftServer *server); // 4J - removed params InetAddress address, int port); MinecraftServer* server;
~ServerConnection();
void NewIncomingSocket(Socket *socket); // 4J - added
void removeSpamProtection(Socket *socket) { }// 4J Stu - Not implemented as not required public:
ServerConnection(
MinecraftServer*
server); // 4J - removed params InetAddress address, int port);
~ServerConnection();
void NewIncomingSocket(Socket* socket); // 4J - added
void removeSpamProtection(Socket* socket) {
} // 4J Stu - Not implemented as not required
void addPlayerConnection(std::shared_ptr<PlayerConnection> uc); void addPlayerConnection(std::shared_ptr<PlayerConnection> uc);
private: private:
void handleConnection(std::shared_ptr<PendingConnection> uc); void handleConnection(std::shared_ptr<PendingConnection> uc);
public: public:
void stop(); void stop();
void tick(); void tick();
// 4J Added // 4J Added
bool addPendingTextureRequest(const std::wstring &textureName); bool addPendingTextureRequest(const std::wstring& textureName);
void handleTextureReceived(const std::wstring &textureName); void handleTextureReceived(const std::wstring& textureName);
void handleTextureAndGeometryReceived(const std::wstring &textureName); void handleTextureAndGeometryReceived(const std::wstring& textureName);
void handleServerSettingsChanged(std::shared_ptr<ServerSettingsChangedPacket> packet); void handleServerSettingsChanged(
std::shared_ptr<ServerSettingsChangedPacket> packet);
}; };

View file

@ -1,29 +1,29 @@
#pragma once #pragma once
class ServerInterface {
class ServerInterface virtual int getConfigInt(const std::wstring& name, int defaultValue) = 0;
{ virtual std::wstring getConfigString(const std::wstring& name,
virtual int getConfigInt(const std::wstring &name, int defaultValue) = 0; const std::wstring& defaultValue) = 0;
virtual std::wstring getConfigString(const std::wstring &name, const std::wstring &defaultValue) = 0; virtual bool getConfigBoolean(const std::wstring& name,
virtual bool getConfigBoolean(const std::wstring &name, bool defaultValue) = 0; bool defaultValue) = 0;
virtual void setProperty(std::wstring &propertyName, void *value) = 0; virtual void setProperty(std::wstring& propertyName, void* value) = 0;
virtual void configSave() = 0; virtual void configSave() = 0;
virtual std::wstring getConfigPath() = 0; virtual std::wstring getConfigPath() = 0;
virtual std::wstring getServerIp() = 0; virtual std::wstring getServerIp() = 0;
virtual int getServerPort() = 0; virtual int getServerPort() = 0;
virtual std::wstring getServerName() = 0; virtual std::wstring getServerName() = 0;
virtual std::wstring getServerVersion() = 0; virtual std::wstring getServerVersion() = 0;
virtual int getPlayerCount() = 0; virtual int getPlayerCount() = 0;
virtual int getMaxPlayers() = 0; virtual int getMaxPlayers() = 0;
virtual std::wstring[] getPlayerNames() = 0; virtual std::wstring[] getPlayerNames() = 0;
virtual std::wstring getWorldName() = 0; virtual std::wstring getWorldName() = 0;
virtual std::wstring getPluginNames() = 0; virtual std::wstring getPluginNames() = 0;
virtual void disablePlugin() = 0; virtual void disablePlugin() = 0;
virtual std::wstring runCommand(const std::wstring &command) = 0; virtual std::wstring runCommand(const std::wstring& command) = 0;
virtual bool isDebugging() = 0; virtual bool isDebugging() = 0;
// Logging // Logging
virtual void info(const std::wstring &string) = 0; virtual void info(const std::wstring& string) = 0;
virtual void warn(const std::wstring &string) = 0; virtual void warn(const std::wstring& string) = 0;
virtual void error(const std::wstring &string) = 0; virtual void error(const std::wstring& string) = 0;
virtual void debug(const std::wstring &string) = 0; virtual void debug(const std::wstring& string) = 0;
}; };

View file

@ -22,16 +22,15 @@
#define false 0 #define false 0
// Iggy GDraw support functions - normally in the Iggy library, stubbed here // Iggy GDraw support functions - normally in the Iggy library, stubbed here
void * IggyGDrawMallocAnnotated(SINTa size, const char *file, int line) { void* IggyGDrawMallocAnnotated(SINTa size, const char* file, int line) {
(void)file; (void)line; (void)file;
(void)line;
return malloc((size_t)size); return malloc((size_t)size);
} }
void IggyGDrawFree(void *ptr) { void IggyGDrawFree(void* ptr) { free(ptr); }
free(ptr);
}
void IggyGDrawSendWarning(Iggy *f, char const *message, ...) { void IggyGDrawSendWarning(Iggy* f, char const* message, ...) {
(void)f; (void)f;
va_list args; va_list args;
va_start(args, message); va_start(args, message);
@ -41,8 +40,9 @@ void IggyGDrawSendWarning(Iggy *f, char const *message, ...) {
va_end(args); va_end(args);
} }
void IggyDiscardVertexBufferCallback(void *owner, void *buf) { void IggyDiscardVertexBufferCallback(void* owner, void* buf) {
(void)owner; (void)buf; (void)owner;
(void)buf;
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -55,61 +55,67 @@ void IggyDiscardVertexBufferCallback(void *owner, void *buf) {
// The shared code calls them by name and the real functions are used directly. // The shared code calls them by name and the real functions are used directly.
// //
#define GDRAW_GL_EXTENSION_LIST \ #define GDRAW_GL_EXTENSION_LIST \
/* identifier import procname */ \ /* identifier import procname */ \
/* GL_ARB_vertex_buffer_object */ \ /* GL_ARB_vertex_buffer_object */ \
GLE(GenBuffers, "GenBuffersARB", GENBUFFERSARB) \ GLE(GenBuffers, "GenBuffersARB", GENBUFFERSARB) \
GLE(DeleteBuffers, "DeleteBuffersARB", DELETEBUFFERSARB) \ GLE(DeleteBuffers, "DeleteBuffersARB", DELETEBUFFERSARB) \
GLE(BindBuffer, "BindBufferARB", BINDBUFFERARB) \ GLE(BindBuffer, "BindBufferARB", BINDBUFFERARB) \
GLE(BufferData, "BufferDataARB", BUFFERDATAARB) \ GLE(BufferData, "BufferDataARB", BUFFERDATAARB) \
GLE(MapBuffer, "MapBufferARB", MAPBUFFERARB) \ GLE(MapBuffer, "MapBufferARB", MAPBUFFERARB) \
GLE(UnmapBuffer, "UnmapBufferARB", UNMAPBUFFERARB) \ GLE(UnmapBuffer, "UnmapBufferARB", UNMAPBUFFERARB) \
GLE(VertexAttribPointer, "VertexAttribPointerARB", VERTEXATTRIBPOINTERARB) \ GLE(VertexAttribPointer, "VertexAttribPointerARB", VERTEXATTRIBPOINTERARB) \
GLE(EnableVertexAttribArray, "EnableVertexAttribArrayARB", ENABLEVERTEXATTRIBARRAYARB) \ GLE(EnableVertexAttribArray, "EnableVertexAttribArrayARB", \
GLE(DisableVertexAttribArray, "DisableVertexAttribArrayARB", DISABLEVERTEXATTRIBARRAYARB) \ ENABLEVERTEXATTRIBARRAYARB) \
/* GL_ARB_shader_objects */ \ GLE(DisableVertexAttribArray, "DisableVertexAttribArrayARB", \
GLE(CreateShader, "CreateShaderObjectARB", CREATESHADEROBJECTARB) \ DISABLEVERTEXATTRIBARRAYARB) \
GLE(DeleteShader, "DeleteObjectARB", DELETEOBJECTARB) \ /* GL_ARB_shader_objects */ \
GLE(ShaderSource, "ShaderSourceARB", SHADERSOURCEARB) \ GLE(CreateShader, "CreateShaderObjectARB", CREATESHADEROBJECTARB) \
GLE(CompileShader, "CompileShaderARB", COMPILESHADERARB) \ GLE(DeleteShader, "DeleteObjectARB", DELETEOBJECTARB) \
GLE(GetShaderiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ GLE(ShaderSource, "ShaderSourceARB", SHADERSOURCEARB) \
GLE(GetShaderInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ GLE(CompileShader, "CompileShaderARB", COMPILESHADERARB) \
GLE(CreateProgram, "CreateProgramObjectARB", CREATEPROGRAMOBJECTARB) \ GLE(GetShaderiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \
GLE(DeleteProgram, "DeleteObjectARB", DELETEOBJECTARB) \ GLE(GetShaderInfoLog, "GetInfoLogARB", GETINFOLOGARB) \
GLE(AttachShader, "AttachObjectARB", ATTACHOBJECTARB) \ GLE(CreateProgram, "CreateProgramObjectARB", CREATEPROGRAMOBJECTARB) \
GLE(LinkProgram, "LinkProgramARB", LINKPROGRAMARB) \ GLE(DeleteProgram, "DeleteObjectARB", DELETEOBJECTARB) \
GLE(GetUniformLocation, "GetUniformLocationARB", GETUNIFORMLOCATIONARB) \ GLE(AttachShader, "AttachObjectARB", ATTACHOBJECTARB) \
GLE(UseProgram, "UseProgramObjectARB", USEPROGRAMOBJECTARB) \ GLE(LinkProgram, "LinkProgramARB", LINKPROGRAMARB) \
GLE(GetProgramiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \ GLE(GetUniformLocation, "GetUniformLocationARB", GETUNIFORMLOCATIONARB) \
GLE(GetProgramInfoLog, "GetInfoLogARB", GETINFOLOGARB) \ GLE(UseProgram, "UseProgramObjectARB", USEPROGRAMOBJECTARB) \
GLE(Uniform1i, "Uniform1iARB", UNIFORM1IARB) \ GLE(GetProgramiv, "GetObjectParameterivARB", GETOBJECTPARAMETERIVARB) \
GLE(Uniform4f, "Uniform4fARB", UNIFORM4FARB) \ GLE(GetProgramInfoLog, "GetInfoLogARB", GETINFOLOGARB) \
GLE(Uniform4fv, "Uniform4fvARB", UNIFORM4FVARB) \ GLE(Uniform1i, "Uniform1iARB", UNIFORM1IARB) \
/* GL_ARB_vertex_shader */ \ GLE(Uniform4f, "Uniform4fARB", UNIFORM4FARB) \
GLE(BindAttribLocation, "BindAttribLocationARB", BINDATTRIBLOCATIONARB) \ GLE(Uniform4fv, "Uniform4fvARB", UNIFORM4FVARB) \
/* Missing from WGL but needed by shared code */ \ /* GL_ARB_vertex_shader */ \
GLE(Uniform1f, "Uniform1fARB", UNIFORM1FARB) \ GLE(BindAttribLocation, "BindAttribLocationARB", BINDATTRIBLOCATIONARB) \
/* GL_EXT_framebuffer_object */ \ /* Missing from WGL but needed by shared code */ \
GLE(GenRenderbuffers, "GenRenderbuffersEXT", GENRENDERBUFFERSEXT) \ GLE(Uniform1f, "Uniform1fARB", UNIFORM1FARB) \
GLE(DeleteRenderbuffers, "DeleteRenderbuffersEXT", DELETERENDERBUFFERSEXT) \ /* GL_EXT_framebuffer_object */ \
GLE(BindRenderbuffer, "BindRenderbufferEXT", BINDRENDERBUFFEREXT) \ GLE(GenRenderbuffers, "GenRenderbuffersEXT", GENRENDERBUFFERSEXT) \
GLE(RenderbufferStorage, "RenderbufferStorageEXT", RENDERBUFFERSTORAGEEXT) \ GLE(DeleteRenderbuffers, "DeleteRenderbuffersEXT", DELETERENDERBUFFERSEXT) \
GLE(GenFramebuffers, "GenFramebuffersEXT", GENFRAMEBUFFERSEXT) \ GLE(BindRenderbuffer, "BindRenderbufferEXT", BINDRENDERBUFFEREXT) \
GLE(DeleteFramebuffers, "DeleteFramebuffersEXT", DELETEFRAMEBUFFERSEXT) \ GLE(RenderbufferStorage, "RenderbufferStorageEXT", RENDERBUFFERSTORAGEEXT) \
GLE(BindFramebuffer, "BindFramebufferEXT", BINDFRAMEBUFFEREXT) \ GLE(GenFramebuffers, "GenFramebuffersEXT", GENFRAMEBUFFERSEXT) \
GLE(CheckFramebufferStatus, "CheckFramebufferStatusEXT", CHECKFRAMEBUFFERSTATUSEXT) \ GLE(DeleteFramebuffers, "DeleteFramebuffersEXT", DELETEFRAMEBUFFERSEXT) \
GLE(FramebufferRenderbuffer, "FramebufferRenderbufferEXT", FRAMEBUFFERRENDERBUFFEREXT) \ GLE(BindFramebuffer, "BindFramebufferEXT", BINDFRAMEBUFFEREXT) \
GLE(FramebufferTexture2D, "FramebufferTexture2DEXT", FRAMEBUFFERTEXTURE2DEXT) \ GLE(CheckFramebufferStatus, "CheckFramebufferStatusEXT", \
GLE(GenerateMipmap, "GenerateMipmapEXT", GENERATEMIPMAPEXT) \ CHECKFRAMEBUFFERSTATUSEXT) \
/* GL_EXT_framebuffer_blit */ \ GLE(FramebufferRenderbuffer, "FramebufferRenderbufferEXT", \
GLE(BlitFramebuffer, "BlitFramebufferEXT", BLITFRAMEBUFFEREXT) \ FRAMEBUFFERRENDERBUFFEREXT) \
/* GL_EXT_framebuffer_multisample */ \ GLE(FramebufferTexture2D, "FramebufferTexture2DEXT", \
GLE(RenderbufferStorageMultisample, "RenderbufferStorageMultisampleEXT",RENDERBUFFERSTORAGEMULTISAMPLEEXT) \ FRAMEBUFFERTEXTURE2DEXT) \
/* <end> */ GLE(GenerateMipmap, "GenerateMipmapEXT", GENERATEMIPMAPEXT) \
/* GL_EXT_framebuffer_blit */ \
GLE(BlitFramebuffer, "BlitFramebufferEXT", BLITFRAMEBUFFEREXT) \
/* GL_EXT_framebuffer_multisample */ \
GLE(RenderbufferStorageMultisample, "RenderbufferStorageMultisampleEXT", \
RENDERBUFFERSTORAGEMULTISAMPLEEXT) \
/* <end> */
#define gdraw_GLx_(id) gdraw_GL_##id #define gdraw_GLx_(id) gdraw_GL_##id
#define GDRAW_GLx_(id) GDRAW_GL_##id #define GDRAW_GLx_(id) GDRAW_GL_##id
#define GDRAW_SHADERS "gdraw_gl_shaders.inl" #define GDRAW_SHADERS "gdraw_gl_shaders.inl"
// On Linux, GLhandleARB is void* (not GLuint) but the shader functions // On Linux, GLhandleARB is void* (not GLuint) but the shader functions
// actually return/take GLuint values. Use GLuint as our handle type, // actually return/take GLuint values. Use GLuint as our handle type,
@ -123,20 +129,18 @@ typedef gdraw_gl_resourcetype gdraw_resourcetype;
GDRAW_GL_EXTENSION_LIST GDRAW_GL_EXTENSION_LIST
#undef GLE #undef GLE
static void load_extensions(void) static void load_extensions(void) {
{ #define GLE(id, import, procname) \
#define GLE(id, import, procname) gl##id = (PFNGL##procname##PROC) SDL_GL_GetProcAddress("gl" import); gl##id = (PFNGL##procname##PROC)SDL_GL_GetProcAddress("gl" import);
GDRAW_GL_EXTENSION_LIST GDRAW_GL_EXTENSION_LIST
#undef GLE #undef GLE
} }
static void clear_renderstate_platform_specific(void) static void clear_renderstate_platform_specific(void) {
{
glDisable(GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
} }
static void error_msg_platform_specific(const char *msg) static void error_msg_platform_specific(const char* msg) {
{
fprintf(stderr, "[GDraw GL] %s\n", msg); fprintf(stderr, "[GDraw GL] %s\n", msg);
} }
@ -151,7 +155,10 @@ static void error_msg_platform_specific(const char *msg)
#ifdef RR_BREAK #ifdef RR_BREAK
#undef RR_BREAK #undef RR_BREAK
#endif #endif
#define RR_BREAK() do { fprintf(stderr, "[GDraw] RR_BREAK suppressed (GL error)\n"); } while(0) #define RR_BREAK() \
do { \
fprintf(stderr, "[GDraw] RR_BREAK suppressed (GL error)\n"); \
} while (0)
#include "../../../Windows64/Iggy/gdraw/gdraw_gl_shared.inl" #include "../../../Windows64/Iggy/gdraw/gdraw_gl_shared.inl"
@ -160,32 +167,42 @@ static void error_msg_platform_specific(const char *msg)
// Initialization and platform-specific functionality // Initialization and platform-specific functionality
// //
GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) GDrawFunctions* gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples) {
{
static const TextureFormatDesc tex_formats[] = { static const TextureFormatDesc tex_formats[] = {
{ IFT_FORMAT_rgba_8888, 1, 1, 4, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE }, {IFT_FORMAT_rgba_8888, 1, 1, 4, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE},
{ IFT_FORMAT_rgba_4444_LE, 1, 1, 2, GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 }, {IFT_FORMAT_rgba_4444_LE, 1, 1, 2, GL_RGBA4, GL_RGBA,
{ IFT_FORMAT_rgba_5551_LE, 1, 1, 2, GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1 }, GL_UNSIGNED_SHORT_4_4_4_4},
{ IFT_FORMAT_la_88, 1, 1, 2, GL_LUMINANCE8_ALPHA8, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE }, {IFT_FORMAT_rgba_5551_LE, 1, 1, 2, GL_RGB5_A1, GL_RGBA,
{ IFT_FORMAT_la_44, 1, 1, 1, GL_LUMINANCE4_ALPHA4, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE }, GL_UNSIGNED_SHORT_5_5_5_1},
{ IFT_FORMAT_i_8, 1, 1, 1, GL_INTENSITY8, GL_ALPHA, GL_UNSIGNED_BYTE }, {IFT_FORMAT_la_88, 1, 1, 2, GL_LUMINANCE8_ALPHA8, GL_LUMINANCE_ALPHA,
{ IFT_FORMAT_i_4, 1, 1, 1, GL_INTENSITY4, GL_ALPHA, GL_UNSIGNED_BYTE }, GL_UNSIGNED_BYTE},
{ IFT_FORMAT_l_8, 1, 1, 1, GL_LUMINANCE8, GL_LUMINANCE, GL_UNSIGNED_BYTE }, {IFT_FORMAT_la_44, 1, 1, 1, GL_LUMINANCE4_ALPHA4, GL_LUMINANCE_ALPHA,
{ IFT_FORMAT_l_4, 1, 1, 1, GL_LUMINANCE4, GL_LUMINANCE, GL_UNSIGNED_BYTE }, GL_UNSIGNED_BYTE},
{ IFT_FORMAT_DXT1, 4, 4, 8, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 0, GL_UNSIGNED_BYTE }, {IFT_FORMAT_i_8, 1, 1, 1, GL_INTENSITY8, GL_ALPHA, GL_UNSIGNED_BYTE},
{ IFT_FORMAT_DXT3, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 0, GL_UNSIGNED_BYTE }, {IFT_FORMAT_i_4, 1, 1, 1, GL_INTENSITY4, GL_ALPHA, GL_UNSIGNED_BYTE},
{ IFT_FORMAT_DXT5, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0, GL_UNSIGNED_BYTE }, {IFT_FORMAT_l_8, 1, 1, 1, GL_LUMINANCE8, GL_LUMINANCE,
{ 0, 0, 0, 0, 0, 0, 0 }, GL_UNSIGNED_BYTE},
{IFT_FORMAT_l_4, 1, 1, 1, GL_LUMINANCE4, GL_LUMINANCE,
GL_UNSIGNED_BYTE},
{IFT_FORMAT_DXT1, 4, 4, 8, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 0,
GL_UNSIGNED_BYTE},
{IFT_FORMAT_DXT3, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 0,
GL_UNSIGNED_BYTE},
{IFT_FORMAT_DXT5, 4, 4, 16, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0,
GL_UNSIGNED_BYTE},
{0, 0, 0, 0, 0, 0, 0},
}; };
GDrawFunctions *funcs; GDrawFunctions* funcs;
const char *s; const char* s;
GLint n; GLint n;
// check for the extensions we need // check for the extensions we need
s = (const char *) glGetString(GL_EXTENSIONS); s = (const char*)glGetString(GL_EXTENSIONS);
if (s == NULL) { if (s == NULL) {
fprintf(stderr, "[GDraw GL] glGetString(GL_EXTENSIONS) returned NULL - GL context not current?\n"); fprintf(stderr,
"[GDraw GL] glGetString(GL_EXTENSIONS) returned NULL - GL "
"context not current?\n");
assert(s != NULL); assert(s != NULL);
return NULL; return NULL;
} }
@ -199,8 +216,7 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples)
!hasext(s, "GL_EXT_framebuffer_object") || !hasext(s, "GL_EXT_framebuffer_object") ||
!hasext(s, "GL_ARB_shader_objects") || !hasext(s, "GL_ARB_shader_objects") ||
!hasext(s, "GL_ARB_vertex_shader") || !hasext(s, "GL_ARB_vertex_shader") ||
!hasext(s, "GL_ARB_fragment_shader")) !hasext(s, "GL_ARB_fragment_shader")) {
{
fprintf(stderr, "[GDraw GL] Required GL extensions not available\n"); fprintf(stderr, "[GDraw GL] Required GL extensions not available\n");
return NULL; return NULL;
} }
@ -211,17 +227,17 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples)
load_extensions(); load_extensions();
funcs = create_context(w, h); funcs = create_context(w, h);
if (!funcs) if (!funcs) return NULL;
return NULL;
gdraw->tex_formats = tex_formats; gdraw->tex_formats = tex_formats;
// check for optional extensions // check for optional extensions
gdraw->has_mapbuffer = true; // part of core VBO extension on regular GL gdraw->has_mapbuffer = true; // part of core VBO extension on regular GL
gdraw->has_depth24 = true; // we just assume. gdraw->has_depth24 = true; // we just assume.
gdraw->has_texture_max_level = true; // core on regular GL gdraw->has_texture_max_level = true; // core on regular GL
if (hasext(s, "GL_EXT_packed_depth_stencil")) gdraw->has_packed_depth_stencil = true; if (hasext(s, "GL_EXT_packed_depth_stencil"))
gdraw->has_packed_depth_stencil = true;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &n); glGetIntegerv(GL_MAX_TEXTURE_SIZE, &n);
gdraw->has_conditional_non_power_of_two = n < 8192; gdraw->has_conditional_non_power_of_two = n < 8192;
@ -234,7 +250,9 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples)
opengl_check(); opengl_check();
fprintf(stderr, "[GDraw GL] Context created successfully (%dx%d, msaa=%d)\n", w, h, msaa_samples); fprintf(stderr,
"[GDraw GL] Context created successfully (%dx%d, msaa=%d)\n", w, h,
msaa_samples);
return funcs; return funcs;
} }
@ -243,14 +261,15 @@ GDrawFunctions *gdraw_GL_CreateContext(S32 w, S32 h, S32 msaa_samples)
// 4J-specific custom draw functions // 4J-specific custom draw functions
// //
void gdraw_GL_BeginCustomDraw_4J(IggyCustomDrawCallbackRegion *region, F32 *matrix) void gdraw_GL_BeginCustomDraw_4J(IggyCustomDrawCallbackRegion* region,
{ F32* matrix) {
// Same as BeginCustomDraw but uses different depth param // Same as BeginCustomDraw but uses different depth param
clear_renderstate(); clear_renderstate();
gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection, depth_from_id(0), 1); gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection,
depth_from_id(0), 1);
} }
void gdraw_GL_CalculateCustomDraw_4J(IggyCustomDrawCallbackRegion *region, F32 *matrix) void gdraw_GL_CalculateCustomDraw_4J(IggyCustomDrawCallbackRegion* region,
{ F32* matrix) {
gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection, 0.0f, 0); gdraw_GetObjectSpaceMatrix(matrix, region->o2w, gdraw->projection, 0.0f, 0);
} }

View file

@ -8,35 +8,49 @@
extern "C" { extern "C" {
#endif #endif
typedef enum gdraw_gl_resourcetype typedef enum gdraw_gl_resourcetype {
{ GDRAW_GL_RESOURCE_rendertarget,
GDRAW_GL_RESOURCE_rendertarget, GDRAW_GL_RESOURCE_texture,
GDRAW_GL_RESOURCE_texture, GDRAW_GL_RESOURCE_vertexbuffer,
GDRAW_GL_RESOURCE_vertexbuffer,
GDRAW_GL_RESOURCE__count, GDRAW_GL_RESOURCE__count,
} gdraw_gl_resourcetype; } gdraw_gl_resourcetype;
struct IggyCustomDrawCallbackRegion; struct IggyCustomDrawCallbackRegion;
extern int gdraw_GL_SetResourceLimits(gdraw_gl_resourcetype type, S32 num_handles, S32 num_bytes); extern int gdraw_GL_SetResourceLimits(gdraw_gl_resourcetype type,
extern GDrawFunctions * gdraw_GL_CreateContext(S32 min_w, S32 min_h, S32 msaa_samples); S32 num_handles, S32 num_bytes);
extern GDrawFunctions* gdraw_GL_CreateContext(S32 min_w, S32 min_h,
S32 msaa_samples);
extern void gdraw_GL_DestroyContext(void); extern void gdraw_GL_DestroyContext(void);
extern void gdraw_GL_SetTileOrigin(S32 vx, S32 vy, unsigned int framebuffer); // framebuffer=FBO handle, or 0 for main frame buffer extern void gdraw_GL_SetTileOrigin(
S32 vx, S32 vy,
unsigned int
framebuffer); // framebuffer=FBO handle, or 0 for main frame buffer
extern void gdraw_GL_NoMoreGDrawThisFrame(void); extern void gdraw_GL_NoMoreGDrawThisFrame(void);
extern GDrawTexture *gdraw_GL_WrappedTextureCreate(S32 gl_texture_handle, S32 width, S32 height, int has_mipmaps); extern GDrawTexture* gdraw_GL_WrappedTextureCreate(S32 gl_texture_handle,
extern void gdraw_GL_WrappedTextureChange(GDrawTexture *tex, S32 new_gl_texture_handle, S32 new_width, S32 new_height, int new_has_mipmaps); S32 width, S32 height,
extern void gdraw_GL_WrappedTextureDestroy(GDrawTexture *tex); int has_mipmaps);
extern void gdraw_GL_WrappedTextureChange(GDrawTexture* tex,
S32 new_gl_texture_handle,
S32 new_width, S32 new_height,
int new_has_mipmaps);
extern void gdraw_GL_WrappedTextureDestroy(GDrawTexture* tex);
extern void gdraw_GL_BeginCustomDraw(struct IggyCustomDrawCallbackRegion *region, float *matrix); extern void gdraw_GL_BeginCustomDraw(
extern void gdraw_GL_EndCustomDraw(struct IggyCustomDrawCallbackRegion *region); struct IggyCustomDrawCallbackRegion* region, float* matrix);
extern void gdraw_GL_EndCustomDraw(struct IggyCustomDrawCallbackRegion* region);
extern void gdraw_GL_CalculateCustomDraw_4J(struct IggyCustomDrawCallbackRegion *region, float *matrix); extern void gdraw_GL_CalculateCustomDraw_4J(
extern void gdraw_GL_BeginCustomDraw_4J(struct IggyCustomDrawCallbackRegion *region, float *matrix); struct IggyCustomDrawCallbackRegion* region, float* matrix);
extern void gdraw_GL_BeginCustomDraw_4J(
struct IggyCustomDrawCallbackRegion* region, float* matrix);
extern GDrawTexture * gdraw_GL_MakeTextureFromResource(unsigned char *resource_file, S32 resource_len, IggyFileTextureRaw *texture); extern GDrawTexture* gdraw_GL_MakeTextureFromResource(
extern void gdraw_GL_DestroyTextureFromResource(GDrawTexture *tex); unsigned char* resource_file, S32 resource_len,
IggyFileTextureRaw* texture);
extern void gdraw_GL_DestroyTextureFromResource(GDrawTexture* tex);
#ifdef __cplusplus #ifdef __cplusplus
} }

View file

@ -2,4 +2,6 @@
#include "LinuxLeaderboardManager.h" #include "LinuxLeaderboardManager.h"
LeaderboardManager *LeaderboardManager::m_instance = new LinuxLeaderboardManager(); //Singleton instance of the LeaderboardManager LeaderboardManager* LeaderboardManager::m_instance =
new LinuxLeaderboardManager(); // Singleton instance of the
// LeaderboardManager

View file

@ -2,35 +2,50 @@
#include "../../Common/Leaderboards/LeaderboardManager.h" #include "../../Common/Leaderboards/LeaderboardManager.h"
class LinuxLeaderboardManager : public LeaderboardManager class LinuxLeaderboardManager : public LeaderboardManager {
{
public: public:
virtual void Tick() {} virtual void Tick() {}
//Open a session // Open a session
virtual bool OpenSession() { return true; } virtual bool OpenSession() { return true; }
//Close a session // Close a session
virtual void CloseSession() {} virtual void CloseSession() {}
//Delete a session // Delete a session
virtual void DeleteSession() {} virtual void DeleteSession() {}
//Write the given stats // Write the given stats
//This is called synchronously and will not free any memory allocated for views when it is done // This is called synchronously and will not free any memory allocated for
// views when it is done
virtual bool WriteStats(unsigned int viewCount, ViewIn views) { return false; } virtual bool WriteStats(unsigned int viewCount, ViewIn views) {
return false;
}
virtual bool ReadStats_Friends(LeaderboardReadListener *callback, int difficulty, EStatsType type, PlayerUID myUID) { return false; } virtual bool ReadStats_Friends(LeaderboardReadListener* callback,
virtual bool ReadStats_MyScore(LeaderboardReadListener *callback, int difficulty, EStatsType type, PlayerUID myUID, unsigned int readCount) { return false; } int difficulty, EStatsType type,
virtual bool ReadStats_TopRank(LeaderboardReadListener *callback, int difficulty, EStatsType type, unsigned int startIndex, unsigned int readCount) { return false; } PlayerUID myUID) {
return false;
}
virtual bool ReadStats_MyScore(LeaderboardReadListener* callback,
int difficulty, EStatsType type,
PlayerUID myUID, unsigned int readCount) {
return false;
}
virtual bool ReadStats_TopRank(LeaderboardReadListener* callback,
int difficulty, EStatsType type,
unsigned int startIndex,
unsigned int readCount) {
return false;
}
//Perform a flush of the stats // Perform a flush of the stats
virtual void FlushStats() {} virtual void FlushStats() {}
//Cancel the current operation // Cancel the current operation
virtual void CancelOperation() {} virtual void CancelOperation() {}
//Is the leaderboard manager idle. // Is the leaderboard manager idle.
virtual bool isIdle() { return true; } virtual bool isIdle() { return true; }
}; };

View file

@ -9,96 +9,81 @@
#include "../../Minecraft.World/IO/Streams/FloatBuffer.h" #include "../../Minecraft.World/IO/Streams/FloatBuffer.h"
#include "../../Minecraft.World/IO/Streams/ByteBuffer.h" #include "../../Minecraft.World/IO/Streams/ByteBuffer.h"
int glGenTextures() {
int glGenTextures() GLuint id = 0;
{ ::glGenTextures(1, &id);
GLuint id = 0; return (int)id;
::glGenTextures(1, &id);
return (int)id;
} }
void glGenTextures(IntBuffer *buf) void glGenTextures(IntBuffer* buf) {
{ GLuint id = 0;
GLuint id = 0; ::glGenTextures(1, &id);
::glGenTextures(1, &id); buf->put((int)id);
buf->put((int)id); buf->flip();
buf->flip();
} }
void glDeleteTextures(int id) void glDeleteTextures(int id) {
{ GLuint uid = (GLuint)id;
GLuint uid = (GLuint)id; ::glDeleteTextures(1, &uid);
::glDeleteTextures(1, &uid);
} }
void glDeleteTextures(IntBuffer *buf) void glDeleteTextures(IntBuffer* buf) {
{ int id = buf->get(0);
int id = buf->get(0); GLuint uid = (GLuint)id;
GLuint uid = (GLuint)id; ::glDeleteTextures(1, &uid);
::glDeleteTextures(1, &uid);
} }
void glLight(int light, int pname, FloatBuffer *params) void glLight(int light, int pname, FloatBuffer* params) {
{ ::glLightfv((GLenum)light, (GLenum)pname, params->_getDataPointer());
::glLightfv((GLenum)light, (GLenum)pname, params->_getDataPointer());
} }
void glLightModel(int pname, FloatBuffer *params) void glLightModel(int pname, FloatBuffer* params) {
{ ::glLightModelfv((GLenum)pname, params->_getDataPointer());
::glLightModelfv((GLenum)pname, params->_getDataPointer());
} }
void glGetFloat(int pname, FloatBuffer *params) void glGetFloat(int pname, FloatBuffer* params) {
{ ::glGetFloatv((GLenum)pname, params->_getDataPointer());
::glGetFloatv((GLenum)pname, params->_getDataPointer());
} }
void glTexGen(int coord, int pname, FloatBuffer *params) void glTexGen(int coord, int pname, FloatBuffer* params) {
{ ::glTexGenfv((GLenum)coord, (GLenum)pname, params->_getDataPointer());
::glTexGenfv((GLenum)coord, (GLenum)pname, params->_getDataPointer());
} }
void glFog(int pname, FloatBuffer *params) void glFog(int pname, FloatBuffer* params) {
{ ::glFogfv((GLenum)pname, params->_getDataPointer());
::glFogfv((GLenum)pname, params->_getDataPointer());
} }
void glTexCoordPointer(int size, int type, FloatBuffer *pointer) void glTexCoordPointer(int size, int type, FloatBuffer* pointer) {
{ ::glTexCoordPointer(size, (GLenum)type, 0, pointer->_getDataPointer());
::glTexCoordPointer(size, (GLenum)type, 0, pointer->_getDataPointer());
} }
void glNormalPointer(int type, ByteBuffer *pointer) void glNormalPointer(int type, ByteBuffer* pointer) {
{ ::glNormalPointer((GLenum)type, 0, pointer->getBuffer());
::glNormalPointer((GLenum)type, 0, pointer->getBuffer());
} }
void glColorPointer(int size, bool normalized, int stride, ByteBuffer *pointer) void glColorPointer(int size, bool normalized, int stride,
{ ByteBuffer* pointer) {
(void)normalized; (void)normalized;
::glColorPointer(size, GL_UNSIGNED_BYTE, stride, pointer->getBuffer()); ::glColorPointer(size, GL_UNSIGNED_BYTE, stride, pointer->getBuffer());
} }
void glVertexPointer(int size, int type, FloatBuffer *pointer) void glVertexPointer(int size, int type, FloatBuffer* pointer) {
{ ::glVertexPointer(size, (GLenum)type, 0, pointer->_getDataPointer());
::glVertexPointer(size, (GLenum)type, 0, pointer->_getDataPointer());
} }
void glEndList(int) void glEndList(int) { ::glEndList(); }
{
::glEndList(); void glTexImage2D(int target, int level, int internalformat, int width,
int height, int border, int format, int type,
ByteBuffer* pixels) {
void* data = pixels ? pixels->getBuffer() : nullptr;
::glTexImage2D((GLenum)target, level, internalformat, width, height, border,
(GLenum)format, (GLenum)type, data);
} }
void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, ByteBuffer *pixels) void glCallLists(IntBuffer* lists) {
{ int count = lists->limit() - lists->position();
void *data = pixels ? pixels->getBuffer() : nullptr; ::glCallLists(count, GL_INT, lists->getBuffer());
::glTexImage2D((GLenum)target, level, internalformat, width, height, border, (GLenum)format, (GLenum)type, data);
}
void glCallLists(IntBuffer *lists)
{
int count = lists->limit() - lists->position();
::glCallLists(count, GL_INT, lists->getBuffer());
} }
static PFNGLGENQUERIESARBPROC _glGenQueriesARB = nullptr; static PFNGLGENQUERIESARBPROC _glGenQueriesARB = nullptr;
@ -107,55 +92,52 @@ static PFNGLENDQUERYARBPROC _glEndQueryARB = nullptr;
static PFNGLGETQUERYOBJECTUIVARBPROC _glGetQueryObjectuivARB = nullptr; static PFNGLGETQUERYOBJECTUIVARBPROC _glGetQueryObjectuivARB = nullptr;
static bool _queriesInitialized = false; static bool _queriesInitialized = false;
static void initQueryFuncs() static void initQueryFuncs() {
{ if (_queriesInitialized) return;
if (_queriesInitialized) return; _queriesInitialized = true;
_queriesInitialized = true; _glGenQueriesARB =
_glGenQueriesARB = (PFNGLGENQUERIESARBPROC)dlsym(RTLD_DEFAULT, "glGenQueriesARB"); (PFNGLGENQUERIESARBPROC)dlsym(RTLD_DEFAULT, "glGenQueriesARB");
_glBeginQueryARB = (PFNGLBEGINQUERYARBPROC)dlsym(RTLD_DEFAULT, "glBeginQueryARB"); _glBeginQueryARB =
_glEndQueryARB = (PFNGLENDQUERYARBPROC)dlsym(RTLD_DEFAULT, "glEndQueryARB"); (PFNGLBEGINQUERYARBPROC)dlsym(RTLD_DEFAULT, "glBeginQueryARB");
_glGetQueryObjectuivARB = (PFNGLGETQUERYOBJECTUIVARBPROC)dlsym(RTLD_DEFAULT, "glGetQueryObjectuivARB"); _glEndQueryARB = (PFNGLENDQUERYARBPROC)dlsym(RTLD_DEFAULT, "glEndQueryARB");
_glGetQueryObjectuivARB = (PFNGLGETQUERYOBJECTUIVARBPROC)dlsym(
RTLD_DEFAULT, "glGetQueryObjectuivARB");
} }
void glGenQueriesARB(IntBuffer *buf) void glGenQueriesARB(IntBuffer* buf) {
{ initQueryFuncs();
initQueryFuncs(); if (_glGenQueriesARB) {
if (_glGenQueriesARB) GLuint id = 0;
{ _glGenQueriesARB(1, &id);
GLuint id = 0; buf->put((int)id);
_glGenQueriesARB(1, &id); buf->flip();
buf->put((int)id); }
buf->flip();
}
} }
void glBeginQueryARB(int target, int id) void glBeginQueryARB(int target, int id) {
{ initQueryFuncs();
initQueryFuncs(); if (_glBeginQueryARB) _glBeginQueryARB((GLenum)target, (GLuint)id);
if (_glBeginQueryARB) _glBeginQueryARB((GLenum)target, (GLuint)id);
} }
void glEndQueryARB(int target) void glEndQueryARB(int target) {
{ initQueryFuncs();
initQueryFuncs(); if (_glEndQueryARB) _glEndQueryARB((GLenum)target);
if (_glEndQueryARB) _glEndQueryARB((GLenum)target);
} }
void glGetQueryObjectuARB(int id, int pname, IntBuffer *params) void glGetQueryObjectuARB(int id, int pname, IntBuffer* params) {
{ initQueryFuncs();
initQueryFuncs(); if (_glGetQueryObjectuivARB) {
if (_glGetQueryObjectuivARB) GLuint val = 0;
{ _glGetQueryObjectuivARB((GLuint)id, (GLenum)pname, &val);
GLuint val = 0; params->put((int)val);
_glGetQueryObjectuivARB((GLuint)id, (GLenum)pname, &val); params->flip();
params->put((int)val); }
params->flip();
}
} }
void glReadPixels(int x, int y, int width, int height, int format, int type, ByteBuffer *pixels) void glReadPixels(int x, int y, int width, int height, int format, int type,
{ ByteBuffer* pixels) {
::glReadPixels(x, y, width, height, (GLenum)format, (GLenum)type, pixels->getBuffer()); ::glReadPixels(x, y, width, height, (GLenum)format, (GLenum)type,
pixels->getBuffer());
} }
#endif #endif

View file

@ -13,64 +13,55 @@
CConsoleMinecraftApp app; CConsoleMinecraftApp app;
#define CONTEXT_GAME_STATE 0 #define CONTEXT_GAME_STATE 0
CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() CConsoleMinecraftApp::CConsoleMinecraftApp() : CMinecraftApp() {}
{
void CConsoleMinecraftApp::SetRichPresenceContext(int iPad, int contextId) {
ProfileManager.SetRichPresenceContextValue(iPad, CONTEXT_GAME_STATE,
contextId);
} }
void CConsoleMinecraftApp::SetRichPresenceContext(int iPad, int contextId) void CConsoleMinecraftApp::StoreLaunchData() {}
{ void CConsoleMinecraftApp::ExitGame() {}
ProfileManager.SetRichPresenceContextValue(iPad,CONTEXT_GAME_STATE,contextId); void CConsoleMinecraftApp::FatalLoadError() {
} app.DebugPrintf(
"CConsoleMinecraftApp::FatalLoadError - asserting 0 and dying...\n");
void CConsoleMinecraftApp::StoreLaunchData()
{
}
void CConsoleMinecraftApp::ExitGame()
{
}
void CConsoleMinecraftApp::FatalLoadError()
{
app.DebugPrintf("CConsoleMinecraftApp::FatalLoadError - asserting 0 and dying...\n");
assert(0); assert(0);
} }
void CConsoleMinecraftApp::CaptureSaveThumbnail() void CConsoleMinecraftApp::CaptureSaveThumbnail() {}
{ void CConsoleMinecraftApp::GetSaveThumbnail(std::uint8_t** thumbnailData,
} unsigned int* thumbnailSize) {}
void CConsoleMinecraftApp::GetSaveThumbnail(std::uint8_t **thumbnailData, unsigned int *thumbnailSize) void CConsoleMinecraftApp::ReleaseSaveThumbnail() {}
{
}
void CConsoleMinecraftApp::ReleaseSaveThumbnail()
{
}
void CConsoleMinecraftApp::GetScreenshot(int iPad, std::uint8_t **screenshotData, unsigned int *screenshotSize) void CConsoleMinecraftApp::GetScreenshot(int iPad,
{ std::uint8_t** screenshotData,
} unsigned int* screenshotSize) {}
void CConsoleMinecraftApp::TemporaryCreateGameStart() void CConsoleMinecraftApp::TemporaryCreateGameStart() {
{ //////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////// From CScene_Main::OnInit ///From CScene_Main::OnInit
app.setLevelGenerationOptions(NULL); app.setLevelGenerationOptions(NULL);
// From CScene_Main::RunPlayGame // From CScene_Main::RunPlayGame
Minecraft *pMinecraft=Minecraft::GetInstance(); Minecraft* pMinecraft = Minecraft::GetInstance();
app.ReleaseSaveThumbnail(); app.ReleaseSaveThumbnail();
ProfileManager.SetLockedProfile(0); ProfileManager.SetLockedProfile(0);
pMinecraft->user->name = L"Windows"; pMinecraft->user->name = L"Windows";
app.ApplyGameSettingsChanged(0); app.ApplyGameSettingsChanged(0);
////////////////////////////////////////////////////////////////////////////////////////////// From CScene_MultiGameJoinLoad::OnInit //////////////////////////////////////////////////////////////////////////////////////////////
///From CScene_MultiGameJoinLoad::OnInit
MinecraftServer::resetFlags(); MinecraftServer::resetFlags();
// From CScene_MultiGameJoinLoad::OnNotifyPressEx // From CScene_MultiGameJoinLoad::OnNotifyPressEx
app.SetTutorialMode( false ); app.SetTutorialMode(false);
app.SetCorruptSaveDeleted(false); app.SetCorruptSaveDeleted(false);
////////////////////////////////////////////////////////////////////////////////////////////// From CScene_MultiGameCreate::CreateGame //////////////////////////////////////////////////////////////////////////////////////////////
///From CScene_MultiGameCreate::CreateGame
app.ClearTerrainFeaturePosition(); app.ClearTerrainFeaturePosition();
std::wstring wWorldName = L"TestWorld"; std::wstring wWorldName = L"TestWorld";
@ -79,60 +70,62 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart()
StorageManager.SetSaveTitle(wWorldName.c_str()); StorageManager.SetSaveTitle(wWorldName.c_str());
bool isFlat = false; bool isFlat = false;
__int64 seedValue = 0; // BiomeSource::findSeed(isFlat?LevelType::lvl_flat:LevelType::lvl_normal); // 4J - was (new Random())->nextLong() - now trying to actually find a seed to suit our requirements __int64 seedValue =
0; // BiomeSource::findSeed(isFlat?LevelType::lvl_flat:LevelType::lvl_normal);
// // 4J - was (new Random())->nextLong() - now trying to actually
// find a seed to suit our requirements
NetworkGameInitData *param = new NetworkGameInitData(); NetworkGameInitData* param = new NetworkGameInitData();
param->seed = seedValue; param->seed = seedValue;
param->saveData = NULL; param->saveData = NULL;
app.SetGameHostOption(eGameHostOption_Difficulty,0); app.SetGameHostOption(eGameHostOption_Difficulty, 0);
app.SetGameHostOption(eGameHostOption_FriendsOfFriends,0); app.SetGameHostOption(eGameHostOption_FriendsOfFriends, 0);
app.SetGameHostOption(eGameHostOption_Gamertags,1); app.SetGameHostOption(eGameHostOption_Gamertags, 1);
app.SetGameHostOption(eGameHostOption_BedrockFog,1); app.SetGameHostOption(eGameHostOption_BedrockFog, 1);
app.SetGameHostOption(eGameHostOption_GameType,GameType::CREATIVE->getId() ); // LevelSettings::GAMETYPE_SURVIVAL app.SetGameHostOption(
app.SetGameHostOption(eGameHostOption_LevelType, 0 ); eGameHostOption_GameType,
app.SetGameHostOption(eGameHostOption_Structures, 1 ); GameType::CREATIVE->getId()); // LevelSettings::GAMETYPE_SURVIVAL
app.SetGameHostOption(eGameHostOption_BonusChest, 0 ); app.SetGameHostOption(eGameHostOption_LevelType, 0);
app.SetGameHostOption(eGameHostOption_Structures, 1);
app.SetGameHostOption(eGameHostOption_BonusChest, 0);
app.SetGameHostOption(eGameHostOption_PvP, 1); app.SetGameHostOption(eGameHostOption_PvP, 1);
app.SetGameHostOption(eGameHostOption_TrustPlayers, 1 ); app.SetGameHostOption(eGameHostOption_TrustPlayers, 1);
app.SetGameHostOption(eGameHostOption_FireSpreads, 1 ); app.SetGameHostOption(eGameHostOption_FireSpreads, 1);
app.SetGameHostOption(eGameHostOption_TNT, 1 ); app.SetGameHostOption(eGameHostOption_TNT, 1);
app.SetGameHostOption(eGameHostOption_HostCanFly, 1); app.SetGameHostOption(eGameHostOption_HostCanFly, 1);
app.SetGameHostOption(eGameHostOption_HostCanChangeHunger, 1); app.SetGameHostOption(eGameHostOption_HostCanChangeHunger, 1);
app.SetGameHostOption(eGameHostOption_HostCanBeInvisible, 1 ); app.SetGameHostOption(eGameHostOption_HostCanBeInvisible, 1);
param->settings = app.GetGameHostOption( eGameHostOption_All ); param->settings = app.GetGameHostOption(eGameHostOption_All);
g_NetworkManager.FakeLocalPlayerJoined(); g_NetworkManager.FakeLocalPlayerJoined();
LoadingInputParams *loadingParams = new LoadingInputParams(); LoadingInputParams* loadingParams = new LoadingInputParams();
loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc;
loadingParams->lpParam = (LPVOID)param; loadingParams->lpParam = (LPVOID)param;
// Reset the autosave time // Reset the autosave time
app.SetAutosaveTimerTime(); app.SetAutosaveTimerTime();
C4JThread* thread = new C4JThread(loadingParams->func, loadingParams->lpParam, "RunNetworkGame"); C4JThread* thread = new C4JThread(loadingParams->func,
loadingParams->lpParam, "RunNetworkGame");
thread->Run(); thread->Run();
} }
int CConsoleMinecraftApp::GetLocalTMSFileIndex(WCHAR *wchTMSFile,bool bFilenameIncludesExtension,eFileExtensionType eEXT) int CConsoleMinecraftApp::GetLocalTMSFileIndex(WCHAR* wchTMSFile,
{ bool bFilenameIncludesExtension,
eFileExtensionType eEXT) {
return -1; return -1;
} }
int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR *wchTMSFile) int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR* wchTMSFile) { return -1; }
{
int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR* wchTMSFile,
eFileExtensionType eExt) {
return -1; return -1;
} }
int CConsoleMinecraftApp::LoadLocalTMSFile(WCHAR *wchTMSFile, eFileExtensionType eExt) void CConsoleMinecraftApp::FreeLocalTMSFiles(eTMSFileType eType) {}
{
return -1;
}
void CConsoleMinecraftApp::FreeLocalTMSFiles(eTMSFileType eType)
{
}

View file

@ -1,34 +1,38 @@
#pragma once #pragma once
class CConsoleMinecraftApp : public CMinecraftApp class CConsoleMinecraftApp : public CMinecraftApp {
{
public: public:
CConsoleMinecraftApp(); CConsoleMinecraftApp();
virtual void SetRichPresenceContext(int iPad, int contextId); virtual void SetRichPresenceContext(int iPad, int contextId);
virtual void StoreLaunchData(); virtual void StoreLaunchData();
virtual void ExitGame(); virtual void ExitGame();
virtual void FatalLoadError(); virtual void FatalLoadError();
virtual void CaptureSaveThumbnail(); virtual void CaptureSaveThumbnail();
virtual void GetSaveThumbnail(std::uint8_t **thumbnailData, unsigned int *thumbnailSize); virtual void GetSaveThumbnail(std::uint8_t** thumbnailData,
virtual void ReleaseSaveThumbnail(); unsigned int* thumbnailSize);
virtual void GetScreenshot(int iPad, std::uint8_t **screenshotData, unsigned int *screenshotSize); virtual void ReleaseSaveThumbnail();
virtual void GetScreenshot(int iPad, std::uint8_t** screenshotData,
unsigned int* screenshotSize);
virtual int LoadLocalTMSFile(WCHAR *wchTMSFile); virtual int LoadLocalTMSFile(WCHAR* wchTMSFile);
virtual int LoadLocalTMSFile(WCHAR *wchTMSFile, eFileExtensionType eExt); virtual int LoadLocalTMSFile(WCHAR* wchTMSFile, eFileExtensionType eExt);
virtual void FreeLocalTMSFiles(eTMSFileType eType); virtual void FreeLocalTMSFiles(eTMSFileType eType);
virtual int GetLocalTMSFileIndex(WCHAR *wchTMSFile,bool bFilenameIncludesExtension,eFileExtensionType eEXT=eFileExtensionType_PNG); virtual int GetLocalTMSFileIndex(
WCHAR* wchTMSFile, bool bFilenameIncludesExtension,
eFileExtensionType eEXT = eFileExtensionType_PNG);
// BANNED LEVEL LIST // BANNED LEVEL LIST
virtual void ReadBannedList(int iPad, eTMSAction action=(eTMSAction)0, bool bCallback=false) {} virtual void ReadBannedList(int iPad, eTMSAction action = (eTMSAction)0,
bool bCallback = false) {}
C4JStringTable *GetStringTable() { return NULL;} C4JStringTable* GetStringTable() { return NULL; }
// original code // original code
virtual void TemporaryCreateGameStart(); virtual void TemporaryCreateGameStart();
}; };
extern CConsoleMinecraftApp app; extern CConsoleMinecraftApp app;

File diff suppressed because it is too large Load diff

View file

@ -8,6 +8,9 @@ void ShutdownManager::StartShutdown() {}
void ShutdownManager::MainThreadHandleShutdown() {} void ShutdownManager::MainThreadHandleShutdown() {}
void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/) {} void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/) {}
void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/, C4JThread::EventArray * /*eventArray*/) {} void ShutdownManager::HasStarted(ShutdownManager::EThreadId /*threadId*/,
bool ShutdownManager::ShouldRun(ShutdownManager::EThreadId /*threadId*/) { return true; } C4JThread::EventArray* /*eventArray*/) {}
bool ShutdownManager::ShouldRun(ShutdownManager::EThreadId /*threadId*/) {
return true;
}
void ShutdownManager::HasFinished(ShutdownManager::EThreadId /*threadId*/) {} void ShutdownManager::HasFinished(ShutdownManager::EThreadId /*threadId*/) {}

View file

@ -12,115 +12,105 @@
ConsoleUIController ui; ConsoleUIController ui;
void ConsoleUIController::init(S32 w, S32 h) void ConsoleUIController::init(S32 w, S32 h) {
{
#ifdef _ENABLEIGGY #ifdef _ENABLEIGGY
// Shared init // Shared init
preInit(w, h); preInit(w, h);
//init // init
gdraw_funcs = gdraw_GL_CreateContext(w, h, 0); gdraw_funcs = gdraw_GL_CreateContext(w, h, 0);
if (!gdraw_funcs) if (!gdraw_funcs) {
{ app.DebugPrintf("Failed to initialise GDraw GL!\n");
app.DebugPrintf("Failed to initialise GDraw GL!\n"); fprintf(stderr,
fprintf(stderr, "[Linux_UIController] Failed to initialise GDraw GL!\n"); "[Linux_UIController] Failed to initialise GDraw GL!\n");
// nott fatal for now // nott fatal for now
} } else {
else gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_vertexbuffer, 5000,
{ 16 * 1024 * 1024);
gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_texture, 5000,
128 * 1024 * 1024);
gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_rendertarget, 10,
32 * 1024 * 1024);
gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_vertexbuffer, 5000, 16 * 1024 * 1024); IggySetGDraw(gdraw_funcs);
gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_texture, 5000, 128 * 1024 * 1024); }
gdraw_GL_SetResourceLimits(GDRAW_GL_RESOURCE_rendertarget, 10, 32 * 1024 * 1024);
IggySetGDraw(gdraw_funcs); postInit();
}
postInit();
#endif #endif
} }
void ConsoleUIController::render() void ConsoleUIController::render() {
{
#ifdef _ENABLEIGGY #ifdef _ENABLEIGGY
if (!gdraw_funcs) if (!gdraw_funcs) return;
return;
gdraw_GL_SetTileOrigin(0, 0, 0); gdraw_GL_SetTileOrigin(0, 0, 0);
// render // render
renderScenes(); renderScenes();
gdraw_GL_NoMoreGDrawThisFrame(); gdraw_GL_NoMoreGDrawThisFrame();
#endif #endif
} }
void ConsoleUIController::beginIggyCustomDraw4J(IggyCustomDrawCallbackRegion *region, CustomDrawData *customDrawRegion) void ConsoleUIController::beginIggyCustomDraw4J(
{ IggyCustomDrawCallbackRegion* region, CustomDrawData* customDrawRegion) {
gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat); gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat);
} }
CustomDrawData *ConsoleUIController::setupCustomDraw(UIScene *scene, IggyCustomDrawCallbackRegion *region) CustomDrawData* ConsoleUIController::setupCustomDraw(
{ UIScene* scene, IggyCustomDrawCallbackRegion* region) {
CustomDrawData *customDrawRegion = new CustomDrawData(); CustomDrawData* customDrawRegion = new CustomDrawData();
customDrawRegion->x0 = region->x0; customDrawRegion->x0 = region->x0;
customDrawRegion->x1 = region->x1; customDrawRegion->x1 = region->x1;
customDrawRegion->y0 = region->y0; customDrawRegion->y0 = region->y0;
customDrawRegion->y1 = region->y1; customDrawRegion->y1 = region->y1;
gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat);
gdraw_GL_BeginCustomDraw_4J(region, customDrawRegion->mat);
setupCustomDrawGameStateAndMatrices(scene, customDrawRegion); setupCustomDrawGameStateAndMatrices(scene, customDrawRegion);
return customDrawRegion; return customDrawRegion;
} }
CustomDrawData *ConsoleUIController::calculateCustomDraw(IggyCustomDrawCallbackRegion *region) CustomDrawData* ConsoleUIController::calculateCustomDraw(
{ IggyCustomDrawCallbackRegion* region) {
CustomDrawData *customDrawRegion = new CustomDrawData(); CustomDrawData* customDrawRegion = new CustomDrawData();
customDrawRegion->x0 = region->x0; customDrawRegion->x0 = region->x0;
customDrawRegion->x1 = region->x1; customDrawRegion->x1 = region->x1;
customDrawRegion->y0 = region->y0; customDrawRegion->y0 = region->y0;
customDrawRegion->y1 = region->y1; customDrawRegion->y1 = region->y1;
gdraw_GL_CalculateCustomDraw_4J(region, customDrawRegion->mat); gdraw_GL_CalculateCustomDraw_4J(region, customDrawRegion->mat);
return customDrawRegion; return customDrawRegion;
} }
void ConsoleUIController::endCustomDraw(IggyCustomDrawCallbackRegion *region) void ConsoleUIController::endCustomDraw(IggyCustomDrawCallbackRegion* region) {
{ endCustomDrawGameStateAndMatrices();
endCustomDrawGameStateAndMatrices();
gdraw_GL_EndCustomDraw(region); gdraw_GL_EndCustomDraw(region);
} }
void ConsoleUIController::setTileOrigin(S32 xPos, S32 yPos) void ConsoleUIController::setTileOrigin(S32 xPos, S32 yPos) {
{ gdraw_GL_SetTileOrigin(xPos, yPos, 0);
gdraw_GL_SetTileOrigin(xPos, yPos, 0);
} }
GDrawTexture *ConsoleUIController::getSubstitutionTexture(int textureId) GDrawTexture* ConsoleUIController::getSubstitutionTexture(int textureId) {
{ // todo impl
// todo impl return nullptr;
return nullptr;
} }
void ConsoleUIController::destroySubstitutionTexture(void *destroyCallBackData, GDrawTexture *handle) void ConsoleUIController::destroySubstitutionTexture(void* destroyCallBackData,
{ GDrawTexture* handle) {
if (handle) if (handle) gdraw_GL_WrappedTextureDestroy(handle);
gdraw_GL_WrappedTextureDestroy(handle);
} }
void ConsoleUIController::shutdown() void ConsoleUIController::shutdown() {
{
#ifdef _ENABLEIGGY #ifdef _ENABLEIGGY
if (gdraw_funcs) if (gdraw_funcs) {
{ gdraw_GL_DestroyContext();
gdraw_GL_DestroyContext(); gdraw_funcs = nullptr;
gdraw_funcs = nullptr; }
}
#endif #endif
} }

View file

@ -2,26 +2,29 @@
#include "../Common/UI/UIController.h" #include "../Common/UI/UIController.h"
class ConsoleUIController : public UIController class ConsoleUIController : public UIController {
{
public: public:
void init(S32 w, S32 h); void init(S32 w, S32 h);
void render(); void render();
void beginIggyCustomDraw4J(IggyCustomDrawCallbackRegion *region, CustomDrawData *customDrawRegion); void beginIggyCustomDraw4J(IggyCustomDrawCallbackRegion* region,
virtual CustomDrawData *setupCustomDraw(UIScene *scene, IggyCustomDrawCallbackRegion *region); CustomDrawData* customDrawRegion);
virtual CustomDrawData *calculateCustomDraw(IggyCustomDrawCallbackRegion *region); virtual CustomDrawData* setupCustomDraw(
virtual void endCustomDraw(IggyCustomDrawCallbackRegion *region); UIScene* scene, IggyCustomDrawCallbackRegion* region);
virtual CustomDrawData* calculateCustomDraw(
IggyCustomDrawCallbackRegion* region);
virtual void endCustomDraw(IggyCustomDrawCallbackRegion* region);
protected: protected:
virtual void setTileOrigin(S32 xPos, S32 yPos); virtual void setTileOrigin(S32 xPos, S32 yPos);
public: public:
GDrawTexture *getSubstitutionTexture(int textureId); GDrawTexture* getSubstitutionTexture(int textureId);
void destroySubstitutionTexture(void *destroyCallBackData, GDrawTexture *handle); void destroySubstitutionTexture(void* destroyCallBackData,
GDrawTexture* handle);
public: public:
void shutdown(); void shutdown();
}; };
extern ConsoleUIController ui; extern ConsoleUIController ui;

View file

@ -5,17 +5,11 @@
#ifndef _SOCIAL_MANAGER_H #ifndef _SOCIAL_MANAGER_H
#define _SOCIAL_MANAGER_H #define _SOCIAL_MANAGER_H
enum ESocialNetwork enum ESocialNetwork { eFacebook = 0, eNumSocialNetworks };
{
eFacebook = 0,
eNumSocialNetworks
};
class CSocialManager class CSocialManager {
{
public: public:
static CSocialManager* Instance() static CSocialManager* Instance() {
{
static CSocialManager s_instance; static CSocialManager s_instance;
return &s_instance; return &s_instance;
} }
@ -23,21 +17,21 @@ public:
void Initialise() {} void Initialise() {}
void Tick() {} void Tick() {}
bool RefreshPostingCapability() { return false; } bool RefreshPostingCapability() { return false; }
bool IsTitleAllowedToPostAnything() { return false; } bool IsTitleAllowedToPostAnything() { return false; }
bool IsTitleAllowedToPostImages() { return false; } bool IsTitleAllowedToPostImages() { return false; }
bool IsTitleAllowedToPostLinks() { return false; } bool IsTitleAllowedToPostLinks() { return false; }
bool AreAllUsersAllowedToPostImages() { return false; } bool AreAllUsersAllowedToPostImages() { return false; }
bool PostLinkToSocialNetwork( ESocialNetwork, DWORD, bool ) { return false; } bool PostLinkToSocialNetwork(ESocialNetwork, DWORD, bool) { return false; }
bool PostImageToSocialNetwork( ESocialNetwork, DWORD, bool ) { return false; } bool PostImageToSocialNetwork(ESocialNetwork, DWORD, bool) { return false; }
void SetSocialPostText( const WCHAR*, const WCHAR*, const WCHAR* ) {} void SetSocialPostText(const WCHAR*, const WCHAR*, const WCHAR*) {}
private: private:
CSocialManager() {} CSocialManager() {}
CSocialManager( const CSocialManager& ); CSocialManager(const CSocialManager&);
CSocialManager& operator=( const CSocialManager& ); CSocialManager& operator=(const CSocialManager&);
}; };
#endif // _SOCIAL_MANAGER_H #endif // _SOCIAL_MANAGER_H

View file

@ -11,334 +11,413 @@
#include "DirectXMath.h" #include "DirectXMath.h"
namespace DirectX namespace DirectX {
{
enum ContainmentType enum ContainmentType { DISJOINT = 0, INTERSECTS = 1, CONTAINS = 2 };
{
DISJOINT = 0,
INTERSECTS = 1,
CONTAINS = 2
};
enum PlaneIntersectionType enum PlaneIntersectionType { FRONT = 0, INTERSECTING = 1, BACK = 2 };
{
FRONT = 0,
INTERSECTING = 1,
BACK = 2
};
struct BoundingBox; struct BoundingBox;
struct BoundingOrientedBox; struct BoundingOrientedBox;
struct BoundingFrustum; struct BoundingFrustum;
#ifdef _MSC_VER #ifdef _MSC_VER
#pragma warning(push) #pragma warning(push)
#pragma warning(disable:4324 4820) #pragma warning(disable : 4324 4820)
// C4324: alignment padding warnings // C4324: alignment padding warnings
// C4820: Off by default noise // C4820: Off by default noise
#endif #endif
//------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------
// Bounding sphere // Bounding sphere
//------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------
struct BoundingSphere struct BoundingSphere {
{ XMFLOAT3 Center; // Center of the sphere.
XMFLOAT3 Center; // Center of the sphere. float Radius; // Radius of the sphere.
float Radius; // Radius of the sphere.
// Creators
// Creators BoundingSphere() noexcept : Center(0, 0, 0), Radius(1.f) {}
BoundingSphere() noexcept : Center(0, 0, 0), Radius(1.f) {}
BoundingSphere(const BoundingSphere&) = default;
BoundingSphere(const BoundingSphere&) = default; BoundingSphere& operator=(const BoundingSphere&) = default;
BoundingSphere& operator=(const BoundingSphere&) = default;
BoundingSphere(BoundingSphere&&) = default;
BoundingSphere(BoundingSphere&&) = default; BoundingSphere& operator=(BoundingSphere&&) = default;
BoundingSphere& operator=(BoundingSphere&&) = default;
constexpr BoundingSphere(_In_ const XMFLOAT3& center,
constexpr BoundingSphere(_In_ const XMFLOAT3& center, _In_ float radius) noexcept _In_ float radius) noexcept
: Center(center), Radius(radius) {} : Center(center), Radius(radius) {}
// Methods // Methods
void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, _In_ FXMMATRIX M) const noexcept; void XM_CALLCONV Transform(_Out_ BoundingSphere& Out,
void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; _In_ FXMMATRIX M) const noexcept;
// Transform the sphere void XM_CALLCONV Transform(_Out_ BoundingSphere& Out, _In_ float Scale,
_In_ FXMVECTOR Rotation,
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; _In_ FXMVECTOR Translation) const noexcept;
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; // Transform the sphere
ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept;
ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept;
ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1,
ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; _In_ FXMVECTOR V2) const noexcept;
ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept;
bool Intersects(_In_ const BoundingSphere& sh) const noexcept; ContainmentType Contains(_In_ const BoundingBox& box) const noexcept;
bool Intersects(_In_ const BoundingBox& box) const noexcept; ContainmentType Contains(
bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; _In_ const BoundingOrientedBox& box) const noexcept;
bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept;
bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; bool Intersects(_In_ const BoundingSphere& sh) const noexcept;
// Triangle-sphere test bool Intersects(_In_ const BoundingBox& box) const noexcept;
bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept;
PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; bool Intersects(_In_ const BoundingFrustum& fr) const noexcept;
// Plane-sphere test
bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1,
bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; _In_ FXMVECTOR V2) const noexcept;
// Ray-sphere test // Triangle-sphere test
ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, PlaneIntersectionType XM_CALLCONV
_In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; Intersects(_In_ FXMVECTOR Plane) const noexcept;
// Test sphere against six planes (see BoundingFrustum::GetPlanes) // Plane-sphere test
// Static methods bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction,
static void CreateMerged(_Out_ BoundingSphere& Out, _In_ const BoundingSphere& S1, _In_ const BoundingSphere& S2) noexcept; _Out_ float& Dist) const noexcept;
// Ray-sphere test
static void CreateFromBoundingBox(_Out_ BoundingSphere& Out, _In_ const BoundingBox& box) noexcept;
static void CreateFromBoundingBox(_Out_ BoundingSphere& Out, _In_ const BoundingOrientedBox& box) noexcept; ContainmentType XM_CALLCONV
ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1,
static void CreateFromPoints(_Out_ BoundingSphere& Out, _In_ size_t Count, _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3,
_In_reads_bytes_(sizeof(XMFLOAT3) + Stride * (Count - 1)) const XMFLOAT3* pPoints, _In_ size_t Stride) noexcept; _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept;
// Test sphere against six planes (see BoundingFrustum::GetPlanes)
static void CreateFromFrustum(_Out_ BoundingSphere& Out, _In_ const BoundingFrustum& fr) noexcept;
}; // Static methods
static void CreateMerged(_Out_ BoundingSphere& Out,
//------------------------------------------------------------------------------------- _In_ const BoundingSphere& S1,
// Axis-aligned bounding box _In_ const BoundingSphere& S2) noexcept;
//-------------------------------------------------------------------------------------
struct BoundingBox static void CreateFromBoundingBox(_Out_ BoundingSphere& Out,
{ _In_ const BoundingBox& box) noexcept;
static constexpr size_t CORNER_COUNT = 8; static void CreateFromBoundingBox(
_Out_ BoundingSphere& Out,
XMFLOAT3 Center; // Center of the box. _In_ const BoundingOrientedBox& box) noexcept;
XMFLOAT3 Extents; // Distance from the center to each side.
static void CreateFromPoints(_Out_ BoundingSphere& Out, _In_ size_t Count,
// Creators _In_reads_bytes_(sizeof(XMFLOAT3) +
BoundingBox() noexcept : Center(0, 0, 0), Extents(1.f, 1.f, 1.f) {} Stride * (Count - 1))
const XMFLOAT3* pPoints,
BoundingBox(const BoundingBox&) = default; _In_ size_t Stride) noexcept;
BoundingBox& operator=(const BoundingBox&) = default;
static void CreateFromFrustum(_Out_ BoundingSphere& Out,
BoundingBox(BoundingBox&&) = default; _In_ const BoundingFrustum& fr) noexcept;
BoundingBox& operator=(BoundingBox&&) = default; };
constexpr BoundingBox(_In_ const XMFLOAT3& center, _In_ const XMFLOAT3& extents) noexcept //-------------------------------------------------------------------------------------
: Center(center), Extents(extents) {} // Axis-aligned bounding box
//-------------------------------------------------------------------------------------
// Methods struct BoundingBox {
void XM_CALLCONV Transform(_Out_ BoundingBox& Out, _In_ FXMMATRIX M) const noexcept; static constexpr size_t CORNER_COUNT = 8;
void XM_CALLCONV Transform(_Out_ BoundingBox& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept;
XMFLOAT3 Center; // Center of the box.
void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; XMFLOAT3 Extents; // Distance from the center to each side.
// Gets the 8 corners of the box
// Creators
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; BoundingBox() noexcept : Center(0, 0, 0), Extents(1.f, 1.f, 1.f) {}
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept;
ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; BoundingBox(const BoundingBox&) = default;
ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; BoundingBox& operator=(const BoundingBox&) = default;
ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept;
ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; BoundingBox(BoundingBox&&) = default;
BoundingBox& operator=(BoundingBox&&) = default;
bool Intersects(_In_ const BoundingSphere& sh) const noexcept;
bool Intersects(_In_ const BoundingBox& box) const noexcept; constexpr BoundingBox(_In_ const XMFLOAT3& center,
bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; _In_ const XMFLOAT3& extents) noexcept
bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; : Center(center), Extents(extents) {}
bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; // Methods
// Triangle-Box test void XM_CALLCONV Transform(_Out_ BoundingBox& Out,
_In_ FXMMATRIX M) const noexcept;
PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; void XM_CALLCONV Transform(_Out_ BoundingBox& Out, _In_ float Scale,
// Plane-box test _In_ FXMVECTOR Rotation,
_In_ FXMVECTOR Translation) const noexcept;
bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept;
// Ray-Box test void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept;
// Gets the 8 corners of the box
ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2,
_In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept;
// Test box against six planes (see BoundingFrustum::GetPlanes) ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1,
_In_ FXMVECTOR V2) const noexcept;
// Static methods ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept;
static void CreateMerged(_Out_ BoundingBox& Out, _In_ const BoundingBox& b1, _In_ const BoundingBox& b2) noexcept; ContainmentType Contains(_In_ const BoundingBox& box) const noexcept;
ContainmentType Contains(
static void CreateFromSphere(_Out_ BoundingBox& Out, _In_ const BoundingSphere& sh) noexcept; _In_ const BoundingOrientedBox& box) const noexcept;
ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept;
static void XM_CALLCONV CreateFromPoints(_Out_ BoundingBox& Out, _In_ FXMVECTOR pt1, _In_ FXMVECTOR pt2) noexcept;
static void CreateFromPoints(_Out_ BoundingBox& Out, _In_ size_t Count, bool Intersects(_In_ const BoundingSphere& sh) const noexcept;
_In_reads_bytes_(sizeof(XMFLOAT3) + Stride * (Count - 1)) const XMFLOAT3* pPoints, _In_ size_t Stride) noexcept; bool Intersects(_In_ const BoundingBox& box) const noexcept;
}; bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept;
bool Intersects(_In_ const BoundingFrustum& fr) const noexcept;
//-------------------------------------------------------------------------------------
// Oriented bounding box bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1,
//------------------------------------------------------------------------------------- _In_ FXMVECTOR V2) const noexcept;
struct BoundingOrientedBox // Triangle-Box test
{
static constexpr size_t CORNER_COUNT = 8; PlaneIntersectionType XM_CALLCONV
Intersects(_In_ FXMVECTOR Plane) const noexcept;
XMFLOAT3 Center; // Center of the box. // Plane-box test
XMFLOAT3 Extents; // Distance from the center to each side.
XMFLOAT4 Orientation; // Unit quaternion representing rotation (box -> world). bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction,
_Out_ float& Dist) const noexcept;
// Creators // Ray-Box test
BoundingOrientedBox() noexcept : Center(0, 0, 0), Extents(1.f, 1.f, 1.f), Orientation(0, 0, 0, 1.f) {}
ContainmentType XM_CALLCONV
BoundingOrientedBox(const BoundingOrientedBox&) = default; ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1,
BoundingOrientedBox& operator=(const BoundingOrientedBox&) = default; _In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3,
_In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept;
BoundingOrientedBox(BoundingOrientedBox&&) = default; // Test box against six planes (see BoundingFrustum::GetPlanes)
BoundingOrientedBox& operator=(BoundingOrientedBox&&) = default;
// Static methods
constexpr BoundingOrientedBox(_In_ const XMFLOAT3& center, _In_ const XMFLOAT3& extents, _In_ const XMFLOAT4& orientation) noexcept static void CreateMerged(_Out_ BoundingBox& Out, _In_ const BoundingBox& b1,
: Center(center), Extents(extents), Orientation(orientation) {} _In_ const BoundingBox& b2) noexcept;
// Methods static void CreateFromSphere(_Out_ BoundingBox& Out,
void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, _In_ FXMMATRIX M) const noexcept; _In_ const BoundingSphere& sh) noexcept;
void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept;
static void XM_CALLCONV CreateFromPoints(_Out_ BoundingBox& Out,
void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; _In_ FXMVECTOR pt1,
// Gets the 8 corners of the box _In_ FXMVECTOR pt2) noexcept;
static void CreateFromPoints(_Out_ BoundingBox& Out, _In_ size_t Count,
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; _In_reads_bytes_(sizeof(XMFLOAT3) +
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; Stride * (Count - 1))
ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept; const XMFLOAT3* pPoints,
ContainmentType Contains(_In_ const BoundingBox& box) const noexcept; _In_ size_t Stride) noexcept;
ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; };
ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept;
//-------------------------------------------------------------------------------------
bool Intersects(_In_ const BoundingSphere& sh) const noexcept; // Oriented bounding box
bool Intersects(_In_ const BoundingBox& box) const noexcept; //-------------------------------------------------------------------------------------
bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; struct BoundingOrientedBox {
bool Intersects(_In_ const BoundingFrustum& fr) const noexcept; static constexpr size_t CORNER_COUNT = 8;
bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; XMFLOAT3 Center; // Center of the box.
// Triangle-OrientedBox test XMFLOAT3 Extents; // Distance from the center to each side.
XMFLOAT4
PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; Orientation; // Unit quaternion representing rotation (box -> world).
// Plane-OrientedBox test
// Creators
bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; BoundingOrientedBox() noexcept
// Ray-OrientedBox test : Center(0, 0, 0), Extents(1.f, 1.f, 1.f), Orientation(0, 0, 0, 1.f) {}
ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, BoundingOrientedBox(const BoundingOrientedBox&) = default;
_In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; BoundingOrientedBox& operator=(const BoundingOrientedBox&) = default;
// Test OrientedBox against six planes (see BoundingFrustum::GetPlanes)
BoundingOrientedBox(BoundingOrientedBox&&) = default;
// Static methods BoundingOrientedBox& operator=(BoundingOrientedBox&&) = default;
static void CreateFromBoundingBox(_Out_ BoundingOrientedBox& Out, _In_ const BoundingBox& box) noexcept;
constexpr BoundingOrientedBox(_In_ const XMFLOAT3& center,
static void CreateFromPoints(_Out_ BoundingOrientedBox& Out, _In_ size_t Count, _In_ const XMFLOAT3& extents,
_In_reads_bytes_(sizeof(XMFLOAT3) + Stride * (Count - 1)) const XMFLOAT3* pPoints, _In_ size_t Stride) noexcept; _In_ const XMFLOAT4& orientation) noexcept
}; : Center(center), Extents(extents), Orientation(orientation) {}
//------------------------------------------------------------------------------------- // Methods
// Bounding frustum void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out,
//------------------------------------------------------------------------------------- _In_ FXMMATRIX M) const noexcept;
struct BoundingFrustum void XM_CALLCONV Transform(_Out_ BoundingOrientedBox& Out, _In_ float Scale,
{ _In_ FXMVECTOR Rotation,
static constexpr size_t CORNER_COUNT = 8; _In_ FXMVECTOR Translation) const noexcept;
XMFLOAT3 Origin; // Origin of the frustum (and projection). void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept;
XMFLOAT4 Orientation; // Quaternion representing rotation. // Gets the 8 corners of the box
float RightSlope; // Positive X (X/Z) ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept;
float LeftSlope; // Negative X ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1,
float TopSlope; // Positive Y (Y/Z) _In_ FXMVECTOR V2) const noexcept;
float BottomSlope; // Negative Y ContainmentType Contains(_In_ const BoundingSphere& sh) const noexcept;
float Near, Far; // Z of the near plane and far plane. ContainmentType Contains(_In_ const BoundingBox& box) const noexcept;
ContainmentType Contains(
// Creators _In_ const BoundingOrientedBox& box) const noexcept;
BoundingFrustum() noexcept : ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept;
Origin(0, 0, 0), Orientation(0, 0, 0, 1.f), RightSlope(1.f), LeftSlope(-1.f),
TopSlope(1.f), BottomSlope(-1.f), Near(0), Far(1.f) {} bool Intersects(_In_ const BoundingSphere& sh) const noexcept;
bool Intersects(_In_ const BoundingBox& box) const noexcept;
BoundingFrustum(const BoundingFrustum&) = default; bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept;
BoundingFrustum& operator=(const BoundingFrustum&) = default; bool Intersects(_In_ const BoundingFrustum& fr) const noexcept;
BoundingFrustum(BoundingFrustum&&) = default; bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1,
BoundingFrustum& operator=(BoundingFrustum&&) = default; _In_ FXMVECTOR V2) const noexcept;
// Triangle-OrientedBox test
constexpr BoundingFrustum(_In_ const XMFLOAT3& origin, _In_ const XMFLOAT4& orientation,
_In_ float rightSlope, _In_ float leftSlope, _In_ float topSlope, _In_ float bottomSlope, PlaneIntersectionType XM_CALLCONV
_In_ float nearPlane, _In_ float farPlane) noexcept Intersects(_In_ FXMVECTOR Plane) const noexcept;
: Origin(origin), Orientation(orientation), // Plane-OrientedBox test
RightSlope(rightSlope), LeftSlope(leftSlope), TopSlope(topSlope), BottomSlope(bottomSlope),
Near(nearPlane), Far(farPlane) {} bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction,
BoundingFrustum(_In_ CXMMATRIX Projection, bool rhcoords = false) noexcept; _Out_ float& Dist) const noexcept;
// Ray-OrientedBox test
// Methods
void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, _In_ FXMMATRIX M) const noexcept; ContainmentType XM_CALLCONV
void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, _In_ float Scale, _In_ FXMVECTOR Rotation, _In_ FXMVECTOR Translation) const noexcept; ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1,
_In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3,
void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept; _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept;
// Gets the 8 corners of the frustum // Test OrientedBox against six planes (see BoundingFrustum::GetPlanes)
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept; // Static methods
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; static void CreateFromBoundingBox(_Out_ BoundingOrientedBox& Out,
ContainmentType Contains(_In_ const BoundingSphere& sp) const noexcept; _In_ const BoundingBox& box) noexcept;
ContainmentType Contains(_In_ const BoundingBox& box) const noexcept;
ContainmentType Contains(_In_ const BoundingOrientedBox& box) const noexcept; static void CreateFromPoints(_Out_ BoundingOrientedBox& Out,
ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept; _In_ size_t Count,
// Frustum-Frustum test _In_reads_bytes_(sizeof(XMFLOAT3) +
Stride * (Count - 1))
bool Intersects(_In_ const BoundingSphere& sh) const noexcept; const XMFLOAT3* pPoints,
bool Intersects(_In_ const BoundingBox& box) const noexcept; _In_ size_t Stride) noexcept;
bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept; };
bool Intersects(_In_ const BoundingFrustum& fr) const noexcept;
//-------------------------------------------------------------------------------------
bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2) const noexcept; // Bounding frustum
// Triangle-Frustum test //-------------------------------------------------------------------------------------
struct BoundingFrustum {
PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR Plane) const noexcept; static constexpr size_t CORNER_COUNT = 8;
// Plane-Frustum test
XMFLOAT3 Origin; // Origin of the frustum (and projection).
bool XM_CALLCONV Intersects(_In_ FXMVECTOR rayOrigin, _In_ FXMVECTOR Direction, _Out_ float& Dist) const noexcept; XMFLOAT4 Orientation; // Quaternion representing rotation.
// Ray-Frustum test
float RightSlope; // Positive X (X/Z)
ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1, _In_ FXMVECTOR Plane2, float LeftSlope; // Negative X
_In_ GXMVECTOR Plane3, _In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept; float TopSlope; // Positive Y (Y/Z)
// Test frustum against six planes (see BoundingFrustum::GetPlanes) float BottomSlope; // Negative Y
float Near, Far; // Z of the near plane and far plane.
void GetPlanes(_Out_opt_ XMVECTOR* NearPlane, _Out_opt_ XMVECTOR* FarPlane, _Out_opt_ XMVECTOR* RightPlane,
_Out_opt_ XMVECTOR* LeftPlane, _Out_opt_ XMVECTOR* TopPlane, _Out_opt_ XMVECTOR* BottomPlane) const noexcept; // Creators
// Create 6 Planes representation of Frustum BoundingFrustum() noexcept
: Origin(0, 0, 0),
// Static methods Orientation(0, 0, 0, 1.f),
static void XM_CALLCONV CreateFromMatrix(_Out_ BoundingFrustum& Out, _In_ FXMMATRIX Projection, bool rhcoords = false) noexcept; RightSlope(1.f),
}; LeftSlope(-1.f),
TopSlope(1.f),
//----------------------------------------------------------------------------- BottomSlope(-1.f),
// Triangle intersection testing routines. Near(0),
//----------------------------------------------------------------------------- Far(1.f) {}
namespace TriangleTests
{ BoundingFrustum(const BoundingFrustum&) = default;
bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction, _In_ FXMVECTOR V0, _In_ GXMVECTOR V1, _In_ HXMVECTOR V2, _Out_ float& Dist) noexcept; BoundingFrustum& operator=(const BoundingFrustum&) = default;
// Ray-Triangle
BoundingFrustum(BoundingFrustum&&) = default;
bool XM_CALLCONV Intersects(_In_ FXMVECTOR A0, _In_ FXMVECTOR A1, _In_ FXMVECTOR A2, _In_ GXMVECTOR B0, _In_ HXMVECTOR B1, _In_ HXMVECTOR B2) noexcept; BoundingFrustum& operator=(BoundingFrustum&&) = default;
// Triangle-Triangle
constexpr BoundingFrustum(_In_ const XMFLOAT3& origin,
PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2, _In_ GXMVECTOR Plane) noexcept; _In_ const XMFLOAT4& orientation,
// Plane-Triangle _In_ float rightSlope, _In_ float leftSlope,
_In_ float topSlope, _In_ float bottomSlope,
ContainmentType XM_CALLCONV ContainedBy(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2, _In_ float nearPlane,
_In_ float farPlane) noexcept
: Origin(origin),
Orientation(orientation),
RightSlope(rightSlope),
LeftSlope(leftSlope),
TopSlope(topSlope),
BottomSlope(bottomSlope),
Near(nearPlane),
Far(farPlane) {}
BoundingFrustum(_In_ CXMMATRIX Projection, bool rhcoords = false) noexcept;
// Methods
void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out,
_In_ FXMMATRIX M) const noexcept;
void XM_CALLCONV Transform(_Out_ BoundingFrustum& Out, _In_ float Scale,
_In_ FXMVECTOR Rotation,
_In_ FXMVECTOR Translation) const noexcept;
void GetCorners(_Out_writes_(8) XMFLOAT3* Corners) const noexcept;
// Gets the 8 corners of the frustum
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR Point) const noexcept;
ContainmentType XM_CALLCONV Contains(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1,
_In_ FXMVECTOR V2) const noexcept;
ContainmentType Contains(_In_ const BoundingSphere& sp) const noexcept;
ContainmentType Contains(_In_ const BoundingBox& box) const noexcept;
ContainmentType Contains(
_In_ const BoundingOrientedBox& box) const noexcept;
ContainmentType Contains(_In_ const BoundingFrustum& fr) const noexcept;
// Frustum-Frustum test
bool Intersects(_In_ const BoundingSphere& sh) const noexcept;
bool Intersects(_In_ const BoundingBox& box) const noexcept;
bool Intersects(_In_ const BoundingOrientedBox& box) const noexcept;
bool Intersects(_In_ const BoundingFrustum& fr) const noexcept;
bool XM_CALLCONV Intersects(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1,
_In_ FXMVECTOR V2) const noexcept;
// Triangle-Frustum test
PlaneIntersectionType XM_CALLCONV
Intersects(_In_ FXMVECTOR Plane) const noexcept;
// Plane-Frustum test
bool XM_CALLCONV Intersects(_In_ FXMVECTOR rayOrigin,
_In_ FXMVECTOR Direction,
_Out_ float& Dist) const noexcept;
// Ray-Frustum test
ContainmentType XM_CALLCONV
ContainedBy(_In_ FXMVECTOR Plane0, _In_ FXMVECTOR Plane1,
_In_ FXMVECTOR Plane2, _In_ GXMVECTOR Plane3,
_In_ HXMVECTOR Plane4, _In_ HXMVECTOR Plane5) const noexcept;
// Test frustum against six planes (see BoundingFrustum::GetPlanes)
void GetPlanes(_Out_opt_ XMVECTOR* NearPlane, _Out_opt_ XMVECTOR* FarPlane,
_Out_opt_ XMVECTOR* RightPlane,
_Out_opt_ XMVECTOR* LeftPlane, _Out_opt_ XMVECTOR* TopPlane,
_Out_opt_ XMVECTOR* BottomPlane) const noexcept;
// Create 6 Planes representation of Frustum
// Static methods
static void XM_CALLCONV CreateFromMatrix(_Out_ BoundingFrustum& Out,
_In_ FXMMATRIX Projection,
bool rhcoords = false) noexcept;
};
//-----------------------------------------------------------------------------
// Triangle intersection testing routines.
//-----------------------------------------------------------------------------
namespace TriangleTests {
bool XM_CALLCONV Intersects(_In_ FXMVECTOR Origin, _In_ FXMVECTOR Direction,
_In_ FXMVECTOR V0, _In_ GXMVECTOR V1,
_In_ HXMVECTOR V2, _Out_ float& Dist) noexcept;
// Ray-Triangle
bool XM_CALLCONV Intersects(_In_ FXMVECTOR A0, _In_ FXMVECTOR A1,
_In_ FXMVECTOR A2, _In_ GXMVECTOR B0,
_In_ HXMVECTOR B1, _In_ HXMVECTOR B2) noexcept;
// Triangle-Triangle
PlaneIntersectionType XM_CALLCONV Intersects(_In_ FXMVECTOR V0,
_In_ FXMVECTOR V1,
_In_ FXMVECTOR V2,
_In_ GXMVECTOR Plane) noexcept;
// Plane-Triangle
ContainmentType XM_CALLCONV
ContainedBy(_In_ FXMVECTOR V0, _In_ FXMVECTOR V1, _In_ FXMVECTOR V2,
_In_ GXMVECTOR Plane0, _In_ HXMVECTOR Plane1, _In_ HXMVECTOR Plane2, _In_ GXMVECTOR Plane0, _In_ HXMVECTOR Plane1, _In_ HXMVECTOR Plane2,
_In_ CXMVECTOR Plane3, _In_ CXMVECTOR Plane4, _In_ CXMVECTOR Plane5) noexcept; _In_ CXMVECTOR Plane3, _In_ CXMVECTOR Plane4,
// Test a triangle against six planes at once (see BoundingFrustum::GetPlanes) _In_ CXMVECTOR Plane5) noexcept;
} // Test a triangle against six planes at once (see BoundingFrustum::GetPlanes)
} // namespace TriangleTests
#ifdef _MSC_VER #ifdef _MSC_VER
#pragma warning(pop) #pragma warning(pop)
#endif #endif
/**************************************************************************** /****************************************************************************
* *
* Implementation * Implementation
* *
****************************************************************************/ ****************************************************************************/
#ifdef _MSC_VER #ifdef _MSC_VER
#pragma warning(push) #pragma warning(push)
#pragma warning(disable : 4068 4365 4616 6001) #pragma warning(disable : 4068 4365 4616 6001)
// C4068/4616: ignore unknown pragmas // C4068/4616: ignore unknown pragmas
// C4365: Off by default noise // C4365: Off by default noise
// C6001: False positives // C6001: False positives
#endif #endif
#ifdef _PREFAST_ #ifdef _PREFAST_
@ -366,5 +445,4 @@ namespace DirectX
#pragma warning(pop) #pragma warning(pop)
#endif #endif
} // namespace DirectX } // namespace DirectX

View file

@ -11,302 +11,490 @@
#include "DirectXMath.h" #include "DirectXMath.h"
namespace DirectX namespace DirectX {
{
namespace Colors namespace Colors {
{ // Standard colors (Red/Green/Blue/Alpha) in sRGB colorspace
// Standard colors (Red/Green/Blue/Alpha) in sRGB colorspace XMGLOBALCONST XMVECTORF32 AliceBlue = {
XMGLOBALCONST XMVECTORF32 AliceBlue = { { { 0.941176534f, 0.972549081f, 1.f, 1.f } } }; {{0.941176534f, 0.972549081f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 AntiqueWhite = { { { 0.980392218f, 0.921568692f, 0.843137324f, 1.f } } }; XMGLOBALCONST XMVECTORF32 AntiqueWhite = {
XMGLOBALCONST XMVECTORF32 Aqua = { { { 0.f, 1.f, 1.f, 1.f } } }; {{0.980392218f, 0.921568692f, 0.843137324f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Aquamarine = { { { 0.498039246f, 1.f, 0.831372619f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Aqua = {{{0.f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Azure = { { { 0.941176534f, 1.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Aquamarine = {
XMGLOBALCONST XMVECTORF32 Beige = { { { 0.960784376f, 0.960784376f, 0.862745166f, 1.f } } }; {{0.498039246f, 1.f, 0.831372619f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Bisque = { { { 1.f, 0.894117713f, 0.768627524f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Azure = {{{0.941176534f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Black = { { { 0.f, 0.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Beige = {
XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { { { 1.f, 0.921568692f, 0.803921640f, 1.f } } }; {{0.960784376f, 0.960784376f, 0.862745166f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Blue = { { { 0.f, 0.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Bisque = {{{1.f, 0.894117713f, 0.768627524f, 1.f}}};
XMGLOBALCONST XMVECTORF32 BlueViolet = { { { 0.541176498f, 0.168627456f, 0.886274576f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Black = {{{0.f, 0.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Brown = { { { 0.647058845f, 0.164705887f, 0.164705887f, 1.f } } }; XMGLOBALCONST XMVECTORF32 BlanchedAlmond = {
XMGLOBALCONST XMVECTORF32 BurlyWood = { { { 0.870588303f, 0.721568644f, 0.529411793f, 1.f } } }; {{1.f, 0.921568692f, 0.803921640f, 1.f}}};
XMGLOBALCONST XMVECTORF32 CadetBlue = { { { 0.372549027f, 0.619607866f, 0.627451003f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Blue = {{{0.f, 0.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Chartreuse = { { { 0.498039246f, 1.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 BlueViolet = {
XMGLOBALCONST XMVECTORF32 Chocolate = { { { 0.823529482f, 0.411764741f, 0.117647067f, 1.f } } }; {{0.541176498f, 0.168627456f, 0.886274576f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Coral = { { { 1.f, 0.498039246f, 0.313725501f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Brown = {
XMGLOBALCONST XMVECTORF32 CornflowerBlue = { { { 0.392156899f, 0.584313750f, 0.929411829f, 1.f } } }; {{0.647058845f, 0.164705887f, 0.164705887f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Cornsilk = { { { 1.f, 0.972549081f, 0.862745166f, 1.f } } }; XMGLOBALCONST XMVECTORF32 BurlyWood = {
XMGLOBALCONST XMVECTORF32 Crimson = { { { 0.862745166f, 0.078431375f, 0.235294133f, 1.f } } }; {{0.870588303f, 0.721568644f, 0.529411793f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Cyan = { { { 0.f, 1.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 CadetBlue = {
XMGLOBALCONST XMVECTORF32 DarkBlue = { { { 0.f, 0.f, 0.545098066f, 1.f } } }; {{0.372549027f, 0.619607866f, 0.627451003f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkCyan = { { { 0.f, 0.545098066f, 0.545098066f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Chartreuse = {{{0.498039246f, 1.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { { { 0.721568644f, 0.525490224f, 0.043137256f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Chocolate = {
XMGLOBALCONST XMVECTORF32 DarkGray = { { { 0.662745118f, 0.662745118f, 0.662745118f, 1.f } } }; {{0.823529482f, 0.411764741f, 0.117647067f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkGreen = { { { 0.f, 0.392156899f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Coral = {{{1.f, 0.498039246f, 0.313725501f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkKhaki = { { { 0.741176486f, 0.717647076f, 0.419607878f, 1.f } } }; XMGLOBALCONST XMVECTORF32 CornflowerBlue = {
XMGLOBALCONST XMVECTORF32 DarkMagenta = { { { 0.545098066f, 0.f, 0.545098066f, 1.f } } }; {{0.392156899f, 0.584313750f, 0.929411829f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { { { 0.333333343f, 0.419607878f, 0.184313729f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Cornsilk = {{{1.f, 0.972549081f, 0.862745166f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkOrange = { { { 1.f, 0.549019635f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Crimson = {
XMGLOBALCONST XMVECTORF32 DarkOrchid = { { { 0.600000024f, 0.196078449f, 0.800000072f, 1.f } } }; {{0.862745166f, 0.078431375f, 0.235294133f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkRed = { { { 0.545098066f, 0.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Cyan = {{{0.f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkSalmon = { { { 0.913725555f, 0.588235319f, 0.478431404f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkBlue = {{{0.f, 0.f, 0.545098066f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { { { 0.560784340f, 0.737254918f, 0.545098066f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkCyan = {{{0.f, 0.545098066f, 0.545098066f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { { { 0.282352954f, 0.239215702f, 0.545098066f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkGoldenrod = {
XMGLOBALCONST XMVECTORF32 DarkSlateGray = { { { 0.184313729f, 0.309803933f, 0.309803933f, 1.f } } }; {{0.721568644f, 0.525490224f, 0.043137256f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkTurquoise = { { { 0.f, 0.807843208f, 0.819607913f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkGray = {
XMGLOBALCONST XMVECTORF32 DarkViolet = { { { 0.580392182f, 0.f, 0.827451050f, 1.f } } }; {{0.662745118f, 0.662745118f, 0.662745118f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DeepPink = { { { 1.f, 0.078431375f, 0.576470613f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkGreen = {{{0.f, 0.392156899f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DeepSkyBlue = { { { 0.f, 0.749019623f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkKhaki = {
XMGLOBALCONST XMVECTORF32 DimGray = { { { 0.411764741f, 0.411764741f, 0.411764741f, 1.f } } }; {{0.741176486f, 0.717647076f, 0.419607878f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DodgerBlue = { { { 0.117647067f, 0.564705908f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkMagenta = {
XMGLOBALCONST XMVECTORF32 Firebrick = { { { 0.698039234f, 0.133333340f, 0.133333340f, 1.f } } }; {{0.545098066f, 0.f, 0.545098066f, 1.f}}};
XMGLOBALCONST XMVECTORF32 FloralWhite = { { { 1.f, 0.980392218f, 0.941176534f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkOliveGreen = {
XMGLOBALCONST XMVECTORF32 ForestGreen = { { { 0.133333340f, 0.545098066f, 0.133333340f, 1.f } } }; {{0.333333343f, 0.419607878f, 0.184313729f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Fuchsia = { { { 1.f, 0.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkOrange = {{{1.f, 0.549019635f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Gainsboro = { { { 0.862745166f, 0.862745166f, 0.862745166f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkOrchid = {
XMGLOBALCONST XMVECTORF32 GhostWhite = { { { 0.972549081f, 0.972549081f, 1.f, 1.f } } }; {{0.600000024f, 0.196078449f, 0.800000072f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Gold = { { { 1.f, 0.843137324f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkRed = {{{0.545098066f, 0.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Goldenrod = { { { 0.854902029f, 0.647058845f, 0.125490203f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkSalmon = {
XMGLOBALCONST XMVECTORF32 Gray = { { { 0.501960814f, 0.501960814f, 0.501960814f, 1.f } } }; {{0.913725555f, 0.588235319f, 0.478431404f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Green = { { { 0.f, 0.501960814f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkSeaGreen = {
XMGLOBALCONST XMVECTORF32 GreenYellow = { { { 0.678431392f, 1.f, 0.184313729f, 1.f } } }; {{0.560784340f, 0.737254918f, 0.545098066f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Honeydew = { { { 0.941176534f, 1.f, 0.941176534f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkSlateBlue = {
XMGLOBALCONST XMVECTORF32 HotPink = { { { 1.f, 0.411764741f, 0.705882370f, 1.f } } }; {{0.282352954f, 0.239215702f, 0.545098066f, 1.f}}};
XMGLOBALCONST XMVECTORF32 IndianRed = { { { 0.803921640f, 0.360784322f, 0.360784322f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkSlateGray = {
XMGLOBALCONST XMVECTORF32 Indigo = { { { 0.294117659f, 0.f, 0.509803951f, 1.f } } }; {{0.184313729f, 0.309803933f, 0.309803933f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Ivory = { { { 1.f, 1.f, 0.941176534f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkTurquoise = {
XMGLOBALCONST XMVECTORF32 Khaki = { { { 0.941176534f, 0.901960850f, 0.549019635f, 1.f } } }; {{0.f, 0.807843208f, 0.819607913f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Lavender = { { { 0.901960850f, 0.901960850f, 0.980392218f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkViolet = {
XMGLOBALCONST XMVECTORF32 LavenderBlush = { { { 1.f, 0.941176534f, 0.960784376f, 1.f } } }; {{0.580392182f, 0.f, 0.827451050f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LawnGreen = { { { 0.486274540f, 0.988235354f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DeepPink = {{{1.f, 0.078431375f, 0.576470613f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LemonChiffon = { { { 1.f, 0.980392218f, 0.803921640f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DeepSkyBlue = {{{0.f, 0.749019623f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightBlue = { { { 0.678431392f, 0.847058892f, 0.901960850f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DimGray = {
XMGLOBALCONST XMVECTORF32 LightCoral = { { { 0.941176534f, 0.501960814f, 0.501960814f, 1.f } } }; {{0.411764741f, 0.411764741f, 0.411764741f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightCyan = { { { 0.878431439f, 1.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DodgerBlue = {
XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { { { 0.980392218f, 0.980392218f, 0.823529482f, 1.f } } }; {{0.117647067f, 0.564705908f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightGray = { { { 0.827451050f, 0.827451050f, 0.827451050f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Firebrick = {
XMGLOBALCONST XMVECTORF32 LightGreen = { { { 0.564705908f, 0.933333397f, 0.564705908f, 1.f } } }; {{0.698039234f, 0.133333340f, 0.133333340f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightPink = { { { 1.f, 0.713725507f, 0.756862819f, 1.f } } }; XMGLOBALCONST XMVECTORF32 FloralWhite = {
XMGLOBALCONST XMVECTORF32 LightSalmon = { { { 1.f, 0.627451003f, 0.478431404f, 1.f } } }; {{1.f, 0.980392218f, 0.941176534f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightSeaGreen = { { { 0.125490203f, 0.698039234f, 0.666666687f, 1.f } } }; XMGLOBALCONST XMVECTORF32 ForestGreen = {
XMGLOBALCONST XMVECTORF32 LightSkyBlue = { { { 0.529411793f, 0.807843208f, 0.980392218f, 1.f } } }; {{0.133333340f, 0.545098066f, 0.133333340f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightSlateGray = { { { 0.466666698f, 0.533333361f, 0.600000024f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Fuchsia = {{{1.f, 0.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightSteelBlue = { { { 0.690196097f, 0.768627524f, 0.870588303f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Gainsboro = {
XMGLOBALCONST XMVECTORF32 LightYellow = { { { 1.f, 1.f, 0.878431439f, 1.f } } }; {{0.862745166f, 0.862745166f, 0.862745166f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Lime = { { { 0.f, 1.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 GhostWhite = {
XMGLOBALCONST XMVECTORF32 LimeGreen = { { { 0.196078449f, 0.803921640f, 0.196078449f, 1.f } } }; {{0.972549081f, 0.972549081f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Linen = { { { 0.980392218f, 0.941176534f, 0.901960850f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Gold = {{{1.f, 0.843137324f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Magenta = { { { 1.f, 0.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Goldenrod = {
XMGLOBALCONST XMVECTORF32 Maroon = { { { 0.501960814f, 0.f, 0.f, 1.f } } }; {{0.854902029f, 0.647058845f, 0.125490203f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumAquamarine = { { { 0.400000036f, 0.803921640f, 0.666666687f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Gray = {
XMGLOBALCONST XMVECTORF32 MediumBlue = { { { 0.f, 0.f, 0.803921640f, 1.f } } }; {{0.501960814f, 0.501960814f, 0.501960814f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumOrchid = { { { 0.729411781f, 0.333333343f, 0.827451050f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Green = {{{0.f, 0.501960814f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumPurple = { { { 0.576470613f, 0.439215720f, 0.858823597f, 1.f } } }; XMGLOBALCONST XMVECTORF32 GreenYellow = {
XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { { { 0.235294133f, 0.701960802f, 0.443137288f, 1.f } } }; {{0.678431392f, 1.f, 0.184313729f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { { { 0.482352972f, 0.407843173f, 0.933333397f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Honeydew = {{{0.941176534f, 1.f, 0.941176534f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { { { 0.f, 0.980392218f, 0.603921592f, 1.f } } }; XMGLOBALCONST XMVECTORF32 HotPink = {{{1.f, 0.411764741f, 0.705882370f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumTurquoise = { { { 0.282352954f, 0.819607913f, 0.800000072f, 1.f } } }; XMGLOBALCONST XMVECTORF32 IndianRed = {
XMGLOBALCONST XMVECTORF32 MediumVioletRed = { { { 0.780392230f, 0.082352944f, 0.521568656f, 1.f } } }; {{0.803921640f, 0.360784322f, 0.360784322f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MidnightBlue = { { { 0.098039225f, 0.098039225f, 0.439215720f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Indigo = {{{0.294117659f, 0.f, 0.509803951f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MintCream = { { { 0.960784376f, 1.f, 0.980392218f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Ivory = {{{1.f, 1.f, 0.941176534f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MistyRose = { { { 1.f, 0.894117713f, 0.882353008f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Khaki = {
XMGLOBALCONST XMVECTORF32 Moccasin = { { { 1.f, 0.894117713f, 0.709803939f, 1.f } } }; {{0.941176534f, 0.901960850f, 0.549019635f, 1.f}}};
XMGLOBALCONST XMVECTORF32 NavajoWhite = { { { 1.f, 0.870588303f, 0.678431392f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Lavender = {
XMGLOBALCONST XMVECTORF32 Navy = { { { 0.f, 0.f, 0.501960814f, 1.f } } }; {{0.901960850f, 0.901960850f, 0.980392218f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OldLace = { { { 0.992156923f, 0.960784376f, 0.901960850f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LavenderBlush = {
XMGLOBALCONST XMVECTORF32 Olive = { { { 0.501960814f, 0.501960814f, 0.f, 1.f } } }; {{1.f, 0.941176534f, 0.960784376f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OliveDrab = { { { 0.419607878f, 0.556862772f, 0.137254909f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LawnGreen = {
XMGLOBALCONST XMVECTORF32 Orange = { { { 1.f, 0.647058845f, 0.f, 1.f } } }; {{0.486274540f, 0.988235354f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OrangeRed = { { { 1.f, 0.270588249f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LemonChiffon = {
XMGLOBALCONST XMVECTORF32 Orchid = { { { 0.854902029f, 0.439215720f, 0.839215755f, 1.f } } }; {{1.f, 0.980392218f, 0.803921640f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { { { 0.933333397f, 0.909803987f, 0.666666687f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightBlue = {
XMGLOBALCONST XMVECTORF32 PaleGreen = { { { 0.596078455f, 0.984313786f, 0.596078455f, 1.f } } }; {{0.678431392f, 0.847058892f, 0.901960850f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleTurquoise = { { { 0.686274529f, 0.933333397f, 0.933333397f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightCoral = {
XMGLOBALCONST XMVECTORF32 PaleVioletRed = { { { 0.858823597f, 0.439215720f, 0.576470613f, 1.f } } }; {{0.941176534f, 0.501960814f, 0.501960814f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PapayaWhip = { { { 1.f, 0.937254965f, 0.835294187f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightCyan = {{{0.878431439f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PeachPuff = { { { 1.f, 0.854902029f, 0.725490212f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = {
XMGLOBALCONST XMVECTORF32 Peru = { { { 0.803921640f, 0.521568656f, 0.247058839f, 1.f } } }; {{0.980392218f, 0.980392218f, 0.823529482f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Pink = { { { 1.f, 0.752941251f, 0.796078503f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightGray = {
XMGLOBALCONST XMVECTORF32 Plum = { { { 0.866666734f, 0.627451003f, 0.866666734f, 1.f } } }; {{0.827451050f, 0.827451050f, 0.827451050f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PowderBlue = { { { 0.690196097f, 0.878431439f, 0.901960850f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightGreen = {
XMGLOBALCONST XMVECTORF32 Purple = { { { 0.501960814f, 0.f, 0.501960814f, 1.f } } }; {{0.564705908f, 0.933333397f, 0.564705908f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Red = { { { 1.f, 0.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightPink = {
XMGLOBALCONST XMVECTORF32 RosyBrown = { { { 0.737254918f, 0.560784340f, 0.560784340f, 1.f } } }; {{1.f, 0.713725507f, 0.756862819f, 1.f}}};
XMGLOBALCONST XMVECTORF32 RoyalBlue = { { { 0.254901975f, 0.411764741f, 0.882353008f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSalmon = {
XMGLOBALCONST XMVECTORF32 SaddleBrown = { { { 0.545098066f, 0.270588249f, 0.074509807f, 1.f } } }; {{1.f, 0.627451003f, 0.478431404f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Salmon = { { { 0.980392218f, 0.501960814f, 0.447058856f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSeaGreen = {
XMGLOBALCONST XMVECTORF32 SandyBrown = { { { 0.956862807f, 0.643137276f, 0.376470625f, 1.f } } }; {{0.125490203f, 0.698039234f, 0.666666687f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SeaGreen = { { { 0.180392161f, 0.545098066f, 0.341176480f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSkyBlue = {
XMGLOBALCONST XMVECTORF32 SeaShell = { { { 1.f, 0.960784376f, 0.933333397f, 1.f } } }; {{0.529411793f, 0.807843208f, 0.980392218f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Sienna = { { { 0.627451003f, 0.321568638f, 0.176470593f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSlateGray = {
XMGLOBALCONST XMVECTORF32 Silver = { { { 0.752941251f, 0.752941251f, 0.752941251f, 1.f } } }; {{0.466666698f, 0.533333361f, 0.600000024f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SkyBlue = { { { 0.529411793f, 0.807843208f, 0.921568692f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSteelBlue = {
XMGLOBALCONST XMVECTORF32 SlateBlue = { { { 0.415686309f, 0.352941185f, 0.803921640f, 1.f } } }; {{0.690196097f, 0.768627524f, 0.870588303f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SlateGray = { { { 0.439215720f, 0.501960814f, 0.564705908f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightYellow = {{{1.f, 1.f, 0.878431439f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Snow = { { { 1.f, 0.980392218f, 0.980392218f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Lime = {{{0.f, 1.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SpringGreen = { { { 0.f, 1.f, 0.498039246f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LimeGreen = {
XMGLOBALCONST XMVECTORF32 SteelBlue = { { { 0.274509817f, 0.509803951f, 0.705882370f, 1.f } } }; {{0.196078449f, 0.803921640f, 0.196078449f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Tan = { { { 0.823529482f, 0.705882370f, 0.549019635f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Linen = {
XMGLOBALCONST XMVECTORF32 Teal = { { { 0.f, 0.501960814f, 0.501960814f, 1.f } } }; {{0.980392218f, 0.941176534f, 0.901960850f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Thistle = { { { 0.847058892f, 0.749019623f, 0.847058892f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Magenta = {{{1.f, 0.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Tomato = { { { 1.f, 0.388235331f, 0.278431386f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Maroon = {{{0.501960814f, 0.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Transparent = { { { 0.f, 0.f, 0.f, 0.f } } }; XMGLOBALCONST XMVECTORF32 MediumAquamarine = {
XMGLOBALCONST XMVECTORF32 Turquoise = { { { 0.250980407f, 0.878431439f, 0.815686345f, 1.f } } }; {{0.400000036f, 0.803921640f, 0.666666687f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Violet = { { { 0.933333397f, 0.509803951f, 0.933333397f, 1.f } } }; XMGLOBALCONST XMVECTORF32 MediumBlue = {{{0.f, 0.f, 0.803921640f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Wheat = { { { 0.960784376f, 0.870588303f, 0.701960802f, 1.f } } }; XMGLOBALCONST XMVECTORF32 MediumOrchid = {
XMGLOBALCONST XMVECTORF32 White = { { { 1.f, 1.f, 1.f, 1.f } } }; {{0.729411781f, 0.333333343f, 0.827451050f, 1.f}}};
XMGLOBALCONST XMVECTORF32 WhiteSmoke = { { { 0.960784376f, 0.960784376f, 0.960784376f, 1.f } } }; XMGLOBALCONST XMVECTORF32 MediumPurple = {
XMGLOBALCONST XMVECTORF32 Yellow = { { { 1.f, 1.f, 0.f, 1.f } } }; {{0.576470613f, 0.439215720f, 0.858823597f, 1.f}}};
XMGLOBALCONST XMVECTORF32 YellowGreen = { { { 0.603921592f, 0.803921640f, 0.196078449f, 1.f } } }; XMGLOBALCONST XMVECTORF32 MediumSeaGreen = {
{{0.235294133f, 0.701960802f, 0.443137288f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumSlateBlue = {
{{0.482352972f, 0.407843173f, 0.933333397f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumSpringGreen = {
{{0.f, 0.980392218f, 0.603921592f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumTurquoise = {
{{0.282352954f, 0.819607913f, 0.800000072f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumVioletRed = {
{{0.780392230f, 0.082352944f, 0.521568656f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MidnightBlue = {
{{0.098039225f, 0.098039225f, 0.439215720f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MintCream = {
{{0.960784376f, 1.f, 0.980392218f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MistyRose = {
{{1.f, 0.894117713f, 0.882353008f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Moccasin = {{{1.f, 0.894117713f, 0.709803939f, 1.f}}};
XMGLOBALCONST XMVECTORF32 NavajoWhite = {
{{1.f, 0.870588303f, 0.678431392f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Navy = {{{0.f, 0.f, 0.501960814f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OldLace = {
{{0.992156923f, 0.960784376f, 0.901960850f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Olive = {{{0.501960814f, 0.501960814f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OliveDrab = {
{{0.419607878f, 0.556862772f, 0.137254909f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Orange = {{{1.f, 0.647058845f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OrangeRed = {{{1.f, 0.270588249f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Orchid = {
{{0.854902029f, 0.439215720f, 0.839215755f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleGoldenrod = {
{{0.933333397f, 0.909803987f, 0.666666687f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleGreen = {
{{0.596078455f, 0.984313786f, 0.596078455f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleTurquoise = {
{{0.686274529f, 0.933333397f, 0.933333397f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleVioletRed = {
{{0.858823597f, 0.439215720f, 0.576470613f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PapayaWhip = {
{{1.f, 0.937254965f, 0.835294187f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PeachPuff = {
{{1.f, 0.854902029f, 0.725490212f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Peru = {
{{0.803921640f, 0.521568656f, 0.247058839f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Pink = {{{1.f, 0.752941251f, 0.796078503f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Plum = {
{{0.866666734f, 0.627451003f, 0.866666734f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PowderBlue = {
{{0.690196097f, 0.878431439f, 0.901960850f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Purple = {{{0.501960814f, 0.f, 0.501960814f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Red = {{{1.f, 0.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 RosyBrown = {
{{0.737254918f, 0.560784340f, 0.560784340f, 1.f}}};
XMGLOBALCONST XMVECTORF32 RoyalBlue = {
{{0.254901975f, 0.411764741f, 0.882353008f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SaddleBrown = {
{{0.545098066f, 0.270588249f, 0.074509807f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Salmon = {
{{0.980392218f, 0.501960814f, 0.447058856f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SandyBrown = {
{{0.956862807f, 0.643137276f, 0.376470625f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SeaGreen = {
{{0.180392161f, 0.545098066f, 0.341176480f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SeaShell = {{{1.f, 0.960784376f, 0.933333397f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Sienna = {
{{0.627451003f, 0.321568638f, 0.176470593f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Silver = {
{{0.752941251f, 0.752941251f, 0.752941251f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SkyBlue = {
{{0.529411793f, 0.807843208f, 0.921568692f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SlateBlue = {
{{0.415686309f, 0.352941185f, 0.803921640f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SlateGray = {
{{0.439215720f, 0.501960814f, 0.564705908f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Snow = {{{1.f, 0.980392218f, 0.980392218f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SpringGreen = {{{0.f, 1.f, 0.498039246f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SteelBlue = {
{{0.274509817f, 0.509803951f, 0.705882370f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Tan = {
{{0.823529482f, 0.705882370f, 0.549019635f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Teal = {{{0.f, 0.501960814f, 0.501960814f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Thistle = {
{{0.847058892f, 0.749019623f, 0.847058892f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Tomato = {{{1.f, 0.388235331f, 0.278431386f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Transparent = {{{0.f, 0.f, 0.f, 0.f}}};
XMGLOBALCONST XMVECTORF32 Turquoise = {
{{0.250980407f, 0.878431439f, 0.815686345f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Violet = {
{{0.933333397f, 0.509803951f, 0.933333397f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Wheat = {
{{0.960784376f, 0.870588303f, 0.701960802f, 1.f}}};
XMGLOBALCONST XMVECTORF32 White = {{{1.f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 WhiteSmoke = {
{{0.960784376f, 0.960784376f, 0.960784376f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Yellow = {{{1.f, 1.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 YellowGreen = {
{{0.603921592f, 0.803921640f, 0.196078449f, 1.f}}};
} // namespace Colors } // namespace Colors
namespace ColorsLinear namespace ColorsLinear {
{ // Standard colors (Red/Green/Blue/Alpha) in linear colorspace
// Standard colors (Red/Green/Blue/Alpha) in linear colorspace XMGLOBALCONST XMVECTORF32 AliceBlue = {
XMGLOBALCONST XMVECTORF32 AliceBlue = { { { 0.871367335f, 0.938685894f, 1.f, 1.f } } }; {{0.871367335f, 0.938685894f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 AntiqueWhite = { { { 0.955973506f, 0.830770075f, 0.679542601f, 1.f } } }; XMGLOBALCONST XMVECTORF32 AntiqueWhite = {
XMGLOBALCONST XMVECTORF32 Aqua = { { { 0.f, 1.f, 1.f, 1.f } } }; {{0.955973506f, 0.830770075f, 0.679542601f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Aquamarine = { { { 0.212230787f, 1.f, 0.658374965f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Aqua = {{{0.f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Azure = { { { 0.871367335f, 1.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Aquamarine = {
XMGLOBALCONST XMVECTORF32 Beige = { { { 0.913098991f, 0.913098991f, 0.715693772f, 1.f } } }; {{0.212230787f, 1.f, 0.658374965f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Bisque = { { { 1.f, 0.775822461f, 0.552011609f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Azure = {{{0.871367335f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Black = { { { 0.f, 0.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Beige = {
XMGLOBALCONST XMVECTORF32 BlanchedAlmond = { { { 1.f, 0.830770075f, 0.610495746f, 1.f } } }; {{0.913098991f, 0.913098991f, 0.715693772f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Blue = { { { 0.f, 0.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Bisque = {{{1.f, 0.775822461f, 0.552011609f, 1.f}}};
XMGLOBALCONST XMVECTORF32 BlueViolet = { { { 0.254152179f, 0.024157630f, 0.760524750f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Black = {{{0.f, 0.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Brown = { { { 0.376262218f, 0.023153365f, 0.023153365f, 1.f } } }; XMGLOBALCONST XMVECTORF32 BlanchedAlmond = {
XMGLOBALCONST XMVECTORF32 BurlyWood = { { { 0.730461001f, 0.479320228f, 0.242281199f, 1.f } } }; {{1.f, 0.830770075f, 0.610495746f, 1.f}}};
XMGLOBALCONST XMVECTORF32 CadetBlue = { { { 0.114435382f, 0.341914445f, 0.351532698f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Blue = {{{0.f, 0.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Chartreuse = { { { 0.212230787f, 1.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 BlueViolet = {
XMGLOBALCONST XMVECTORF32 Chocolate = { { { 0.644479871f, 0.141263321f, 0.012983031f, 1.f } } }; {{0.254152179f, 0.024157630f, 0.760524750f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Coral = { { { 1.f, 0.212230787f, 0.080219828f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Brown = {
XMGLOBALCONST XMVECTORF32 CornflowerBlue = { { { 0.127437726f, 0.300543845f, 0.846873462f, 1.f } } }; {{0.376262218f, 0.023153365f, 0.023153365f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Cornsilk = { { { 1.f, 0.938685894f, 0.715693772f, 1.f } } }; XMGLOBALCONST XMVECTORF32 BurlyWood = {
XMGLOBALCONST XMVECTORF32 Crimson = { { { 0.715693772f, 0.006995410f, 0.045186214f, 1.f } } }; {{0.730461001f, 0.479320228f, 0.242281199f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Cyan = { { { 0.f, 1.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 CadetBlue = {
XMGLOBALCONST XMVECTORF32 DarkBlue = { { { 0.f, 0.f, 0.258182913f, 1.f } } }; {{0.114435382f, 0.341914445f, 0.351532698f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkCyan = { { { 0.f, 0.258182913f, 0.258182913f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Chartreuse = {{{0.212230787f, 1.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkGoldenrod = { { { 0.479320228f, 0.238397658f, 0.003346536f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Chocolate = {
XMGLOBALCONST XMVECTORF32 DarkGray = { { { 0.396755308f, 0.396755308f, 0.396755308f, 1.f } } }; {{0.644479871f, 0.141263321f, 0.012983031f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkGreen = { { { 0.f, 0.127437726f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Coral = {{{1.f, 0.212230787f, 0.080219828f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkKhaki = { { { 0.508881450f, 0.473531544f, 0.147027299f, 1.f } } }; XMGLOBALCONST XMVECTORF32 CornflowerBlue = {
XMGLOBALCONST XMVECTORF32 DarkMagenta = { { { 0.258182913f, 0.f, 0.258182913f, 1.f } } }; {{0.127437726f, 0.300543845f, 0.846873462f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkOliveGreen = { { { 0.090841733f, 0.147027299f, 0.028426038f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Cornsilk = {{{1.f, 0.938685894f, 0.715693772f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkOrange = { { { 1.f, 0.262250721f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Crimson = {
XMGLOBALCONST XMVECTORF32 DarkOrchid = { { { 0.318546832f, 0.031896040f, 0.603827536f, 1.f } } }; {{0.715693772f, 0.006995410f, 0.045186214f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkRed = { { { 0.258182913f, 0.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Cyan = {{{0.f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkSalmon = { { { 0.814846814f, 0.304987371f, 0.194617867f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkBlue = {{{0.f, 0.f, 0.258182913f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkSeaGreen = { { { 0.274677366f, 0.502886593f, 0.258182913f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkCyan = {{{0.f, 0.258182913f, 0.258182913f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkSlateBlue = { { { 0.064803280f, 0.046665095f, 0.258182913f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkGoldenrod = {
XMGLOBALCONST XMVECTORF32 DarkSlateGray = { { { 0.028426038f, 0.078187428f, 0.078187428f, 1.f } } }; {{0.479320228f, 0.238397658f, 0.003346536f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DarkTurquoise = { { { 0.f, 0.617206752f, 0.637597024f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkGray = {
XMGLOBALCONST XMVECTORF32 DarkViolet = { { { 0.296138316f, 0.f, 0.651405811f, 1.f } } }; {{0.396755308f, 0.396755308f, 0.396755308f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DeepPink = { { { 1.f, 0.006995410f, 0.291770697f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkGreen = {{{0.f, 0.127437726f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DeepSkyBlue = { { { 0.f, 0.520995677f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkKhaki = {
XMGLOBALCONST XMVECTORF32 DimGray = { { { 0.141263321f, 0.141263321f, 0.141263321f, 1.f } } }; {{0.508881450f, 0.473531544f, 0.147027299f, 1.f}}};
XMGLOBALCONST XMVECTORF32 DodgerBlue = { { { 0.012983031f, 0.278894335f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkMagenta = {
XMGLOBALCONST XMVECTORF32 Firebrick = { { { 0.445201248f, 0.015996292f, 0.015996292f, 1.f } } }; {{0.258182913f, 0.f, 0.258182913f, 1.f}}};
XMGLOBALCONST XMVECTORF32 FloralWhite = { { { 1.f, 0.955973506f, 0.871367335f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkOliveGreen = {
XMGLOBALCONST XMVECTORF32 ForestGreen = { { { 0.015996292f, 0.258182913f, 0.015996292f, 1.f } } }; {{0.090841733f, 0.147027299f, 0.028426038f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Fuchsia = { { { 1.f, 0.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkOrange = {{{1.f, 0.262250721f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Gainsboro = { { { 0.715693772f, 0.715693772f, 0.715693772f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkOrchid = {
XMGLOBALCONST XMVECTORF32 GhostWhite = { { { 0.938685894f, 0.938685894f, 1.f, 1.f } } }; {{0.318546832f, 0.031896040f, 0.603827536f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Gold = { { { 1.f, 0.679542601f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkRed = {{{0.258182913f, 0.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Goldenrod = { { { 0.701102138f, 0.376262218f, 0.014443844f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkSalmon = {
XMGLOBALCONST XMVECTORF32 Gray = { { { 0.215860531f, 0.215860531f, 0.215860531f, 1.f } } }; {{0.814846814f, 0.304987371f, 0.194617867f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Green = { { { 0.f, 0.215860531f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkSeaGreen = {
XMGLOBALCONST XMVECTORF32 GreenYellow = { { { 0.417885154f, 1.f, 0.028426038f, 1.f } } }; {{0.274677366f, 0.502886593f, 0.258182913f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Honeydew = { { { 0.871367335f, 1.f, 0.871367335f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkSlateBlue = {
XMGLOBALCONST XMVECTORF32 HotPink = { { { 1.f, 0.141263321f, 0.456411064f, 1.f } } }; {{0.064803280f, 0.046665095f, 0.258182913f, 1.f}}};
XMGLOBALCONST XMVECTORF32 IndianRed = { { { 0.610495746f, 0.107023112f, 0.107023112f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkSlateGray = {
XMGLOBALCONST XMVECTORF32 Indigo = { { { 0.070360109f, 0.f, 0.223227978f, 1.f } } }; {{0.028426038f, 0.078187428f, 0.078187428f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Ivory = { { { 1.f, 1.f, 0.871367335f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkTurquoise = {
XMGLOBALCONST XMVECTORF32 Khaki = { { { 0.871367335f, 0.791298151f, 0.262250721f, 1.f } } }; {{0.f, 0.617206752f, 0.637597024f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Lavender = { { { 0.791298151f, 0.791298151f, 0.955973506f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DarkViolet = {
XMGLOBALCONST XMVECTORF32 LavenderBlush = { { { 1.f, 0.871367335f, 0.913098991f, 1.f } } }; {{0.296138316f, 0.f, 0.651405811f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LawnGreen = { { { 0.201556295f, 0.973445475f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DeepPink = {{{1.f, 0.006995410f, 0.291770697f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LemonChiffon = { { { 1.f, 0.955973506f, 0.610495746f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DeepSkyBlue = {{{0.f, 0.520995677f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightBlue = { { { 0.417885154f, 0.686685443f, 0.791298151f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DimGray = {
XMGLOBALCONST XMVECTORF32 LightCoral = { { { 0.871367335f, 0.215860531f, 0.215860531f, 1.f } } }; {{0.141263321f, 0.141263321f, 0.141263321f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightCyan = { { { 0.745404482f, 1.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 DodgerBlue = {
XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = { { { 0.955973506f, 0.955973506f, 0.644479871f, 1.f } } }; {{0.012983031f, 0.278894335f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightGray = { { { 0.651405811f, 0.651405811f, 0.651405811f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Firebrick = {
XMGLOBALCONST XMVECTORF32 LightGreen = { { { 0.278894335f, 0.854992807f, 0.278894335f, 1.f } } }; {{0.445201248f, 0.015996292f, 0.015996292f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightPink = { { { 1.f, 0.467783839f, 0.533276618f, 1.f } } }; XMGLOBALCONST XMVECTORF32 FloralWhite = {
XMGLOBALCONST XMVECTORF32 LightSalmon = { { { 1.f, 0.351532698f, 0.194617867f, 1.f } } }; {{1.f, 0.955973506f, 0.871367335f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightSeaGreen = { { { 0.014443844f, 0.445201248f, 0.401977867f, 1.f } } }; XMGLOBALCONST XMVECTORF32 ForestGreen = {
XMGLOBALCONST XMVECTORF32 LightSkyBlue = { { { 0.242281199f, 0.617206752f, 0.955973506f, 1.f } } }; {{0.015996292f, 0.258182913f, 0.015996292f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightSlateGray = { { { 0.184475034f, 0.246201396f, 0.318546832f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Fuchsia = {{{1.f, 0.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 LightSteelBlue = { { { 0.434153706f, 0.552011609f, 0.730461001f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Gainsboro = {
XMGLOBALCONST XMVECTORF32 LightYellow = { { { 1.f, 1.f, 0.745404482f, 1.f } } }; {{0.715693772f, 0.715693772f, 0.715693772f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Lime = { { { 0.f, 1.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 GhostWhite = {
XMGLOBALCONST XMVECTORF32 LimeGreen = { { { 0.031896040f, 0.610495746f, 0.031896040f, 1.f } } }; {{0.938685894f, 0.938685894f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Linen = { { { 0.955973506f, 0.871367335f, 0.791298151f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Gold = {{{1.f, 0.679542601f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Magenta = { { { 1.f, 0.f, 1.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Goldenrod = {
XMGLOBALCONST XMVECTORF32 Maroon = { { { 0.215860531f, 0.f, 0.f, 1.f } } }; {{0.701102138f, 0.376262218f, 0.014443844f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumAquamarine = { { { 0.132868364f, 0.610495746f, 0.401977867f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Gray = {
XMGLOBALCONST XMVECTORF32 MediumBlue = { { { 0.f, 0.f, 0.610495746f, 1.f } } }; {{0.215860531f, 0.215860531f, 0.215860531f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumOrchid = { { { 0.491020888f, 0.090841733f, 0.651405811f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Green = {{{0.f, 0.215860531f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumPurple = { { { 0.291770697f, 0.162029430f, 0.708376050f, 1.f } } }; XMGLOBALCONST XMVECTORF32 GreenYellow = {
XMGLOBALCONST XMVECTORF32 MediumSeaGreen = { { { 0.045186214f, 0.450785846f, 0.165132239f, 1.f } } }; {{0.417885154f, 1.f, 0.028426038f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumSlateBlue = { { { 0.198069349f, 0.138431653f, 0.854992807f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Honeydew = {{{0.871367335f, 1.f, 0.871367335f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumSpringGreen = { { { 0.f, 0.955973506f, 0.323143244f, 1.f } } }; XMGLOBALCONST XMVECTORF32 HotPink = {{{1.f, 0.141263321f, 0.456411064f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumTurquoise = { { { 0.064803280f, 0.637597024f, 0.603827536f, 1.f } } }; XMGLOBALCONST XMVECTORF32 IndianRed = {
XMGLOBALCONST XMVECTORF32 MediumVioletRed = { { { 0.571125031f, 0.007499032f, 0.234550655f, 1.f } } }; {{0.610495746f, 0.107023112f, 0.107023112f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MidnightBlue = { { { 0.009721218f, 0.009721218f, 0.162029430f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Indigo = {{{0.070360109f, 0.f, 0.223227978f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MintCream = { { { 0.913098991f, 1.f, 0.955973506f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Ivory = {{{1.f, 1.f, 0.871367335f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MistyRose = { { { 1.f, 0.775822461f, 0.752942443f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Khaki = {
XMGLOBALCONST XMVECTORF32 Moccasin = { { { 1.f, 0.775822461f, 0.462077051f, 1.f } } }; {{0.871367335f, 0.791298151f, 0.262250721f, 1.f}}};
XMGLOBALCONST XMVECTORF32 NavajoWhite = { { { 1.f, 0.730461001f, 0.417885154f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Lavender = {
XMGLOBALCONST XMVECTORF32 Navy = { { { 0.f, 0.f, 0.215860531f, 1.f } } }; {{0.791298151f, 0.791298151f, 0.955973506f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OldLace = { { { 0.982250869f, 0.913098991f, 0.791298151f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LavenderBlush = {
XMGLOBALCONST XMVECTORF32 Olive = { { { 0.215860531f, 0.215860531f, 0.f, 1.f } } }; {{1.f, 0.871367335f, 0.913098991f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OliveDrab = { { { 0.147027299f, 0.270497859f, 0.016807375f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LawnGreen = {
XMGLOBALCONST XMVECTORF32 Orange = { { { 1.f, 0.376262218f, 0.f, 1.f } } }; {{0.201556295f, 0.973445475f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OrangeRed = { { { 1.f, 0.059511241f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LemonChiffon = {
XMGLOBALCONST XMVECTORF32 Orchid = { { { 0.701102138f, 0.162029430f, 0.672443330f, 1.f } } }; {{1.f, 0.955973506f, 0.610495746f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleGoldenrod = { { { 0.854992807f, 0.806952477f, 0.401977867f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightBlue = {
XMGLOBALCONST XMVECTORF32 PaleGreen = { { { 0.313988745f, 0.964686573f, 0.313988745f, 1.f } } }; {{0.417885154f, 0.686685443f, 0.791298151f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleTurquoise = { { { 0.428690553f, 0.854992807f, 0.854992807f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightCoral = {
XMGLOBALCONST XMVECTORF32 PaleVioletRed = { { { 0.708376050f, 0.162029430f, 0.291770697f, 1.f } } }; {{0.871367335f, 0.215860531f, 0.215860531f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PapayaWhip = { { { 1.f, 0.863157392f, 0.665387452f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightCyan = {{{0.745404482f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PeachPuff = { { { 1.f, 0.701102138f, 0.485149980f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightGoldenrodYellow = {
XMGLOBALCONST XMVECTORF32 Peru = { { { 0.610495746f, 0.234550655f, 0.049706575f, 1.f } } }; {{0.955973506f, 0.955973506f, 0.644479871f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Pink = { { { 1.f, 0.527115345f, 0.597202003f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightGray = {
XMGLOBALCONST XMVECTORF32 Plum = { { { 0.723055363f, 0.351532698f, 0.723055363f, 1.f } } }; {{0.651405811f, 0.651405811f, 0.651405811f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PowderBlue = { { { 0.434153706f, 0.745404482f, 0.791298151f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightGreen = {
XMGLOBALCONST XMVECTORF32 Purple = { { { 0.215860531f, 0.f, 0.215860531f, 1.f } } }; {{0.278894335f, 0.854992807f, 0.278894335f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Red = { { { 1.f, 0.f, 0.f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightPink = {
XMGLOBALCONST XMVECTORF32 RosyBrown = { { { 0.502886593f, 0.274677366f, 0.274677366f, 1.f } } }; {{1.f, 0.467783839f, 0.533276618f, 1.f}}};
XMGLOBALCONST XMVECTORF32 RoyalBlue = { { { 0.052860655f, 0.141263321f, 0.752942443f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSalmon = {
XMGLOBALCONST XMVECTORF32 SaddleBrown = { { { 0.258182913f, 0.059511241f, 0.006512091f, 1.f } } }; {{1.f, 0.351532698f, 0.194617867f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Salmon = { { { 0.955973506f, 0.215860531f, 0.168269455f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSeaGreen = {
XMGLOBALCONST XMVECTORF32 SandyBrown = { { { 0.904661357f, 0.371237785f, 0.116970696f, 1.f } } }; {{0.014443844f, 0.445201248f, 0.401977867f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SeaGreen = { { { 0.027320892f, 0.258182913f, 0.095307484f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSkyBlue = {
XMGLOBALCONST XMVECTORF32 SeaShell = { { { 1.f, 0.913098991f, 0.854992807f, 1.f } } }; {{0.242281199f, 0.617206752f, 0.955973506f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Sienna = { { { 0.351532698f, 0.084376216f, 0.026241222f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSlateGray = {
XMGLOBALCONST XMVECTORF32 Silver = { { { 0.527115345f, 0.527115345f, 0.527115345f, 1.f } } }; {{0.184475034f, 0.246201396f, 0.318546832f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SkyBlue = { { { 0.242281199f, 0.617206752f, 0.830770075f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightSteelBlue = {
XMGLOBALCONST XMVECTORF32 SlateBlue = { { { 0.144128501f, 0.102241747f, 0.610495746f, 1.f } } }; {{0.434153706f, 0.552011609f, 0.730461001f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SlateGray = { { { 0.162029430f, 0.215860531f, 0.278894335f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LightYellow = {{{1.f, 1.f, 0.745404482f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Snow = { { { 1.f, 0.955973506f, 0.955973506f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Lime = {{{0.f, 1.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SpringGreen = { { { 0.f, 1.f, 0.212230787f, 1.f } } }; XMGLOBALCONST XMVECTORF32 LimeGreen = {
XMGLOBALCONST XMVECTORF32 SteelBlue = { { { 0.061246071f, 0.223227978f, 0.456411064f, 1.f } } }; {{0.031896040f, 0.610495746f, 0.031896040f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Tan = { { { 0.644479871f, 0.456411064f, 0.262250721f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Linen = {
XMGLOBALCONST XMVECTORF32 Teal = { { { 0.f, 0.215860531f, 0.215860531f, 1.f } } }; {{0.955973506f, 0.871367335f, 0.791298151f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Thistle = { { { 0.686685443f, 0.520995677f, 0.686685443f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Magenta = {{{1.f, 0.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Tomato = { { { 1.f, 0.124771863f, 0.063010029f, 1.f } } }; XMGLOBALCONST XMVECTORF32 Maroon = {{{0.215860531f, 0.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Transparent = { { { 0.f, 0.f, 0.f, 0.f } } }; XMGLOBALCONST XMVECTORF32 MediumAquamarine = {
XMGLOBALCONST XMVECTORF32 Turquoise = { { { 0.051269468f, 0.745404482f, 0.630757332f, 1.f } } }; {{0.132868364f, 0.610495746f, 0.401977867f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Violet = { { { 0.854992807f, 0.223227978f, 0.854992807f, 1.f } } }; XMGLOBALCONST XMVECTORF32 MediumBlue = {{{0.f, 0.f, 0.610495746f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Wheat = { { { 0.913098991f, 0.730461001f, 0.450785846f, 1.f } } }; XMGLOBALCONST XMVECTORF32 MediumOrchid = {
XMGLOBALCONST XMVECTORF32 White = { { { 1.f, 1.f, 1.f, 1.f } } }; {{0.491020888f, 0.090841733f, 0.651405811f, 1.f}}};
XMGLOBALCONST XMVECTORF32 WhiteSmoke = { { { 0.913098991f, 0.913098991f, 0.913098991f, 1.f } } }; XMGLOBALCONST XMVECTORF32 MediumPurple = {
XMGLOBALCONST XMVECTORF32 Yellow = { { { 1.f, 1.f, 0.f, 1.f } } }; {{0.291770697f, 0.162029430f, 0.708376050f, 1.f}}};
XMGLOBALCONST XMVECTORF32 YellowGreen = { { { 0.323143244f, 0.610495746f, 0.031896040f, 1.f } } }; XMGLOBALCONST XMVECTORF32 MediumSeaGreen = {
{{0.045186214f, 0.450785846f, 0.165132239f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumSlateBlue = {
{{0.198069349f, 0.138431653f, 0.854992807f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumSpringGreen = {
{{0.f, 0.955973506f, 0.323143244f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumTurquoise = {
{{0.064803280f, 0.637597024f, 0.603827536f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MediumVioletRed = {
{{0.571125031f, 0.007499032f, 0.234550655f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MidnightBlue = {
{{0.009721218f, 0.009721218f, 0.162029430f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MintCream = {
{{0.913098991f, 1.f, 0.955973506f, 1.f}}};
XMGLOBALCONST XMVECTORF32 MistyRose = {
{{1.f, 0.775822461f, 0.752942443f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Moccasin = {{{1.f, 0.775822461f, 0.462077051f, 1.f}}};
XMGLOBALCONST XMVECTORF32 NavajoWhite = {
{{1.f, 0.730461001f, 0.417885154f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Navy = {{{0.f, 0.f, 0.215860531f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OldLace = {
{{0.982250869f, 0.913098991f, 0.791298151f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Olive = {{{0.215860531f, 0.215860531f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OliveDrab = {
{{0.147027299f, 0.270497859f, 0.016807375f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Orange = {{{1.f, 0.376262218f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 OrangeRed = {{{1.f, 0.059511241f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Orchid = {
{{0.701102138f, 0.162029430f, 0.672443330f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleGoldenrod = {
{{0.854992807f, 0.806952477f, 0.401977867f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleGreen = {
{{0.313988745f, 0.964686573f, 0.313988745f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleTurquoise = {
{{0.428690553f, 0.854992807f, 0.854992807f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PaleVioletRed = {
{{0.708376050f, 0.162029430f, 0.291770697f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PapayaWhip = {
{{1.f, 0.863157392f, 0.665387452f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PeachPuff = {
{{1.f, 0.701102138f, 0.485149980f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Peru = {
{{0.610495746f, 0.234550655f, 0.049706575f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Pink = {{{1.f, 0.527115345f, 0.597202003f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Plum = {
{{0.723055363f, 0.351532698f, 0.723055363f, 1.f}}};
XMGLOBALCONST XMVECTORF32 PowderBlue = {
{{0.434153706f, 0.745404482f, 0.791298151f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Purple = {{{0.215860531f, 0.f, 0.215860531f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Red = {{{1.f, 0.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 RosyBrown = {
{{0.502886593f, 0.274677366f, 0.274677366f, 1.f}}};
XMGLOBALCONST XMVECTORF32 RoyalBlue = {
{{0.052860655f, 0.141263321f, 0.752942443f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SaddleBrown = {
{{0.258182913f, 0.059511241f, 0.006512091f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Salmon = {
{{0.955973506f, 0.215860531f, 0.168269455f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SandyBrown = {
{{0.904661357f, 0.371237785f, 0.116970696f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SeaGreen = {
{{0.027320892f, 0.258182913f, 0.095307484f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SeaShell = {{{1.f, 0.913098991f, 0.854992807f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Sienna = {
{{0.351532698f, 0.084376216f, 0.026241222f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Silver = {
{{0.527115345f, 0.527115345f, 0.527115345f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SkyBlue = {
{{0.242281199f, 0.617206752f, 0.830770075f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SlateBlue = {
{{0.144128501f, 0.102241747f, 0.610495746f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SlateGray = {
{{0.162029430f, 0.215860531f, 0.278894335f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Snow = {{{1.f, 0.955973506f, 0.955973506f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SpringGreen = {{{0.f, 1.f, 0.212230787f, 1.f}}};
XMGLOBALCONST XMVECTORF32 SteelBlue = {
{{0.061246071f, 0.223227978f, 0.456411064f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Tan = {
{{0.644479871f, 0.456411064f, 0.262250721f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Teal = {{{0.f, 0.215860531f, 0.215860531f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Thistle = {
{{0.686685443f, 0.520995677f, 0.686685443f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Tomato = {{{1.f, 0.124771863f, 0.063010029f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Transparent = {{{0.f, 0.f, 0.f, 0.f}}};
XMGLOBALCONST XMVECTORF32 Turquoise = {
{{0.051269468f, 0.745404482f, 0.630757332f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Violet = {
{{0.854992807f, 0.223227978f, 0.854992807f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Wheat = {
{{0.913098991f, 0.730461001f, 0.450785846f, 1.f}}};
XMGLOBALCONST XMVECTORF32 White = {{{1.f, 1.f, 1.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 WhiteSmoke = {
{{0.913098991f, 0.913098991f, 0.913098991f, 1.f}}};
XMGLOBALCONST XMVECTORF32 Yellow = {{{1.f, 1.f, 0.f, 1.f}}};
XMGLOBALCONST XMVECTORF32 YellowGreen = {
{{0.323143244f, 0.610495746f, 0.031896040f, 1.f}}};
} // namespace ColorsLinear } // namespace ColorsLinear
} // namespace DirectX
} // namespace DirectX

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -32,4 +32,4 @@
#include "xbox_stubs.h" #include "xbox_stubs.h"
#include "iggy_stubs.h" #include "iggy_stubs.h"
#endif // STUBS_H #endif // STUBS_H

View file

@ -8,12 +8,11 @@
using namespace DirectX; using namespace DirectX;
typedef struct _RECT typedef struct _RECT {
{ LONG left;
LONG left; LONG top;
LONG top; LONG right;
LONG right; LONG bottom;
LONG bottom;
} RECT, *PRECT; } RECT, *PRECT;
// stole- i mean borrowed from OrbisStubs.h // stole- i mean borrowed from OrbisStubs.h
@ -27,45 +26,42 @@ typedef void ID3D11Buffer;
// typedef DWORD (*PTHREAD_START_ROUTINE)( LPVOID lpThreadParameter); // typedef DWORD (*PTHREAD_START_ROUTINE)( LPVOID lpThreadParameter);
// typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE; // typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE;
// Used only by windows/durango gdraw and UIController. Will be unnecessary once we have our own // Used only by windows/durango gdraw and UIController. Will be unnecessary once
// UIController stubs. // we have our own UIController stubs.
typedef void ID3D11ShaderResourceView; typedef void ID3D11ShaderResourceView;
typedef void ID3D11Resource; typedef void ID3D11Resource;
typedef void ID3D11Texture2D; typedef void ID3D11Texture2D;
typedef void D3D11_TEXTURE2D_DESC; typedef void D3D11_TEXTURE2D_DESC;
enum D3D11_BLEND enum D3D11_BLEND {
{ D3D11_BLEND_ZERO = 1,
D3D11_BLEND_ZERO = 1, D3D11_BLEND_ONE = 2,
D3D11_BLEND_ONE = 2, D3D11_BLEND_SRC_COLOR = 3,
D3D11_BLEND_SRC_COLOR = 3, D3D11_BLEND_INV_SRC_COLOR = 4,
D3D11_BLEND_INV_SRC_COLOR = 4, D3D11_BLEND_SRC_ALPHA = 5,
D3D11_BLEND_SRC_ALPHA = 5, D3D11_BLEND_INV_SRC_ALPHA = 6,
D3D11_BLEND_INV_SRC_ALPHA = 6, D3D11_BLEND_DEST_ALPHA = 7,
D3D11_BLEND_DEST_ALPHA = 7, D3D11_BLEND_INV_DEST_ALPHA = 8,
D3D11_BLEND_INV_DEST_ALPHA = 8, D3D11_BLEND_DEST_COLOR = 9,
D3D11_BLEND_DEST_COLOR = 9, D3D11_BLEND_INV_DEST_COLOR = 10,
D3D11_BLEND_INV_DEST_COLOR = 10, D3D11_BLEND_SRC_ALPHA_SAT = 11,
D3D11_BLEND_SRC_ALPHA_SAT = 11, D3D11_BLEND_BLEND_FACTOR = 14,
D3D11_BLEND_BLEND_FACTOR = 14, D3D11_BLEND_INV_BLEND_FACTOR = 15,
D3D11_BLEND_INV_BLEND_FACTOR = 15, D3D11_BLEND_SRC1_COLOR = 16,
D3D11_BLEND_SRC1_COLOR = 16, D3D11_BLEND_INV_SRC1_COLOR = 17,
D3D11_BLEND_INV_SRC1_COLOR = 17, D3D11_BLEND_SRC1_ALPHA = 18,
D3D11_BLEND_SRC1_ALPHA = 18, D3D11_BLEND_INV_SRC1_ALPHA = 19
D3D11_BLEND_INV_SRC1_ALPHA = 19
}; };
enum D3D11_COMPARISON_FUNC {
enum D3D11_COMPARISON_FUNC D3D11_COMPARISON_NEVER = 1,
{ D3D11_COMPARISON_LESS = 2,
D3D11_COMPARISON_NEVER = 1, D3D11_COMPARISON_EQUAL = 3,
D3D11_COMPARISON_LESS = 2, D3D11_COMPARISON_LESS_EQUAL = 4,
D3D11_COMPARISON_EQUAL = 3, D3D11_COMPARISON_GREATER = 5,
D3D11_COMPARISON_LESS_EQUAL = 4, D3D11_COMPARISON_NOT_EQUAL = 6,
D3D11_COMPARISON_GREATER = 5, D3D11_COMPARISON_GREATER_EQUAL = 7,
D3D11_COMPARISON_NOT_EQUAL = 6, D3D11_COMPARISON_ALWAYS = 8
D3D11_COMPARISON_GREATER_EQUAL = 7,
D3D11_COMPARISON_ALWAYS = 8
}; };
#endif // D3D11STUBS_H #endif // D3D11STUBS_H

View file

@ -3,225 +3,258 @@
#pragma once #pragma once
#include "../../Windows64/Iggy/include/iggy.h" #include "../../Windows64/Iggy/include/iggy.h"
#define STUBBED {} #define STUBBED \
{ \
}
RADEXPFUNC inline IggyValuePath * RADEXPLINK IggyPlayerRootPath(Iggy *f) { RADEXPFUNC inline IggyValuePath* RADEXPLINK IggyPlayerRootPath(Iggy* f) {
STUBBED; STUBBED;
return nullptr; return nullptr;
} }
RADEXPFUNC inline IggyResult RADEXPLINK IggyPlayerCallMethodRS(Iggy *f, IggyDataValue *result, IggyValuePath *target, IggyName methodname, S32 numargs, IggyDataValue *args) { RADEXPFUNC inline IggyResult RADEXPLINK
STUBBED; IggyPlayerCallMethodRS(Iggy* f, IggyDataValue* result, IggyValuePath* target,
return IGGY_RESULT_SUCCESS; IggyName methodname, S32 numargs, IggyDataValue* args) {
STUBBED;
return IGGY_RESULT_SUCCESS;
} }
RADEXPFUNC inline void RADEXPLINK IggyPlayerDestroy(Iggy *player) { RADEXPFUNC inline void RADEXPLINK IggyPlayerDestroy(Iggy* player) { STUBBED; }
STUBBED; RADEXPFUNC inline void RADEXPLINK IggyPlayerSetDisplaySize(Iggy* f, S32 w,
} S32 h) {
RADEXPFUNC inline void RADEXPLINK IggyPlayerSetDisplaySize(Iggy *f, S32 w, S32 h) { STUBBED;
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesStart(Iggy *f) { RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesStart(Iggy* f) { STUBBED; }
STUBBED;
}
RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTile(Iggy *f, S32 x0, S32 y0, S32 x1, S32 y1, S32 padding) { RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTile(Iggy* f, S32 x0, S32 y0,
STUBBED; S32 x1, S32 y1,
} S32 padding) {
RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesEnd(Iggy *f) { STUBBED;
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggyPlayerDrawTilesEnd(Iggy* f) { STUBBED; }
// Each fake Iggy player gets its own state block // Each fake Iggy player gets its own state block
struct FakeIggyPlayer { struct FakeIggyPlayer {
int tickCount; int tickCount;
bool needsTick; bool needsTick;
IggyProperties props; IggyProperties props;
void *userdata; void* userdata;
}; };
// Simple player pool // Simple player pool
static FakeIggyPlayer s_fakePlayers[64]; static FakeIggyPlayer s_fakePlayers[64];
static int s_fakePlayerCount = 0; static int s_fakePlayerCount = 0;
RADEXPFUNC inline Iggy * RADEXPLINK IggyPlayerCreateFromMemory( RADEXPFUNC inline Iggy* RADEXPLINK IggyPlayerCreateFromMemory(
void const * data, void const* data, U32 data_size_in_bytes, IggyPlayerConfig* config) {
U32 data_size_in_bytes, if (s_fakePlayerCount >= 64) return nullptr;
IggyPlayerConfig *config) { FakeIggyPlayer* fp = &s_fakePlayers[s_fakePlayerCount++];
if(s_fakePlayerCount >= 64) return nullptr; fp->tickCount = 0;
FakeIggyPlayer *fp = &s_fakePlayers[s_fakePlayerCount++]; fp->needsTick = true;
fp->tickCount = 0; fp->userdata = nullptr;
fp->needsTick = true; // Default to 1920x1080 at 30fps
fp->userdata = nullptr; memset(&fp->props, 0, sizeof(fp->props));
// Default to 1920x1080 at 30fps fp->props.movie_width_in_pixels = 1920;
memset(&fp->props, 0, sizeof(fp->props)); fp->props.movie_height_in_pixels = 1080;
fp->props.movie_width_in_pixels = 1920; fp->props.movie_frame_rate_from_file_in_fps = 30.0f;
fp->props.movie_height_in_pixels = 1080; fp->props.movie_frame_rate_current_in_fps = 30.0f;
fp->props.movie_frame_rate_from_file_in_fps = 30.0f; fprintf(stderr, "[Iggy Stub] Created fake player %d (data=%p, size=%u)\n",
fp->props.movie_frame_rate_current_in_fps = 30.0f; s_fakePlayerCount - 1, data, data_size_in_bytes);
fprintf(stderr, "[Iggy Stub] Created fake player %d (data=%p, size=%u)\n", s_fakePlayerCount-1, data, data_size_in_bytes); return (Iggy*)fp;
return (Iggy*)fp;
} }
static FakeIggyPlayer* getFakePlayer(Iggy *player) { static FakeIggyPlayer* getFakePlayer(Iggy* player) {
return (FakeIggyPlayer*)player; return (FakeIggyPlayer*)player;
} }
RADEXPFUNC inline void RADEXPLINK IggyPlayerInitializeAndTickRS(Iggy *player) { RADEXPFUNC inline void RADEXPLINK IggyPlayerInitializeAndTickRS(Iggy* player) {
FakeIggyPlayer *fp = getFakePlayer(player); FakeIggyPlayer* fp = getFakePlayer(player);
if(fp) { fp->tickCount = 0; fp->needsTick = true; } if (fp) {
fp->tickCount = 0;
fp->needsTick = true;
}
} }
RADEXPFUNC inline IggyProperties * RADEXPLINK IggyPlayerProperties(Iggy *player) { RADEXPFUNC inline IggyProperties* RADEXPLINK
FakeIggyPlayer *fp = getFakePlayer(player); IggyPlayerProperties(Iggy* player) {
if(fp) return &fp->props; FakeIggyPlayer* fp = getFakePlayer(player);
static IggyProperties defaultProps = {}; if (fp) return &fp->props;
return &defaultProps; static IggyProperties defaultProps = {};
return &defaultProps;
} }
RADEXPFUNC inline void RADEXPLINK IggyPlayerSetUserdata(Iggy *player, void *userdata) { RADEXPFUNC inline void RADEXPLINK IggyPlayerSetUserdata(Iggy* player,
FakeIggyPlayer *fp = getFakePlayer(player); void* userdata) {
if(fp) fp->userdata = userdata; FakeIggyPlayer* fp = getFakePlayer(player);
if (fp) fp->userdata = userdata;
} }
RADEXPFUNC inline IggyName RADEXPLINK IggyPlayerCreateFastName(Iggy *f, IggyUTF16 const *name, S32 len) { RADEXPFUNC inline IggyName RADEXPLINK
STUBBED; IggyPlayerCreateFastName(Iggy* f, IggyUTF16 const* name, S32 len) {
return 0; STUBBED;
return 0;
} }
RADEXPFUNC inline rrbool RADEXPLINK IggyDebugGetMemoryUseInfo(Iggy *player, IggyLibrary lib, char const *category_string, S32 category_stringlen, S32 iteration, IggyMemoryUseInfo *data) { RADEXPFUNC inline rrbool RADEXPLINK IggyDebugGetMemoryUseInfo(
STUBBED; Iggy* player, IggyLibrary lib, char const* category_string,
return false; S32 category_stringlen, S32 iteration, IggyMemoryUseInfo* data) {
STUBBED;
return false;
} }
RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerReadyToTick(Iggy *player) { RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerReadyToTick(Iggy* player) {
FakeIggyPlayer *fp = getFakePlayer(player); FakeIggyPlayer* fp = getFakePlayer(player);
if(fp && fp->needsTick) return true; if (fp && fp->needsTick) return true;
return false; return false;
} }
RADEXPFUNC inline void RADEXPLINK IggyPlayerTickRS(Iggy *player) { RADEXPFUNC inline void RADEXPLINK IggyPlayerTickRS(Iggy* player) {
FakeIggyPlayer *fp = getFakePlayer(player); FakeIggyPlayer* fp = getFakePlayer(player);
if(fp) { if (fp) {
fp->tickCount++; fp->tickCount++;
// Allow one tick per frame cycle // Allow one tick per frame cycle
fp->needsTick = false; fp->needsTick = false;
} }
} }
RADEXPFUNC inline void RADEXPLINK IggyPlayerDraw(Iggy *f) { RADEXPFUNC inline void RADEXPLINK IggyPlayerDraw(Iggy* f) {
// Re-arm tick for next frame // Re-arm tick for next frame
FakeIggyPlayer *fp = getFakePlayer(f); FakeIggyPlayer* fp = getFakePlayer(f);
if(fp) fp->needsTick = true; if (fp) fp->needsTick = true;
} }
RADEXPFUNC inline void RADEXPLINK IggyMakeEventKey(IggyEvent *event, IggyKeyevent event_type, IggyKeycode keycode, IggyKeyloc keyloc) { RADEXPFUNC inline void RADEXPLINK IggyMakeEventKey(IggyEvent* event,
STUBBED; IggyKeyevent event_type,
IggyKeycode keycode,
IggyKeyloc keyloc) {
STUBBED;
} }
RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerDispatchEventRS(Iggy *player, IggyEvent *event, IggyEventResult *result) { RADEXPFUNC inline rrbool RADEXPLINK IggyPlayerDispatchEventRS(
STUBBED; Iggy* player, IggyEvent* event, IggyEventResult* result) {
return false; STUBBED;
return false;
} }
RADEXPFUNC inline void RADEXPLINK IggyFontRemoveUTF8(const char *fontname, S32 namelen_in_bytes, U32 fontflags) { RADEXPFUNC inline void RADEXPLINK IggyFontRemoveUTF8(const char* fontname,
STUBBED; S32 namelen_in_bytes,
U32 fontflags) {
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggyFontInstallBitmapUTF8(const IggyBitmapFontProvider *bmf, const char *fontname, S32 namelen_in_bytes, U32 fontflags) { RADEXPFUNC inline void RADEXPLINK IggyFontInstallBitmapUTF8(
STUBBED; const IggyBitmapFontProvider* bmf, const char* fontname,
S32 namelen_in_bytes, U32 fontflags) {
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggyFontSetIndirectUTF8(const char *request_name, S32 request_namelen, U32 request_flags, const char *result_name, S32 result_namelen, U32 result_flags) { RADEXPFUNC inline void RADEXPLINK IggyFontSetIndirectUTF8(
STUBBED; const char* request_name, S32 request_namelen, U32 request_flags,
const char* result_name, S32 result_namelen, U32 result_flags) {
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeUTF8(const void *truetype_storage, S32 ttc_index, const char *fontname, S32 namelen_in_bytes, U32 fontflags) { RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeUTF8(
STUBBED; const void* truetype_storage, S32 ttc_index, const char* fontname,
S32 namelen_in_bytes, U32 fontflags) {
STUBBED;
} }
RADEXPFUNC inline rrbool RADEXPLINK IggyValuePathMakeNameRef(IggyValuePath *result, IggyValuePath *parent, char const *text_utf8) { RADEXPFUNC inline rrbool RADEXPLINK IggyValuePathMakeNameRef(
STUBBED; IggyValuePath* result, IggyValuePath* parent, char const* text_utf8) {
return false; STUBBED;
return false;
} }
RADEXPFUNC inline IggyResult RADEXPLINK IggyValueGetBooleanRS(IggyValuePath *var, IggyName sub_name, char const *sub_name_utf8, rrbool *result) { RADEXPFUNC inline IggyResult RADEXPLINK
STUBBED; IggyValueGetBooleanRS(IggyValuePath* var, IggyName sub_name,
return IGGY_RESULT_SUCCESS; char const* sub_name_utf8, rrbool* result) {
STUBBED;
return IGGY_RESULT_SUCCESS;
} }
RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeFallbackCodepointUTF8(const char *fontname, S32 len, U32 fontflags, S32 fallback_codepoint) { RADEXPFUNC inline void RADEXPLINK IggyFontInstallTruetypeFallbackCodepointUTF8(
STUBBED; const char* fontname, S32 len, U32 fontflags, S32 fallback_codepoint) {
STUBBED;
} }
RADEXPFUNC inline IggyResult RADEXPLINK IggyValueGetF64RS(IggyValuePath *var, IggyName sub_name, char const *sub_name_utf8, F64 *result) { RADEXPFUNC inline IggyResult RADEXPLINK
STUBBED; IggyValueGetF64RS(IggyValuePath* var, IggyName sub_name,
return IGGY_RESULT_SUCCESS; char const* sub_name_utf8, F64* result) {
STUBBED;
return IGGY_RESULT_SUCCESS;
} }
RADEXPFUNC inline rrbool RADEXPLINK IggyValueSetBooleanRS(IggyValuePath *var, IggyName sub_name, char const *sub_name_utf8, rrbool value) { RADEXPFUNC inline rrbool RADEXPLINK
STUBBED; IggyValueSetBooleanRS(IggyValuePath* var, IggyName sub_name,
return true; char const* sub_name_utf8, rrbool value) {
STUBBED;
return true;
} }
RADEXPFUNC inline void RADEXPLINK IggyInit(IggyAllocator *allocator) { RADEXPFUNC inline void RADEXPLINK IggyInit(IggyAllocator* allocator) {
STUBBED; STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggySetWarningCallback(Iggy_WarningFunction *error, void *user_callback_data) { RADEXPFUNC inline void RADEXPLINK
STUBBED; IggySetWarningCallback(Iggy_WarningFunction* error, void* user_callback_data) {
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggySetTraceCallbackUTF8(Iggy_TraceFunctionUTF8 *trace_utf8, void *user_callback_data) { RADEXPFUNC inline void RADEXPLINK IggySetTraceCallbackUTF8(
STUBBED; Iggy_TraceFunctionUTF8* trace_utf8, void* user_callback_data) {
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggySetFontCachingCalculationBuffer( RADEXPFUNC inline void RADEXPLINK
S32 max_chars, IggySetFontCachingCalculationBuffer(S32 max_chars, void* optional_temp_buffer,
void *optional_temp_buffer, S32 optional_temp_buffer_size_in_bytes) {
S32 optional_temp_buffer_size_in_bytes) { STUBBED;
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggySetCustomDrawCallback(Iggy_CustomDrawCallback *custom_draw, void *user_callback_data) { RADEXPFUNC inline void RADEXPLINK IggySetCustomDrawCallback(
STUBBED; Iggy_CustomDrawCallback* custom_draw, void* user_callback_data) {
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggySetAS3ExternalFunctionCallbackUTF16(Iggy_AS3ExternalFunctionUTF16 *as3_external_function_utf16, void *user_callback_data) { RADEXPFUNC inline void RADEXPLINK IggySetAS3ExternalFunctionCallbackUTF16(
STUBBED; Iggy_AS3ExternalFunctionUTF16* as3_external_function_utf16,
void* user_callback_data) {
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggyMakeEventMouseMove(IggyEvent *event, S32 x, S32 y) { RADEXPFUNC inline void RADEXPLINK IggyMakeEventMouseMove(IggyEvent* event,
STUBBED; S32 x, S32 y) {
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggySetTextureSubstitutionCallbacks(Iggy_TextureSubstitutionCreateCallback *texture_create, Iggy_TextureSubstitutionDestroyCallback *texture_destroy, void *user_callback_data) { RADEXPFUNC inline void RADEXPLINK IggySetTextureSubstitutionCallbacks(
STUBBED; Iggy_TextureSubstitutionCreateCallback* texture_create,
Iggy_TextureSubstitutionDestroyCallback* texture_destroy,
void* user_callback_data) {
STUBBED;
} }
RADEXPFUNC inline void * RADEXPLINK IggyPlayerGetUserdata(Iggy *player) { RADEXPFUNC inline void* RADEXPLINK IggyPlayerGetUserdata(Iggy* player) {
FakeIggyPlayer *fp = getFakePlayer(player); FakeIggyPlayer* fp = getFakePlayer(player);
if(fp) return fp->userdata; if (fp) return fp->userdata;
return 0; return 0;
} }
RADEXPFUNC inline IggyLibrary RADEXPLINK IggyLibraryCreateFromMemoryUTF16( RADEXPFUNC inline IggyLibrary RADEXPLINK IggyLibraryCreateFromMemoryUTF16(
IggyUTF16 const * url_utf16_null_terminated, IggyUTF16 const* url_utf16_null_terminated, void const* data,
void const * data, U32 data_size_in_bytes, IggyPlayerConfig* config) {
U32 data_size_in_bytes, STUBBED;
IggyPlayerConfig *config) { return 0;
STUBBED;
return 0;
} }
RADEXPFUNC inline void RADEXPLINK IggyLibraryDestroy(IggyLibrary lib) { RADEXPFUNC inline void RADEXPLINK IggyLibraryDestroy(IggyLibrary lib) {
STUBBED; STUBBED;
} }
// Iggy is fake // Iggy is fake
static GDrawFunctions *s_iggy_gdraw_funcs = 0; static GDrawFunctions* s_iggy_gdraw_funcs = 0;
RADEXPFUNC inline void RADEXPLINK IggySetGDraw(GDrawFunctions *gdraw_funcs) { RADEXPFUNC inline void RADEXPLINK IggySetGDraw(GDrawFunctions* gdraw_funcs) {
s_iggy_gdraw_funcs = gdraw_funcs; s_iggy_gdraw_funcs = gdraw_funcs;
} }
// Audio stubs // Audio stubs
RADEXPFUNC inline void RADEXPLINK IggyAudioUseDefault(void) { RADEXPFUNC inline void RADEXPLINK IggyAudioUseDefault(void) { STUBBED; }
STUBBED;
}
// Explorer/Perfmon, shit implmentation // Explorer/Perfmon, shit implmentation
RADEXPFUNC inline void * RADEXPLINK IggyExpCreate(const char *host, int port, void *storage, int storage_size) { RADEXPFUNC inline void* RADEXPLINK IggyExpCreate(const char* host, int port,
STUBBED; void* storage,
return 0; int storage_size) {
STUBBED;
return 0;
} }
RADEXPFUNC inline void RADEXPLINK IggyUseExplorer(Iggy *player, void *explorer) { RADEXPFUNC inline void RADEXPLINK IggyUseExplorer(Iggy* player,
STUBBED; void* explorer) {
STUBBED;
} }
RADEXPFUNC inline void * RADEXPLINK IggyPerfmonCreate(void *(*alloc_func)(unsigned long), void (*free_func)(void *), void *user) { RADEXPFUNC inline void* RADEXPLINK IggyPerfmonCreate(
STUBBED; void* (*alloc_func)(unsigned long), void (*free_func)(void*), void* user) {
return 0; STUBBED;
} return 0;
RADEXPFUNC inline void RADEXPLINK IggyInstallPerfmon(void *perfmon) {
STUBBED;
} }
RADEXPFUNC inline void RADEXPLINK IggyInstallPerfmon(void* perfmon) { STUBBED; }
// GDraw memory/warning functions are defined in gdraw_glfw.c (C linkage) // GDraw memory/warning functions are defined in gdraw_glfw.c (C linkage)
// Juicey you stupid idiot do NOT define them here // Juicey you stupid idiot do NOT define them here
#endif // IGGYSTUBS_H #endif // IGGYSTUBS_H

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@
// //
//============================================================================= //=============================================================================
#if !defined( XBOXSTUBS_H ) && !defined( _X360 ) #if !defined(XBOXSTUBS_H) && !defined(_X360)
#define XBOXSTUBS_H #define XBOXSTUBS_H
#ifdef _WIN32 #ifdef _WIN32
@ -12,7 +12,7 @@
#endif #endif
// DecalOverdose: not available in 4J // DecalOverdose: not available in 4J
//#include "tier0/platform.h" // #include "tier0/platform.h"
#define POSIX #define POSIX
@ -23,66 +23,65 @@ typedef long long int int64;
#define FORCEINLINE inline #define FORCEINLINE inline
// Content creation/open flags // Content creation/open flags
#define XCONTENTFLAG_NONE 0x00 #define XCONTENTFLAG_NONE 0x00
#define XCONTENTFLAG_CREATENEW 0x00 #define XCONTENTFLAG_CREATENEW 0x00
#define XCONTENTFLAG_CREATEALWAYS 0x00 #define XCONTENTFLAG_CREATEALWAYS 0x00
#define XCONTENTFLAG_OPENEXISTING 0x00 #define XCONTENTFLAG_OPENEXISTING 0x00
#define XCONTENTFLAG_OPENALWAYS 0x00 #define XCONTENTFLAG_OPENALWAYS 0x00
#define XCONTENTFLAG_TRUNCATEEXISTING 0x00 #define XCONTENTFLAG_TRUNCATEEXISTING 0x00
// Content attributes // Content attributes
#define XCONTENTFLAG_NOPROFILE_TRANSFER 0x00 #define XCONTENTFLAG_NOPROFILE_TRANSFER 0x00
#define XCONTENTFLAG_NODEVICE_TRANSFER 0x00 #define XCONTENTFLAG_NODEVICE_TRANSFER 0x00
#define XCONTENTFLAG_STRONG_SIGNED 0x00 #define XCONTENTFLAG_STRONG_SIGNED 0x00
#define XCONTENTFLAG_ALLOWPROFILE_TRANSFER 0x00 #define XCONTENTFLAG_ALLOWPROFILE_TRANSFER 0x00
#define XCONTENTFLAG_MOVEONLY_TRANSFER 0x00 #define XCONTENTFLAG_MOVEONLY_TRANSFER 0x00
// Console device ports // Console device ports
#define XDEVICE_PORT0 0 #define XDEVICE_PORT0 0
#define XDEVICE_PORT1 1 #define XDEVICE_PORT1 1
#define XDEVICE_PORT2 2 #define XDEVICE_PORT2 2
#define XDEVICE_PORT3 3 #define XDEVICE_PORT3 3
// #define XUSER_MAX_COUNT 4 // #define XUSER_MAX_COUNT 4
#define XUSER_INDEX_NONE 0x000000FE #define XUSER_INDEX_NONE 0x000000FE
#define XBX_CLR_DEFAULT 0xFF000000 #define XBX_CLR_DEFAULT 0xFF000000
#define XBX_CLR_WARNING 0x0000FFFF #define XBX_CLR_WARNING 0x0000FFFF
#define XBX_CLR_ERROR 0x000000FF #define XBX_CLR_ERROR 0x000000FF
#define XBOX_MINBORDERSAFE 0 #define XBOX_MINBORDERSAFE 0
#define XBOX_MAXBORDERSAFE 0 #define XBOX_MAXBORDERSAFE 0
typedef enum typedef enum {
{ XK_NULL,
XK_NULL, XK_BUTTON_UP,
XK_BUTTON_UP, XK_BUTTON_DOWN,
XK_BUTTON_DOWN, XK_BUTTON_LEFT,
XK_BUTTON_LEFT, XK_BUTTON_RIGHT,
XK_BUTTON_RIGHT, XK_BUTTON_START,
XK_BUTTON_START, XK_BUTTON_BACK,
XK_BUTTON_BACK, XK_BUTTON_STICK1,
XK_BUTTON_STICK1, XK_BUTTON_STICK2,
XK_BUTTON_STICK2, XK_BUTTON_A,
XK_BUTTON_A, XK_BUTTON_B,
XK_BUTTON_B, XK_BUTTON_X,
XK_BUTTON_X, XK_BUTTON_Y,
XK_BUTTON_Y, XK_BUTTON_LEFT_SHOULDER,
XK_BUTTON_LEFT_SHOULDER, XK_BUTTON_RIGHT_SHOULDER,
XK_BUTTON_RIGHT_SHOULDER, XK_BUTTON_LTRIGGER,
XK_BUTTON_LTRIGGER, XK_BUTTON_RTRIGGER,
XK_BUTTON_RTRIGGER, XK_STICK1_UP,
XK_STICK1_UP, XK_STICK1_DOWN,
XK_STICK1_DOWN, XK_STICK1_LEFT,
XK_STICK1_LEFT, XK_STICK1_RIGHT,
XK_STICK1_RIGHT, XK_STICK2_UP,
XK_STICK2_UP, XK_STICK2_DOWN,
XK_STICK2_DOWN, XK_STICK2_LEFT,
XK_STICK2_LEFT, XK_STICK2_RIGHT,
XK_STICK2_RIGHT, XK_MAX_KEYS,
XK_MAX_KEYS,
} xKey_t; } xKey_t;
//typedef enum // typedef enum
//{ //{
// XVRB_NONE, // off // XVRB_NONE, // off
// XVRB_ERROR, // fatal error // XVRB_ERROR, // fatal error
@ -90,74 +89,70 @@ typedef enum
// XVRB_WARNING, // non-fatal warnings // XVRB_WARNING, // non-fatal warnings
// XVRB_STATUS, // status reports // XVRB_STATUS, // status reports
// XVRB_ALL, // XVRB_ALL,
//} xverbose_e; // } xverbose_e;
#ifdef POSIX #ifdef POSIX
typedef DWORD COLORREF; typedef DWORD COLORREF;
#endif #endif
#ifndef INVALID_HANDLE_VALUE #ifndef INVALID_HANDLE_VALUE
#define INVALID_HANDLE_VALUE ((HANDLE)-1) #define INVALID_HANDLE_VALUE ((HANDLE) - 1)
#endif #endif
// typedef struct { // typedef struct {
// IN_ADDR ina; // IP address (zero if not static/DHCP) // IN_ADDR ina; // IP address (zero if not
// IN_ADDR inaOnline; // Online IP address (zero if not online) // static/DHCP) IN_ADDR inaOnline; // Online IP address
// WORD wPortOnline; // Online port // (zero if not online) WORD wPortOnline; // Online
// BYTE abEnet[6]; // Ethernet MAC address // port BYTE abEnet[6]; // Ethernet MAC address BYTE
// BYTE abOnline[20]; // Online identification // abOnline[20]; // Online identification } XNADDR;
// } XNADDR;
typedef int XNADDR; typedef int XNADDR;
typedef uint64 XUID; typedef uint64 XUID;
typedef struct { typedef struct {
BYTE ab[8]; // xbox to xbox key identifier BYTE ab[8]; // xbox to xbox key identifier
} XNKID; } XNKID;
typedef struct { typedef struct {
BYTE ab[16]; // xbox to xbox key exchange key BYTE ab[16]; // xbox to xbox key exchange key
} XNKEY; } XNKEY;
typedef struct _XSESSION_INFO typedef struct _XSESSION_INFO {
{ XNKID sessionID; // 8 bytes
XNKID sessionID; // 8 bytes XNADDR hostAddress; // 36 bytes
XNADDR hostAddress; // 36 bytes XNKEY keyExchangeKey; // 16 bytes
XNKEY keyExchangeKey; // 16 bytes
} XSESSION_INFO, *PXSESSION_INFO; } XSESSION_INFO, *PXSESSION_INFO;
typedef struct _XSESSION_REGISTRANT typedef struct _XSESSION_REGISTRANT {
{ uint64 qwMachineID;
uint64 qwMachineID; DWORD bTrustworthiness;
DWORD bTrustworthiness; DWORD bNumUsers;
DWORD bNumUsers; XUID* rgUsers;
XUID *rgUsers;
} XSESSION_REGISTRANT; } XSESSION_REGISTRANT;
typedef struct _XSESSION_REGISTRATION_RESULTS typedef struct _XSESSION_REGISTRATION_RESULTS {
{ DWORD wNumRegistrants;
DWORD wNumRegistrants; XSESSION_REGISTRANT* rgRegistrants;
XSESSION_REGISTRANT *rgRegistrants;
} XSESSION_REGISTRATION_RESULTS, *PXSESSION_REGISTRATION_RESULTS; } XSESSION_REGISTRATION_RESULTS, *PXSESSION_REGISTRATION_RESULTS;
#define XSESSION_CREATE_HOST 0 #define XSESSION_CREATE_HOST 0
#define XUSER_DATA_TYPE_INT32 0 #define XUSER_DATA_TYPE_INT32 0
#define XSESSION_CREATE_USES_ARBITRATION 0 #define XSESSION_CREATE_USES_ARBITRATION 0
#define XNET_QOS_LISTEN_ENABLE 0 #define XNET_QOS_LISTEN_ENABLE 0
#define XNET_QOS_LISTEN_DISABLE 0 #define XNET_QOS_LISTEN_DISABLE 0
#define XNET_QOS_LISTEN_SET_DATA 0 #define XNET_QOS_LISTEN_SET_DATA 0
FORCEINLINE void XBX_ProcessEvents() {} FORCEINLINE void XBX_ProcessEvents() {}
FORCEINLINE unsigned int XBX_GetSystemTime() { return 0; } FORCEINLINE unsigned int XBX_GetSystemTime() { return 0; }
FORCEINLINE int XBX_GetPrimaryUserId() { return 0; } FORCEINLINE int XBX_GetPrimaryUserId() { return 0; }
FORCEINLINE void XBX_SetPrimaryUserId( DWORD idx ) {} FORCEINLINE void XBX_SetPrimaryUserId(DWORD idx) {}
FORCEINLINE int XBX_GetStorageDeviceId() { return 0; } FORCEINLINE int XBX_GetStorageDeviceId() { return 0; }
FORCEINLINE void XBX_SetStorageDeviceId( DWORD idx ) {} FORCEINLINE void XBX_SetStorageDeviceId(DWORD idx) {}
FORCEINLINE const char *XBX_GetLanguageString() { return ""; } FORCEINLINE const char* XBX_GetLanguageString() { return ""; }
FORCEINLINE bool XBX_IsLocalized() { return false; } FORCEINLINE bool XBX_IsLocalized() { return false; }
#define XBX_INVALID_STORAGE_ID ((DWORD) -1) #define XBX_INVALID_STORAGE_ID ((DWORD) - 1)
#define XBX_STORAGE_DECLINED ((DWORD) -2) #define XBX_STORAGE_DECLINED ((DWORD) - 2)
#endif // XBOXSTUBS_H #endif // XBOXSTUBS_H

View file

@ -18,13 +18,18 @@ void PIXSetMarkerDeprecated(int a, const char* b, ...) {}
#include "../Xbox/Network/NetworkPlayerXbox.h" #include "../Xbox/Network/NetworkPlayerXbox.h"
NetworkPlayerXbox::NetworkPlayerXbox(IQNetPlayer* p) : m_qnetPlayer(p), m_pSocket(nullptr) {} NetworkPlayerXbox::NetworkPlayerXbox(IQNetPlayer* p)
: m_qnetPlayer(p), m_pSocket(nullptr) {}
IQNetPlayer* NetworkPlayerXbox::GetQNetPlayer() { return m_qnetPlayer; } IQNetPlayer* NetworkPlayerXbox::GetQNetPlayer() { return m_qnetPlayer; }
unsigned char NetworkPlayerXbox::GetSmallId() { return 0; } unsigned char NetworkPlayerXbox::GetSmallId() { return 0; }
void NetworkPlayerXbox::SendData(INetworkPlayer*, const void*, int, bool) {} void NetworkPlayerXbox::SendData(INetworkPlayer*, const void*, int, bool) {}
bool NetworkPlayerXbox::IsSameSystem(INetworkPlayer*) { return false; } bool NetworkPlayerXbox::IsSameSystem(INetworkPlayer*) { return false; }
int NetworkPlayerXbox::GetSendQueueSizeBytes(INetworkPlayer*, bool) { return 0; } int NetworkPlayerXbox::GetSendQueueSizeBytes(INetworkPlayer*, bool) {
int NetworkPlayerXbox::GetSendQueueSizeMessages(INetworkPlayer*, bool) { return 0; } return 0;
}
int NetworkPlayerXbox::GetSendQueueSizeMessages(INetworkPlayer*, bool) {
return 0;
}
int NetworkPlayerXbox::GetCurrentRtt() { return 0; } int NetworkPlayerXbox::GetCurrentRtt() { return 0; }
bool NetworkPlayerXbox::IsHost() { return false; } bool NetworkPlayerXbox::IsHost() { return false; }
bool NetworkPlayerXbox::IsGuest() { return false; } bool NetworkPlayerXbox::IsGuest() { return false; }

View file

@ -20,210 +20,212 @@
#include "../../Minecraft.World/Util/BasicTypeContainers.h" #include "../../Minecraft.World/Util/BasicTypeContainers.h"
#include "../Network/PlayerConnection.h" #include "../Network/PlayerConnection.h"
EntityTracker::EntityTracker(ServerLevel *level) EntityTracker::EntityTracker(ServerLevel* level) {
{
this->level = level; this->level = level;
maxRange = level->getServer()->getPlayers()->getMaxRange(); maxRange = level->getServer()->getPlayers()->getMaxRange();
} }
void EntityTracker::addEntity(std::shared_ptr<Entity> e) void EntityTracker::addEntity(std::shared_ptr<Entity> e) {
{ if (e->GetType() == eTYPE_SERVERPLAYER) {
if (e->GetType() == eTYPE_SERVERPLAYER)
{
addEntity(e, 32 * 16, 2); addEntity(e, 32 * 16, 2);
std::shared_ptr<ServerPlayer> player = std::dynamic_pointer_cast<ServerPlayer>(e); std::shared_ptr<ServerPlayer> player =
for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) std::dynamic_pointer_cast<ServerPlayer>(e);
{ for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) {
if( (*it)->e != player ) if ((*it)->e != player) {
{ (*it)->updatePlayer(this, player);
(*it)->updatePlayer(this, player); }
} }
} } else if (e->GetType() == eTYPE_FISHINGHOOK)
} addEntity(e, 16 * 4, 5, true);
else if (e->GetType() == eTYPE_FISHINGHOOK) addEntity(e, 16 * 4, 5, true); else if (e->GetType() == eTYPE_SMALL_FIREBALL)
else if (e->GetType() == eTYPE_SMALL_FIREBALL) addEntity(e, 16 * 4, 10, false); addEntity(e, 16 * 4, 10, false);
else if (e->GetType() == eTYPE_DRAGON_FIREBALL) addEntity(e, 16 * 4, 10, false); // 4J Added TU9 else if (e->GetType() == eTYPE_DRAGON_FIREBALL)
else if (e->GetType() == eTYPE_ARROW) addEntity(e, 16 * 4, 20, false); addEntity(e, 16 * 4, 10, false); // 4J Added TU9
else if (e->GetType() == eTYPE_FIREBALL) addEntity(e, 16 * 4, 10, false); else if (e->GetType() == eTYPE_ARROW)
else if (e->GetType() == eTYPE_SNOWBALL) addEntity(e, 16 * 4, 10, true); addEntity(e, 16 * 4, 20, false);
else if (e->GetType() == eTYPE_THROWNENDERPEARL) addEntity(e, 16 * 4, 10, true); else if (e->GetType() == eTYPE_FIREBALL)
else if (e->GetType() == eTYPE_EYEOFENDERSIGNAL ) addEntity(e, 16 * 4, 4, true); addEntity(e, 16 * 4, 10, false);
else if (e->GetType() == eTYPE_THROWNEGG) addEntity(e, 16 * 4, 10, true); else if (e->GetType() == eTYPE_SNOWBALL)
else if (e->GetType() == eTYPE_THROWNPOTION ) addEntity(e, 16 * 4, 10, true); addEntity(e, 16 * 4, 10, true);
else if (e->GetType() == eTYPE_THROWNEXPBOTTLE) addEntity(e, 16 * 4, 10, true); else if (e->GetType() == eTYPE_THROWNENDERPEARL)
else if (e->GetType() == eTYPE_ITEMENTITY) addEntity(e, 16 * 4, 20, true); addEntity(e, 16 * 4, 10, true);
else if (e->GetType() == eTYPE_MINECART) addEntity(e, 16 * 5, 3, true); else if (e->GetType() == eTYPE_EYEOFENDERSIGNAL)
else if (e->GetType() == eTYPE_BOAT) addEntity(e, 16 * 5, 3, true); addEntity(e, 16 * 4, 4, true);
else if (e->GetType() == eTYPE_SQUID) addEntity(e, 16 * 4, 3, true); else if (e->GetType() == eTYPE_THROWNEGG)
else if (std::dynamic_pointer_cast<Creature>(e)!=NULL) addEntity(e, 16 * 5, 3, true); addEntity(e, 16 * 4, 10, true);
else if (e->GetType() == eTYPE_ENDERDRAGON ) addEntity(e, 16 * 10, 3, true); else if (e->GetType() == eTYPE_THROWNPOTION)
else if (e->GetType() == eTYPE_PRIMEDTNT) addEntity(e, 16 * 10, 10, true); addEntity(e, 16 * 4, 10, true);
else if (e->GetType() == eTYPE_FALLINGTILE) addEntity(e, 16 * 10, 20, true); else if (e->GetType() == eTYPE_THROWNEXPBOTTLE)
else if (e->GetType() == eTYPE_PAINTING) addEntity(e, 16 * 10, INT_MAX, false); addEntity(e, 16 * 4, 10, true);
else if (e->GetType() == eTYPE_EXPERIENCEORB) addEntity(e, 16 * 10, 20, true); else if (e->GetType() == eTYPE_ITEMENTITY)
else if (e->GetType() == eTYPE_ENDER_CRYSTAL) addEntity(e, 16 * 16, INT_MAX, false); addEntity(e, 16 * 4, 20, true);
else if (e->GetType() == eTYPE_ITEM_FRAME) addEntity(e, 16 * 10, INT_MAX, false); else if (e->GetType() == eTYPE_MINECART)
addEntity(e, 16 * 5, 3, true);
else if (e->GetType() == eTYPE_BOAT)
addEntity(e, 16 * 5, 3, true);
else if (e->GetType() == eTYPE_SQUID)
addEntity(e, 16 * 4, 3, true);
else if (std::dynamic_pointer_cast<Creature>(e) != NULL)
addEntity(e, 16 * 5, 3, true);
else if (e->GetType() == eTYPE_ENDERDRAGON)
addEntity(e, 16 * 10, 3, true);
else if (e->GetType() == eTYPE_PRIMEDTNT)
addEntity(e, 16 * 10, 10, true);
else if (e->GetType() == eTYPE_FALLINGTILE)
addEntity(e, 16 * 10, 20, true);
else if (e->GetType() == eTYPE_PAINTING)
addEntity(e, 16 * 10, INT_MAX, false);
else if (e->GetType() == eTYPE_EXPERIENCEORB)
addEntity(e, 16 * 10, 20, true);
else if (e->GetType() == eTYPE_ENDER_CRYSTAL)
addEntity(e, 16 * 16, INT_MAX, false);
else if (e->GetType() == eTYPE_ITEM_FRAME)
addEntity(e, 16 * 10, INT_MAX, false);
} }
void EntityTracker::addEntity(std::shared_ptr<Entity> e, int range, int updateInterval) void EntityTracker::addEntity(std::shared_ptr<Entity> e, int range,
{ int updateInterval) {
addEntity(e, range, updateInterval, false); addEntity(e, range, updateInterval, false);
} }
void EntityTracker::addEntity(std::shared_ptr<Entity> e, int range, int updateInterval, bool trackDeltas) void EntityTracker::addEntity(std::shared_ptr<Entity> e, int range,
{ int updateInterval, bool trackDeltas) {
if (range > maxRange) range = maxRange; if (range > maxRange) range = maxRange;
if (entityMap.find(e->entityId) != entityMap.end()) if (entityMap.find(e->entityId) != entityMap.end()) {
{ assert(false); // Entity already tracked
assert(false); // Entity already tracked }
} if (e->entityId >= 2048) {
if( e->entityId >= 2048 ) __debugbreak();
{ }
__debugbreak(); std::shared_ptr<TrackedEntity> te = std::shared_ptr<TrackedEntity>(
} new TrackedEntity(e, range, updateInterval, trackDeltas));
std::shared_ptr<TrackedEntity> te = std::shared_ptr<TrackedEntity>( new TrackedEntity(e, range, updateInterval, trackDeltas) ); entities.insert(te);
entities.insert(te);
entityMap[e->entityId] = te; entityMap[e->entityId] = te;
te->updatePlayers(this, &level->players); te->updatePlayers(this, &level->players);
} }
// 4J - have split removeEntity into two bits - it used to do the equivalent of EntityTracker::removePlayer followed by EntityTracker::removeEntity. // 4J - have split removeEntity into two bits - it used to do the equivalent of
// This is to allow us to now choose to remove the player as a "seenBy" only when the player has actually been removed from the level's own player array // EntityTracker::removePlayer followed by EntityTracker::removeEntity. This is
void EntityTracker::removeEntity(std::shared_ptr<Entity> e) // to allow us to now choose to remove the player as a "seenBy" only when the
{ // player has actually been removed from the level's own player array
AUTO_VAR(it, entityMap.find(e->entityId)); void EntityTracker::removeEntity(std::shared_ptr<Entity> e) {
if( it != entityMap.end() ) AUTO_VAR(it, entityMap.find(e->entityId));
{ if (it != entityMap.end()) {
std::shared_ptr<TrackedEntity> te = it->second; std::shared_ptr<TrackedEntity> te = it->second;
entityMap.erase(it); entityMap.erase(it);
entities.erase(te); entities.erase(te);
te->broadcastRemoved(); te->broadcastRemoved();
}
}
void EntityTracker::removePlayer(std::shared_ptr<Entity> e)
{
if (e->GetType() == eTYPE_SERVERPLAYER)
{
std::shared_ptr<ServerPlayer> player = std::dynamic_pointer_cast<ServerPlayer>(e);
for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ )
{
(*it)->removePlayer(player);
}
} }
} }
void EntityTracker::tick() void EntityTracker::removePlayer(std::shared_ptr<Entity> e) {
{ if (e->GetType() == eTYPE_SERVERPLAYER) {
std::vector<std::shared_ptr<ServerPlayer> > movedPlayers; std::shared_ptr<ServerPlayer> player =
for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) std::dynamic_pointer_cast<ServerPlayer>(e);
{ for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) {
std::shared_ptr<TrackedEntity> te = *it; (*it)->removePlayer(player);
te->tick(this, &level->players);
if (te->moved && te->e->GetType() == eTYPE_SERVERPLAYER)
{
movedPlayers.push_back(std::dynamic_pointer_cast<ServerPlayer>(te->e));
} }
} }
}
// 4J Stu - If one player on a system is updated, then make sure they all are as they all have their void EntityTracker::tick() {
// range extended to include entities visible by any other player on the system std::vector<std::shared_ptr<ServerPlayer> > movedPlayers;
// Fix for #11194 - Gameplay: Host player and their split-screen avatars can become invisible and invulnerable to client. for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) {
MinecraftServer *server = MinecraftServer::getInstance(); std::shared_ptr<TrackedEntity> te = *it;
for( unsigned int i = 0; i < server->getPlayers()->players.size(); i++ ) te->tick(this, &level->players);
{ if (te->moved && te->e->GetType() == eTYPE_SERVERPLAYER) {
std::shared_ptr<ServerPlayer> ep = server->getPlayers()->players[i]; movedPlayers.push_back(
if( ep->dimension != level->dimension->id ) continue; std::dynamic_pointer_cast<ServerPlayer>(te->e));
}
}
if( ep->connection == NULL ) continue; // 4J Stu - If one player on a system is updated, then make sure they all
INetworkPlayer *thisPlayer = ep->connection->getNetworkPlayer(); // are as they all have their range extended to include entities visible by
if( thisPlayer == NULL ) continue; // any other player on the system Fix for #11194 - Gameplay: Host player and
// their split-screen avatars can become invisible and invulnerable to
// client.
MinecraftServer* server = MinecraftServer::getInstance();
for (unsigned int i = 0; i < server->getPlayers()->players.size(); i++) {
std::shared_ptr<ServerPlayer> ep = server->getPlayers()->players[i];
if (ep->dimension != level->dimension->id) continue;
bool addPlayer = false; if (ep->connection == NULL) continue;
for (unsigned int j = 0; j < movedPlayers.size(); j++) INetworkPlayer* thisPlayer = ep->connection->getNetworkPlayer();
{ if (thisPlayer == NULL) continue;
std::shared_ptr<ServerPlayer> sp = movedPlayers[j];
if( sp == ep ) break; bool addPlayer = false;
for (unsigned int j = 0; j < movedPlayers.size(); j++) {
std::shared_ptr<ServerPlayer> sp = movedPlayers[j];
if(sp->connection == NULL) continue; if (sp == ep) break;
INetworkPlayer *otherPlayer = sp->connection->getNetworkPlayer();
if( otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer) )
{
addPlayer = true;
break;
}
}
if( addPlayer ) movedPlayers.push_back( ep );
}
for (unsigned int i = 0; i < movedPlayers.size(); i++) if (sp->connection == NULL) continue;
{ INetworkPlayer* otherPlayer = sp->connection->getNetworkPlayer();
if (otherPlayer != NULL && thisPlayer->IsSameSystem(otherPlayer)) {
addPlayer = true;
break;
}
}
if (addPlayer) movedPlayers.push_back(ep);
}
for (unsigned int i = 0; i < movedPlayers.size(); i++) {
std::shared_ptr<ServerPlayer> player = movedPlayers[i]; std::shared_ptr<ServerPlayer> player = movedPlayers[i];
if(player->connection == NULL) continue; if (player->connection == NULL) continue;
for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) {
{ std::shared_ptr<TrackedEntity> te = *it;
std::shared_ptr<TrackedEntity> te = *it; if (te->e != player) {
if (te->e != player)
{
te->updatePlayer(this, player); te->updatePlayer(this, player);
} }
} }
} }
// 4J Stu - We want to do this for dead players as they don't tick normally // 4J Stu - We want to do this for dead players as they don't tick normally
for(AUTO_VAR(it, level->players.begin()); it != level->players.end(); ++it) for (AUTO_VAR(it, level->players.begin()); it != level->players.end();
{ ++it) {
std::shared_ptr<ServerPlayer> player = std::dynamic_pointer_cast<ServerPlayer>(*it); std::shared_ptr<ServerPlayer> player =
if(!player->isAlive()) std::dynamic_pointer_cast<ServerPlayer>(*it);
{ if (!player->isAlive()) {
player->flushEntitiesToRemove(); player->flushEntitiesToRemove();
} }
} }
} }
void EntityTracker::broadcast(std::shared_ptr<Entity> e, std::shared_ptr<Packet> packet) void EntityTracker::broadcast(std::shared_ptr<Entity> e,
{ std::shared_ptr<Packet> packet) {
AUTO_VAR(it, entityMap.find( e->entityId )); AUTO_VAR(it, entityMap.find(e->entityId));
if( it != entityMap.end() ) if (it != entityMap.end()) {
{ std::shared_ptr<TrackedEntity> te = it->second;
std::shared_ptr<TrackedEntity> te = it->second; te->broadcast(packet);
te->broadcast(packet); }
}
} }
void EntityTracker::broadcastAndSend(std::shared_ptr<Entity> e, std::shared_ptr<Packet> packet) void EntityTracker::broadcastAndSend(std::shared_ptr<Entity> e,
{ std::shared_ptr<Packet> packet) {
AUTO_VAR(it, entityMap.find( e->entityId )); AUTO_VAR(it, entityMap.find(e->entityId));
if( it != entityMap.end() ) if (it != entityMap.end()) {
{ std::shared_ptr<TrackedEntity> te = it->second;
std::shared_ptr<TrackedEntity> te = it->second; te->broadcastAndSend(packet);
te->broadcastAndSend(packet); }
}
} }
void EntityTracker::clear(std::shared_ptr<ServerPlayer> serverPlayer) void EntityTracker::clear(std::shared_ptr<ServerPlayer> serverPlayer) {
{ for (AUTO_VAR(it, entities.begin()); it != entities.end(); it++) {
for( AUTO_VAR(it, entities.begin()); it != entities.end(); it++ ) std::shared_ptr<TrackedEntity> te = *it;
{ te->clear(serverPlayer);
std::shared_ptr<TrackedEntity> te = *it; }
te->clear(serverPlayer);
}
} }
// AP added for Vita so the range can be increased once the level starts // AP added for Vita so the range can be increased once the level starts
void EntityTracker::updateMaxRange() void EntityTracker::updateMaxRange() {
{
maxRange = level->getServer()->getPlayers()->getMaxRange(); maxRange = level->getServer()->getPlayers()->getMaxRange();
} }
std::shared_ptr<TrackedEntity> EntityTracker::getTracker(
std::shared_ptr<TrackedEntity> EntityTracker::getTracker(std::shared_ptr<Entity> e) std::shared_ptr<Entity> e) {
{ AUTO_VAR(it, entityMap.find(e->entityId));
AUTO_VAR(it, entityMap.find(e->entityId)); if (it != entityMap.end()) {
if( it != entityMap.end() ) return it->second;
{ }
return it->second; return nullptr;
}
return nullptr;
} }

View file

@ -7,30 +7,30 @@ class TrackedEntity;
class MinecraftServer; class MinecraftServer;
class Packet; class Packet;
class EntityTracker {
class EntityTracker
{
private: private:
ServerLevel *level; ServerLevel* level;
std::unordered_set<std::shared_ptr<TrackedEntity> > entities; std::unordered_set<std::shared_ptr<TrackedEntity> > entities;
std::unordered_map<int, std::shared_ptr<TrackedEntity> , IntKeyHash2, IntKeyEq> entityMap; // was IntHashMap std::unordered_map<int, std::shared_ptr<TrackedEntity>, IntKeyHash2,
IntKeyEq>
entityMap; // was IntHashMap
int maxRange; int maxRange;
public: public:
EntityTracker(ServerLevel *level); EntityTracker(ServerLevel* level);
void addEntity(std::shared_ptr<Entity> e); void addEntity(std::shared_ptr<Entity> e);
void addEntity(std::shared_ptr<Entity> e, int range, int updateInterval); void addEntity(std::shared_ptr<Entity> e, int range, int updateInterval);
void addEntity(std::shared_ptr<Entity> e, int range, int updateInterval, bool trackDeltas); void addEntity(std::shared_ptr<Entity> e, int range, int updateInterval,
bool trackDeltas);
void removeEntity(std::shared_ptr<Entity> e); void removeEntity(std::shared_ptr<Entity> e);
void removePlayer(std::shared_ptr<Entity> e); // 4J added void removePlayer(std::shared_ptr<Entity> e); // 4J added
void tick(); void tick();
void broadcast(std::shared_ptr<Entity> e, std::shared_ptr<Packet> packet); void broadcast(std::shared_ptr<Entity> e, std::shared_ptr<Packet> packet);
void broadcastAndSend(std::shared_ptr<Entity> e, std::shared_ptr<Packet> packet); void broadcastAndSend(std::shared_ptr<Entity> e,
std::shared_ptr<Packet> packet);
void clear(std::shared_ptr<ServerPlayer> serverPlayer); void clear(std::shared_ptr<ServerPlayer> serverPlayer);
void updateMaxRange(); // AP added for Vita void updateMaxRange(); // AP added for Vita
// 4J-JEV: Added, needed access to tracked entity of a riders mount.
// 4J-JEV: Added, needed access to tracked entity of a riders mount. std::shared_ptr<TrackedEntity> getTracker(std::shared_ptr<Entity> entity);
std::shared_ptr<TrackedEntity> getTracker(std::shared_ptr<Entity> entity);
}; };

File diff suppressed because it is too large Load diff

View file

@ -14,187 +14,199 @@ class Input;
class Stat; class Stat;
class Minecraft; class Minecraft;
// Time in seconds before the players presence is update to Idle // Time in seconds before the players presence is update to Idle
#define PLAYER_IDLE_TIME 300 #define PLAYER_IDLE_TIME 300
class LocalPlayer : public Player class LocalPlayer : public Player {
{
public: public:
static const int SPRINT_DURATION = 20 * 30; static const int SPRINT_DURATION = 20 * 30;
Input* input;
Input *input;
protected: protected:
Minecraft *minecraft; Minecraft* minecraft;
int sprintTriggerTime; int sprintTriggerTime;
bool sprintTriggerRegisteredReturn; // 4J added bool sprintTriggerRegisteredReturn; // 4J added
bool twoJumpsRegistered; // 4J added bool twoJumpsRegistered; // 4J added
unsigned int m_uiInactiveTicks; // To measure time for idle anims unsigned int m_uiInactiveTicks; // To measure time for idle anims
unsigned long long m_awardedThisSession; unsigned long long m_awardedThisSession;
// 4J - Last time we checked for achievement uunlocks. // 4J - Last time we checked for achievement uunlocks.
//long long m_lastAchievementUpdate; // long long m_lastAchievementUpdate;
public: public:
int sprintTime; int sprintTime;
float yBob, xBob; float yBob, xBob;
float yBobO, xBobO; float yBobO, xBobO;
LocalPlayer(Minecraft *minecraft, Level *level, User *user, int dimension); LocalPlayer(Minecraft* minecraft, Level* level, User* user, int dimension);
virtual ~LocalPlayer(); virtual ~LocalPlayer();
void move(double xa, double ya, double za, bool noEntityCubes=false); // 4J - added noEntityCubes parameter void move(
double xa, double ya, double za,
bool noEntityCubes = false); // 4J - added noEntityCubes parameter
int m_iScreenSection; // assuming 4player splitscreen for now, or -1 for
int m_iScreenSection; // assuming 4player splitscreen for now, or -1 for single player // single player
__uint64 ullButtonsPressed; // Stores the button presses, since the inputmanager can be ticked faster than the minecraft __uint64
// player tick, and a button press and release combo can be missed in the minecraft::tick ullButtonsPressed; // Stores the button presses, since the inputmanager
// can be ticked faster than the minecraft player
// tick, and a button press and release combo can be
// missed in the minecraft::tick
__uint64 ullDpad_last; __uint64 ullDpad_last;
__uint64 ullDpad_this; __uint64 ullDpad_this;
__uint64 ullDpad_filtered; __uint64 ullDpad_filtered;
// 4J-PB - moved these in from the minecraft structure, since they are per player things for splitscreen // 4J-PB - moved these in from the minecraft structure, since they are per
//int ticks; // player things for splitscreen
int missTime; // int ticks;
int lastClickTick[2]; int missTime;
bool isRaining ; int lastClickTick[2];
int m_iThirdPersonView; bool isRaining;
int m_iThirdPersonView;
bool m_bHasAwardedStayinFrosty; bool m_bHasAwardedStayinFrosty;
private: private:
float flyX, flyY, flyZ; float flyX, flyY, flyZ;
protected:
// 4J-PB - player's xbox pad
int m_iPad;
bool m_bIsIdle; protected:
// 4J-PB - player's xbox pad
int m_iPad;
bool m_bIsIdle;
private: private:
// local player fly // local player fly
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// smooth camera settings // smooth camera settings
SmoothFloat smoothFlyX; SmoothFloat smoothFlyX;
SmoothFloat smoothFlyY; SmoothFloat smoothFlyY;
SmoothFloat smoothFlyZ; SmoothFloat smoothFlyZ;
void calculateFlight(float xa, float ya, float za); void calculateFlight(float xa, float ya, float za);
public: public:
virtual void serverAiStep(); virtual void serverAiStep();
protected: protected:
bool isEffectiveAI(); bool isEffectiveAI();
public: public:
virtual void aiStep(); virtual void aiStep();
virtual void changeDimension(int i); virtual void changeDimension(int i);
virtual float getFieldOfViewModifier(); virtual float getFieldOfViewModifier();
virtual void addAdditonalSaveData(CompoundTag *entityTag); virtual void addAdditonalSaveData(CompoundTag* entityTag);
virtual void readAdditionalSaveData(CompoundTag *entityTag); virtual void readAdditionalSaveData(CompoundTag* entityTag);
virtual void closeContainer(); virtual void closeContainer();
virtual void openTextEdit(std::shared_ptr<SignTileEntity> sign); virtual void openTextEdit(std::shared_ptr<SignTileEntity> sign);
virtual bool openContainer(std::shared_ptr<Container> container); // 4J added bool return virtual bool openContainer(
virtual bool startCrafting(int x, int y, int z); // 4J added bool return std::shared_ptr<Container> container); // 4J added bool return
virtual bool startEnchanting(int x, int y, int z); // 4J added bool return virtual bool startCrafting(int x, int y, int z); // 4J added bool return
virtual bool startRepairing(int x, int y, int z); virtual bool startEnchanting(int x, int y, int z); // 4J added bool return
virtual bool openFurnace(std::shared_ptr<FurnaceTileEntity> furnace); // 4J added bool return virtual bool startRepairing(int x, int y, int z);
virtual bool openBrewingStand(std::shared_ptr<BrewingStandTileEntity> brewingStand); // 4J added bool return virtual bool openFurnace(
virtual bool openTrap(std::shared_ptr<DispenserTileEntity> trap); // 4J added bool return std::shared_ptr<FurnaceTileEntity> furnace); // 4J added bool return
virtual bool openTrading(std::shared_ptr<Merchant> traderTarget); virtual bool openBrewingStand(std::shared_ptr<BrewingStandTileEntity>
virtual void crit(std::shared_ptr<Entity> e); brewingStand); // 4J added bool return
virtual void magicCrit(std::shared_ptr<Entity> e); virtual bool openTrap(
std::shared_ptr<DispenserTileEntity> trap); // 4J added bool return
virtual bool openTrading(std::shared_ptr<Merchant> traderTarget);
virtual void crit(std::shared_ptr<Entity> e);
virtual void magicCrit(std::shared_ptr<Entity> e);
virtual void take(std::shared_ptr<Entity> e, int orgCount); virtual void take(std::shared_ptr<Entity> e, int orgCount);
virtual void chat(const std::wstring& message); virtual void chat(const std::wstring& message);
virtual bool isSneaking(); virtual bool isSneaking();
//virtual bool isIdle(); // virtual bool isIdle();
virtual void hurtTo(int newHealth, ETelemetryChallenges damageSource); virtual void hurtTo(int newHealth, ETelemetryChallenges damageSource);
virtual void respawn(); virtual void respawn();
virtual void animateRespawn(); virtual void animateRespawn();
virtual void displayClientMessage(int messageId); virtual void displayClientMessage(int messageId);
virtual void awardStat(Stat *stat, byteArray param); virtual void awardStat(Stat* stat, byteArray param);
virtual int ThirdPersonView() { return m_iThirdPersonView;} virtual int ThirdPersonView() { return m_iThirdPersonView; }
// 4J - have changed 3rd person view to be 0 if not enabled, 1 for mode like original, 2 reversed mode // 4J - have changed 3rd person view to be 0 if not enabled, 1 for mode like
virtual void SetThirdPersonView(int val) {m_iThirdPersonView=val;} // original, 2 reversed mode
virtual void SetThirdPersonView(int val) { m_iThirdPersonView = val; }
void ResetInactiveTicks() { m_uiInactiveTicks=0;} void ResetInactiveTicks() { m_uiInactiveTicks = 0; }
unsigned int GetInactiveTicks() { return m_uiInactiveTicks;} unsigned int GetInactiveTicks() { return m_uiInactiveTicks; }
void IncrementInactiveTicks() { if(m_uiInactiveTicks<255) m_uiInactiveTicks++;} void IncrementInactiveTicks() {
if (m_uiInactiveTicks < 255) m_uiInactiveTicks++;
}
void mapPlayerChunk(unsigned int); void mapPlayerChunk(unsigned int);
// 4J-PB - xbox pad for this player // 4J-PB - xbox pad for this player
void SetXboxPad(int iPad) {m_iPad=iPad;} void SetXboxPad(int iPad) { m_iPad = iPad; }
int GetXboxPad() {return m_iPad;} int GetXboxPad() { return m_iPad; }
void SetPlayerRespawned(bool bVal) {m_bPlayerRespawned=bVal;} void SetPlayerRespawned(bool bVal) { m_bPlayerRespawned = bVal; }
bool GetPlayerRespawned() {return m_bPlayerRespawned;} bool GetPlayerRespawned() { return m_bPlayerRespawned; }
// 4J-PB - Moved these in here from the minecraft structure since they are local player related // 4J-PB - Moved these in here from the minecraft structure since they are
void handleMouseDown(int button, bool down); // local player related
bool handleMouseClick(int button); void handleMouseDown(int button, bool down);
bool handleMouseClick(int button);
// 4J - added for improved autorepeat // 4J - added for improved autorepeat
bool creativeModeHandleMouseClick(int button, bool buttonPressed); bool creativeModeHandleMouseClick(int button, bool buttonPressed);
float lastClickX; float lastClickX;
float lastClickY; float lastClickY;
float lastClickZ; float lastClickZ;
float lastClickdX; float lastClickdX;
float lastClickdY; float lastClickdY;
float lastClickdZ; float lastClickdZ;
enum eLastClickState enum eLastClickState {
{ lastClick_invalid,
lastClick_invalid, lastClick_init,
lastClick_init, lastClick_moving,
lastClick_moving, lastClick_stopped,
lastClick_stopped, lastClick_oldRepeat,
lastClick_oldRepeat, lastClick_disabled
lastClick_disabled };
}; float lastClickTolerance;
float lastClickTolerance; int lastClickState;
int lastClickState;
// 4J Stu - Added to allow callback to tutorial to stay within Minecraft.Client // 4J Stu - Added to allow callback to tutorial to stay within
virtual void onCrafted(std::shared_ptr<ItemInstance> item); // Minecraft.Client
virtual void onCrafted(std::shared_ptr<ItemInstance> item);
virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); virtual void setAndBroadcastCustomSkin(std::uint32_t skinId);
virtual void setAndBroadcastCustomCape(std::uint32_t capeId); virtual void setAndBroadcastCustomCape(std::uint32_t capeId);
private: private:
bool isSolidBlock(int x, int y, int z); bool isSolidBlock(int x, int y, int z);
bool m_bPlayerRespawned; bool m_bPlayerRespawned;
protected: protected:
bool checkInTile(double x, double y, double z); bool checkInTile(double x, double y, double z);
public: public:
void setSprinting(bool value); void setSprinting(bool value);
void setExperienceValues(float experienceProgress, int totalExp, int experienceLevel); void setExperienceValues(float experienceProgress, int totalExp,
int experienceLevel);
bool hasPermission(EGameCommand command); bool hasPermission(EGameCommand command);
void updateRichPresence(); void updateRichPresence();
// 4J Stu - Added for telemetry // 4J Stu - Added for telemetry
float m_sessionTimeStart; float m_sessionTimeStart;
float m_dimensionTimeStart; float m_dimensionTimeStart;
public: public:
void SetSessionTimerStart(void); void SetSessionTimerStart(void);
float getSessionTimer(void); float getSessionTimer(void);
float getAndResetChangeDimensionTimer(); float getAndResetChangeDimensionTimer();
virtual void handleCollectItem(std::shared_ptr<ItemInstance> item); virtual void handleCollectItem(std::shared_ptr<ItemInstance> item);
void SetPlayerAdditionalModelParts(std::vector<ModelPart *>pAdditionalModelParts); void SetPlayerAdditionalModelParts(
std::vector<ModelPart*> pAdditionalModelParts);
private: private:
std::vector<ModelPart *> m_pAdditionalModelParts; std::vector<ModelPart*> m_pAdditionalModelParts;
}; };

View file

@ -13,9 +13,9 @@
#include "../../Minecraft.World/Headers/net.minecraft.world.inventory.h" #include "../../Minecraft.World/Headers/net.minecraft.world.inventory.h"
#include "../../Minecraft.World/Headers/net.minecraft.h" #include "../../Minecraft.World/Headers/net.minecraft.h"
MultiPlayerGameMode::MultiPlayerGameMode(Minecraft *minecraft, ClientConnection *connection) MultiPlayerGameMode::MultiPlayerGameMode(Minecraft* minecraft,
{ ClientConnection* connection) {
// 4J - added initialisers // 4J - added initialisers
xDestroyBlock = -1; xDestroyBlock = -1;
yDestroyBlock = -1; yDestroyBlock = -1;
zDestroyBlock = -1; zDestroyBlock = -1;
@ -24,112 +24,102 @@ MultiPlayerGameMode::MultiPlayerGameMode(Minecraft *minecraft, ClientConnection
destroyTicks = 0; destroyTicks = 0;
destroyDelay = 0; destroyDelay = 0;
isDestroying = false; isDestroying = false;
carriedItem = 0; carriedItem = 0;
localPlayerMode = GameType::SURVIVAL; localPlayerMode = GameType::SURVIVAL;
this->minecraft = minecraft; this->minecraft = minecraft;
this->connection = connection; this->connection = connection;
} }
void MultiPlayerGameMode::creativeDestroyBlock(Minecraft *minecraft, MultiPlayerGameMode *gameMode, int x, int y, int z, int face) void MultiPlayerGameMode::creativeDestroyBlock(Minecraft* minecraft,
{ MultiPlayerGameMode* gameMode,
if (!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) int x, int y, int z, int face) {
{ if (!minecraft->level->extinguishFire(minecraft->player, x, y, z, face)) {
gameMode->destroyBlock(x, y, z, face); gameMode->destroyBlock(x, y, z, face);
} }
} }
void MultiPlayerGameMode::adjustPlayer(std::shared_ptr<Player> player) void MultiPlayerGameMode::adjustPlayer(std::shared_ptr<Player> player) {
{ localPlayerMode->updatePlayerAbilities(&player->abilities);
localPlayerMode->updatePlayerAbilities(&player->abilities);
} }
bool MultiPlayerGameMode::isCutScene() bool MultiPlayerGameMode::isCutScene() { return false; }
{
return false; void MultiPlayerGameMode::setLocalMode(GameType* mode) {
localPlayerMode = mode;
localPlayerMode->updatePlayerAbilities(&minecraft->player->abilities);
} }
void MultiPlayerGameMode::setLocalMode(GameType *mode) void MultiPlayerGameMode::initPlayer(std::shared_ptr<Player> player) {
{ player->yRot = -180;
localPlayerMode = mode;
localPlayerMode->updatePlayerAbilities(&minecraft->player->abilities);
} }
void MultiPlayerGameMode::initPlayer(std::shared_ptr<Player> player) bool MultiPlayerGameMode::canHurtPlayer() {
{ return localPlayerMode->isSurvival();
player->yRot = -180;
} }
bool MultiPlayerGameMode::canHurtPlayer() bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face) {
{ if (localPlayerMode->isReadOnly()) {
return localPlayerMode->isSurvival(); return false;
} }
bool MultiPlayerGameMode::destroyBlock(int x, int y, int z, int face) Level* level = minecraft->level;
{ Tile* oldTile = Tile::tiles[level->getTile(x, y, z)];
if (localPlayerMode->isReadOnly())
{
return false;
}
Level *level = minecraft->level; if (oldTile == NULL) return false;
Tile *oldTile = Tile::tiles[level->getTile(x, y, z)];
if (oldTile == NULL) return false; level->levelEvent(
LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z,
oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT));
level->levelEvent(LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, oldTile->id + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT)); int data = level->getData(x, y, z);
bool changed = level->setTile(x, y, z, 0);
if (changed) {
oldTile->destroy(level, x, y, z, data);
}
int data = level->getData(x, y, z); if (!localPlayerMode->isCreative()) {
bool changed = level->setTile(x, y, z, 0); std::shared_ptr<ItemInstance> item =
if (changed) minecraft->player->getSelectedItem();
{ if (item != NULL) {
oldTile->destroy(level, x, y, z, data); item->mineBlock(level, oldTile->id, x, y, z, minecraft->player);
} if (item->count == 0) {
minecraft->player->removeSelectedItem();
if (!localPlayerMode->isCreative()) }
{ }
std::shared_ptr<ItemInstance> item = minecraft->player->getSelectedItem(); }
if (item != NULL)
{
item->mineBlock(level, oldTile->id, x, y, z, minecraft->player);
if (item->count == 0)
{
minecraft->player->removeSelectedItem();
}
}
}
return changed; return changed;
} }
void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) {
{ if (!minecraft->player->isAllowedToMine()) return;
if(!minecraft->player->isAllowedToMine()) return; if (localPlayerMode->isReadOnly()) {
if (localPlayerMode->isReadOnly()) return;
{ }
return;
}
if (localPlayerMode->isCreative()) if (localPlayerMode->isCreative()) {
{ connection->send(
connection->send(std::shared_ptr<PlayerActionPacket>( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) )); std::shared_ptr<PlayerActionPacket>(new PlayerActionPacket(
creativeDestroyBlock(minecraft, this, x, y, z, face); PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face)));
destroyDelay = 5; creativeDestroyBlock(minecraft, this, x, y, z, face);
} destroyDelay = 5;
else if (!isDestroying || x != xDestroyBlock || y != yDestroyBlock || z != zDestroyBlock) } else if (!isDestroying || x != xDestroyBlock || y != yDestroyBlock ||
{ z != zDestroyBlock) {
connection->send( std::shared_ptr<PlayerActionPacket>( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) ) ); connection->send(
std::shared_ptr<PlayerActionPacket>(new PlayerActionPacket(
PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face)));
int t = minecraft->level->getTile(x, y, z); int t = minecraft->level->getTile(x, y, z);
if (t > 0 && destroyProgress == 0) Tile::tiles[t]->attack(minecraft->level, x, y, z, minecraft->player); if (t > 0 && destroyProgress == 0)
Tile::tiles[t]->attack(minecraft->level, x, y, z,
minecraft->player);
if (t > 0 && if (t > 0 &&
(Tile::tiles[t]->getDestroyProgress(minecraft->player, minecraft->player->level, x, y, z) >= 1 || (Tile::tiles[t]->getDestroyProgress(
(app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<<eDebugSetting_InstantDestroy)) minecraft->player, minecraft->player->level, x, y, z) >= 1 ||
) (app.DebugSettingsOn() &&
) app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad()) &
{ (1L << eDebugSetting_InstantDestroy)))) {
destroyBlock(x, y, z, face); destroyBlock(x, y, z, face);
} } else {
else
{
isDestroying = true; isDestroying = true;
xDestroyBlock = x; xDestroyBlock = x;
yDestroyBlock = y; yDestroyBlock = y;
@ -137,342 +127,351 @@ void MultiPlayerGameMode::startDestroyBlock(int x, int y, int z, int face)
destroyProgress = 0; destroyProgress = 0;
oDestroyProgress = 0; oDestroyProgress = 0;
destroyTicks = 0; destroyTicks = 0;
minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, (int)(destroyProgress * 10) - 1); minecraft->level->destroyTileProgress(
minecraft->player->entityId, xDestroyBlock, yDestroyBlock,
zDestroyBlock, (int)(destroyProgress * 10) - 1);
} }
} }
} }
void MultiPlayerGameMode::stopDestroyBlock() void MultiPlayerGameMode::stopDestroyBlock() {
{ if (isDestroying) {
if (isDestroying) connection->send(
{ std::shared_ptr<PlayerActionPacket>(new PlayerActionPacket(
connection->send(std::shared_ptr<PlayerActionPacket>(new PlayerActionPacket(PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1))); PlayerActionPacket::ABORT_DESTROY_BLOCK, xDestroyBlock,
} yDestroyBlock, zDestroyBlock, -1)));
}
isDestroying = false; isDestroying = false;
destroyProgress = 0; destroyProgress = 0;
minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); minecraft->level->destroyTileProgress(minecraft->player->entityId,
xDestroyBlock, yDestroyBlock,
zDestroyBlock, -1);
} }
void MultiPlayerGameMode::continueDestroyBlock(int x, int y, int z, int face) void MultiPlayerGameMode::continueDestroyBlock(int x, int y, int z, int face) {
{ if (!minecraft->player->isAllowedToMine()) return;
if(!minecraft->player->isAllowedToMine()) return;
ensureHasSentCarriedItem(); ensureHasSentCarriedItem();
// connection.send(new PlayerActionPacket(PlayerActionPacket.CONTINUE_DESTROY_BLOCK, x, y, z, face)); // connection.send(new
// PlayerActionPacket(PlayerActionPacket.CONTINUE_DESTROY_BLOCK, x,
// y, z, face));
if (destroyDelay > 0) if (destroyDelay > 0) {
{
destroyDelay--; destroyDelay--;
return; return;
} }
if (localPlayerMode->isCreative()) if (localPlayerMode->isCreative()) {
{ destroyDelay = 5;
destroyDelay = 5; connection->send(
connection->send(std::shared_ptr<PlayerActionPacket>( new PlayerActionPacket(PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face) ) ); std::shared_ptr<PlayerActionPacket>(new PlayerActionPacket(
creativeDestroyBlock(minecraft, this, x, y, z, face); PlayerActionPacket::START_DESTROY_BLOCK, x, y, z, face)));
return; creativeDestroyBlock(minecraft, this, x, y, z, face);
} return;
}
if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) {
{
int t = minecraft->level->getTile(x, y, z); int t = minecraft->level->getTile(x, y, z);
if (t == 0) if (t == 0) {
{
isDestroying = false; isDestroying = false;
return; return;
} }
Tile *tile = Tile::tiles[t]; Tile* tile = Tile::tiles[t];
destroyProgress += tile->getDestroyProgress(minecraft->player, minecraft->player->level, x, y, z); destroyProgress += tile->getDestroyProgress(
minecraft->player, minecraft->player->level, x, y, z);
if (destroyTicks % 4 == 0) if (destroyTicks % 4 == 0) {
{ if (tile != NULL) {
if (tile != NULL) int iStepSound = tile->soundType->getStepSound();
{
int iStepSound=tile->soundType->getStepSound();
minecraft->soundEngine->play(iStepSound, x + 0.5f, y + 0.5f, z + 0.5f, (tile->soundType->getVolume() + 1) / 8, tile->soundType->getPitch() * 0.5f); minecraft->soundEngine->play(
iStepSound, x + 0.5f, y + 0.5f, z + 0.5f,
(tile->soundType->getVolume() + 1) / 8,
tile->soundType->getPitch() * 0.5f);
} }
} }
destroyTicks++; destroyTicks++;
if (destroyProgress >= 1) if (destroyProgress >= 1) {
{
isDestroying = false; isDestroying = false;
connection->send( std::shared_ptr<PlayerActionPacket>( new PlayerActionPacket(PlayerActionPacket::STOP_DESTROY_BLOCK, x, y, z, face) ) ); connection->send(
destroyBlock(x, y, z, face); std::shared_ptr<PlayerActionPacket>(new PlayerActionPacket(
PlayerActionPacket::STOP_DESTROY_BLOCK, x, y, z, face)));
destroyBlock(x, y, z, face);
destroyProgress = 0; destroyProgress = 0;
oDestroyProgress = 0; oDestroyProgress = 0;
destroyTicks = 0; destroyTicks = 0;
destroyDelay = 5; destroyDelay = 5;
} }
minecraft->level->destroyTileProgress(minecraft->player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, (int)(destroyProgress * 10) - 1); minecraft->level->destroyTileProgress(
} minecraft->player->entityId, xDestroyBlock, yDestroyBlock,
else zDestroyBlock, (int)(destroyProgress * 10) - 1);
{ } else {
startDestroyBlock(x, y, z, face); startDestroyBlock(x, y, z, face);
} }
} }
float MultiPlayerGameMode::getPickRange() float MultiPlayerGameMode::getPickRange() {
{ if (localPlayerMode->isCreative()) {
if (localPlayerMode->isCreative()) return 5.0f;
{ }
return 5.0f; return 4.5f;
}
return 4.5f;
} }
void MultiPlayerGameMode::tick() void MultiPlayerGameMode::tick() {
{
ensureHasSentCarriedItem(); ensureHasSentCarriedItem();
oDestroyProgress = destroyProgress; oDestroyProgress = destroyProgress;
//minecraft->soundEngine->playMusicTick(); // minecraft->soundEngine->playMusicTick();
} }
void MultiPlayerGameMode::ensureHasSentCarriedItem() void MultiPlayerGameMode::ensureHasSentCarriedItem() {
{
int newItem = minecraft->player->inventory->selected; int newItem = minecraft->player->inventory->selected;
if (newItem != carriedItem) if (newItem != carriedItem) {
{
carriedItem = newItem; carriedItem = newItem;
connection->send( std::shared_ptr<SetCarriedItemPacket>( new SetCarriedItemPacket(carriedItem) ) ); connection->send(std::shared_ptr<SetCarriedItemPacket>(
new SetCarriedItemPacket(carriedItem)));
} }
} }
bool MultiPlayerGameMode::useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly, bool *pbUsedItem) bool MultiPlayerGameMode::useItemOn(std::shared_ptr<Player> player,
{ Level* level,
if( pbUsedItem ) *pbUsedItem = false; // Did we actually use the held item? std::shared_ptr<ItemInstance> item, int x,
int y, int z, int face, Vec3* hit,
bool bTestUseOnly, bool* pbUsedItem) {
if (pbUsedItem) *pbUsedItem = false; // Did we actually use the held item?
// 4J-PB - Adding a test only version to allow tooltips to be displayed // 4J-PB - Adding a test only version to allow tooltips to be displayed
if(!bTestUseOnly) if (!bTestUseOnly) {
{ ensureHasSentCarriedItem();
ensureHasSentCarriedItem(); }
} float clickX = (float)hit->x - x;
float clickX = (float) hit->x - x; float clickY = (float)hit->y - y;
float clickY = (float) hit->y - y; float clickZ = (float)hit->z - z;
float clickZ = (float) hit->z - z; bool didSomething = false;
bool didSomething = false; int t = level->getTile(x, y, z);
int t = level->getTile(x, y, z);
if (t > 0 && player->isAllowedToUse(Tile::tiles[t]))
{
if(bTestUseOnly)
{
switch(t)
{
case Tile::recordPlayer_Id:
case Tile::bed_Id: // special case for a bed
if (Tile::tiles[t]->TestUse(level, x, y, z, player ))
{
return true;
}
else if (t==Tile::bed_Id) // 4J-JEV: You can still use items on record players (ie. set fire to them).
{
// bed is too far away, or something
return false;
}
break;
default:
if (Tile::tiles[t]->TestUse()) return true;
break;
}
}
else
{
if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ)) didSomething = true;
}
}
if (!didSomething && item != NULL && dynamic_cast<TileItem *>(item->getItem())) if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) {
{ if (bTestUseOnly) {
TileItem *tile = dynamic_cast<TileItem *>(item->getItem()); switch (t) {
if (!tile->mayPlace(level, x, y, z, face, player, item)) return false; case Tile::recordPlayer_Id:
} case Tile::bed_Id: // special case for a bed
if (Tile::tiles[t]->TestUse(level, x, y, z, player)) {
return true;
} else if (t == Tile::bed_Id) // 4J-JEV: You can still use
// items on record players
// (ie. set fire to them).
{
// bed is too far away, or something
return false;
}
break;
default:
if (Tile::tiles[t]->TestUse()) return true;
break;
}
} else {
if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX,
clickY, clickZ))
didSomething = true;
}
}
// 4J Stu - In Java we send the use packet before the above check for item being NULL if (!didSomething && item != NULL &&
// so the following never gets executed but the packet still gets sent (for opening chests etc) dynamic_cast<TileItem*>(item->getItem())) {
if(item != NULL) TileItem* tile = dynamic_cast<TileItem*>(item->getItem());
{ if (!tile->mayPlace(level, x, y, z, face, player, item)) return false;
if(!didSomething && player->isAllowedToUse(item)) }
{
if (localPlayerMode->isCreative())
{
int aux = item->getAuxValue();
int count = item->count;
didSomething = item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnly);
item->setAuxValue(aux);
item->count = count;
}
else
{
didSomething = item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnly);
}
if( didSomething )
{
if( pbUsedItem ) *pbUsedItem = true;
}
}
}
else
{
// 4J - Bit of a hack, however seems preferable to any larger changes which would have more chance of causing unwanted side effects.
// If we aren't going to be actually performing the use method locally, then call this method with its "soundOnly" parameter set to true.
// This is an addition from the java version, and as its name suggests, doesn't actually perform the use locally but just makes any sounds that
// are meant to be directly caused by this. If we don't do this, then the sounds never happen as the tile's use method is only called on the
// server, and that won't allow any sounds that are directly made, or broadcast back level events to us that would make the sound, since we are
// the source of the event.
if( ( t > 0 ) && ( !bTestUseOnly ) && player->isAllowedToUse(Tile::tiles[t]) )
{
Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ, true);
}
}
// 4J Stu - Do the action before we send the packet, so that our predicted count is sent in the packet and the server // 4J Stu - In Java we send the use packet before the above check for item
// doesn't think it has to update us // being NULL so the following never gets executed but the packet still gets
// Fix for #7904 - Gameplay: Players can dupe torches by throwing them repeatedly into water. // sent (for opening chests etc)
if(!bTestUseOnly) if (item != NULL) {
{ if (!didSomething && player->isAllowedToUse(item)) {
connection->send( std::shared_ptr<UseItemPacket>( new UseItemPacket(x, y, z, face, player->inventory->getSelected(), clickX, clickY, clickZ) ) ); if (localPlayerMode->isCreative()) {
} int aux = item->getAuxValue();
int count = item->count;
didSomething = item->useOn(player, level, x, y, z, face, clickX,
clickY, clickZ, bTestUseOnly);
item->setAuxValue(aux);
item->count = count;
} else {
didSomething = item->useOn(player, level, x, y, z, face, clickX,
clickY, clickZ, bTestUseOnly);
}
if (didSomething) {
if (pbUsedItem) *pbUsedItem = true;
}
}
} else {
// 4J - Bit of a hack, however seems preferable to any larger changes
// which would have more chance of causing unwanted side effects. If we
// aren't going to be actually performing the use method locally, then
// call this method with its "soundOnly" parameter set to true. This is
// an addition from the java version, and as its name suggests, doesn't
// actually perform the use locally but just makes any sounds that are
// meant to be directly caused by this. If we don't do this, then the
// sounds never happen as the tile's use method is only called on the
// server, and that won't allow any sounds that are directly made, or
// broadcast back level events to us that would make the sound, since we
// are the source of the event.
if ((t > 0) && (!bTestUseOnly) &&
player->isAllowedToUse(Tile::tiles[t])) {
Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY,
clickZ, true);
}
}
// 4J Stu - Do the action before we send the packet, so that our predicted
// count is sent in the packet and the server doesn't think it has to update
// us Fix for #7904 - Gameplay: Players can dupe torches by throwing them
// repeatedly into water.
if (!bTestUseOnly) {
connection->send(std::shared_ptr<UseItemPacket>(
new UseItemPacket(x, y, z, face, player->inventory->getSelected(),
clickX, clickY, clickZ)));
}
return didSomething; return didSomething;
} }
bool MultiPlayerGameMode::useItem(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, bool bTestUseOnly) bool MultiPlayerGameMode::useItem(std::shared_ptr<Player> player, Level* level,
{ std::shared_ptr<ItemInstance> item,
if(!player->isAllowedToUse(item)) return false; bool bTestUseOnly) {
if (!player->isAllowedToUse(item)) return false;
// 4J-PB - Adding a test only version to allow tooltips to be displayed // 4J-PB - Adding a test only version to allow tooltips to be displayed
if(!bTestUseOnly) if (!bTestUseOnly) {
{ ensureHasSentCarriedItem();
ensureHasSentCarriedItem(); }
}
// 4J Stu - Do the action before we send the packet, so that our predicted count is sent in the packet and the server // 4J Stu - Do the action before we send the packet, so that our predicted
// doesn't think it has to update us, or can update us if we are wrong // count is sent in the packet and the server doesn't think it has to update
// Fix for #13120 - Using a bucket of water or lava in the spawn area (centre of the map) causes the inventory to get out of sync // us, or can update us if we are wrong Fix for #13120 - Using a bucket of
// water or lava in the spawn area (centre of the map) causes the inventory
// to get out of sync
bool result = false; bool result = false;
// 4J-PB added for tooltips to test use only // 4J-PB added for tooltips to test use only
if(bTestUseOnly) if (bTestUseOnly) {
{ result = item->TestUse(level, player);
result = item->TestUse(level, player); } else {
} int oldCount = item->count;
else std::shared_ptr<ItemInstance> itemInstance = item->use(level, player);
{ if ((itemInstance != NULL && itemInstance != item) ||
int oldCount = item->count; (itemInstance != NULL && itemInstance->count != oldCount)) {
std::shared_ptr<ItemInstance> itemInstance = item->use(level, player); player->inventory->items[player->inventory->selected] =
if ((itemInstance != NULL && itemInstance != item) || (itemInstance != NULL && itemInstance->count != oldCount)) itemInstance;
{ if (itemInstance->count == 0) {
player->inventory->items[player->inventory->selected] = itemInstance; player->inventory->items[player->inventory->selected] = nullptr;
if (itemInstance->count == 0) }
{ result = true;
player->inventory->items[player->inventory->selected] = nullptr; }
} }
result = true;
} if (!bTestUseOnly) {
} connection->send(std::shared_ptr<UseItemPacket>(new UseItemPacket(
-1, -1, -1, 255, player->inventory->getSelected(), 0, 0, 0)));
if(!bTestUseOnly) }
{
connection->send( std::shared_ptr<UseItemPacket>( new UseItemPacket(-1, -1, -1, 255, player->inventory->getSelected(), 0, 0, 0) ) );
}
return result; return result;
} }
std::shared_ptr<MultiplayerLocalPlayer> MultiPlayerGameMode::createPlayer(Level *level) std::shared_ptr<MultiplayerLocalPlayer> MultiPlayerGameMode::createPlayer(
{ Level* level) {
return std::shared_ptr<MultiplayerLocalPlayer>( new MultiplayerLocalPlayer(minecraft, level, minecraft->user, connection) ); return std::shared_ptr<MultiplayerLocalPlayer>(new MultiplayerLocalPlayer(
minecraft, level, minecraft->user, connection));
} }
void MultiPlayerGameMode::attack(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity) void MultiPlayerGameMode::attack(std::shared_ptr<Player> player,
{ std::shared_ptr<Entity> entity) {
ensureHasSentCarriedItem(); ensureHasSentCarriedItem();
connection->send( std::shared_ptr<InteractPacket>( new InteractPacket(player->entityId, entity->entityId, InteractPacket::ATTACK) ) ); connection->send(std::shared_ptr<InteractPacket>(new InteractPacket(
player->entityId, entity->entityId, InteractPacket::ATTACK)));
player->attack(entity); player->attack(entity);
} }
bool MultiPlayerGameMode::interact(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity) bool MultiPlayerGameMode::interact(std::shared_ptr<Player> player,
{ std::shared_ptr<Entity> entity) {
ensureHasSentCarriedItem(); ensureHasSentCarriedItem();
connection->send(std::shared_ptr<InteractPacket>( new InteractPacket(player->entityId, entity->entityId, InteractPacket::INTERACT) ) ); connection->send(std::shared_ptr<InteractPacket>(new InteractPacket(
player->entityId, entity->entityId, InteractPacket::INTERACT)));
return player->interact(entity); return player->interact(entity);
} }
std::shared_ptr<ItemInstance> MultiPlayerGameMode::handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr<Player> player) std::shared_ptr<ItemInstance> MultiPlayerGameMode::handleInventoryMouseClick(
{ int containerId, int slotNum, int buttonNum, bool quickKeyHeld,
std::shared_ptr<Player> player) {
short changeUid = player->containerMenu->backup(player->inventory); short changeUid = player->containerMenu->backup(player->inventory);
std::shared_ptr<ItemInstance> clicked = player->containerMenu->clicked(slotNum, buttonNum, quickKeyHeld?AbstractContainerMenu::CLICK_QUICK_MOVE:AbstractContainerMenu::CLICK_PICKUP, player); std::shared_ptr<ItemInstance> clicked = player->containerMenu->clicked(
connection->send( std::shared_ptr<ContainerClickPacket>( new ContainerClickPacket(containerId, slotNum, buttonNum, quickKeyHeld, clicked, changeUid) ) ); slotNum, buttonNum,
quickKeyHeld ? AbstractContainerMenu::CLICK_QUICK_MOVE
: AbstractContainerMenu::CLICK_PICKUP,
player);
connection->send(std::shared_ptr<ContainerClickPacket>(
new ContainerClickPacket(containerId, slotNum, buttonNum, quickKeyHeld,
clicked, changeUid)));
return clicked; return clicked;
} }
void MultiPlayerGameMode::handleInventoryButtonClick(int containerId, int buttonId) void MultiPlayerGameMode::handleInventoryButtonClick(int containerId,
{ int buttonId) {
connection->send(std::shared_ptr<ContainerButtonClickPacket>( new ContainerButtonClickPacket(containerId, buttonId) )); connection->send(std::shared_ptr<ContainerButtonClickPacket>(
new ContainerButtonClickPacket(containerId, buttonId)));
} }
void MultiPlayerGameMode::handleCreativeModeItemAdd(std::shared_ptr<ItemInstance> clicked, int slot) void MultiPlayerGameMode::handleCreativeModeItemAdd(
{ std::shared_ptr<ItemInstance> clicked, int slot) {
if (localPlayerMode->isCreative()) if (localPlayerMode->isCreative()) {
{ connection->send(std::shared_ptr<SetCreativeModeSlotPacket>(
connection->send(std::shared_ptr<SetCreativeModeSlotPacket>( new SetCreativeModeSlotPacket(slot, clicked) ) ); new SetCreativeModeSlotPacket(slot, clicked)));
} }
} }
void MultiPlayerGameMode::handleCreativeModeItemDrop(std::shared_ptr<ItemInstance> clicked) void MultiPlayerGameMode::handleCreativeModeItemDrop(
{ std::shared_ptr<ItemInstance> clicked) {
if (localPlayerMode->isCreative() && clicked != NULL) if (localPlayerMode->isCreative() && clicked != NULL) {
{ connection->send(std::shared_ptr<SetCreativeModeSlotPacket>(
connection->send(std::shared_ptr<SetCreativeModeSlotPacket>( new SetCreativeModeSlotPacket(-1, clicked) ) ); new SetCreativeModeSlotPacket(-1, clicked)));
} }
} }
void MultiPlayerGameMode::releaseUsingItem(std::shared_ptr<Player> player) void MultiPlayerGameMode::releaseUsingItem(std::shared_ptr<Player> player) {
{ ensureHasSentCarriedItem();
ensureHasSentCarriedItem(); connection->send(std::shared_ptr<PlayerActionPacket>(new PlayerActionPacket(
connection->send(std::shared_ptr<PlayerActionPacket>( new PlayerActionPacket(PlayerActionPacket::RELEASE_USE_ITEM, 0, 0, 0, 255) ) ); PlayerActionPacket::RELEASE_USE_ITEM, 0, 0, 0, 255)));
player->releaseUsingItem(); player->releaseUsingItem();
} }
bool MultiPlayerGameMode::hasExperience() bool MultiPlayerGameMode::hasExperience() { return true; }
{
return true; bool MultiPlayerGameMode::hasMissTime() {
return !localPlayerMode->isCreative();
} }
bool MultiPlayerGameMode::hasMissTime() bool MultiPlayerGameMode::hasInfiniteItems() {
{ return localPlayerMode->isCreative();
return !localPlayerMode->isCreative();
} }
bool MultiPlayerGameMode::hasInfiniteItems() bool MultiPlayerGameMode::hasFarPickRange() {
{ return localPlayerMode->isCreative();
return localPlayerMode->isCreative();
} }
bool MultiPlayerGameMode::hasFarPickRange() bool MultiPlayerGameMode::handleCraftItem(int recipe,
{ std::shared_ptr<Player> player) {
return localPlayerMode->isCreative();
}
bool MultiPlayerGameMode::handleCraftItem(int recipe, std::shared_ptr<Player> player)
{
short changeUid = player->containerMenu->backup(player->inventory); short changeUid = player->containerMenu->backup(player->inventory);
connection->send( std::shared_ptr<CraftItemPacket>( new CraftItemPacket(recipe, changeUid) ) ); connection->send(std::shared_ptr<CraftItemPacket>(
new CraftItemPacket(recipe, changeUid)));
return true; return true;
} }
void MultiPlayerGameMode::handleDebugOptions(unsigned int uiVal, std::shared_ptr<Player> player) void MultiPlayerGameMode::handleDebugOptions(unsigned int uiVal,
{ std::shared_ptr<Player> player) {
player->SetDebugOptions(uiVal); player->SetDebugOptions(uiVal);
connection->send( std::shared_ptr<DebugOptionsPacket>( new DebugOptionsPacket(uiVal) ) ); connection->send(
std::shared_ptr<DebugOptionsPacket>(new DebugOptionsPacket(uiVal)));
} }

View file

@ -4,65 +4,80 @@ class ClientConnection;
class GameType; class GameType;
class Vec3; class Vec3;
class MultiPlayerGameMode class MultiPlayerGameMode {
{
private: private:
int xDestroyBlock; int xDestroyBlock;
int yDestroyBlock; int yDestroyBlock;
int zDestroyBlock; int zDestroyBlock;
float destroyProgress; float destroyProgress;
float oDestroyProgress; float oDestroyProgress;
int destroyTicks; // 4J was float but doesn't seem to need to be int destroyTicks; // 4J was float but doesn't seem to need to be
int destroyDelay; int destroyDelay;
bool isDestroying; bool isDestroying;
GameType *localPlayerMode; GameType* localPlayerMode;
ClientConnection *connection; ClientConnection* connection;
protected: protected:
Minecraft *minecraft; Minecraft* minecraft;
public: public:
MultiPlayerGameMode(Minecraft *minecraft, ClientConnection *connection); MultiPlayerGameMode(Minecraft* minecraft, ClientConnection* connection);
virtual ~MultiPlayerGameMode(){} virtual ~MultiPlayerGameMode() {}
static void creativeDestroyBlock(Minecraft *minecraft, MultiPlayerGameMode *gameMode, int x, int y, int z, int face); static void creativeDestroyBlock(Minecraft* minecraft,
void adjustPlayer(std::shared_ptr<Player> player); MultiPlayerGameMode* gameMode, int x,
bool isCutScene(); int y, int z, int face);
void setLocalMode(GameType *mode); void adjustPlayer(std::shared_ptr<Player> player);
bool isCutScene();
void setLocalMode(GameType* mode);
virtual void initPlayer(std::shared_ptr<Player> player); virtual void initPlayer(std::shared_ptr<Player> player);
virtual bool canHurtPlayer(); virtual bool canHurtPlayer();
virtual bool destroyBlock(int x, int y, int z, int face); virtual bool destroyBlock(int x, int y, int z, int face);
virtual void startDestroyBlock(int x, int y, int z, int face); virtual void startDestroyBlock(int x, int y, int z, int face);
virtual void stopDestroyBlock(); virtual void stopDestroyBlock();
virtual void continueDestroyBlock(int x, int y, int z, int face); virtual void continueDestroyBlock(int x, int y, int z, int face);
virtual float getPickRange(); virtual float getPickRange();
virtual void tick(); virtual void tick();
private:
int carriedItem;
private: private:
void ensureHasSentCarriedItem(); int carriedItem;
private:
void ensureHasSentCarriedItem();
public: public:
virtual bool useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, Vec3 *hit, bool bTestUseOnly=false, bool *pbUsedItem=NULL); virtual bool useItemOn(std::shared_ptr<Player> player, Level* level,
virtual bool useItem(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, bool bTestUseOnly=false); std::shared_ptr<ItemInstance> item, int x, int y,
virtual std::shared_ptr<MultiplayerLocalPlayer> createPlayer(Level *level); int z, int face, Vec3* hit,
virtual void attack(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity); bool bTestUseOnly = false, bool* pbUsedItem = NULL);
virtual bool interact(std::shared_ptr<Player> player, std::shared_ptr<Entity> entity); virtual bool useItem(std::shared_ptr<Player> player, Level* level,
virtual std::shared_ptr<ItemInstance> handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, bool quickKeyHeld, std::shared_ptr<Player> player); std::shared_ptr<ItemInstance> item,
virtual void handleInventoryButtonClick(int containerId, int buttonId); bool bTestUseOnly = false);
virtual void handleCreativeModeItemAdd(std::shared_ptr<ItemInstance> clicked, int slot); virtual std::shared_ptr<MultiplayerLocalPlayer> createPlayer(Level* level);
virtual void handleCreativeModeItemDrop(std::shared_ptr<ItemInstance> clicked); virtual void attack(std::shared_ptr<Player> player,
virtual void releaseUsingItem(std::shared_ptr<Player> player); std::shared_ptr<Entity> entity);
virtual bool hasExperience(); virtual bool interact(std::shared_ptr<Player> player,
virtual bool hasMissTime(); std::shared_ptr<Entity> entity);
virtual bool hasInfiniteItems(); virtual std::shared_ptr<ItemInstance> handleInventoryMouseClick(
virtual bool hasFarPickRange(); int containerId, int slotNum, int buttonNum, bool quickKeyHeld,
std::shared_ptr<Player> player);
// 4J Stu - Added so we can send packets for this in the network game virtual void handleInventoryButtonClick(int containerId, int buttonId);
virtual bool handleCraftItem(int recipe, std::shared_ptr<Player> player); virtual void handleCreativeModeItemAdd(
virtual void handleDebugOptions(unsigned int uiVal, std::shared_ptr<Player> player); std::shared_ptr<ItemInstance> clicked, int slot);
virtual void handleCreativeModeItemDrop(
std::shared_ptr<ItemInstance> clicked);
virtual void releaseUsingItem(std::shared_ptr<Player> player);
virtual bool hasExperience();
virtual bool hasMissTime();
virtual bool hasInfiniteItems();
virtual bool hasFarPickRange();
// 4J Stu - Added for tutorial checks // 4J Stu - Added so we can send packets for this in the network game
virtual bool isInputAllowed(int mapping) { return true; } virtual bool handleCraftItem(int recipe, std::shared_ptr<Player> player);
virtual bool isTutorial() { return false; } virtual void handleDebugOptions(unsigned int uiVal,
virtual Tutorial *getTutorial() { return NULL; } std::shared_ptr<Player> player);
// 4J Stu - Added for tutorial checks
virtual bool isInputAllowed(int mapping) { return true; }
virtual bool isTutorial() { return false; }
virtual Tutorial* getTutorial() { return NULL; }
}; };

View file

@ -1,5 +1,5 @@
#include "../Platform/stdafx.h" #include "../Platform/stdafx.h"
//#include "../../Minecraft.World/Util/JavaMath.h" // #include "../../Minecraft.World/Util/JavaMath.h"
#include "MultiPlayerLocalPlayer.h" #include "MultiPlayerLocalPlayer.h"
#include "../Network/ClientConnection.h" #include "../Network/ClientConnection.h"
#include "../../Minecraft.World/Headers/net.minecraft.world.level.h" #include "../../Minecraft.World/Headers/net.minecraft.world.level.h"
@ -13,91 +13,107 @@
#include "../../Minecraft.World/Level/LevelData.h" #include "../../Minecraft.World/Level/LevelData.h"
#include "../../Minecraft.World/Headers/net.minecraft.world.entity.item.h" #include "../../Minecraft.World/Headers/net.minecraft.world.entity.item.h"
MultiplayerLocalPlayer::MultiplayerLocalPlayer(Minecraft* minecraft,
Level* level, User* user,
ClientConnection* connection)
MultiplayerLocalPlayer::MultiplayerLocalPlayer(Minecraft *minecraft, Level *level, User *user, ClientConnection *connection) : LocalPlayer(minecraft, level, user, level->dimension->id) : LocalPlayer(minecraft, level, user, level->dimension->id) {
{ // 4J - added initialisers
// 4J - added initialisers
flashOnSetHealth = false; flashOnSetHealth = false;
xLast = yLast1 = yLast2 = zLast = 0; xLast = yLast1 = yLast2 = zLast = 0;
yRotLast = xRotLast = 0; yRotLast = xRotLast = 0;
lastOnGround = false; lastOnGround = false;
lastSneaked = false; lastSneaked = false;
lastIdle = false; lastIdle = false;
lastSprinting = false; lastSprinting = false;
positionReminder = 0; positionReminder = 0;
this->connection = connection; this->connection = connection;
} }
bool MultiplayerLocalPlayer::hurt(DamageSource *source, int dmg) bool MultiplayerLocalPlayer::hurt(DamageSource* source, int dmg) {
{ return false;
return false;
} }
void MultiplayerLocalPlayer::heal(int heal) void MultiplayerLocalPlayer::heal(int heal) {}
{
}
void MultiplayerLocalPlayer::tick() void MultiplayerLocalPlayer::tick() {
{ // 4J Added
// 4J Added // 4J-PB - changing this to a game host option ot hide gamertags
// 4J-PB - changing this to a game host option ot hide gamertags // bool bIsisPrimaryHost=g_NetworkManager.IsHost() &&
//bool bIsisPrimaryHost=g_NetworkManager.IsHost() && (ProfileManager.GetPrimaryPad()==m_iPad); // (ProfileManager.GetPrimaryPad()==m_iPad);
/*if((app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0) != m_bShownOnMaps) /*if((app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0) !=
{ m_bShownOnMaps)
m_bShownOnMaps = (app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0); {
if (m_bShownOnMaps) connection->send( std::shared_ptr<PlayerCommandPacket>( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::SHOW_ON_MAPS) ) ); m_bShownOnMaps =
else connection->send( std::shared_ptr<PlayerCommandPacket>( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::HIDE_ON_MAPS) ) ); (app.GetGameSettings(m_iPad,eGameSetting_PlayerVisibleInMap)!=0); if
}*/ (m_bShownOnMaps) connection->send( std::shared_ptr<PlayerCommandPacket>( new
PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::SHOW_ON_MAPS) )
); else connection->send( std::shared_ptr<PlayerCommandPacket>( new
PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::HIDE_ON_MAPS) )
);
}*/
if (!level->hasChunkAt(Mth::floor(x), 0, Mth::floor(z))) return; if (!level->hasChunkAt(Mth::floor(x), 0, Mth::floor(z))) return;
double tempX = x, tempY = y, tempZ = z; double tempX = x, tempY = y, tempZ = z;
LocalPlayer::tick(); LocalPlayer::tick();
//if( !minecraft->localgameModes[m_iPad]->isTutorial() || minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(tempX, tempY, tempZ, x, y, z) ) // if( !minecraft->localgameModes[m_iPad]->isTutorial() ||
if(minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(tempX, tempY, tempZ, x, y, z)) // minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(tempX,
{ // tempY, tempZ, x, y, z) )
sendPosition(); if (minecraft->localgameModes[m_iPad]->getTutorial()->canMoveToPosition(
} tempX, tempY, tempZ, x, y, z)) {
else sendPosition();
{ } else {
//app.Debugprintf("Cannot move to position (%f, %f, %f), falling back to (%f, %f, %f)\n", x, y, z, tempX, y, tempZ); // app.Debugprintf("Cannot move to position (%f, %f, %f), falling back
this->setPos(tempX, y, tempZ); // to (%f, %f, %f)\n", x, y, z, tempX, y, tempZ);
} this->setPos(tempX, y, tempZ);
}
} }
void MultiplayerLocalPlayer::sendPosition() void MultiplayerLocalPlayer::sendPosition() {
{ bool sprinting = isSprinting();
bool sprinting = isSprinting(); if (sprinting != lastSprinting) {
if (sprinting != lastSprinting) if (sprinting)
{ connection->send(
if (sprinting) connection->send(std::shared_ptr<PlayerCommandPacket>( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_SPRINTING))); std::shared_ptr<PlayerCommandPacket>(new PlayerCommandPacket(
else connection->send(std::shared_ptr<PlayerCommandPacket>( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SPRINTING))); shared_from_this(), PlayerCommandPacket::START_SPRINTING)));
else
connection->send(
std::shared_ptr<PlayerCommandPacket>(new PlayerCommandPacket(
shared_from_this(), PlayerCommandPacket::STOP_SPRINTING)));
lastSprinting = sprinting; lastSprinting = sprinting;
} }
bool sneaking = isSneaking(); bool sneaking = isSneaking();
if (sneaking != lastSneaked) if (sneaking != lastSneaked) {
{ if (sneaking)
if (sneaking) connection->send( std::shared_ptr<PlayerCommandPacket>( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_SNEAKING) ) ); connection->send(
else connection->send( std::shared_ptr<PlayerCommandPacket>( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SNEAKING) ) ); std::shared_ptr<PlayerCommandPacket>(new PlayerCommandPacket(
shared_from_this(), PlayerCommandPacket::START_SNEAKING)));
else
connection->send(
std::shared_ptr<PlayerCommandPacket>(new PlayerCommandPacket(
shared_from_this(), PlayerCommandPacket::STOP_SNEAKING)));
lastSneaked = sneaking; lastSneaked = sneaking;
} }
bool idle = isIdle(); bool idle = isIdle();
if (idle != lastIdle) if (idle != lastIdle) {
{ if (idle)
if (idle) connection->send( std::shared_ptr<PlayerCommandPacket>( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::START_IDLEANIM) ) ); connection->send(
else connection->send( std::shared_ptr<PlayerCommandPacket>( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_IDLEANIM) ) ); std::shared_ptr<PlayerCommandPacket>(new PlayerCommandPacket(
shared_from_this(), PlayerCommandPacket::START_IDLEANIM)));
else
connection->send(
std::shared_ptr<PlayerCommandPacket>(new PlayerCommandPacket(
shared_from_this(), PlayerCommandPacket::STOP_IDLEANIM)));
lastIdle = idle; lastIdle = idle;
} }
double xdd = x - xLast; double xdd = x - xLast;
double ydd1 = bb->y0 - yLast1; double ydd1 = bb->y0 - yLast1;
@ -106,266 +122,244 @@ void MultiplayerLocalPlayer::sendPosition()
double rydd = yRot - yRotLast; double rydd = yRot - yRotLast;
double rxdd = xRot - xRotLast; double rxdd = xRot - xRotLast;
bool move = (xdd * xdd + ydd1 * ydd1 + zdd * zdd) > 0.03 * 0.03 || positionReminder >= POSITION_REMINDER_INTERVAL; bool move = (xdd * xdd + ydd1 * ydd1 + zdd * zdd) > 0.03 * 0.03 ||
positionReminder >= POSITION_REMINDER_INTERVAL;
bool rot = rydd != 0 || rxdd != 0; bool rot = rydd != 0 || rxdd != 0;
if (riding != NULL) if (riding != NULL) {
{ connection->send(
connection->send( std::shared_ptr<MovePlayerPacket>( new MovePlayerPacket::PosRot(xd, -999, -999, zd, yRot, xRot, onGround, abilities.flying) ) ); std::shared_ptr<MovePlayerPacket>(new MovePlayerPacket::PosRot(
xd, -999, -999, zd, yRot, xRot, onGround, abilities.flying)));
move = false; move = false;
} } else {
else if (move && rot) {
{ connection->send(
if (move && rot) std::shared_ptr<MovePlayerPacket>(new MovePlayerPacket::PosRot(
{ x, bb->y0, y, z, yRot, xRot, onGround, abilities.flying)));
connection->send( std::shared_ptr<MovePlayerPacket>( new MovePlayerPacket::PosRot(x, bb->y0, y, z, yRot, xRot, onGround, abilities.flying) ) ); } else if (move) {
} connection->send(
else if (move) std::shared_ptr<MovePlayerPacket>(new MovePlayerPacket::Pos(
{ x, bb->y0, y, z, onGround, abilities.flying)));
connection->send( std::shared_ptr<MovePlayerPacket>( new MovePlayerPacket::Pos(x, bb->y0, y, z, onGround, abilities.flying) ) ); } else if (rot) {
} connection->send(
else if (rot) std::shared_ptr<MovePlayerPacket>(new MovePlayerPacket::Rot(
{ yRot, xRot, onGround, abilities.flying)));
connection->send( std::shared_ptr<MovePlayerPacket>( new MovePlayerPacket::Rot(yRot, xRot, onGround, abilities.flying) ) ); } else {
} connection->send(std::shared_ptr<MovePlayerPacket>(
else new MovePlayerPacket(onGround, abilities.flying)));
{
connection->send( std::shared_ptr<MovePlayerPacket>( new MovePlayerPacket(onGround, abilities.flying) ) );
} }
} }
positionReminder++; positionReminder++;
lastOnGround = onGround; lastOnGround = onGround;
if (move) if (move) {
{
xLast = x; xLast = x;
yLast1 = bb->y0; yLast1 = bb->y0;
yLast2 = y; yLast2 = y;
zLast = z; zLast = z;
positionReminder = 0; positionReminder = 0;
} }
if (rot) if (rot) {
{
yRotLast = yRot; yRotLast = yRot;
xRotLast = xRot; xRotLast = xRot;
} }
} }
std::shared_ptr<ItemEntity> MultiplayerLocalPlayer::drop() std::shared_ptr<ItemEntity> MultiplayerLocalPlayer::drop() {
{ connection->send(std::shared_ptr<PlayerActionPacket>(
connection->send( std::shared_ptr<PlayerActionPacket>( new PlayerActionPacket(PlayerActionPacket::DROP_ITEM, 0, 0, 0, 0) ) ); new PlayerActionPacket(PlayerActionPacket::DROP_ITEM, 0, 0, 0, 0)));
return nullptr; return nullptr;
} }
void MultiplayerLocalPlayer::reallyDrop(std::shared_ptr<ItemEntity> itemEntity) void MultiplayerLocalPlayer::reallyDrop(
{ std::shared_ptr<ItemEntity> itemEntity) {}
void MultiplayerLocalPlayer::chat(const std::wstring& message) {
connection->send(std::shared_ptr<ChatPacket>(new ChatPacket(message)));
} }
void MultiplayerLocalPlayer::chat(const std::wstring& message) void MultiplayerLocalPlayer::swing() {
{ LocalPlayer::swing();
connection->send( std::shared_ptr<ChatPacket>( new ChatPacket(message) ) ); connection->send(std::shared_ptr<AnimatePacket>(
new AnimatePacket(shared_from_this(), AnimatePacket::SWING)));
} }
void MultiplayerLocalPlayer::swing() void MultiplayerLocalPlayer::respawn() {
{ connection->send(std::shared_ptr<ClientCommandPacket>(
LocalPlayer::swing(); new ClientCommandPacket(ClientCommandPacket::PERFORM_RESPAWN)));
connection->send( std::shared_ptr<AnimatePacket>( new AnimatePacket(shared_from_this(), AnimatePacket::SWING) ) );
} }
void MultiplayerLocalPlayer::respawn() void MultiplayerLocalPlayer::actuallyHurt(DamageSource* source, int dmg) {
{ setHealth(getHealth() - dmg);
connection->send( std::shared_ptr<ClientCommandPacket>( new ClientCommandPacket(ClientCommandPacket::PERFORM_RESPAWN)));
}
void MultiplayerLocalPlayer::actuallyHurt(DamageSource *source, int dmg)
{
setHealth(getHealth() - dmg);
} }
// 4J Added override to capture event for tutorial messages // 4J Added override to capture event for tutorial messages
void MultiplayerLocalPlayer::completeUsingItem() void MultiplayerLocalPlayer::completeUsingItem() {
{ Minecraft* pMinecraft = Minecraft::GetInstance();
Minecraft *pMinecraft = Minecraft::GetInstance(); if (useItem != NULL && pMinecraft->localgameModes[m_iPad] != NULL) {
if(useItem != NULL && pMinecraft->localgameModes[m_iPad] != NULL ) TutorialMode* gameMode =
{ (TutorialMode*)pMinecraft->localgameModes[m_iPad];
TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; Tutorial* tutorial = gameMode->getTutorial();
Tutorial *tutorial = gameMode->getTutorial(); tutorial->completeUsingItem(useItem);
tutorial->completeUsingItem(useItem); }
} Player::completeUsingItem();
Player::completeUsingItem();
} }
void MultiplayerLocalPlayer::onEffectAdded(MobEffectInstance *effect) void MultiplayerLocalPlayer::onEffectAdded(MobEffectInstance* effect) {
{ Minecraft* pMinecraft = Minecraft::GetInstance();
Minecraft *pMinecraft = Minecraft::GetInstance(); if (pMinecraft->localgameModes[m_iPad] != NULL) {
if(pMinecraft->localgameModes[m_iPad] != NULL ) TutorialMode* gameMode =
{ (TutorialMode*)pMinecraft->localgameModes[m_iPad];
TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; Tutorial* tutorial = gameMode->getTutorial();
Tutorial *tutorial = gameMode->getTutorial(); tutorial->onEffectChanged(MobEffect::effects[effect->getId()]);
tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); }
} Player::onEffectAdded(effect);
Player::onEffectAdded(effect);
} }
void MultiplayerLocalPlayer::onEffectUpdated(MobEffectInstance* effect) {
void MultiplayerLocalPlayer::onEffectUpdated(MobEffectInstance *effect) Minecraft* pMinecraft = Minecraft::GetInstance();
{ if (pMinecraft->localgameModes[m_iPad] != NULL) {
Minecraft *pMinecraft = Minecraft::GetInstance(); TutorialMode* gameMode =
if(pMinecraft->localgameModes[m_iPad] != NULL ) (TutorialMode*)pMinecraft->localgameModes[m_iPad];
{ Tutorial* tutorial = gameMode->getTutorial();
TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; tutorial->onEffectChanged(MobEffect::effects[effect->getId()]);
Tutorial *tutorial = gameMode->getTutorial(); }
tutorial->onEffectChanged(MobEffect::effects[effect->getId()]); Player::onEffectUpdated(effect);
}
Player::onEffectUpdated(effect);
} }
void MultiplayerLocalPlayer::onEffectRemoved(MobEffectInstance* effect) {
void MultiplayerLocalPlayer::onEffectRemoved(MobEffectInstance *effect) Minecraft* pMinecraft = Minecraft::GetInstance();
{ if (pMinecraft->localgameModes[m_iPad] != NULL) {
Minecraft *pMinecraft = Minecraft::GetInstance(); TutorialMode* gameMode =
if(pMinecraft->localgameModes[m_iPad] != NULL ) (TutorialMode*)pMinecraft->localgameModes[m_iPad];
{ Tutorial* tutorial = gameMode->getTutorial();
TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad]; tutorial->onEffectChanged(MobEffect::effects[effect->getId()], true);
Tutorial *tutorial = gameMode->getTutorial(); }
tutorial->onEffectChanged(MobEffect::effects[effect->getId()],true); Player::onEffectRemoved(effect);
}
Player::onEffectRemoved(effect);
} }
void MultiplayerLocalPlayer::closeContainer() void MultiplayerLocalPlayer::closeContainer() {
{ connection->send(std::shared_ptr<ContainerClosePacket>(
connection->send( std::shared_ptr<ContainerClosePacket>( new ContainerClosePacket(containerMenu->containerId) ) ); new ContainerClosePacket(containerMenu->containerId)));
inventory->setCarried(nullptr); inventory->setCarried(nullptr);
LocalPlayer::closeContainer(); LocalPlayer::closeContainer();
} }
void MultiplayerLocalPlayer::hurtTo(int newHealth, ETelemetryChallenges damageSource) void MultiplayerLocalPlayer::hurtTo(int newHealth,
{ ETelemetryChallenges damageSource) {
if (flashOnSetHealth) if (flashOnSetHealth) {
{ LocalPlayer::hurtTo(newHealth, damageSource);
LocalPlayer::hurtTo(newHealth, damageSource); } else {
} setHealth(newHealth);
else flashOnSetHealth = true;
{ }
setHealth(newHealth);
flashOnSetHealth = true;
}
} }
void MultiplayerLocalPlayer::awardStat(Stat *stat, byteArray param) void MultiplayerLocalPlayer::awardStat(Stat* stat, byteArray param) {
{ if (stat == NULL) {
if (stat == NULL) delete[] param.data;
{
delete [] param.data;
return; return;
} }
if (stat->awardLocallyOnly) if (stat->awardLocallyOnly) {
{ LocalPlayer::awardStat(stat, param);
LocalPlayer::awardStat(stat, param); } else {
} delete[] param.data;
else
{
delete [] param.data;
return; return;
} }
} }
void MultiplayerLocalPlayer::awardStatFromServer(Stat *stat, byteArray param) void MultiplayerLocalPlayer::awardStatFromServer(Stat* stat, byteArray param) {
{ if (stat != NULL && !stat->awardLocallyOnly) {
if ( stat != NULL && !stat->awardLocallyOnly ) LocalPlayer::awardStat(stat, param);
{ } else
LocalPlayer::awardStat(stat, param); delete[] param.data;
}
else delete [] param.data;
} }
void MultiplayerLocalPlayer::onUpdateAbilities() void MultiplayerLocalPlayer::onUpdateAbilities() {
{ connection->send(std::shared_ptr<PlayerAbilitiesPacket>(
connection->send(std::shared_ptr<PlayerAbilitiesPacket>(new PlayerAbilitiesPacket(&abilities))); new PlayerAbilitiesPacket(&abilities)));
} }
bool MultiplayerLocalPlayer::isLocalPlayer() bool MultiplayerLocalPlayer::isLocalPlayer() { return true; }
{
return true; void MultiplayerLocalPlayer::ride(std::shared_ptr<Entity> e) {
bool wasRiding = riding != NULL;
LocalPlayer::ride(e);
bool isRiding = riding != NULL;
if (isRiding) {
ETelemetryChallenges eventType = eTelemetryChallenges_Unknown;
if (this->riding != NULL) {
switch (riding->GetType()) {
case eTYPE_BOAT:
eventType = eTelemetryInGame_Ride_Boat;
break;
case eTYPE_MINECART:
eventType = eTelemetryInGame_Ride_Minecart;
break;
case eTYPE_PIG:
eventType = eTelemetryInGame_Ride_Pig;
break;
default:
break;
};
}
TelemetryManager->RecordEnemyKilledOrOvercome(GetXboxPad(), 0, y, 0, 0,
0, 0, eventType);
}
updateRichPresence();
Minecraft* pMinecraft = Minecraft::GetInstance();
if (pMinecraft->localgameModes[m_iPad] != NULL) {
TutorialMode* gameMode =
(TutorialMode*)pMinecraft->localgameModes[m_iPad];
if (wasRiding && !isRiding) {
gameMode->getTutorial()->changeTutorialState(
e_Tutorial_State_Gameplay);
} else if (!wasRiding && isRiding) {
if (std::dynamic_pointer_cast<Minecart>(e) != NULL)
gameMode->getTutorial()->changeTutorialState(
e_Tutorial_State_Riding_Minecart);
else if (std::dynamic_pointer_cast<Boat>(e) != NULL)
gameMode->getTutorial()->changeTutorialState(
e_Tutorial_State_Riding_Boat);
}
}
} }
void MultiplayerLocalPlayer::ride(std::shared_ptr<Entity> e) void MultiplayerLocalPlayer::StopSleeping() {
{ connection->send(
bool wasRiding = riding != NULL; std::shared_ptr<PlayerCommandPacket>(new PlayerCommandPacket(
LocalPlayer::ride(e); shared_from_this(), PlayerCommandPacket::STOP_SLEEPING)));
bool isRiding = riding != NULL;
if( isRiding )
{
ETelemetryChallenges eventType = eTelemetryChallenges_Unknown;
if( this->riding != NULL )
{
switch(riding->GetType())
{
case eTYPE_BOAT:
eventType = eTelemetryInGame_Ride_Boat;
break;
case eTYPE_MINECART:
eventType = eTelemetryInGame_Ride_Minecart;
break;
case eTYPE_PIG:
eventType = eTelemetryInGame_Ride_Pig;
break;
default:
break;
};
}
TelemetryManager->RecordEnemyKilledOrOvercome(GetXboxPad(), 0, y, 0, 0, 0, 0, eventType);
}
updateRichPresence();
Minecraft *pMinecraft = Minecraft::GetInstance();
if( pMinecraft->localgameModes[m_iPad] != NULL )
{
TutorialMode *gameMode = (TutorialMode *)pMinecraft->localgameModes[m_iPad];
if(wasRiding && !isRiding)
{
gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Gameplay);
}
else if (!wasRiding && isRiding)
{
if(std::dynamic_pointer_cast<Minecart>(e) != NULL)
gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Riding_Minecart);
else if(std::dynamic_pointer_cast<Boat>(e) != NULL)
gameMode->getTutorial()->changeTutorialState(e_Tutorial_State_Riding_Boat);
}
}
}
void MultiplayerLocalPlayer::StopSleeping()
{
connection->send( std::shared_ptr<PlayerCommandPacket>( new PlayerCommandPacket(shared_from_this(), PlayerCommandPacket::STOP_SLEEPING) ) );
} }
// 4J Added // 4J Added
void MultiplayerLocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) void MultiplayerLocalPlayer::setAndBroadcastCustomSkin(std::uint32_t skinId) {
{ std::uint32_t oldSkinIndex = getCustomSkin();
std::uint32_t oldSkinIndex = getCustomSkin(); LocalPlayer::setCustomSkin(skinId);
LocalPlayer::setCustomSkin(skinId);
#ifndef _CONTENT_PACKAGE #ifndef _CONTENT_PACKAGE
wprintf(L"Skin for local player %ls has changed to %ls (%d)\n", name.c_str(), customTextureUrl.c_str(), getPlayerDefaultSkin() ); wprintf(L"Skin for local player %ls has changed to %ls (%d)\n",
name.c_str(), customTextureUrl.c_str(), getPlayerDefaultSkin());
#endif #endif
if(getCustomSkin() != oldSkinIndex) connection->send( std::shared_ptr<TextureAndGeometryChangePacket>( new TextureAndGeometryChangePacket( shared_from_this(), app.GetPlayerSkinName(GetXboxPad()) ) ) ); if (getCustomSkin() != oldSkinIndex)
connection->send(std::shared_ptr<TextureAndGeometryChangePacket>(
new TextureAndGeometryChangePacket(
shared_from_this(), app.GetPlayerSkinName(GetXboxPad()))));
} }
void MultiplayerLocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) void MultiplayerLocalPlayer::setAndBroadcastCustomCape(std::uint32_t capeId) {
{ std::uint32_t oldCapeIndex = getCustomCape();
std::uint32_t oldCapeIndex = getCustomCape(); LocalPlayer::setCustomCape(capeId);
LocalPlayer::setCustomCape(capeId);
#ifndef _CONTENT_PACKAGE #ifndef _CONTENT_PACKAGE
wprintf(L"Cape for local player %ls has changed to %ls\n", name.c_str(), customTextureUrl2.c_str()); wprintf(L"Cape for local player %ls has changed to %ls\n", name.c_str(),
customTextureUrl2.c_str());
#endif #endif
if(getCustomCape() != oldCapeIndex) connection->send( std::shared_ptr<TextureChangePacket>( new TextureChangePacket( shared_from_this(), TextureChangePacket::e_TextureChange_Cape, app.GetPlayerCapeName(GetXboxPad()) ) ) ); if (getCustomCape() != oldCapeIndex)
connection->send(
std::shared_ptr<TextureChangePacket>(new TextureChangePacket(
shared_from_this(), TextureChangePacket::e_TextureChange_Cape,
app.GetPlayerCapeName(GetXboxPad()))));
} }

View file

@ -7,68 +7,80 @@ class ClientConnection;
class Minecraft; class Minecraft;
class Level; class Level;
class MultiplayerLocalPlayer : public LocalPlayer class MultiplayerLocalPlayer : public LocalPlayer {
{
private: private:
static const int POSITION_REMINDER_INTERVAL = SharedConstants::TICKS_PER_SECOND; static const int POSITION_REMINDER_INTERVAL =
SharedConstants::TICKS_PER_SECOND;
public: public:
ClientConnection *connection; ClientConnection* connection;
private: private:
bool flashOnSetHealth; bool flashOnSetHealth;
public: public:
MultiplayerLocalPlayer(Minecraft *minecraft, Level *level, User *user, ClientConnection *connection); MultiplayerLocalPlayer(Minecraft* minecraft, Level* level, User* user,
ClientConnection* connection);
private: private:
double xLast, yLast1, yLast2, zLast; double xLast, yLast1, yLast2, zLast;
float yRotLast, xRotLast; float yRotLast, xRotLast;
public: public:
virtual bool hurt(DamageSource *source, int dmg); virtual bool hurt(DamageSource* source, int dmg);
virtual void heal(int heal); virtual void heal(int heal);
virtual void tick(); virtual void tick();
private:
bool lastOnGround;
bool lastSneaked;
bool lastIdle;
bool lastSprinting;
int positionReminder;
public:
void sendPosition();
using Player::drop; private:
virtual std::shared_ptr<ItemEntity> drop(); bool lastOnGround;
protected: bool lastSneaked;
virtual void reallyDrop(std::shared_ptr<ItemEntity> itemEntity); bool lastIdle;
bool lastSprinting;
int positionReminder;
public: public:
virtual void chat(const std::wstring& message); void sendPosition();
using Player::drop;
virtual std::shared_ptr<ItemEntity> drop();
protected:
virtual void reallyDrop(std::shared_ptr<ItemEntity> itemEntity);
public:
virtual void chat(const std::wstring& message);
virtual void swing(); virtual void swing();
virtual void respawn(); virtual void respawn();
protected: protected:
virtual void actuallyHurt(DamageSource *source, int dmg); virtual void actuallyHurt(DamageSource* source, int dmg);
// 4J Added override to capture event for tutorial messages // 4J Added override to capture event for tutorial messages
virtual void completeUsingItem(); virtual void completeUsingItem();
// 4J Added overrides to capture events for tutorial
virtual void onEffectAdded(MobEffectInstance* effect);
virtual void onEffectUpdated(MobEffectInstance* effect);
virtual void onEffectRemoved(MobEffectInstance* effect);
// 4J Added overrides to capture events for tutorial
virtual void onEffectAdded(MobEffectInstance *effect);
virtual void onEffectUpdated(MobEffectInstance *effect);
virtual void onEffectRemoved(MobEffectInstance *effect);
public: public:
virtual void closeContainer(); virtual void closeContainer();
virtual void hurtTo(int newHealth, ETelemetryChallenges damageSource); virtual void hurtTo(int newHealth, ETelemetryChallenges damageSource);
virtual void awardStat(Stat *stat, byteArray param); virtual void awardStat(Stat* stat, byteArray param);
void awardStatFromServer(Stat *stat, byteArray param); void awardStatFromServer(Stat* stat, byteArray param);
void onUpdateAbilities(); void onUpdateAbilities();
bool isLocalPlayer(); bool isLocalPlayer();
// 4J - send the custom skin texture data if there is one // 4J - send the custom skin texture data if there is one
//void CustomSkin(PBYTE pbData, DWORD dwBytes); // void CustomSkin(PBYTE pbData, DWORD dwBytes);
// 4J Overriding this so we can flag an event for the tutorial // 4J Overriding this so we can flag an event for the tutorial
virtual void ride(std::shared_ptr<Entity> e); virtual void ride(std::shared_ptr<Entity> e);
// 4J - added for the Stop Sleeping // 4J - added for the Stop Sleeping
virtual void StopSleeping(); virtual void StopSleeping();
// 4J Added // 4J Added
virtual void setAndBroadcastCustomSkin(std::uint32_t skinId); virtual void setAndBroadcastCustomSkin(std::uint32_t skinId);
virtual void setAndBroadcastCustomCape(std::uint32_t capeId); virtual void setAndBroadcastCustomCape(std::uint32_t capeId);
}; };

View file

@ -3,45 +3,39 @@
#include "../../Minecraft.World/Headers/net.minecraft.world.item.h" #include "../../Minecraft.World/Headers/net.minecraft.world.item.h"
#include "../../Minecraft.World/Util/Mth.h" #include "../../Minecraft.World/Util/Mth.h"
RemotePlayer::RemotePlayer(Level *level, const std::wstring& name) : Player(level) RemotePlayer::RemotePlayer(Level* level, const std::wstring& name)
{ : Player(level) {
// 4J - added initialisers // 4J - added initialisers
hasStartedUsingItem = false; hasStartedUsingItem = false;
lSteps = 0; lSteps = 0;
lx = ly = lz = lyr = lxr = 0.0; lx = ly = lz = lyr = lxr = 0.0;
fallTime = 0.0f; fallTime = 0.0f;
this->name = name; this->name = name;
m_UUID = name; m_UUID = name;
app.DebugPrintf("Created RemotePlayer with name %ls\n", name.c_str() ); app.DebugPrintf("Created RemotePlayer with name %ls\n", name.c_str());
heightOffset = 0; heightOffset = 0;
this->footSize = 0; this->footSize = 0;
if (name.length() > 0) if (name.length() > 0) {
{ customTextureUrl = L""; // L"http://s3.amazonaws.com/MinecraftSkins/" +
customTextureUrl = L"";//L"http://s3.amazonaws.com/MinecraftSkins/" + name + L".png"; // name + L".png";
} }
this->noPhysics = true; this->noPhysics = true;
bedOffsetY = 4 / 16.0f; bedOffsetY = 4 / 16.0f;
this->viewScale = 10; this->viewScale = 10;
} }
void RemotePlayer::setDefaultHeadHeight() void RemotePlayer::setDefaultHeadHeight() { heightOffset = 0; }
{
heightOffset = 0;
}
bool RemotePlayer::hurt(DamageSource *source, int dmg) bool RemotePlayer::hurt(DamageSource* source, int dmg) { return true; }
{
return true;
}
void RemotePlayer::lerpTo(double x, double y, double z, float yRot, float xRot, int steps) void RemotePlayer::lerpTo(double x, double y, double z, float yRot, float xRot,
{ int steps) {
// heightOffset = 0; // heightOffset = 0;
lx = x; lx = x;
ly = y; ly = y;
lz = z; lz = z;
@ -51,8 +45,7 @@ void RemotePlayer::lerpTo(double x, double y, double z, float yRot, float xRot,
lSteps = steps; lSteps = steps;
} }
void RemotePlayer::tick() void RemotePlayer::tick() {
{
bedOffsetY = 0 / 16.0f; bedOffsetY = 0 / 16.0f;
Player::tick(); Player::tick();
@ -64,50 +57,43 @@ void RemotePlayer::tick()
walkAnimSpeed += (wst - walkAnimSpeed) * 0.4f; walkAnimSpeed += (wst - walkAnimSpeed) * 0.4f;
walkAnimPos += walkAnimSpeed; walkAnimPos += walkAnimSpeed;
if (!hasStartedUsingItem && isUsingItemFlag() && inventory->items[inventory->selected] != NULL) if (!hasStartedUsingItem && isUsingItemFlag() &&
{ inventory->items[inventory->selected] != NULL) {
std::shared_ptr<ItemInstance> item = inventory->items[inventory->selected]; std::shared_ptr<ItemInstance> item =
startUsingItem(inventory->items[inventory->selected], Item::items[item->id]->getUseDuration(item)); inventory->items[inventory->selected];
hasStartedUsingItem = true; startUsingItem(inventory->items[inventory->selected],
} Item::items[item->id]->getUseDuration(item));
else if (hasStartedUsingItem && !isUsingItemFlag()) hasStartedUsingItem = true;
{ } else if (hasStartedUsingItem && !isUsingItemFlag()) {
stopUsingItem(); stopUsingItem();
hasStartedUsingItem = false; hasStartedUsingItem = false;
} }
// if (eatItem != null) { // if (eatItem != null) {
// if (eatItemTickCount <= 25 && eatItemTickCount % 4 == 0) { // if (eatItemTickCount <= 25 && eatItemTickCount % 4 == 0) {
// spawnEatParticles(eatItem, 5); // spawnEatParticles(eatItem, 5);
// } // }
// eatItemTickCount--; // eatItemTickCount--;
// if (eatItemTickCount <= 0) { // if (eatItemTickCount <= 0) {
// spawnEatParticles(eatItem, 16); // spawnEatParticles(eatItem, 16);
// swing(); // swing();
// eatItem = null; // eatItem = null;
// } // }
// } // }
} }
float RemotePlayer::getShadowHeightOffs() float RemotePlayer::getShadowHeightOffs() { return 0; }
{
return 0;
}
void RemotePlayer::aiStep() void RemotePlayer::aiStep() {
{
Player::serverAiStep(); Player::serverAiStep();
if (lSteps > 0) if (lSteps > 0) {
{
double xt = x + (lx - x) / lSteps; double xt = x + (lx - x) / lSteps;
double yt = y + (ly - y) / lSteps; double yt = y + (ly - y) / lSteps;
double zt = z + (lz - z) / lSteps; double zt = z + (lz - z) / lSteps;
double yrd = lyr - yRot; double yrd = lyr - yRot;
while (yrd < -180) while (yrd < -180) yrd += 360;
yrd += 360; while (yrd >= 180) yrd -= 360;
while (yrd >= 180)
yrd -= 360;
yRot += (float)((yrd) / lSteps); yRot += (float)((yrd) / lSteps);
xRot += (float)((lxr - xRot) / lSteps); xRot += (float)((lxr - xRot) / lSteps);
@ -118,35 +104,29 @@ void RemotePlayer::aiStep()
} }
oBob = bob; oBob = bob;
float tBob = (float) Mth::sqrt(xd * xd + zd * zd); float tBob = (float)Mth::sqrt(xd * xd + zd * zd);
float tTilt = (float) atan(-yd * 0.2f) * 15.0f; float tTilt = (float)atan(-yd * 0.2f) * 15.0f;
if (tBob > 0.1f) tBob = 0.1f; if (tBob > 0.1f) tBob = 0.1f;
if (!onGround || getHealth() <= 0) tBob = 0; if (!onGround || getHealth() <= 0) tBob = 0;
if (onGround || getHealth() <= 0) tTilt = 0; if (onGround || getHealth() <= 0) tTilt = 0;
bob += (tBob - bob) * 0.4f; bob += (tBob - bob) * 0.4f;
tilt += (tTilt - tilt) * 0.8f; tilt += (tTilt - tilt) * 0.8f;
} }
// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game // 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer
void RemotePlayer::setEquippedSlot(int slot, std::shared_ptr<ItemInstance> item) // Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for
{ // other players in online game
if (slot == 0) void RemotePlayer::setEquippedSlot(int slot,
{ std::shared_ptr<ItemInstance> item) {
if (slot == 0) {
inventory->items[inventory->selected] = item; inventory->items[inventory->selected] = item;
} } else {
else
{
inventory->armor[slot - 1] = item; inventory->armor[slot - 1] = item;
} }
} }
void RemotePlayer::animateRespawn() void RemotePlayer::animateRespawn() {
{ // Player.animateRespawn(this, level);
// Player.animateRespawn(this, level);
} }
float RemotePlayer::getHeadHeight() float RemotePlayer::getHeadHeight() { return 1.82f; }
{
return 1.82f;
}

View file

@ -4,30 +4,39 @@
class Input; class Input;
class RemotePlayer : public Player class RemotePlayer : public Player {
{
private: private:
bool hasStartedUsingItem; bool hasStartedUsingItem;
public: public:
Input *input; Input* input;
RemotePlayer(Level *level, const std::wstring& name); RemotePlayer(Level* level, const std::wstring& name);
protected: protected:
virtual void setDefaultHeadHeight(); virtual void setDefaultHeadHeight();
public: public:
virtual bool hurt(DamageSource *source, int dmg); virtual bool hurt(DamageSource* source, int dmg);
private: private:
int lSteps; int lSteps;
double lx, ly, lz, lyr, lxr; double lx, ly, lz, lyr, lxr;
public: public:
virtual void lerpTo(double x, double y, double z, float yRot, float xRot, int steps); virtual void lerpTo(double x, double y, double z, float yRot, float xRot,
int steps);
float fallTime; float fallTime;
virtual void tick(); virtual void tick();
virtual float getShadowHeightOffs(); virtual float getShadowHeightOffs();
virtual void aiStep(); virtual void aiStep();
virtual void setEquippedSlot(int slot, std::shared_ptr<ItemInstance> item);// 4J Stu - Brought forward change from 1.3 to fix #64688 - Customer Encountered: TU7: Content: Art: Aura of enchanted item is not displayed for other players in online game virtual void setEquippedSlot(
int slot, std::shared_ptr<ItemInstance>
item); // 4J Stu - Brought forward change from 1.3 to fix
// #64688 - Customer Encountered: TU7: Content:
// Art: Aura of enchanted item is not displayed
// for other players in online game
virtual void animateRespawn(); virtual void animateRespawn();
virtual float getHeadHeight(); virtual float getHeadHeight();
bool hasPermission(EGameCommand command) { return false; } bool hasPermission(EGameCommand command) { return false; }
}; };

File diff suppressed because it is too large Load diff

View file

@ -12,153 +12,183 @@ class Entity;
class BrewingStandTileEntity; class BrewingStandTileEntity;
class Merchant; class Merchant;
class ServerPlayer : public Player,
class ServerPlayer : public Player, public net_minecraft_world_inventory::ContainerListener public net_minecraft_world_inventory::ContainerListener {
{
public: public:
eINSTANCEOF GetType() { return eTYPE_SERVERPLAYER; } eINSTANCEOF GetType() { return eTYPE_SERVERPLAYER; }
std::shared_ptr<PlayerConnection> connection; std::shared_ptr<PlayerConnection> connection;
MinecraftServer *server; MinecraftServer* server;
ServerPlayerGameMode *gameMode; ServerPlayerGameMode* gameMode;
double lastMoveX, lastMoveZ; double lastMoveX, lastMoveZ;
std::list<ChunkPos> chunksToSend; std::list<ChunkPos> chunksToSend;
std::vector<int> entitiesToRemove; std::vector<int> entitiesToRemove;
std::unordered_set<ChunkPos, ChunkPosKeyHash, ChunkPosKeyEq> seenChunks; std::unordered_set<ChunkPos, ChunkPosKeyHash, ChunkPosKeyEq> seenChunks;
int spewTimer; int spewTimer;
// 4J-Added, for 'Adventure Time' achievement. // 4J-Added, for 'Adventure Time' achievement.
Biome *currentBiome; Biome* currentBiome;
private: private:
int lastSentHealth; int lastSentHealth;
int lastSentFood; int lastSentFood;
bool lastFoodSaturationZero; bool lastFoodSaturationZero;
int lastSentExp; int lastSentExp;
int invulnerableTime; int invulnerableTime;
int viewDistance; int viewDistance;
int lastBrupSendTickCount; // 4J Added int lastBrupSendTickCount; // 4J Added
public: public:
ServerPlayer(MinecraftServer *server, Level *level, const std::wstring& name, ServerPlayerGameMode *gameMode); ServerPlayer(MinecraftServer* server, Level* level,
~ServerPlayer(); const std::wstring& name, ServerPlayerGameMode* gameMode);
void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added ~ServerPlayer();
void flagEntitiesToBeRemoved(unsigned int* flags,
bool* removedFound); // 4J added
virtual void readAdditionalSaveData(CompoundTag *entityTag); virtual void readAdditionalSaveData(CompoundTag* entityTag);
virtual void addAdditonalSaveData(CompoundTag *entityTag); virtual void addAdditonalSaveData(CompoundTag* entityTag);
virtual void withdrawExperienceLevels(int amount); virtual void withdrawExperienceLevels(int amount);
void initMenu(); void initMenu();
private: private:
ItemInstanceArray lastCarried; ItemInstanceArray lastCarried;
public: public:
virtual ItemInstanceArray getEquipmentSlots(); virtual ItemInstanceArray getEquipmentSlots();
protected: protected:
virtual void setDefaultHeadHeight(); virtual void setDefaultHeadHeight();
public: public:
virtual float getHeadHeight(); virtual float getHeadHeight();
virtual void tick(); virtual void tick();
void flushEntitiesToRemove(); void flushEntitiesToRemove();
virtual std::shared_ptr<ItemInstance> getCarried(int slot); virtual std::shared_ptr<ItemInstance> getCarried(int slot);
virtual void die(DamageSource *source); virtual void die(DamageSource* source);
virtual bool hurt(DamageSource *dmgSource, int dmg); virtual bool hurt(DamageSource* dmgSource, int dmg);
virtual bool isPlayerVersusPlayer(); virtual bool isPlayerVersusPlayer();
void doTick(bool sendChunks, bool dontDelayChunks = false, bool ignorePortal = false); void doTick(bool sendChunks, bool dontDelayChunks = false,
void doTickA(); bool ignorePortal = false);
void doChunkSendingTick(bool dontDelayChunks); void doTickA();
void doTickB(bool ignorePortal); void doChunkSendingTick(bool dontDelayChunks);
virtual void changeDimension(int i); void doTickB(bool ignorePortal);
virtual void changeDimension(int i);
private: private:
void broadcast(std::shared_ptr<TileEntity> te, bool delay = false); void broadcast(std::shared_ptr<TileEntity> te, bool delay = false);
public: public:
virtual void take(std::shared_ptr<Entity> e, int orgCount); virtual void take(std::shared_ptr<Entity> e, int orgCount);
virtual void swing(); virtual void swing();
virtual BedSleepingResult startSleepInBed(int x, int y, int z, bool bTestUse = false); virtual BedSleepingResult startSleepInBed(int x, int y, int z,
bool bTestUse = false);
public: public:
virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint); virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList,
bool saveRespawnPoint);
virtual void ride(std::shared_ptr<Entity> e); virtual void ride(std::shared_ptr<Entity> e);
protected: protected:
virtual void checkFallDamage(double ya, bool onGround); virtual void checkFallDamage(double ya, bool onGround);
public:
void doCheckFallDamage(double ya, bool onGround);
private:
int containerCounter;
public:
bool ignoreSlotUpdateHack;
int latency;
bool wonGame;
bool m_enteredEndExitPortal; // 4J Added
private:
void nextContainerCounter();
public: public:
virtual bool startCrafting(int x, int y, int z); // 4J added bool return void doCheckFallDamage(double ya, bool onGround);
virtual bool startEnchanting(int x, int y, int z); // 4J added bool return
virtual bool startRepairing(int x, int y, int z); // 4J added bool return private:
virtual bool openContainer(std::shared_ptr<Container> container); // 4J added bool return int containerCounter;
virtual bool openFurnace(std::shared_ptr<FurnaceTileEntity> furnace); // 4J added bool return
virtual bool openTrap(std::shared_ptr<DispenserTileEntity> trap); // 4J added bool return public:
virtual bool openBrewingStand(std::shared_ptr<BrewingStandTileEntity> brewingStand); // 4J added bool return bool ignoreSlotUpdateHack;
virtual bool openTrading(std::shared_ptr<Merchant> traderTarget); // 4J added bool return int latency;
virtual void slotChanged(AbstractContainerMenu *container, int slotIndex, std::shared_ptr<ItemInstance> item); bool wonGame;
void refreshContainer(AbstractContainerMenu *menu); bool m_enteredEndExitPortal; // 4J Added
virtual void refreshContainer(AbstractContainerMenu *container, std::vector<std::shared_ptr<ItemInstance> > *items);
virtual void setContainerData(AbstractContainerMenu *container, int id, int value); private:
void nextContainerCounter();
public:
virtual bool startCrafting(int x, int y, int z); // 4J added bool return
virtual bool startEnchanting(int x, int y, int z); // 4J added bool return
virtual bool startRepairing(int x, int y, int z); // 4J added bool return
virtual bool openContainer(
std::shared_ptr<Container> container); // 4J added bool return
virtual bool openFurnace(
std::shared_ptr<FurnaceTileEntity> furnace); // 4J added bool return
virtual bool openTrap(
std::shared_ptr<DispenserTileEntity> trap); // 4J added bool return
virtual bool openBrewingStand(std::shared_ptr<BrewingStandTileEntity>
brewingStand); // 4J added bool return
virtual bool openTrading(
std::shared_ptr<Merchant> traderTarget); // 4J added bool return
virtual void slotChanged(AbstractContainerMenu* container, int slotIndex,
std::shared_ptr<ItemInstance> item);
void refreshContainer(AbstractContainerMenu* menu);
virtual void refreshContainer(
AbstractContainerMenu* container,
std::vector<std::shared_ptr<ItemInstance> >* items);
virtual void setContainerData(AbstractContainerMenu* container, int id,
int value);
virtual void closeContainer(); virtual void closeContainer();
void broadcastCarriedItem(); void broadcastCarriedItem();
void doCloseContainer(); void doCloseContainer();
void setPlayerInput(float xa, float ya, bool jumping, bool sneaking, float xRot, float yRot); void setPlayerInput(float xa, float ya, bool jumping, bool sneaking,
float xRot, float yRot);
virtual void awardStat(Stat *stat, byteArray param); virtual void awardStat(Stat* stat, byteArray param);
void disconnect(); void disconnect();
void resetSentInfo(); void resetSentInfo();
virtual void displayClientMessage(int messageId); virtual void displayClientMessage(int messageId);
protected: protected:
virtual void completeUsingItem(); virtual void completeUsingItem();
public: public:
virtual void startUsingItem(std::shared_ptr<ItemInstance> instance, int duration); virtual void startUsingItem(std::shared_ptr<ItemInstance> instance,
virtual void restoreFrom(std::shared_ptr<Player> oldPlayer, bool restoreAll); int duration);
virtual void restoreFrom(std::shared_ptr<Player> oldPlayer,
bool restoreAll);
protected: protected:
virtual void onEffectAdded(MobEffectInstance *effect); virtual void onEffectAdded(MobEffectInstance* effect);
virtual void onEffectUpdated(MobEffectInstance *effect); virtual void onEffectUpdated(MobEffectInstance* effect);
virtual void onEffectRemoved(MobEffectInstance *effect); virtual void onEffectRemoved(MobEffectInstance* effect);
public: public:
virtual void teleportTo(double x, double y, double z); virtual void teleportTo(double x, double y, double z);
virtual void crit(std::shared_ptr<Entity> entity); virtual void crit(std::shared_ptr<Entity> entity);
virtual void magicCrit(std::shared_ptr<Entity> entity); virtual void magicCrit(std::shared_ptr<Entity> entity);
void onUpdateAbilities(); void onUpdateAbilities();
ServerLevel *getLevel(); ServerLevel* getLevel();
void setGameMode(GameType *mode); void setGameMode(GameType* mode);
void sendMessage(const std::wstring& message, ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom, int customData = -1, const std::wstring& additionalMessage = L""); void sendMessage(
bool hasPermission(EGameCommand command); const std::wstring& message,
// 4J - Don't use ChatPacket::EChatPacketMessage type = ChatPacket::e_ChatCustom,
//void updateOptions(std::shared_ptr<ClientInformationPacket> packet); int customData = -1, const std::wstring& additionalMessage = L"");
int getViewDistance(); bool hasPermission(EGameCommand command);
//bool canChatInColor(); // 4J - Don't use
//int getChatVisibility(); // void updateOptions(std::shared_ptr<ClientInformationPacket> packet);
int getViewDistance();
// bool canChatInColor();
// int getChatVisibility();
public: public:
static int getFlagIndexForChunk(const ChunkPos& pos,
static int getFlagIndexForChunk(const ChunkPos& pos, int dimension); // 4J - added int dimension); // 4J - added
int getPlayerViewDistanceModifier(); // 4J Added, returns a number which is subtracted from the default view distance int getPlayerViewDistanceModifier(); // 4J Added, returns a number which is
// subtracted from the default view
// distance
public: public:
// 4J Stu - Added hooks for the game rules // 4J Stu - Added hooks for the game rules
virtual void handleCollectItem(std::shared_ptr<ItemInstance> item); virtual void handleCollectItem(std::shared_ptr<ItemInstance> item);
#ifndef _CONTENT_PACKAGE #ifndef _CONTENT_PACKAGE
void debug_setPosition(double,double,double,double,double); void debug_setPosition(double, double, double, double, double);
#endif #endif
protected: protected:
// 4J Added to record telemetry of player deaths, this should store the last source of damage // 4J Added to record telemetry of player deaths, this should store the last
ETelemetryChallenges m_lastDamageSource; // source of damage
ETelemetryChallenges m_lastDamageSource;
}; };

View file

@ -13,363 +13,341 @@
#include "../Level/MultiPlayerLevel.h" #include "../Level/MultiPlayerLevel.h"
#include "../Rendering/LevelRenderer.h" #include "../Rendering/LevelRenderer.h"
ServerPlayerGameMode::ServerPlayerGameMode(Level *level) ServerPlayerGameMode::ServerPlayerGameMode(Level* level) {
{ // 4J - added initialisers
// 4J - added initialisers isDestroyingBlock = false;
isDestroyingBlock = false;
destroyProgressStart = 0; destroyProgressStart = 0;
xDestroyBlock = yDestroyBlock = zDestroyBlock = 0; xDestroyBlock = yDestroyBlock = zDestroyBlock = 0;
gameTicks = 0; gameTicks = 0;
hasDelayedDestroy = false; hasDelayedDestroy = false;
delayedDestroyX = delayedDestroyY = delayedDestroyZ = 0; delayedDestroyX = delayedDestroyY = delayedDestroyZ = 0;
delayedTickStart = 0; delayedTickStart = 0;
lastSentState = -1; lastSentState = -1;
gameModeForPlayer = GameType::NOT_SET; gameModeForPlayer = GameType::NOT_SET;
this->level = level; this->level = level;
// 4J Added // 4J Added
m_gameRules = NULL; m_gameRules = NULL;
} }
ServerPlayerGameMode::~ServerPlayerGameMode() ServerPlayerGameMode::~ServerPlayerGameMode() {
{ if (m_gameRules != NULL) delete m_gameRules;
if(m_gameRules!=NULL) delete m_gameRules;
} }
void ServerPlayerGameMode::setGameModeForPlayer(GameType *gameModeForPlayer) void ServerPlayerGameMode::setGameModeForPlayer(GameType* gameModeForPlayer) {
{ this->gameModeForPlayer = gameModeForPlayer;
this->gameModeForPlayer = gameModeForPlayer;
gameModeForPlayer->updatePlayerAbilities(&(player->abilities));
player->onUpdateAbilities();
gameModeForPlayer->updatePlayerAbilities(&(player->abilities));
player->onUpdateAbilities();
} }
GameType *ServerPlayerGameMode::getGameModeForPlayer() GameType* ServerPlayerGameMode::getGameModeForPlayer() {
{ return gameModeForPlayer;
return gameModeForPlayer;
} }
bool ServerPlayerGameMode::isSurvival() bool ServerPlayerGameMode::isSurvival() {
{ return gameModeForPlayer->isSurvival();
return gameModeForPlayer->isSurvival();
} }
bool ServerPlayerGameMode::isCreative() bool ServerPlayerGameMode::isCreative() {
{ return gameModeForPlayer->isCreative();
return gameModeForPlayer->isCreative();
} }
void ServerPlayerGameMode::updateGameMode(GameType *gameType) void ServerPlayerGameMode::updateGameMode(GameType* gameType) {
{ if (gameModeForPlayer == GameType::NOT_SET) {
if (gameModeForPlayer == GameType::NOT_SET) gameModeForPlayer = gameType;
{ }
gameModeForPlayer = gameType; setGameModeForPlayer(gameModeForPlayer);
}
setGameModeForPlayer(gameModeForPlayer);
} }
void ServerPlayerGameMode::tick() void ServerPlayerGameMode::tick() {
{
gameTicks++; gameTicks++;
if (hasDelayedDestroy) if (hasDelayedDestroy) {
{
int ticksSpentDestroying = gameTicks - delayedTickStart; int ticksSpentDestroying = gameTicks - delayedTickStart;
int t = level->getTile(delayedDestroyX, delayedDestroyY, delayedDestroyZ); int t =
if (t == 0) level->getTile(delayedDestroyX, delayedDestroyY, delayedDestroyZ);
{ if (t == 0) {
hasDelayedDestroy = false; hasDelayedDestroy = false;
} } else {
else Tile* tile = Tile::tiles[t];
{ float destroyProgress =
Tile *tile = Tile::tiles[t]; tile->getDestroyProgress(player, player->level, delayedDestroyX,
float destroyProgress = tile->getDestroyProgress(player, player->level, delayedDestroyX, delayedDestroyY, delayedDestroyZ) * (ticksSpentDestroying + 1); delayedDestroyY, delayedDestroyZ) *
int state = (int) (destroyProgress * 10); (ticksSpentDestroying + 1);
int state = (int)(destroyProgress * 10);
if (state != lastSentState) if (state != lastSentState) {
{ level->destroyTileProgress(player->entityId, delayedDestroyX,
level->destroyTileProgress(player->entityId, delayedDestroyX, delayedDestroyY, delayedDestroyZ, state); delayedDestroyY, delayedDestroyZ,
lastSentState = state; state);
} lastSentState = state;
if (destroyProgress >= 1) }
{ if (destroyProgress >= 1) {
hasDelayedDestroy = false; hasDelayedDestroy = false;
destroyBlock(delayedDestroyX, delayedDestroyY, delayedDestroyZ); destroyBlock(delayedDestroyX, delayedDestroyY, delayedDestroyZ);
} }
} }
} } else if (isDestroyingBlock) {
else if (isDestroyingBlock) int t = level->getTile(xDestroyBlock, yDestroyBlock, zDestroyBlock);
{ Tile* tile = Tile::tiles[t];
int t = level->getTile(xDestroyBlock, yDestroyBlock, zDestroyBlock);
Tile *tile = Tile::tiles[t]; if (tile == NULL) {
level->destroyTileProgress(player->entityId, xDestroyBlock,
if (tile == NULL) yDestroyBlock, zDestroyBlock, -1);
{ lastSentState = -1;
level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); isDestroyingBlock = false;
lastSentState = -1; } else {
isDestroyingBlock = false; int ticksSpentDestroying = gameTicks - destroyProgressStart;
} float destroyProgress =
else tile->getDestroyProgress(player, player->level, xDestroyBlock,
{ yDestroyBlock, zDestroyBlock) *
int ticksSpentDestroying = gameTicks - destroyProgressStart; (ticksSpentDestroying + 1);
float destroyProgress = tile->getDestroyProgress(player, player->level, xDestroyBlock, yDestroyBlock, zDestroyBlock) * (ticksSpentDestroying + 1); int state = (int)(destroyProgress * 10);
int state = (int) (destroyProgress * 10);
if (state != lastSentState) {
if (state != lastSentState) level->destroyTileProgress(player->entityId, xDestroyBlock,
{ yDestroyBlock, zDestroyBlock, state);
level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, state); lastSentState = state;
lastSentState = state;
}
}
}
}
void ServerPlayerGameMode::startDestroyBlock(int x, int y, int z, int face)
{
if(!player->isAllowedToMine()) return;
if (gameModeForPlayer->isReadOnly())
{
return;
}
if (isCreative())
{
if(!level->extinguishFire(nullptr, x, y, z, face))
{
destroyBlock(x, y, z);
}
return;
}
level->extinguishFire(player, x, y, z, face);
destroyProgressStart = gameTicks;
float progress = 1.0f;
int t = level->getTile(x, y, z);
if (t > 0)
{
Tile::tiles[t]->attack(level, x, y, z, player);
progress = Tile::tiles[t]->getDestroyProgress(player, player->level, x, y, z);
}
if (t > 0 && (progress >= 1 || (app.DebugSettingsOn() && (player->GetDebugOptions()&(1L<<eDebugSetting_InstantDestroy) ) )))
{
destroyBlock(x, y, z);
}
else
{
isDestroyingBlock = true;
xDestroyBlock = x;
yDestroyBlock = y;
zDestroyBlock = z;
int state = (int) (progress * 10);
level->destroyTileProgress(player->entityId, x, y, z, state);
lastSentState = state;
}
}
void ServerPlayerGameMode::stopDestroyBlock(int x, int y, int z)
{
if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock)
{
// int ticksSpentDestroying = gameTicks - destroyProgressStart;
int t = level->getTile(x, y, z);
if (t != 0)
{
Tile *tile = Tile::tiles[t];
// MGH - removed checking for the destroy progress here, it has already been checked on the client before it sent the packet.
// fixes issues with this failing to destroy because of packets bunching up
// float destroyProgress = tile->getDestroyProgress(player, player->level, x, y, z) * (ticksSpentDestroying + 1);
// if (destroyProgress >= .7f || bIgnoreDestroyProgress)
{
isDestroyingBlock = false;
level->destroyTileProgress(player->entityId, x, y, z, -1);
destroyBlock(x, y, z);
} }
// else if (!hasDelayedDestroy)
// {
// isDestroyingBlock = false;
// hasDelayedDestroy = true;
// delayedDestroyX = x;
// delayedDestroyY = y;
// delayedDestroyZ = z;
// delayedTickStart = destroyProgressStart;
// }
} }
} }
} }
void ServerPlayerGameMode::abortDestroyBlock(int x, int y, int z) void ServerPlayerGameMode::startDestroyBlock(int x, int y, int z, int face) {
{ if (!player->isAllowedToMine()) return;
isDestroyingBlock = false;
level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock, zDestroyBlock, -1); if (gameModeForPlayer->isReadOnly()) {
return;
}
if (isCreative()) {
if (!level->extinguishFire(nullptr, x, y, z, face)) {
destroyBlock(x, y, z);
}
return;
}
level->extinguishFire(player, x, y, z, face);
destroyProgressStart = gameTicks;
float progress = 1.0f;
int t = level->getTile(x, y, z);
if (t > 0) {
Tile::tiles[t]->attack(level, x, y, z, player);
progress =
Tile::tiles[t]->getDestroyProgress(player, player->level, x, y, z);
}
if (t > 0 && (progress >= 1 || (app.DebugSettingsOn() &&
(player->GetDebugOptions() &
(1L << eDebugSetting_InstantDestroy))))) {
destroyBlock(x, y, z);
} else {
isDestroyingBlock = true;
xDestroyBlock = x;
yDestroyBlock = y;
zDestroyBlock = z;
int state = (int)(progress * 10);
level->destroyTileProgress(player->entityId, x, y, z, state);
lastSentState = state;
}
} }
bool ServerPlayerGameMode::superDestroyBlock(int x, int y, int z) void ServerPlayerGameMode::stopDestroyBlock(int x, int y, int z) {
{ if (x == xDestroyBlock && y == yDestroyBlock && z == zDestroyBlock) {
Tile *oldTile = Tile::tiles[level->getTile(x, y, z)]; // int ticksSpentDestroying = gameTicks - destroyProgressStart;
int t = level->getTile(x, y, z);
if (t != 0) {
Tile* tile = Tile::tiles[t];
// MGH - removed checking for the destroy progress here, it has
// already been checked on the client before it sent the packet.
// fixes issues with this failing to destroy
//because of packets bunching up
// float destroyProgress =
// tile->getDestroyProgress(player, player->level, x, y,
// z) * (ticksSpentDestroying + 1); if (destroyProgress
// >= .7f || bIgnoreDestroyProgress)
{
isDestroyingBlock = false;
level->destroyTileProgress(player->entityId, x, y, z, -1);
destroyBlock(x, y, z);
}
// else if (!hasDelayedDestroy)
// {
// isDestroyingBlock = false;
// hasDelayedDestroy = true;
// delayedDestroyX = x;
// delayedDestroyY = y;
// delayedDestroyZ = z;
// delayedTickStart = destroyProgressStart;
// }
}
}
}
void ServerPlayerGameMode::abortDestroyBlock(int x, int y, int z) {
isDestroyingBlock = false;
level->destroyTileProgress(player->entityId, xDestroyBlock, yDestroyBlock,
zDestroyBlock, -1);
}
bool ServerPlayerGameMode::superDestroyBlock(int x, int y, int z) {
Tile* oldTile = Tile::tiles[level->getTile(x, y, z)];
int data = level->getData(x, y, z); int data = level->getData(x, y, z);
if (oldTile != NULL) if (oldTile != NULL) {
{ oldTile->playerWillDestroy(level, x, y, z, data, player);
oldTile->playerWillDestroy(level, x, y, z, data, player); }
}
bool changed = level->setTile(x, y, z, 0); bool changed = level->setTile(x, y, z, 0);
if (oldTile != NULL && changed) if (oldTile != NULL && changed) {
{
oldTile->destroy(level, x, y, z, data); oldTile->destroy(level, x, y, z, data);
} }
return changed; return changed;
} }
bool ServerPlayerGameMode::destroyBlock(int x, int y, int z) bool ServerPlayerGameMode::destroyBlock(int x, int y, int z) {
{ if (gameModeForPlayer->isReadOnly()) {
if (gameModeForPlayer->isReadOnly()) return false;
{ }
return false;
}
int t = level->getTile(x, y, z); int t = level->getTile(x, y, z);
int data = level->getData(x, y, z); int data = level->getData(x, y, z);
level->levelEvent(player, LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z, t + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT));
// 4J - In creative mode, the point where we need to tell the renderer that we are about to destroy a tile via destroyingTileAt is quite complicated.
// If the player being told is remote, then we always want the client to do it as it does the final update. If the player being told is local,
// then we need to update the renderer Here if we are sharing data between host & client as this is the final point where the original data is still intact.
// If the player being told is local, and we aren't sharing data between host & client, then we can just treat it as if it is a remote player and
// it can update the renderer.
bool clientToUpdateRenderer = false;
if( isCreative() )
{
clientToUpdateRenderer = true;
if( std::dynamic_pointer_cast<ServerPlayer>(player)->connection->isLocal() )
{
// Establish whether we are sharing this chunk between client & server
MultiPlayerLevel *clientLevel = Minecraft::GetInstance()->getLevel(level->dimension->id);
if( clientLevel )
{
LevelChunk *lc = clientLevel->getChunkAt( x, z );
#ifdef SHARING_ENABLED
if( lc->sharingTilesAndData )
{
// We are sharing - this is the last point we can tell the renderer
Minecraft::GetInstance()->levelRenderer->destroyedTileManager->destroyingTileAt( clientLevel, x, y, z );
// Don't need to ask the client to do this too level->levelEvent(player, LevelEvent::PARTICLES_DESTROY_BLOCK, x, y, z,
clientToUpdateRenderer = false; t + (level->getData(x, y, z) << Tile::TILE_NUM_SHIFT));
}
// 4J - In creative mode, the point where we need to tell the renderer that
// we are about to destroy a tile via destroyingTileAt is quite complicated.
// If the player being told is remote, then we always want the client to do
// it as it does the final update. If the player being told is local, then
// we need to update the renderer Here if we are sharing data between host &
// client as this is the final point where the original data is still
// intact. If the player being told is local, and we aren't sharing data
// between host & client, then we can just treat it as if it is a remote
// player and it can update the renderer.
bool clientToUpdateRenderer = false;
if (isCreative()) {
clientToUpdateRenderer = true;
if (std::dynamic_pointer_cast<ServerPlayer>(player)
->connection->isLocal()) {
// Establish whether we are sharing this chunk between client &
// server
MultiPlayerLevel* clientLevel =
Minecraft::GetInstance()->getLevel(level->dimension->id);
if (clientLevel) {
LevelChunk* lc = clientLevel->getChunkAt(x, z);
#ifdef SHARING_ENABLED
if (lc->sharingTilesAndData) {
// We are sharing - this is the last point we can tell the
// renderer
Minecraft::GetInstance()
->levelRenderer->destroyedTileManager->destroyingTileAt(
clientLevel, x, y, z);
// Don't need to ask the client to do this too
clientToUpdateRenderer = false;
}
#endif #endif
} }
} }
} }
bool changed = superDestroyBlock(x, y, z); bool changed = superDestroyBlock(x, y, z);
if (isCreative()) if (isCreative()) {
{ std::shared_ptr<TileUpdatePacket> tup =
std::shared_ptr<TileUpdatePacket> tup = std::shared_ptr<TileUpdatePacket>( new TileUpdatePacket(x, y, z, level) ); std::shared_ptr<TileUpdatePacket>(
// 4J - a bit of a hack here, but if we want to tell the client that it needs to inform the renderer of a block being destroyed, then send a block 255 instead of a 0. This is handled in ClientConnection::handleTileUpdate new TileUpdatePacket(x, y, z, level));
if( tup->block == 0 ) // 4J - a bit of a hack here, but if we want to tell the client that it
{ // needs to inform the renderer of a block being destroyed, then send a
if( clientToUpdateRenderer ) tup->block = 255; // block 255 instead of a 0. This is handled in
} // ClientConnection::handleTileUpdate
player->connection->send( tup ); if (tup->block == 0) {
} if (clientToUpdateRenderer) tup->block = 255;
else }
{ player->connection->send(tup);
std::shared_ptr<ItemInstance> item = player->getSelectedItem(); } else {
bool canDestroy = player->canDestroy(Tile::tiles[t]); std::shared_ptr<ItemInstance> item = player->getSelectedItem();
if (item != NULL) bool canDestroy = player->canDestroy(Tile::tiles[t]);
{ if (item != NULL) {
item->mineBlock(level, t, x, y, z, player); item->mineBlock(level, t, x, y, z, player);
if (item->count == 0) if (item->count == 0) {
{ player->removeSelectedItem();
player->removeSelectedItem(); }
} }
} if (changed && canDestroy) {
if (changed && canDestroy) Tile::tiles[t]->playerDestroy(level, player, x, y, z, data);
{ }
Tile::tiles[t]->playerDestroy(level, player, x, y, z, data); }
}
}
return changed; return changed;
} }
bool ServerPlayerGameMode::useItem(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, bool bTestUseOnly) bool ServerPlayerGameMode::useItem(std::shared_ptr<Player> player, Level* level,
{ std::shared_ptr<ItemInstance> item,
if(!player->isAllowedToUse(item)) return false; bool bTestUseOnly) {
if (!player->isAllowedToUse(item)) return false;
int oldCount = item->count; int oldCount = item->count;
int oldAux = item->getAuxValue(); int oldAux = item->getAuxValue();
std::shared_ptr<ItemInstance> itemInstance = item->use(level, player); std::shared_ptr<ItemInstance> itemInstance = item->use(level, player);
if ((itemInstance != NULL && itemInstance != item) || (itemInstance != NULL && itemInstance->count != oldCount) || (itemInstance != NULL && itemInstance->getUseDuration() > 0)) if ((itemInstance != NULL && itemInstance != item) ||
{ (itemInstance != NULL && itemInstance->count != oldCount) ||
(itemInstance != NULL && itemInstance->getUseDuration() > 0)) {
player->inventory->items[player->inventory->selected] = itemInstance; player->inventory->items[player->inventory->selected] = itemInstance;
if (isCreative()) if (isCreative()) {
{ itemInstance->count = oldCount;
itemInstance->count = oldCount; itemInstance->setAuxValue(oldAux);
itemInstance->setAuxValue(oldAux); }
} if (itemInstance->count == 0) {
if (itemInstance->count == 0)
{
player->inventory->items[player->inventory->selected] = nullptr; player->inventory->items[player->inventory->selected] = nullptr;
} }
return true; return true;
} }
return false; return false;
} }
bool ServerPlayerGameMode::useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly, bool *pbUsedItem) bool ServerPlayerGameMode::useItemOn(std::shared_ptr<Player> player,
{ Level* level,
// 4J-PB - Adding a test only version to allow tooltips to be displayed std::shared_ptr<ItemInstance> item, int x,
int t = level->getTile(x, y, z); int y, int z, int face, float clickX,
if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) float clickY, float clickZ,
{ bool bTestUseOnOnly, bool* pbUsedItem) {
if(bTestUseOnOnly) // 4J-PB - Adding a test only version to allow tooltips to be displayed
{ int t = level->getTile(x, y, z);
if (Tile::tiles[t]->TestUse()) return true; if (t > 0 && player->isAllowedToUse(Tile::tiles[t])) {
} if (bTestUseOnOnly) {
else if (Tile::tiles[t]->TestUse()) return true;
{ } else {
if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX, clickY, clickZ)) if (Tile::tiles[t]->use(level, x, y, z, player, face, clickX,
{ clickY, clickZ)) {
if(m_gameRules != NULL) m_gameRules->onUseTile(t,x,y,z); if (m_gameRules != NULL) m_gameRules->onUseTile(t, x, y, z);
return true; return true;
} }
} }
} }
if (item == NULL || !player->isAllowedToUse(item)) return false; if (item == NULL || !player->isAllowedToUse(item)) return false;
if (isCreative()) if (isCreative()) {
{ int aux = item->getAuxValue();
int aux = item->getAuxValue(); int count = item->count;
int count = item->count; bool success =
bool success = item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ); item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ);
item->setAuxValue(aux); item->setAuxValue(aux);
item->count = count; item->count = count;
return success; return success;
} } else {
else return item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ,
{ bTestUseOnOnly);
return item->useOn(player, level, x, y, z, face, clickX, clickY, clickZ, bTestUseOnOnly); }
}
} }
void ServerPlayerGameMode::setLevel(ServerLevel *newLevel) void ServerPlayerGameMode::setLevel(ServerLevel* newLevel) { level = newLevel; }
{
level = newLevel;
}
// 4J Added // 4J Added
void ServerPlayerGameMode::setGameRules(GameRulesInstance *rules) void ServerPlayerGameMode::setGameRules(GameRulesInstance* rules) {
{ if (m_gameRules != NULL) delete m_gameRules;
if(m_gameRules != NULL) delete m_gameRules; m_gameRules = rules;
m_gameRules = rules;
} }

View file

@ -6,17 +6,16 @@ class ServerLevel;
class GameRulesInstance; class GameRulesInstance;
class GameType; class GameType;
class ServerPlayerGameMode class ServerPlayerGameMode {
{
public: public:
Level *level; Level* level;
std::shared_ptr<ServerPlayer> player; std::shared_ptr<ServerPlayer> player;
private: private:
GameType *gameModeForPlayer; GameType* gameModeForPlayer;
private: private:
bool isDestroyingBlock; bool isDestroyingBlock;
int destroyProgressStart; int destroyProgressStart;
int xDestroyBlock, yDestroyBlock, zDestroyBlock; int xDestroyBlock, yDestroyBlock, zDestroyBlock;
int gameTicks; int gameTicks;
@ -24,24 +23,25 @@ private:
bool hasDelayedDestroy; bool hasDelayedDestroy;
int delayedDestroyX, delayedDestroyY, delayedDestroyZ; int delayedDestroyX, delayedDestroyY, delayedDestroyZ;
int delayedTickStart; int delayedTickStart;
int lastSentState; int lastSentState;
private: private:
// 4J Added // 4J Added
GameRulesInstance *m_gameRules; GameRulesInstance* m_gameRules;
public:
void setGameRules(GameRulesInstance *rules);
GameRulesInstance *getGameRules() { return m_gameRules; }
public: public:
ServerPlayerGameMode(Level *level); void setGameRules(GameRulesInstance* rules);
~ServerPlayerGameMode(); GameRulesInstance* getGameRules() { return m_gameRules; }
void setGameModeForPlayer(GameType *gameModeForPlayer); public:
GameType *getGameModeForPlayer(); ServerPlayerGameMode(Level* level);
bool isSurvival(); ~ServerPlayerGameMode();
bool isCreative();
void updateGameMode(GameType *gameType); void setGameModeForPlayer(GameType* gameModeForPlayer);
GameType* getGameModeForPlayer();
bool isSurvival();
bool isCreative();
void updateGameMode(GameType* gameType);
void tick(); void tick();
void startDestroyBlock(int x, int y, int z, int face); void startDestroyBlock(int x, int y, int z, int face);
@ -53,8 +53,12 @@ private:
public: public:
bool destroyBlock(int x, int y, int z); bool destroyBlock(int x, int y, int z);
bool useItem(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, bool bTestUseOnly=false); bool useItem(std::shared_ptr<Player> player, Level* level,
bool useItemOn(std::shared_ptr<Player> player, Level *level, std::shared_ptr<ItemInstance> item, int x, int y, int z, int face, float clickX, float clickY, float clickZ, bool bTestUseOnOnly=false, bool *pbUsedItem=NULL); std::shared_ptr<ItemInstance> item, bool bTestUseOnly = false);
bool useItemOn(std::shared_ptr<Player> player, Level* level,
std::shared_ptr<ItemInstance> item, int x, int y, int z,
int face, float clickX, float clickY, float clickZ,
bool bTestUseOnOnly = false, bool* pbUsedItem = NULL);
void setLevel(ServerLevel *newLevel); void setLevel(ServerLevel* newLevel);
}; };

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