Merge branch 'dev' into feat/iggy-dev

This commit is contained in:
Tropical 2026-03-14 03:25:09 -05:00
commit f66b293e33
2086 changed files with 183603 additions and 184149 deletions

4
.clang-format Normal file
View file

@ -0,0 +1,4 @@
BasedOnStyle: Google
IndentWidth: 4
AccessModifierOffset: -4
SortIncludes: false # FIXME: https://github.com/4jcraft/4jcraft/issues/225

3
.git-blame-ignore-revs Normal file
View file

@ -0,0 +1,3 @@
e8424f2000222490850d2a5227b6b6b0c0a5d6ce
33d0737d1d4a6d8a7f0fa3bf2af2b242b545dc69
631873465238400f8ed8113ac87d63c3d6edf617

34
.github/scripts/check-clang-format.sh vendored Normal file
View file

@ -0,0 +1,34 @@
#!/usr/bin/env bash
set -euo pipefail
formatter="${CLANG_FORMAT_BIN:-clang-format-19}"
base_ref="${1:-}"
head_ref="${2:-HEAD}"
if [[ -z "$base_ref" ]]; then
if git rev-parse --verify HEAD^ >/dev/null 2>&1; then
base_ref="$(git rev-parse HEAD^)"
else
echo "No comparison base available; skipping clang-format check."
exit 0
fi
fi
diff_output="$(
git diff --name-only --diff-filter=ACMR "$base_ref" "$head_ref" -- \
'*.c' '*.cc' '*.cpp' '*.cxx' '*.h' '*.hh' '*.hpp' '*.hxx' '*.inl'
)"
if [[ -z "$diff_output" ]]; then
echo "No changed C/C++ files to check."
exit 0
fi
mapfile -t files <<<"$diff_output"
echo "Checking formatting for changed files:"
printf ' %s\n' "${files[@]}"
"$formatter" --version
"$formatter" --dry-run --Werror "${files[@]}"

69
.github/workflows/clang-format.yml vendored Normal file
View file

@ -0,0 +1,69 @@
name: Clang Format
on:
push:
paths:
- '**.cpp'
- '**.h'
- '**.c'
- '**.cc'
- '**.cxx'
- '**.hh'
- '**.hpp'
- '**.hxx'
- '**.inl'
- '.clang-format'
- '.github/workflows/clang-format.yml'
- '.github/scripts/check-clang-format.sh'
pull_request:
paths:
- '**.cpp'
- '**.h'
- '**.c'
- '**.cc'
- '**.cxx'
- '**.hh'
- '**.hpp'
- '**.hxx'
- '**.inl'
- '.clang-format'
- '.github/workflows/clang-format.yml'
- '.github/scripts/check-clang-format.sh'
jobs:
clang-format:
runs-on: ubuntu-24.04
concurrency:
group: clang-format-${{ github.ref }}
cancel-in-progress: true
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install clang-format
run: |
sudo apt-get update
sudo apt-get install -y clang-format-19
- name: Check changed files
env:
CLANG_FORMAT_BIN: clang-format-19
EVENT_NAME: ${{ github.event_name }}
PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
BEFORE_SHA: ${{ github.event.before }}
CURRENT_SHA: ${{ github.sha }}
run: |
set -euo pipefail
BASE_SHA=""
if [ "$EVENT_NAME" = "pull_request" ]; then
git fetch --no-tags origin "$PR_BASE_REF" --depth=1
BASE_SHA="$(git merge-base "origin/$PR_BASE_REF" "$CURRENT_SHA")"
elif [ -n "$BEFORE_SHA" ] && [ "$BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then
BASE_SHA="$BEFORE_SHA"
fi
bash ./.github/scripts/check-clang-format.sh "$BASE_SHA" "$CURRENT_SHA"

View file

@ -8,24 +8,24 @@
C_4JInput InputManager; C_4JInput InputManager;
static const int KEY_COUNT = SDL_NUM_SCANCODES; static const int KEY_COUNT = SDL_NUM_SCANCODES;
static const float MOUSE_SCALE = 0.015f; static const float MOUSE_SCALE = 0.015f;
// Vars // Vars
static bool s_sdlInitialized = false; static bool s_sdlInitialized = false;
static bool s_keysCurrent[KEY_COUNT] = {}; static bool s_keysCurrent[KEY_COUNT] = {};
static bool s_keysPrev [KEY_COUNT] = {}; static bool s_keysPrev[KEY_COUNT] = {};
static bool s_mouseLeftCurrent = false, s_mouseLeftPrev = false; static bool s_mouseLeftCurrent = false, s_mouseLeftPrev = false;
static bool s_mouseRightCurrent = false, s_mouseRightPrev = false; static bool s_mouseRightCurrent = false, s_mouseRightPrev = false;
static bool s_menuDisplayed[4] = {}; static bool s_menuDisplayed[4] = {};
static bool s_prevMenuDisplayed = false; static bool s_prevMenuDisplayed = false;
static bool s_snapTaken = false; static bool s_snapTaken = false;
static float s_accumRelX = 0, s_accumRelY = 0; static float s_accumRelX = 0, s_accumRelY = 0;
static float s_snapRelX = 0, s_snapRelY = 0; static float s_snapRelX = 0, s_snapRelY = 0;
static int s_scrollTicksForButtonPressed = 0; static int s_scrollTicksForButtonPressed = 0;
static int s_scrollTicksForGetValue = 0; static int s_scrollTicksForGetValue = 0;
static int s_scrollTicksSnap = 0; static int s_scrollTicksSnap = 0;
static bool s_scrollSnapTaken = false; static bool s_scrollSnapTaken = false;
// We set all the watched keys // We set all the watched keys
// I don't know if I'll need to change this if we add chat support soon. // I don't know if I'll need to change this if we add chat support soon.
@ -43,18 +43,35 @@ static const int s_watchedKeys[] = {
SDL_SCANCODE_9, SDL_SCANCODE_Z, SDL_SCANCODE_X, SDL_SCANCODE_C, SDL_SCANCODE_9, SDL_SCANCODE_Z, SDL_SCANCODE_X, SDL_SCANCODE_C,
SDL_SCANCODE_V SDL_SCANCODE_V
}; };
static const int s_watchedKeyCount = (int)(sizeof(s_watchedKeys) / sizeof(s_watchedKeys[0])); static const int s_watchedKeyCount =
(int)(sizeof(s_watchedKeys) / sizeof(s_watchedKeys[0]));
static inline bool KDown (int sc) { return (sc > 0 && sc < KEY_COUNT) ? s_keysCurrent[sc] : false; } static inline bool KDown(int sc) {
static inline bool KPressed (int sc) { return (sc > 0 && sc < KEY_COUNT) ? !s_keysPrev[sc] && s_keysCurrent[sc] : false; } return (sc > 0 && sc < KEY_COUNT) ? s_keysCurrent[sc] : false;
static inline bool KReleased(int sc) { return (sc > 0 && sc < KEY_COUNT) ? s_keysPrev[sc] && !s_keysCurrent[sc] : false; } }
static inline bool KPressed(int sc) {
return (sc > 0 && sc < KEY_COUNT) ? !s_keysPrev[sc] && s_keysCurrent[sc]
: false;
}
static inline bool KReleased(int sc) {
return (sc > 0 && sc < KEY_COUNT) ? s_keysPrev[sc] && !s_keysCurrent[sc]
: false;
}
static inline bool MouseLDown () { return s_mouseLeftCurrent; } static inline bool MouseLDown() { return s_mouseLeftCurrent; }
static inline bool MouseLPressed () { return s_mouseLeftCurrent && !s_mouseLeftPrev; } static inline bool MouseLPressed() {
static inline bool MouseLReleased() { return !s_mouseLeftCurrent && s_mouseLeftPrev; } return s_mouseLeftCurrent && !s_mouseLeftPrev;
static inline bool MouseRDown () { return s_mouseRightCurrent; } }
static inline bool MouseRPressed () { return s_mouseRightCurrent && !s_mouseRightPrev; } static inline bool MouseLReleased() {
static inline bool MouseRReleased() { return !s_mouseRightCurrent && s_mouseRightPrev; } return !s_mouseLeftCurrent && s_mouseLeftPrev;
}
static inline bool MouseRDown() { return s_mouseRightCurrent; }
static inline bool MouseRPressed() {
return s_mouseRightCurrent && !s_mouseRightPrev;
}
static inline bool MouseRReleased() {
return !s_mouseRightCurrent && s_mouseRightPrev;
}
// get directly into SDL events before the game queue can steal them. // get directly into SDL events before the game queue can steal them.
// this took me a while. // this took me a while.
@ -92,8 +109,10 @@ static int ScrollSnap() {
static void TakeSnapIfNeeded() { static void TakeSnapIfNeeded() {
if (!s_snapTaken) { if (!s_snapTaken) {
s_snapRelX = s_accumRelX; s_accumRelX = 0; s_snapRelX = s_accumRelX;
s_snapRelY = s_accumRelY; s_accumRelY = 0; s_accumRelX = 0;
s_snapRelY = s_accumRelY;
s_accumRelY = 0;
s_snapTaken = true; s_snapTaken = true;
} }
} }
@ -107,27 +126,29 @@ void C_4JInput::Initialise(int, unsigned char, unsigned char, unsigned char) {
s_sdlInitialized = true; s_sdlInitialized = true;
} }
memset(s_keysCurrent, 0, sizeof(s_keysCurrent)); memset(s_keysCurrent, 0, sizeof(s_keysCurrent));
memset(s_keysPrev, 0, sizeof(s_keysPrev)); memset(s_keysPrev, 0, sizeof(s_keysPrev));
memset(s_menuDisplayed, 0, sizeof(s_menuDisplayed)); memset(s_menuDisplayed, 0, sizeof(s_menuDisplayed));
s_mouseLeftCurrent = s_mouseLeftPrev = s_mouseRightCurrent = s_mouseRightPrev = false; s_mouseLeftCurrent = s_mouseLeftPrev = s_mouseRightCurrent =
s_mouseRightPrev = false;
s_accumRelX = s_accumRelY = s_snapRelX = s_snapRelY = 0; s_accumRelX = s_accumRelY = s_snapRelX = s_snapRelY = 0;
// i really gotta name these vars better.. // i really gotta name these vars better..
s_scrollTicksForButtonPressed = s_scrollTicksForGetValue = s_scrollTicksSnap = 0; s_scrollTicksForButtonPressed = s_scrollTicksForGetValue =
s_scrollTicksSnap = 0;
s_snapTaken = s_scrollSnapTaken = s_prevMenuDisplayed = false; s_snapTaken = s_scrollSnapTaken = s_prevMenuDisplayed = false;
if (s_sdlInitialized) if (s_sdlInitialized) SDL_SetRelativeMouseMode(SDL_TRUE);
SDL_SetRelativeMouseMode(SDL_TRUE);
} }
// Each tick we update the input state by polling SDL, this is where we get the kbd and mouse state. // Each tick we update the input state by polling SDL, this is where we get the
// kbd and mouse state.
void C_4JInput::Tick() { void C_4JInput::Tick() {
if (!s_sdlInitialized) return; if (!s_sdlInitialized) return;
memcpy(s_keysPrev, s_keysCurrent, sizeof(s_keysCurrent)); memcpy(s_keysPrev, s_keysCurrent, sizeof(s_keysCurrent));
s_mouseLeftPrev = s_mouseLeftCurrent; s_mouseLeftPrev = s_mouseLeftCurrent;
s_mouseRightPrev = s_mouseRightCurrent; s_mouseRightPrev = s_mouseRightCurrent;
s_snapTaken = false; s_snapTaken = false;
s_scrollSnapTaken = false; s_scrollSnapTaken = false;
s_snapRelX = s_snapRelY = 0; s_snapRelX = s_snapRelY = 0;
s_scrollTicksSnap = 0; s_scrollTicksSnap = 0;
@ -138,14 +159,14 @@ void C_4JInput::Tick() {
s_scrollTicksForGetValue = 0; s_scrollTicksForGetValue = 0;
} }
const Uint8 *state = SDL_GetKeyboardState(NULL); const Uint8* state = SDL_GetKeyboardState(NULL);
for (int i = 0; i < s_watchedKeyCount; ++i) { for (int i = 0; i < s_watchedKeyCount; ++i) {
int sc = s_watchedKeys[i]; int sc = s_watchedKeys[i];
if (sc > 0 && sc < KEY_COUNT) s_keysCurrent[sc] = state[sc] != 0; if (sc > 0 && sc < KEY_COUNT) s_keysCurrent[sc] = state[sc] != 0;
} }
Uint32 btns = SDL_GetMouseState(NULL, NULL); Uint32 btns = SDL_GetMouseState(NULL, NULL);
s_mouseLeftCurrent = (btns & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0; s_mouseLeftCurrent = (btns & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0;
s_mouseRightCurrent = (btns & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0; s_mouseRightCurrent = (btns & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
if (!SDL_GetRelativeMouseMode()) { if (!SDL_GetRelativeMouseMode()) {
@ -154,8 +175,11 @@ void C_4JInput::Tick() {
} }
if (!SDL_GetKeyboardFocus()) { if (!SDL_GetKeyboardFocus()) {
SDL_Window *mf = SDL_GetMouseFocus(); SDL_Window* mf = SDL_GetMouseFocus();
if (mf) { SDL_RaiseWindow(mf); SDL_SetWindowGrab(mf, SDL_TRUE); } if (mf) {
SDL_RaiseWindow(mf);
SDL_SetWindowGrab(mf, SDL_TRUE);
}
} }
} }
@ -165,9 +189,9 @@ int C_4JInput::GetHotbarSlotPressed(int iPad) {
constexpr size_t NUM_HOTBAR_SLOTS = 9; constexpr size_t NUM_HOTBAR_SLOTS = 9;
static const int sc[NUM_HOTBAR_SLOTS] = { static const int sc[NUM_HOTBAR_SLOTS] = {
SDL_SCANCODE_1, SDL_SCANCODE_2, SDL_SCANCODE_3, SDL_SCANCODE_4, SDL_SCANCODE_1, SDL_SCANCODE_2, SDL_SCANCODE_3,
SDL_SCANCODE_5, SDL_SCANCODE_6, SDL_SCANCODE_7, SDL_SCANCODE_8, SDL_SCANCODE_4, SDL_SCANCODE_5, SDL_SCANCODE_6,
SDL_SCANCODE_9, SDL_SCANCODE_7, SDL_SCANCODE_8, SDL_SCANCODE_9,
}; };
static bool s_wasDown[NUM_HOTBAR_SLOTS] = {}; static bool s_wasDown[NUM_HOTBAR_SLOTS] = {};
@ -218,45 +242,64 @@ bool C_4JInput::ButtonDown(int iPad, unsigned char ucAction) {
return s_mouseLeftCurrent || s_mouseRightCurrent; return s_mouseLeftCurrent || s_mouseRightCurrent;
} }
switch (ucAction) { switch (ucAction) {
case MINECRAFT_ACTION_ACTION: return MouseLDown() || KDown(SDL_SCANCODE_RETURN); case MINECRAFT_ACTION_ACTION:
case MINECRAFT_ACTION_USE: return MouseRDown() || KDown(SDL_SCANCODE_F); return MouseLDown() || KDown(SDL_SCANCODE_RETURN);
case MINECRAFT_ACTION_SNEAK_TOGGLE: return KDown(SDL_SCANCODE_LSHIFT) || KDown(SDL_SCANCODE_RSHIFT); case MINECRAFT_ACTION_USE:
case MINECRAFT_ACTION_SPRINT: return KDown(SDL_SCANCODE_LCTRL) || KDown(SDL_SCANCODE_RCTRL); return MouseRDown() || KDown(SDL_SCANCODE_F);
case MINECRAFT_ACTION_SNEAK_TOGGLE:
return KDown(SDL_SCANCODE_LSHIFT) || KDown(SDL_SCANCODE_RSHIFT);
case MINECRAFT_ACTION_SPRINT:
return KDown(SDL_SCANCODE_LCTRL) || KDown(SDL_SCANCODE_RCTRL);
case MINECRAFT_ACTION_LEFT_SCROLL: case MINECRAFT_ACTION_LEFT_SCROLL:
case ACTION_MENU_LEFT_SCROLL: return ScrollSnap() > 0; case ACTION_MENU_LEFT_SCROLL:
return ScrollSnap() > 0;
case MINECRAFT_ACTION_RIGHT_SCROLL: case MINECRAFT_ACTION_RIGHT_SCROLL:
case ACTION_MENU_RIGHT_SCROLL: return ScrollSnap() < 0; case ACTION_MENU_RIGHT_SCROLL:
ACTION_CASES(KDown) return ScrollSnap() < 0;
ACTION_CASES(KDown)
} }
} }
// The part that handles completing the action of pressing a button. // The part that handles completing the action of pressing a button.
bool C_4JInput::ButtonPressed(int iPad, unsigned char ucAction) { bool C_4JInput::ButtonPressed(int iPad, unsigned char ucAction) {
if (iPad != 0 || ucAction == 255) return false; if (iPad != 0 || ucAction == 255) return false;
switch (ucAction) { switch (ucAction) {
case MINECRAFT_ACTION_ACTION: return MouseLPressed() || KPressed(SDL_SCANCODE_RETURN); case MINECRAFT_ACTION_ACTION:
case MINECRAFT_ACTION_USE: return MouseRPressed() || KPressed(SDL_SCANCODE_F); return MouseLPressed() || KPressed(SDL_SCANCODE_RETURN);
case MINECRAFT_ACTION_SNEAK_TOGGLE: return KPressed(SDL_SCANCODE_LSHIFT) || KPressed(SDL_SCANCODE_RSHIFT); case MINECRAFT_ACTION_USE:
case MINECRAFT_ACTION_SPRINT: return KPressed(SDL_SCANCODE_LCTRL) || KPressed(SDL_SCANCODE_RCTRL); return MouseRPressed() || KPressed(SDL_SCANCODE_F);
case MINECRAFT_ACTION_SNEAK_TOGGLE:
return KPressed(SDL_SCANCODE_LSHIFT) ||
KPressed(SDL_SCANCODE_RSHIFT);
case MINECRAFT_ACTION_SPRINT:
return KPressed(SDL_SCANCODE_LCTRL) || KPressed(SDL_SCANCODE_RCTRL);
case MINECRAFT_ACTION_LEFT_SCROLL: case MINECRAFT_ACTION_LEFT_SCROLL:
case ACTION_MENU_LEFT_SCROLL: return ScrollSnap() > 0; case ACTION_MENU_LEFT_SCROLL:
return ScrollSnap() > 0;
case MINECRAFT_ACTION_RIGHT_SCROLL: case MINECRAFT_ACTION_RIGHT_SCROLL:
case ACTION_MENU_RIGHT_SCROLL: return ScrollSnap() < 0; case ACTION_MENU_RIGHT_SCROLL:
ACTION_CASES(KPressed) return ScrollSnap() < 0;
ACTION_CASES(KPressed)
} }
} }
// The part that handles Releasing a button. // The part that handles Releasing a button.
bool C_4JInput::ButtonReleased(int iPad, unsigned char ucAction) { bool C_4JInput::ButtonReleased(int iPad, unsigned char ucAction) {
if (iPad != 0 || ucAction == 255) return false; if (iPad != 0 || ucAction == 255) return false;
switch (ucAction) { switch (ucAction) {
case MINECRAFT_ACTION_ACTION: return MouseLReleased() || KReleased(SDL_SCANCODE_RETURN); case MINECRAFT_ACTION_ACTION:
case MINECRAFT_ACTION_USE: return MouseRReleased() || KReleased(SDL_SCANCODE_F); return MouseLReleased() || KReleased(SDL_SCANCODE_RETURN);
case MINECRAFT_ACTION_SNEAK_TOGGLE: return KReleased(SDL_SCANCODE_LSHIFT) || KReleased(SDL_SCANCODE_RSHIFT); case MINECRAFT_ACTION_USE:
case MINECRAFT_ACTION_SPRINT: KReleased(SDL_SCANCODE_LCTRL) || KReleased(SDL_SCANCODE_RCTRL); return MouseRReleased() || KReleased(SDL_SCANCODE_F);
case MINECRAFT_ACTION_SNEAK_TOGGLE:
return KReleased(SDL_SCANCODE_LSHIFT) ||
KReleased(SDL_SCANCODE_RSHIFT);
case MINECRAFT_ACTION_SPRINT:
KReleased(SDL_SCANCODE_LCTRL) || KReleased(SDL_SCANCODE_RCTRL);
case MINECRAFT_ACTION_LEFT_SCROLL: case MINECRAFT_ACTION_LEFT_SCROLL:
case ACTION_MENU_LEFT_SCROLL: case ACTION_MENU_LEFT_SCROLL:
case MINECRAFT_ACTION_RIGHT_SCROLL: case MINECRAFT_ACTION_RIGHT_SCROLL:
case ACTION_MENU_RIGHT_SCROLL: return false; case ACTION_MENU_RIGHT_SCROLL:
ACTION_CASES(KReleased) return false;
ACTION_CASES(KReleased)
} }
} }
@ -280,17 +323,20 @@ unsigned int C_4JInput::GetValue(int iPad, unsigned char ucAction, bool) {
} }
return ButtonDown(iPad, ucAction) ? 1u : 0u; return ButtonDown(iPad, ucAction) ? 1u : 0u;
} }
// Left stick movement, the one that moves the player around or selects menu options. (Soon be tested.) // Left stick movement, the one that moves the player around or selects menu
// options. (Soon be tested.)
float C_4JInput::GetJoypadStick_LX(int, bool) { float C_4JInput::GetJoypadStick_LX(int, bool) {
return (KDown(SDL_SCANCODE_D) ? 1.f : 0.f) - (KDown(SDL_SCANCODE_A) ? 1.f : 0.f); return (KDown(SDL_SCANCODE_D) ? 1.f : 0.f) -
(KDown(SDL_SCANCODE_A) ? 1.f : 0.f);
} }
float C_4JInput::GetJoypadStick_LY(int, bool) { float C_4JInput::GetJoypadStick_LY(int, bool) {
return (KDown(SDL_SCANCODE_W) ? 1.f : 0.f) - (KDown(SDL_SCANCODE_S) ? 1.f : 0.f); return (KDown(SDL_SCANCODE_W) ? 1.f : 0.f) -
(KDown(SDL_SCANCODE_S) ? 1.f : 0.f);
} }
// We use mouse movement and convert it into a Right Stick output using logarithmic scaling // We use mouse movement and convert it into a Right Stick output using
// This is the most important mouse part. Yet it's so small. // logarithmic scaling This is the most important mouse part. Yet it's so small.
static float MouseAxis(float raw) { static float MouseAxis(float raw) {
if (fabsf(raw) < 0.0001f) return 0.f; // from 4j previous code if (fabsf(raw) < 0.0001f) return 0.f; // from 4j previous code
return (raw >= 0.f ? 1.f : -1.f) * sqrtf(fabsf(raw)); return (raw >= 0.f ? 1.f : -1.f) * sqrtf(fabsf(raw));
} }
// We apply the Stick movement on the R(Right) X(2D Position) // We apply the Stick movement on the R(Right) X(2D Position)
@ -306,9 +352,14 @@ float C_4JInput::GetJoypadStick_RY(int, bool) {
return MouseAxis(-s_snapRelY * MOUSE_SCALE); return MouseAxis(-s_snapRelY * MOUSE_SCALE);
} }
unsigned char C_4JInput::GetJoypadLTrigger(int, bool) { return s_mouseRightCurrent ? 255 : 0; } unsigned char C_4JInput::GetJoypadLTrigger(int, bool) {
unsigned char C_4JInput::GetJoypadRTrigger(int, bool) { return s_mouseLeftCurrent ? 255 : 0; } return s_mouseRightCurrent ? 255 : 0;
// We detect if a Menu is visible on the player's screen to the mouse being stuck. }
unsigned char C_4JInput::GetJoypadRTrigger(int, bool) {
return s_mouseLeftCurrent ? 255 : 0;
}
// We detect if a Menu is visible on the player's screen to the mouse being
// stuck.
void C_4JInput::SetMenuDisplayed(int iPad, bool bVal) { void C_4JInput::SetMenuDisplayed(int iPad, bool bVal) {
if (iPad >= 0 && iPad < 4) s_menuDisplayed[iPad] = bVal; if (iPad >= 0 && iPad < 4) s_menuDisplayed[iPad] = bVal;
if (!s_sdlInitialized || bVal == s_prevMenuDisplayed) return; if (!s_sdlInitialized || bVal == s_prevMenuDisplayed) return;
@ -322,25 +373,37 @@ int C_4JInput::GetScrollDelta() {
return v; return v;
} }
void C_4JInput::SetDeadzoneAndMovementRange(unsigned int, unsigned int){} void C_4JInput::SetDeadzoneAndMovementRange(unsigned int, unsigned int) {}
void C_4JInput::SetGameJoypadMaps(unsigned char, unsigned char, unsigned int){} void C_4JInput::SetGameJoypadMaps(unsigned char, unsigned char, unsigned int) {}
unsigned int C_4JInput::GetGameJoypadMaps(unsigned char, unsigned char){ return 0; } unsigned int C_4JInput::GetGameJoypadMaps(unsigned char, unsigned char) {
void C_4JInput::SetJoypadMapVal(int, unsigned char){} return 0;
unsigned char C_4JInput::GetJoypadMapVal(int){ return 0; } }
void C_4JInput::SetJoypadSensitivity(int, float){} void C_4JInput::SetJoypadMapVal(int, unsigned char) {}
void C_4JInput::SetJoypadStickAxisMap(int, unsigned int, unsigned int){} unsigned char C_4JInput::GetJoypadMapVal(int) { return 0; }
void C_4JInput::SetJoypadStickTriggerMap(int, unsigned int, unsigned int){} void C_4JInput::SetJoypadSensitivity(int, float) {}
void C_4JInput::SetKeyRepeatRate(float, float){} void C_4JInput::SetJoypadStickAxisMap(int, unsigned int, unsigned int) {}
void C_4JInput::SetDebugSequence(const char*, int(*)(void *), void *){} void C_4JInput::SetJoypadStickTriggerMap(int, unsigned int, unsigned int) {}
FLOAT C_4JInput::GetIdleSeconds(int){ return 0.f; } void C_4JInput::SetKeyRepeatRate(float, float) {}
bool C_4JInput::IsPadConnected(int iPad){ return iPad == 0; } void C_4JInput::SetDebugSequence(const char*, int (*)(void*), void*) {}
FLOAT C_4JInput::GetIdleSeconds(int) { return 0.f; }
bool C_4JInput::IsPadConnected(int iPad) { return iPad == 0; }
// Silly check, we check if we have a keyboard. // Silly check, we check if we have a keyboard.
EKeyboardResult C_4JInput::RequestKeyboard(const wchar_t *, const wchar_t *, int, unsigned int, EKeyboardResult C_4JInput::RequestKeyboard(const wchar_t*, const wchar_t*, int,
int(*)(void *, const bool), void *, C_4JInput::EKeyboardMode) unsigned int,
{ return EKeyboard_Cancelled; } int (*)(void*, const bool), void*,
C_4JInput::EKeyboardMode) {
return EKeyboard_Cancelled;
}
void C_4JInput::GetText(uint16_t *s){ if (s) s[0] = 0; } void C_4JInput::GetText(uint16_t* s) {
bool C_4JInput::VerifyStrings(wchar_t **, int, int(*)(void *, STRING_VERIFY_RESPONSE *), void *){ return true; } if (s) s[0] = 0;
void C_4JInput::CancelQueuedVerifyStrings(int(*)(void *, STRING_VERIFY_RESPONSE *), void *){} }
void C_4JInput::CancelAllVerifyInProgress(){} bool C_4JInput::VerifyStrings(wchar_t**, int,
int (*)(void*, STRING_VERIFY_RESPONSE*), void*) {
return true;
}
void C_4JInput::CancelQueuedVerifyStrings(int (*)(void*,
STRING_VERIFY_RESPONSE*),
void*) {}
void C_4JInput::CancelAllVerifyInProgress() {}

View file

@ -1,138 +1,163 @@
#pragma once #pragma once
#define MAP_STYLE_0 0 #define MAP_STYLE_0 0
#define MAP_STYLE_1 1 #define MAP_STYLE_1 1
#define MAP_STYLE_2 2 #define MAP_STYLE_2 2
#define _360_JOY_BUTTON_A 0x00000001 #define _360_JOY_BUTTON_A 0x00000001
#define _360_JOY_BUTTON_B 0x00000002 #define _360_JOY_BUTTON_B 0x00000002
#define _360_JOY_BUTTON_X 0x00000004 #define _360_JOY_BUTTON_X 0x00000004
#define _360_JOY_BUTTON_Y 0x00000008 #define _360_JOY_BUTTON_Y 0x00000008
#define _360_JOY_BUTTON_START 0x00000010 #define _360_JOY_BUTTON_START 0x00000010
#define _360_JOY_BUTTON_BACK 0x00000020 #define _360_JOY_BUTTON_BACK 0x00000020
#define _360_JOY_BUTTON_RB 0x00000040 #define _360_JOY_BUTTON_RB 0x00000040
#define _360_JOY_BUTTON_LB 0x00000080 #define _360_JOY_BUTTON_LB 0x00000080
#define _360_JOY_BUTTON_RTHUMB 0x00000100 #define _360_JOY_BUTTON_RTHUMB 0x00000100
#define _360_JOY_BUTTON_LTHUMB 0x00000200 #define _360_JOY_BUTTON_LTHUMB 0x00000200
#define _360_JOY_BUTTON_DPAD_UP 0x00000400 #define _360_JOY_BUTTON_DPAD_UP 0x00000400
#define _360_JOY_BUTTON_DPAD_DOWN 0x00000800 #define _360_JOY_BUTTON_DPAD_DOWN 0x00000800
#define _360_JOY_BUTTON_DPAD_LEFT 0x00001000 #define _360_JOY_BUTTON_DPAD_LEFT 0x00001000
#define _360_JOY_BUTTON_DPAD_RIGHT 0x00002000 #define _360_JOY_BUTTON_DPAD_RIGHT 0x00002000
// fake digital versions of analog values // fake digital versions of analog values
#define _360_JOY_BUTTON_LSTICK_RIGHT 0x00004000 #define _360_JOY_BUTTON_LSTICK_RIGHT 0x00004000
#define _360_JOY_BUTTON_LSTICK_LEFT 0x00008000 #define _360_JOY_BUTTON_LSTICK_LEFT 0x00008000
#define _360_JOY_BUTTON_RSTICK_DOWN 0x00010000 #define _360_JOY_BUTTON_RSTICK_DOWN 0x00010000
#define _360_JOY_BUTTON_RSTICK_UP 0x00020000 #define _360_JOY_BUTTON_RSTICK_UP 0x00020000
#define _360_JOY_BUTTON_RSTICK_RIGHT 0x00040000 #define _360_JOY_BUTTON_RSTICK_RIGHT 0x00040000
#define _360_JOY_BUTTON_RSTICK_LEFT 0x00080000 #define _360_JOY_BUTTON_RSTICK_LEFT 0x00080000
#define _360_JOY_BUTTON_LSTICK_DOWN 0x00100000 #define _360_JOY_BUTTON_LSTICK_DOWN 0x00100000
#define _360_JOY_BUTTON_LSTICK_UP 0x00200000 #define _360_JOY_BUTTON_LSTICK_UP 0x00200000
#define _360_JOY_BUTTON_RT 0x00400000 #define _360_JOY_BUTTON_RT 0x00400000
#define _360_JOY_BUTTON_LT 0x00800000 #define _360_JOY_BUTTON_LT 0x00800000
// Stick axis maps - to allow changes for SouthPaw in-game axis mapping // Stick axis maps - to allow changes for SouthPaw in-game axis mapping
#define AXIS_MAP_LX 0 #define AXIS_MAP_LX 0
#define AXIS_MAP_LY 1 #define AXIS_MAP_LY 1
#define AXIS_MAP_RX 2 #define AXIS_MAP_RX 2
#define AXIS_MAP_RY 3 #define AXIS_MAP_RY 3
// Trigger map - to allow for swap triggers in-game // Trigger map - to allow for swap triggers in-game
#define TRIGGER_MAP_0 0 #define TRIGGER_MAP_0 0
#define TRIGGER_MAP_1 1 #define TRIGGER_MAP_1 1
enum EKeyboardResult enum EKeyboardResult {
{ EKeyboard_Pending,
EKeyboard_Pending, EKeyboard_Cancelled,
EKeyboard_Cancelled, EKeyboard_ResultAccept,
EKeyboard_ResultAccept, EKeyboard_ResultDecline,
EKeyboard_ResultDecline,
}; };
typedef struct _STRING_VERIFY_RESPONSE typedef struct _STRING_VERIFY_RESPONSE {
{ WORD wNumStrings;
WORD wNumStrings; HRESULT* pStringResult;
HRESULT *pStringResult; } STRING_VERIFY_RESPONSE;
}
STRING_VERIFY_RESPONSE;
class C_4JInput class C_4JInput {
{
public: public:
enum EKeyboardMode {
EKeyboardMode_Default,
EKeyboardMode_Numeric,
EKeyboardMode_Password,
EKeyboardMode_Alphabet,
EKeyboardMode_Full,
EKeyboardMode_Alphabet_Extended,
EKeyboardMode_IP_Address,
EKeyboardMode_Phone
};
void Initialise(int iInputStateC, unsigned char ucMapC,
unsigned char ucActionC, unsigned char ucMenuActionC);
void Tick(void);
void SetDeadzoneAndMovementRange(unsigned int uiDeadzone,
unsigned int uiMovementRangeMax);
void SetGameJoypadMaps(unsigned char ucMap, unsigned char ucAction,
unsigned int uiActionVal);
unsigned int GetGameJoypadMaps(unsigned char ucMap, unsigned char ucAction);
void SetJoypadMapVal(int iPad, unsigned char ucMap);
unsigned char GetJoypadMapVal(int iPad);
void SetJoypadSensitivity(int iPad, float fSensitivity);
unsigned int GetValue(int iPad, unsigned char ucAction,
bool bRepeat = false);
bool ButtonPressed(int iPad, unsigned char ucAction = 255); // toggled
bool ButtonReleased(int iPad, unsigned char ucAction); // toggled
bool ButtonDown(int iPad,
unsigned char ucAction = 255); // button held down
// Functions to remap the axis and triggers for in-game (not menus) -
// SouthPaw, etc
void SetJoypadStickAxisMap(int iPad, unsigned int uiFrom,
unsigned int uiTo);
void SetJoypadStickTriggerMap(int iPad, unsigned int uiFrom,
unsigned int uiTo);
void SetKeyRepeatRate(float fRepeatDelaySecs, float fRepeatRateSecs);
void SetDebugSequence(const char* chSequenceA, int (*Func)(void*),
void* lpParam);
FLOAT GetIdleSeconds(int iPad);
bool IsPadConnected(int iPad);
enum EKeyboardMode // In-Game values which may have been remapped due to Southpaw, swap
{ // triggers, etc
EKeyboardMode_Default, float GetJoypadStick_LX(int iPad, bool bCheckMenuDisplay = true);
EKeyboardMode_Numeric, float GetJoypadStick_LY(int iPad, bool bCheckMenuDisplay = true);
EKeyboardMode_Password, float GetJoypadStick_RX(int iPad, bool bCheckMenuDisplay = true);
EKeyboardMode_Alphabet, float GetJoypadStick_RY(int iPad, bool bCheckMenuDisplay = true);
EKeyboardMode_Full, unsigned char GetJoypadLTrigger(int iPad, bool bCheckMenuDisplay = true);
EKeyboardMode_Alphabet_Extended, unsigned char GetJoypadRTrigger(int iPad, bool bCheckMenuDisplay = true);
EKeyboardMode_IP_Address,
EKeyboardMode_Phone
};
void Initialise( int iInputStateC, unsigned char ucMapC,unsigned char ucActionC, unsigned char ucMenuActionC ); void SetMenuDisplayed(int iPad, bool bVal);
void Tick(void); int GetHotbarSlotPressed(int iPad);
void SetDeadzoneAndMovementRange(unsigned int uiDeadzone, unsigned int uiMovementRangeMax ); int GetScrollDelta();
void SetGameJoypadMaps(unsigned char ucMap,unsigned char ucAction,unsigned int uiActionVal);
unsigned int GetGameJoypadMaps(unsigned char ucMap,unsigned char ucAction);
void SetJoypadMapVal(int iPad,unsigned char ucMap);
unsigned char GetJoypadMapVal(int iPad);
void SetJoypadSensitivity(int iPad, float fSensitivity);
unsigned int GetValue(int iPad,unsigned char ucAction, bool bRepeat=false);
bool ButtonPressed(int iPad,unsigned char ucAction=255); // toggled
bool ButtonReleased(int iPad,unsigned char ucAction); //toggled
bool ButtonDown(int iPad,unsigned char ucAction=255); // button held down
// Functions to remap the axis and triggers for in-game (not menus) - SouthPaw, etc
void SetJoypadStickAxisMap(int iPad,unsigned int uiFrom, unsigned int uiTo);
void SetJoypadStickTriggerMap(int iPad,unsigned int uiFrom, unsigned int uiTo);
void SetKeyRepeatRate(float fRepeatDelaySecs,float fRepeatRateSecs);
void SetDebugSequence( const char *chSequenceA,int( *Func)(void *),void *lpParam );
FLOAT GetIdleSeconds(int iPad);
bool IsPadConnected(int iPad);
// In-Game values which may have been remapped due to Southpaw, swap triggers, etc // EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT
float GetJoypadStick_LX(int iPad, bool bCheckMenuDisplay=true); // uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int(
float GetJoypadStick_LY(int iPad, bool bCheckMenuDisplay=true); // *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode
float GetJoypadStick_RX(int iPad, bool bCheckMenuDisplay=true); // eMode,C4JStringTable *pStringTable=NULL); EKeyboardResult
float GetJoypadStick_RY(int iPad, bool bCheckMenuDisplay=true); // RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD
unsigned char GetJoypadLTrigger(int iPad, bool bCheckMenuDisplay=true); // dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const
unsigned char GetJoypadRTrigger(int iPad, bool bCheckMenuDisplay=true); // bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable
// *pStringTable=NULL);
EKeyboardResult RequestKeyboard(const wchar_t* Title, const wchar_t* Text,
int iPad, unsigned int uiMaxChars,
int (*Func)(void*, const bool),
void* lpParam,
C_4JInput::EKeyboardMode eMode);
void GetText(uint16_t* UTF16String);
void SetMenuDisplayed(int iPad, bool bVal); // Online check strings against offensive list - TCR 92
int GetHotbarSlotPressed(int iPad); // TCR # 092 CMTV Player Text String Verification
int GetScrollDelta(); // Requirement Any player-entered text visible to another player on
// Xbox LIVE must be verified using the Xbox LIVE service before being
// transmitted. Text that is rejected by the Xbox LIVE service must not be
// displayed.
//
// Remarks
// This requirement applies to any player-entered string that can
// be exposed to other players on Xbox LIVE. It includes session names,
// content descriptions, text messages, tags, team names, mottos, comments,
// and so on.
//
// Games may decide to not send the text, blank it out, or use
// generic text if the text was rejected by the Xbox LIVE service.
//
// Games verify the text by calling the XStringVerify function.
//
// Exemption It is not required to use the Xbox LIVE service to
// verify real-time text communication. An example of real-time text
// communication is in-game text chat.
//
// Intent Protect players from inappropriate language.
bool VerifyStrings(wchar_t** pwStringA, int iStringC,
int (*Func)(void*, STRING_VERIFY_RESPONSE*),
void* lpParam);
void CancelQueuedVerifyStrings(int (*Func)(void*, STRING_VERIFY_RESPONSE*),
void* lpParam);
void CancelAllVerifyInProgress(void);
// EKeyboardResult RequestKeyboard(UINT uiTitle, UINT uiText, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam,EKeyboardMode eMode,C4JStringTable *pStringTable=NULL); // bool InputDetected(DWORD dwUserIndex,WCHAR *pwchInput);
// EKeyboardResult RequestKeyboard(UINT uiTitle, LPCWSTR pwchDefault, UINT uiDesc, DWORD dwPad, WCHAR *pwchResult, UINT uiResultSize,int( *Func)(LPVOID,const bool),LPVOID lpParam, EKeyboardMode eMode,C4JStringTable *pStringTable=NULL);
EKeyboardResult RequestKeyboard(const wchar_t *Title, const wchar_t *Text, int iPad, unsigned int uiMaxChars, int( *Func)(void *,const bool), void *lpParam, C_4JInput::EKeyboardMode eMode);
void GetText(uint16_t *UTF16String);
// Online check strings against offensive list - TCR 92
// TCR # 092 CMTV Player Text String Verification
// Requirement Any player-entered text visible to another player on Xbox LIVE must be verified using the Xbox LIVE service before being transmitted. Text that is rejected by the Xbox LIVE service must not be displayed.
//
// Remarks
// This requirement applies to any player-entered string that can be exposed to other players on Xbox LIVE. It includes session names, content descriptions, text messages, tags, team names, mottos, comments, and so on.
//
// Games may decide to not send the text, blank it out, or use generic text if the text was rejected by the Xbox LIVE service.
//
// Games verify the text by calling the XStringVerify function.
//
// Exemption It is not required to use the Xbox LIVE service to verify real-time text communication. An example of real-time text communication is in-game text chat.
//
// Intent Protect players from inappropriate language.
bool VerifyStrings(wchar_t **pwStringA,int iStringC,int( *Func)(void *,STRING_VERIFY_RESPONSE *),void *lpParam);
void CancelQueuedVerifyStrings(int( *Func)(void *,STRING_VERIFY_RESPONSE *),void *lpParam);
void CancelAllVerifyInProgress(void);
//bool InputDetected(DWORD dwUserIndex,WCHAR *pwchInput);
}; };
// Singleton // Singleton

View file

@ -5,4 +5,4 @@
#include "../Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h" #include "../Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h"
#endif #endif
#endif //_4J_INPUT_STADAFX_H #endif //_4J_INPUT_STADAFX_H

View file

@ -3,48 +3,85 @@
C_4JProfile ProfileManager; C_4JProfile ProfileManager;
static void *s_profileData[4] = {}; static void* s_profileData[4] = {};
void C_4JProfile::Initialise(DWORD dwTitleID, DWORD dwOfferID, unsigned short usProfileVersion, void C_4JProfile::Initialise(DWORD dwTitleID, DWORD dwOfferID,
UINT uiProfileValuesC, UINT uiProfileSettingsC, DWORD *pdwProfileSettingsA, unsigned short usProfileVersion,
int iGameDefinedDataSizeX4, unsigned int *puiGameDefinedDataChangedBitmask) UINT uiProfileValuesC, UINT uiProfileSettingsC,
{ DWORD* pdwProfileSettingsA,
for (int i = 0; i < 4; i++) int iGameDefinedDataSizeX4,
{ unsigned int* puiGameDefinedDataChangedBitmask) {
for (int i = 0; i < 4; i++) {
s_profileData[i] = new unsigned char[iGameDefinedDataSizeX4 / 4]; s_profileData[i] = new unsigned char[iGameDefinedDataSizeX4 / 4];
memset(s_profileData[i], 0, iGameDefinedDataSizeX4 / 4); memset(s_profileData[i], 0, iGameDefinedDataSizeX4 / 4);
} }
} }
void C_4JProfile::SetTrialTextStringTable(CXuiStringTable *pStringTable, int iAccept, int iReject) {} void C_4JProfile::SetTrialTextStringTable(CXuiStringTable* pStringTable,
void C_4JProfile::SetTrialAwardText(eAwardType AwardType, int iTitle, int iText) {} int iAccept, int iReject) {}
void C_4JProfile::SetTrialAwardText(eAwardType AwardType, int iTitle,
int iText) {}
int C_4JProfile::GetLockedProfile() { return -1; } int C_4JProfile::GetLockedProfile() { return -1; }
void C_4JProfile::SetLockedProfile(int iProf) {} void C_4JProfile::SetLockedProfile(int iProf) {}
bool C_4JProfile::IsSignedIn(int iQuadrant) { return iQuadrant == 0; } bool C_4JProfile::IsSignedIn(int iQuadrant) { return iQuadrant == 0; }
bool C_4JProfile::IsSignedInLive(int iProf) { return false; } bool C_4JProfile::IsSignedInLive(int iProf) { return false; }
bool C_4JProfile::IsGuest(int iQuadrant) { return false; } bool C_4JProfile::IsGuest(int iQuadrant) { return false; }
UINT C_4JProfile::RequestSignInUI(bool bFromInvite, bool bLocalGame, bool bNoGuestsAllowed, bool bMultiplayerSignIn, bool bAddUser, int(*Func)(void *, const bool, const int iPad), void *lpParam, int iQuadrant) { return 0; } UINT C_4JProfile::RequestSignInUI(bool bFromInvite, bool bLocalGame,
UINT C_4JProfile::DisplayOfflineProfile(int(*Func)(void *, const bool, const int iPad), void *lpParam, int iQuadrant) { return 0; } bool bNoGuestsAllowed,
UINT C_4JProfile::RequestConvertOfflineToGuestUI(int(*Func)(void *, const bool, const int iPad), void *lpParam, int iQuadrant) { return 0; } bool bMultiplayerSignIn, bool bAddUser,
int (*Func)(void*, const bool,
const int iPad),
void* lpParam, int iQuadrant) {
return 0;
}
UINT C_4JProfile::DisplayOfflineProfile(int (*Func)(void*, const bool,
const int iPad),
void* lpParam, int iQuadrant) {
return 0;
}
UINT C_4JProfile::RequestConvertOfflineToGuestUI(int (*Func)(void*, const bool,
const int iPad),
void* lpParam, int iQuadrant) {
return 0;
}
void C_4JProfile::SetPrimaryPlayerChanged(bool bVal) {} void C_4JProfile::SetPrimaryPlayerChanged(bool bVal) {}
bool C_4JProfile::QuerySigninStatus(void) { return true; } bool C_4JProfile::QuerySigninStatus(void) { return true; }
void C_4JProfile::GetXUID(int iPad, PlayerUID *pXuid, bool bOnlineXuid) { if (pXuid) *pXuid = 0; } void C_4JProfile::GetXUID(int iPad, PlayerUID* pXuid, bool bOnlineXuid) {
bool C_4JProfile::AreXUIDSEqual(PlayerUID xuid1, PlayerUID xuid2) { return xuid1 == xuid2; } if (pXuid) *pXuid = 0;
}
bool C_4JProfile::AreXUIDSEqual(PlayerUID xuid1, PlayerUID xuid2) {
return xuid1 == xuid2;
}
bool C_4JProfile::XUIDIsGuest(PlayerUID xuid) { return false; } bool C_4JProfile::XUIDIsGuest(PlayerUID xuid) { return false; }
bool C_4JProfile::AllowedToPlayMultiplayer(int iProf) { return true; } bool C_4JProfile::AllowedToPlayMultiplayer(int iProf) { return true; }
bool C_4JProfile::GetChatAndContentRestrictions(int iPad, bool *pbChatRestricted, bool *pbContentRestricted, int *piAge) { bool C_4JProfile::GetChatAndContentRestrictions(int iPad,
bool* pbChatRestricted,
bool* pbContentRestricted,
int* piAge) {
if (pbChatRestricted) *pbChatRestricted = false; if (pbChatRestricted) *pbChatRestricted = false;
if (pbContentRestricted) *pbContentRestricted = false; if (pbContentRestricted) *pbContentRestricted = false;
if (piAge) *piAge = 18; if (piAge) *piAge = 18;
return true; return true;
} }
void C_4JProfile::StartTrialGame() {} void C_4JProfile::StartTrialGame() {}
void C_4JProfile::AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly, bool *allAllowed, bool *friendsAllowed) { void C_4JProfile::AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly,
bool* allAllowed,
bool* friendsAllowed) {
if (allAllowed) *allAllowed = true; if (allAllowed) *allAllowed = true;
if (friendsAllowed) *friendsAllowed = true; if (friendsAllowed) *friendsAllowed = true;
} }
bool C_4JProfile::CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly, PPlayerUID pXuids, unsigned int xuidCount) { return true; } bool C_4JProfile::CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly,
PPlayerUID pXuids,
unsigned int xuidCount) {
return true;
}
void C_4JProfile::ShowProfileCard(int iPad, PlayerUID targetUid) {} void C_4JProfile::ShowProfileCard(int iPad, PlayerUID targetUid) {}
bool C_4JProfile::GetProfileAvatar(int iPad, int(*Func)(void *lpParam, std::uint8_t *thumbnailData, unsigned int thumbnailBytes), void *lpParam) { return false; } bool C_4JProfile::GetProfileAvatar(int iPad,
int (*Func)(void* lpParam,
std::uint8_t* thumbnailData,
unsigned int thumbnailBytes),
void* lpParam) {
return false;
}
void C_4JProfile::CancelProfileAvatarRequest() {} void C_4JProfile::CancelProfileAvatarRequest() {}
int C_4JProfile::GetPrimaryPad() { return 0; } int C_4JProfile::GetPrimaryPad() { return 0; }
void C_4JProfile::SetPrimaryPad(int iPad) {} void C_4JProfile::SetPrimaryPad(int iPad) {}
@ -53,34 +90,68 @@ static char s_gamertag[64] = "Player";
char* C_4JProfile::GetGamertag(int iPad) { return s_gamertag; } char* C_4JProfile::GetGamertag(int iPad) { return s_gamertag; }
std::wstring C_4JProfile::GetDisplayName(int iPad) { return L"Player"; } std::wstring C_4JProfile::GetDisplayName(int iPad) { return L"Player"; }
bool C_4JProfile::IsFullVersion() { return true; } bool C_4JProfile::IsFullVersion() { return true; }
void C_4JProfile::SetSignInChangeCallback(void(*Func)(void *, bool, unsigned int), void *lpParam) {} void C_4JProfile::SetSignInChangeCallback(void (*Func)(void*, bool,
void C_4JProfile::SetNotificationsCallback(void(*Func)(void *, std::uint32_t, unsigned int), void *lpParam) {} unsigned int),
void* lpParam) {}
void C_4JProfile::SetNotificationsCallback(void (*Func)(void*, std::uint32_t,
unsigned int),
void* lpParam) {}
bool C_4JProfile::RegionIsNorthAmerica(void) { return true; } bool C_4JProfile::RegionIsNorthAmerica(void) { return true; }
bool C_4JProfile::LocaleIsUSorCanada(void) { return true; } bool C_4JProfile::LocaleIsUSorCanada(void) { return true; }
HRESULT C_4JProfile::GetLiveConnectionStatus() { return S_OK; } HRESULT C_4JProfile::GetLiveConnectionStatus() { return S_OK; }
bool C_4JProfile::IsSystemUIDisplayed() { return false; } bool C_4JProfile::IsSystemUIDisplayed() { return false; }
void C_4JProfile::SetProfileReadErrorCallback(void(*Func)(void *), void *lpParam) {} void C_4JProfile::SetProfileReadErrorCallback(void (*Func)(void*),
int C_4JProfile::SetDefaultOptionsCallback(int(*Func)(void *, PROFILESETTINGS *, const int iPad), void *lpParam) { return 0; } void* lpParam) {}
int C_4JProfile::SetOldProfileVersionCallback(int(*Func)(void *, unsigned char *, const unsigned short, const int), void *lpParam) { return 0; } int C_4JProfile::SetDefaultOptionsCallback(int (*Func)(void*, PROFILESETTINGS*,
const int iPad),
void* lpParam) {
return 0;
}
int C_4JProfile::SetOldProfileVersionCallback(int (*Func)(void*, unsigned char*,
const unsigned short,
const int),
void* lpParam) {
return 0;
}
static C_4JProfile::PROFILESETTINGS s_defaultSettings = {}; static C_4JProfile::PROFILESETTINGS s_defaultSettings = {};
C_4JProfile::PROFILESETTINGS* C_4JProfile::GetDashboardProfileSettings(int iPad) { return &s_defaultSettings; } C_4JProfile::PROFILESETTINGS* C_4JProfile::GetDashboardProfileSettings(
void C_4JProfile::WriteToProfile(int iQuadrant, bool bGameDefinedDataChanged, bool bOverride5MinuteLimitOnProfileWrites) {} int iPad) {
return &s_defaultSettings;
}
void C_4JProfile::WriteToProfile(int iQuadrant, bool bGameDefinedDataChanged,
bool bOverride5MinuteLimitOnProfileWrites) {}
void C_4JProfile::ForceQueuedProfileWrites(int iPad) {} void C_4JProfile::ForceQueuedProfileWrites(int iPad) {}
void* C_4JProfile::GetGameDefinedProfileData(int iQuadrant) { return s_profileData[iQuadrant]; } void* C_4JProfile::GetGameDefinedProfileData(int iQuadrant) {
return s_profileData[iQuadrant];
}
void C_4JProfile::ResetProfileProcessState() {} void C_4JProfile::ResetProfileProcessState() {}
void C_4JProfile::Tick(void) {} void C_4JProfile::Tick(void) {}
void C_4JProfile::RegisterAward(int iAwardNumber, int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected, void C_4JProfile::RegisterAward(int iAwardNumber, int iGamerconfigID,
CXuiStringTable *pStringTable, int iTitleStr, int iTextStr, int iAcceptStr, char *pszThemeName, unsigned int uiThemeSize) {} eAwardType eType, bool bLeaderboardAffected,
CXuiStringTable* pStringTable, int iTitleStr,
int iTextStr, int iAcceptStr,
char* pszThemeName, unsigned int uiThemeSize) {}
int C_4JProfile::GetAwardId(int iAwardNumber) { return 0; } int C_4JProfile::GetAwardId(int iAwardNumber) { return 0; }
eAwardType C_4JProfile::GetAwardType(int iAwardNumber) { return eAwardType_Achievement; } eAwardType C_4JProfile::GetAwardType(int iAwardNumber) {
bool C_4JProfile::CanBeAwarded(int iQuadrant, int iAwardNumber) { return false; } return eAwardType_Achievement;
}
bool C_4JProfile::CanBeAwarded(int iQuadrant, int iAwardNumber) {
return false;
}
void C_4JProfile::Award(int iQuadrant, int iAwardNumber, bool bForce) {} void C_4JProfile::Award(int iQuadrant, int iAwardNumber, bool bForce) {}
bool C_4JProfile::IsAwardsFlagSet(int iQuadrant, int iAward) { return false; } bool C_4JProfile::IsAwardsFlagSet(int iQuadrant, int iAward) { return false; }
void C_4JProfile::RichPresenceInit(int iPresenceCount, int iContextCount) {} void C_4JProfile::RichPresenceInit(int iPresenceCount, int iContextCount) {}
void C_4JProfile::RegisterRichPresenceContext(int iGameConfigContextID) {} void C_4JProfile::RegisterRichPresenceContext(int iGameConfigContextID) {}
void C_4JProfile::SetRichPresenceContextValue(int iPad, int iContextID, int iVal) {} void C_4JProfile::SetRichPresenceContextValue(int iPad, int iContextID,
void C_4JProfile::SetCurrentGameActivity(int iPad, int iNewPresence, bool bSetOthersToIdle) {} int iVal) {}
void C_4JProfile::DisplayFullVersionPurchase(bool bRequired, int iQuadrant, int iUpsellParam) {} void C_4JProfile::SetCurrentGameActivity(int iPad, int iNewPresence,
void C_4JProfile::SetUpsellCallback(void(*Func)(void *lpParam, eUpsellType type, eUpsellResponse response, int iUserData), void *lpParam) {} bool bSetOthersToIdle) {}
void C_4JProfile::DisplayFullVersionPurchase(bool bRequired, int iQuadrant,
int iUpsellParam) {}
void C_4JProfile::SetUpsellCallback(void (*Func)(void* lpParam,
eUpsellType type,
eUpsellResponse response,
int iUserData),
void* lpParam) {}
void C_4JProfile::SetDebugFullOverride(bool bVal) {} void C_4JProfile::SetDebugFullOverride(bool bVal) {}

View file

@ -2,129 +2,156 @@
#include <cstdint> #include <cstdint>
enum eAwardType enum eAwardType {
{ eAwardType_Achievement = 0,
eAwardType_Achievement = 0, eAwardType_GamerPic,
eAwardType_GamerPic, eAwardType_Theme,
eAwardType_Theme, eAwardType_AvatarItem,
eAwardType_AvatarItem,
}; };
enum eUpsellType enum eUpsellType {
{ eUpsellType_Custom = 0, // This is the default, and means that the upsell
eUpsellType_Custom = 0, // This is the default, and means that the upsell dialog was initiated in the app code // dialog was initiated in the app code
eUpsellType_Achievement, eUpsellType_Achievement,
eUpsellType_GamerPic, eUpsellType_GamerPic,
eUpsellType_Theme, eUpsellType_Theme,
eUpsellType_AvatarItem, eUpsellType_AvatarItem,
}; };
enum eUpsellResponse enum eUpsellResponse {
{ eUpsellResponse_Declined,
eUpsellResponse_Declined, eUpsellResponse_Accepted_NoPurchase,
eUpsellResponse_Accepted_NoPurchase, eUpsellResponse_Accepted_Purchase,
eUpsellResponse_Accepted_Purchase,
}; };
class C_4JProfile {
class C_4JProfile
{
public: public:
struct PROFILESETTINGS struct PROFILESETTINGS {
{ int iYAxisInversion;
int iYAxisInversion; int iControllerSensitivity;
int iControllerSensitivity; int iVibration;
int iVibration; bool bSwapSticks;
bool bSwapSticks; };
};
// 4 players have game defined data, puiGameDefinedDataChangedBitmask needs
// to be checked by the game side to see if there's an update needed - it'll
// have the bits set for players to be updated
void Initialise(DWORD dwTitleID, DWORD dwOfferID,
unsigned short usProfileVersion, UINT uiProfileValuesC,
UINT uiProfileSettingsC, DWORD* pdwProfileSettingsA,
int iGameDefinedDataSizeX4,
unsigned int* puiGameDefinedDataChangedBitmask);
void SetTrialTextStringTable(CXuiStringTable* pStringTable, int iAccept,
int iReject);
void SetTrialAwardText(eAwardType AwardType, int iTitle,
int iText); // achievement popup in the trial game
int GetLockedProfile();
void SetLockedProfile(int iProf);
bool IsSignedIn(int iQuadrant);
bool IsSignedInLive(int iProf);
bool IsGuest(int iQuadrant);
UINT RequestSignInUI(bool bFromInvite, bool bLocalGame,
bool bNoGuestsAllowed, bool bMultiplayerSignIn,
bool bAddUser,
int (*Func)(void*, const bool, const int iPad),
void* lpParam, int iQuadrant = XUSER_INDEX_ANY);
UINT DisplayOfflineProfile(int (*Func)(void*, const bool, const int iPad),
void* lpParam, int iQuadrant = XUSER_INDEX_ANY);
UINT RequestConvertOfflineToGuestUI(int (*Func)(void*, const bool,
const int iPad),
void* lpParam,
int iQuadrant = XUSER_INDEX_ANY);
void SetPrimaryPlayerChanged(bool bVal);
bool QuerySigninStatus(void);
void GetXUID(int iPad, PlayerUID* pXuid, bool bOnlineXuid);
bool AreXUIDSEqual(PlayerUID xuid1, PlayerUID xuid2);
bool XUIDIsGuest(PlayerUID xuid);
bool AllowedToPlayMultiplayer(int iProf);
bool GetChatAndContentRestrictions(int iPad, bool* pbChatRestricted,
bool* pbContentRestricted, int* piAge);
void StartTrialGame(); // disables saves and leaderboard, and change state
// to readyforgame from pregame
void AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly,
bool* allAllowed, bool* friendsAllowed);
bool CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly,
PPlayerUID pXuids, unsigned int xuidCount);
void ShowProfileCard(int iPad, PlayerUID targetUid);
bool GetProfileAvatar(int iPad,
int (*Func)(void* lpParam,
std::uint8_t* thumbnailData,
unsigned int thumbnailBytes),
void* lpParam);
void CancelProfileAvatarRequest();
// 4 players have game defined data, puiGameDefinedDataChangedBitmask needs to be checked by the game side to see if there's an update needed - it'll have the bits set for players to be updated // SYS
void Initialise( DWORD dwTitleID, int GetPrimaryPad();
DWORD dwOfferID, void SetPrimaryPad(int iPad);
unsigned short usProfileVersion, char* GetGamertag(int iPad);
UINT uiProfileValuesC, std::wstring GetDisplayName(int iPad);
UINT uiProfileSettingsC, bool IsFullVersion();
DWORD *pdwProfileSettingsA, void SetSignInChangeCallback(void (*Func)(void*, bool, unsigned int),
int iGameDefinedDataSizeX4, void* lpParam);
unsigned int *puiGameDefinedDataChangedBitmask); void SetNotificationsCallback(void (*Func)(void*, std::uint32_t,
void SetTrialTextStringTable(CXuiStringTable *pStringTable,int iAccept,int iReject); unsigned int),
void SetTrialAwardText(eAwardType AwardType,int iTitle,int iText); // achievement popup in the trial game void* lpParam);
int GetLockedProfile(); bool RegionIsNorthAmerica(void);
void SetLockedProfile(int iProf); bool LocaleIsUSorCanada(void);
bool IsSignedIn(int iQuadrant); HRESULT GetLiveConnectionStatus();
bool IsSignedInLive(int iProf); bool IsSystemUIDisplayed();
bool IsGuest(int iQuadrant); void SetProfileReadErrorCallback(void (*Func)(void*), void* lpParam);
UINT RequestSignInUI(bool bFromInvite,bool bLocalGame,bool bNoGuestsAllowed,bool bMultiplayerSignIn,bool bAddUser, int( *Func)(void *,const bool, const int iPad),void *lpParam,int iQuadrant=XUSER_INDEX_ANY);
UINT DisplayOfflineProfile(int( *Func)(void *,const bool, const int iPad),void *lpParam,int iQuadrant=XUSER_INDEX_ANY);
UINT RequestConvertOfflineToGuestUI(int( *Func)(void *,const bool, const int iPad),void *lpParam,int iQuadrant=XUSER_INDEX_ANY);
void SetPrimaryPlayerChanged(bool bVal);
bool QuerySigninStatus(void);
void GetXUID(int iPad, PlayerUID *pXuid,bool bOnlineXuid);
bool AreXUIDSEqual(PlayerUID xuid1,PlayerUID xuid2);
bool XUIDIsGuest(PlayerUID xuid);
bool AllowedToPlayMultiplayer(int iProf);
bool GetChatAndContentRestrictions(int iPad,bool *pbChatRestricted,bool *pbContentRestricted,int *piAge);
void StartTrialGame(); // disables saves and leaderboard, and change state to readyforgame from pregame
void AllowedPlayerCreatedContent(int iPad, bool thisQuadrantOnly, bool *allAllowed, bool *friendsAllowed);
bool CanViewPlayerCreatedContent(int iPad, bool thisQuadrantOnly, PPlayerUID pXuids, unsigned int xuidCount);
void ShowProfileCard(int iPad, PlayerUID targetUid);
bool GetProfileAvatar(int iPad,int( *Func)(void *lpParam,std::uint8_t *thumbnailData,unsigned int thumbnailBytes), void *lpParam);
void CancelProfileAvatarRequest();
// PROFILE DATA
int SetDefaultOptionsCallback(int (*Func)(void*, PROFILESETTINGS*,
const int iPad),
void* lpParam);
int SetOldProfileVersionCallback(int (*Func)(void*, unsigned char*,
const unsigned short,
const int),
void* lpParam);
PROFILESETTINGS* GetDashboardProfileSettings(int iPad);
void WriteToProfile(int iQuadrant, bool bGameDefinedDataChanged = false,
bool bOverride5MinuteLimitOnProfileWrites = false);
void ForceQueuedProfileWrites(int iPad = XUSER_INDEX_ANY);
void* GetGameDefinedProfileData(int iQuadrant);
void ResetProfileProcessState(); // after a sign out from the primary
// player, call this
void Tick(void);
// SYS // ACHIEVEMENTS & AWARDS
int GetPrimaryPad();
void SetPrimaryPad(int iPad);
char* GetGamertag(int iPad);
std::wstring GetDisplayName(int iPad);
bool IsFullVersion();
void SetSignInChangeCallback(void ( *Func)(void *, bool, unsigned int),void *lpParam);
void SetNotificationsCallback(void ( *Func)(void *, std::uint32_t, unsigned int),void *lpParam);
bool RegionIsNorthAmerica(void);
bool LocaleIsUSorCanada(void);
HRESULT GetLiveConnectionStatus();
bool IsSystemUIDisplayed();
void SetProfileReadErrorCallback(void ( *Func)(void *), void *lpParam);
void RegisterAward(int iAwardNumber, int iGamerconfigID, eAwardType eType,
bool bLeaderboardAffected = false,
CXuiStringTable* pStringTable = NULL, int iTitleStr = -1,
int iTextStr = -1, int iAcceptStr = -1,
char* pszThemeName = NULL,
unsigned int uiThemeSize = 0L);
int GetAwardId(int iAwardNumber);
eAwardType GetAwardType(int iAwardNumber);
bool CanBeAwarded(int iQuadrant, int iAwardNumber);
void Award(int iQuadrant, int iAwardNumber, bool bForce = false);
bool IsAwardsFlagSet(int iQuadrant, int iAward);
// PROFILE DATA // RICH PRESENCE
int SetDefaultOptionsCallback(int( *Func)(void *,PROFILESETTINGS *, const int iPad),void *lpParam);
int SetOldProfileVersionCallback(int( *Func)(void *,unsigned char *, const unsigned short,const int),void *lpParam);
PROFILESETTINGS * GetDashboardProfileSettings(int iPad);
void WriteToProfile(int iQuadrant, bool bGameDefinedDataChanged=false, bool bOverride5MinuteLimitOnProfileWrites=false);
void ForceQueuedProfileWrites(int iPad=XUSER_INDEX_ANY);
void *GetGameDefinedProfileData(int iQuadrant);
void ResetProfileProcessState(); // after a sign out from the primary player, call this
void Tick( void );
// ACHIEVEMENTS & AWARDS void RichPresenceInit(int iPresenceCount, int iContextCount);
void RegisterRichPresenceContext(int iGameConfigContextID);
void SetRichPresenceContextValue(int iPad, int iContextID, int iVal);
void SetCurrentGameActivity(int iPad, int iNewPresence,
bool bSetOthersToIdle = false);
void RegisterAward(int iAwardNumber,int iGamerconfigID, eAwardType eType, bool bLeaderboardAffected=false, // PURCHASE
CXuiStringTable*pStringTable=NULL, int iTitleStr=-1, int iTextStr=-1, int iAcceptStr=-1, char *pszThemeName=NULL, unsigned int uiThemeSize=0L); void DisplayFullVersionPurchase(bool bRequired, int iQuadrant,
int GetAwardId(int iAwardNumber); int iUpsellParam = -1);
eAwardType GetAwardType(int iAwardNumber); void SetUpsellCallback(void (*Func)(void* lpParam, eUpsellType type,
bool CanBeAwarded(int iQuadrant, int iAwardNumber); eUpsellResponse response,
void Award(int iQuadrant, int iAwardNumber, bool bForce=false); int iUserData),
bool IsAwardsFlagSet(int iQuadrant, int iAward); void* lpParam);
// RICH PRESENCE
void RichPresenceInit(int iPresenceCount, int iContextCount);
void RegisterRichPresenceContext(int iGameConfigContextID);
void SetRichPresenceContextValue(int iPad,int iContextID, int iVal);
void SetCurrentGameActivity(int iPad,int iNewPresence, bool bSetOthersToIdle=false);
// PURCHASE
void DisplayFullVersionPurchase(bool bRequired, int iQuadrant, int iUpsellParam = -1);
void SetUpsellCallback(void ( *Func)(void *lpParam, eUpsellType type, eUpsellResponse response, int iUserData),void *lpParam);
// Debug
void SetDebugFullOverride(bool bVal); // To override the license version (trail/full). Only in debug/release, not ContentPackage
// Debug
void SetDebugFullOverride(
bool bVal); // To override the license version (trail/full). Only in
// debug/release, not ContentPackage
}; };
// Singleton // Singleton
extern C_4JProfile ProfileManager; extern C_4JProfile ProfileManager;

View file

@ -1,11 +1,10 @@
#ifndef _4J_PROFILE_STADAFX_H #ifndef _4J_PROFILE_STADAFX_H
#define _4J_PROFILE_STADAFX_H #define _4J_PROFILE_STADAFX_H
#ifdef __linux__ #ifdef __linux__
#include "../Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h" #include "../Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h"
#endif #endif
#include "../Minecraft.World/Platform/x64headers/extraX64.h" #include "../Minecraft.World/Platform/x64headers/extraX64.h"
#endif //_4J_PROFILE_STADAFX_H #endif //_4J_PROFILE_STADAFX_H

File diff suppressed because it is too large Load diff

View file

@ -6,218 +6,230 @@
#include <cstdint> #include <cstdint>
class ImageFileBuffer class ImageFileBuffer {
{
public: public:
enum EImageType enum EImageType { e_typePNG, e_typeJPG };
{
e_typePNG,
e_typeJPG
};
EImageType m_type; EImageType m_type;
void* m_pBuffer; void* m_pBuffer;
int m_bufferSize; int m_bufferSize;
int GetType() { return m_type; } int GetType() { return m_type; }
void *GetBufferPointer() { return m_pBuffer; } void* GetBufferPointer() { return m_pBuffer; }
int GetBufferSize() { return m_bufferSize; } int GetBufferSize() { return m_bufferSize; }
void Release() { free(m_pBuffer); m_pBuffer = NULL; } void Release() {
bool Allocated() { return m_pBuffer != NULL; } free(m_pBuffer);
m_pBuffer = NULL;
}
bool Allocated() { return m_pBuffer != NULL; }
}; };
typedef struct typedef struct {
{ int Width;
int Width; int Height;
int Height; } D3DXIMAGE_INFO;
}D3DXIMAGE_INFO;
typedef struct _XSOCIAL_PREVIEWIMAGE { typedef struct _XSOCIAL_PREVIEWIMAGE {
BYTE *pBytes; BYTE* pBytes;
DWORD Pitch; DWORD Pitch;
DWORD Width; DWORD Width;
DWORD Height; DWORD Height;
// D3DFORMAT Format; // D3DFORMAT Format;
} XSOCIAL_PREVIEWIMAGE, *PXSOCIAL_PREVIEWIMAGE; } XSOCIAL_PREVIEWIMAGE, *PXSOCIAL_PREVIEWIMAGE;
class C4JRender class C4JRender {
{
public: public:
void Tick(); void Tick();
void UpdateGamma(unsigned short usGamma); void UpdateGamma(unsigned short usGamma);
// Matrix stack // Matrix stack
void MatrixMode(int type); void MatrixMode(int type);
void MatrixSetIdentity(); void MatrixSetIdentity();
void MatrixTranslate(float x,float y,float z); void MatrixTranslate(float x, float y, float z);
void MatrixRotate(float angle, float x, float y, float z); void MatrixRotate(float angle, float x, float y, float z);
void MatrixScale(float x, float y, float z); void MatrixScale(float x, float y, float z);
void MatrixPerspective(float fovy, float aspect, float zNear, float zFar); void MatrixPerspective(float fovy, float aspect, float zNear, float zFar);
void MatrixOrthogonal(float left,float right,float bottom,float top,float zNear,float zFar); void MatrixOrthogonal(float left, float right, float bottom, float top,
void MatrixPop(); float zNear, float zFar);
void MatrixPush(); void MatrixPop();
void MatrixMult(float *mat); void MatrixPush();
const float *MatrixGet(int type); void MatrixMult(float* mat);
void Set_matrixDirty(); const float* MatrixGet(int type);
void Set_matrixDirty();
// Core // Core
void Initialise(); void Initialise();
void InitialiseContext(); void InitialiseContext();
// Call before Initialise() to override window size and/or fullscreen mode. // Call before Initialise() to override window size and/or fullscreen mode.
// If not called, the primary monitor's native resolution is used. // If not called, the primary monitor's native resolution is used.
void SetWindowSize(int w, int h); void SetWindowSize(int w, int h);
void SetFullscreen(bool fs); void SetFullscreen(bool fs);
void StartFrame(); void StartFrame();
void DoScreenGrabOnNextPresent(); void DoScreenGrabOnNextPresent();
void Present(); void Present();
void Clear(int flags); void Clear(int flags);
void SetClearColour(const float colourRGBA[4]); void SetClearColour(const float colourRGBA[4]);
bool IsWidescreen(); bool IsWidescreen();
bool IsHiDef(); bool IsHiDef();
void GetFramebufferSize(int &width, int &height); void GetFramebufferSize(int& width, int& height);
void CaptureThumbnail(ImageFileBuffer *pngOut); void CaptureThumbnail(ImageFileBuffer* pngOut);
void CaptureScreen(ImageFileBuffer *jpgOut, XSOCIAL_PREVIEWIMAGE *previewOut); void CaptureScreen(ImageFileBuffer* jpgOut,
void BeginConditionalSurvey(int identifier); XSOCIAL_PREVIEWIMAGE* previewOut);
void EndConditionalSurvey(); void BeginConditionalSurvey(int identifier);
void BeginConditionalRendering(int identifier); void EndConditionalSurvey();
void EndConditionalRendering(); void BeginConditionalRendering(int identifier);
void EndConditionalRendering();
// Vertex data handling // Vertex data handling
typedef enum typedef enum {
{ VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, // Position 3 x float, texture 2 x
VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1, // Position 3 x float, texture 2 x float, colour 4 x byte, normal 4 x byte, padding 1 DWORD // float, colour 4 x byte, normal 4 x
VERTEX_TYPE_COMPRESSED, // Compressed format - see comment at top of VS_PS3_TS2_CS1.hlsl for description of layout // byte, padding 1 DWORD
VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_LIT, // as VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1 with lighting applied, VERTEX_TYPE_COMPRESSED, // Compressed format - see comment at top of
VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, // as VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1 with tex gen // VS_PS3_TS2_CS1.hlsl for description of
VERTEX_TYPE_COUNT // layout
} eVertexType; VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_LIT, // as
// VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1
// with lighting applied,
VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1_TEXGEN, // as
// VERTEX_TYPE_PF3_TF2_CB4_NB4_XW1
// with tex gen
VERTEX_TYPE_COUNT
} eVertexType;
// Pixel shader // Pixel shader
typedef enum typedef enum {
{ PIXEL_SHADER_TYPE_STANDARD,
PIXEL_SHADER_TYPE_STANDARD, PIXEL_SHADER_TYPE_PROJECTION,
PIXEL_SHADER_TYPE_PROJECTION, PIXEL_SHADER_TYPE_FORCELOD,
PIXEL_SHADER_TYPE_FORCELOD, PIXEL_SHADER_COUNT
PIXEL_SHADER_COUNT } ePixelShaderType;
} ePixelShaderType;
typedef enum typedef enum {
{ VIEWPORT_TYPE_FULLSCREEN,
VIEWPORT_TYPE_FULLSCREEN, VIEWPORT_TYPE_SPLIT_TOP,
VIEWPORT_TYPE_SPLIT_TOP, VIEWPORT_TYPE_SPLIT_BOTTOM,
VIEWPORT_TYPE_SPLIT_BOTTOM, VIEWPORT_TYPE_SPLIT_LEFT,
VIEWPORT_TYPE_SPLIT_LEFT, VIEWPORT_TYPE_SPLIT_RIGHT,
VIEWPORT_TYPE_SPLIT_RIGHT, VIEWPORT_TYPE_QUADRANT_TOP_LEFT,
VIEWPORT_TYPE_QUADRANT_TOP_LEFT, VIEWPORT_TYPE_QUADRANT_TOP_RIGHT,
VIEWPORT_TYPE_QUADRANT_TOP_RIGHT, VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT,
VIEWPORT_TYPE_QUADRANT_BOTTOM_LEFT, VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT,
VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT, } eViewportType;
} eViewportType;
typedef enum typedef enum {
{ PRIMITIVE_TYPE_TRIANGLE_LIST,
PRIMITIVE_TYPE_TRIANGLE_LIST, PRIMITIVE_TYPE_TRIANGLE_STRIP,
PRIMITIVE_TYPE_TRIANGLE_STRIP, PRIMITIVE_TYPE_TRIANGLE_FAN,
PRIMITIVE_TYPE_TRIANGLE_FAN, PRIMITIVE_TYPE_QUAD_LIST,
PRIMITIVE_TYPE_QUAD_LIST, PRIMITIVE_TYPE_LINE_LIST,
PRIMITIVE_TYPE_LINE_LIST, PRIMITIVE_TYPE_LINE_STRIP,
PRIMITIVE_TYPE_LINE_STRIP, PRIMITIVE_TYPE_COUNT
PRIMITIVE_TYPE_COUNT } ePrimitiveType;
} ePrimitiveType;
void DrawVertices(ePrimitiveType PrimitiveType, int count, void *dataIn, eVertexType vType, C4JRender::ePixelShaderType psType); void DrawVertices(ePrimitiveType PrimitiveType, int count, void* dataIn,
eVertexType vType, C4JRender::ePixelShaderType psType);
// Command buffers // Command buffers
void CBuffLockStaticCreations(); void CBuffLockStaticCreations();
int CBuffCreate(int count); int CBuffCreate(int count);
void CBuffDelete(int first, int count); void CBuffDelete(int first, int count);
void CBuffStart(int index, bool full = false); void CBuffStart(int index, bool full = false);
void CBuffClear(int index); void CBuffClear(int index);
int CBuffSize(int index); int CBuffSize(int index);
void CBuffEnd(); void CBuffEnd();
bool CBuffCall(int index, bool full = true); bool CBuffCall(int index, bool full = true);
void CBuffTick(); void CBuffTick();
void CBuffDeferredModeStart(); void CBuffDeferredModeStart();
void CBuffDeferredModeEnd(); void CBuffDeferredModeEnd();
typedef enum typedef enum {
{ TEXTURE_FORMAT_RxGyBzAw, // Normal 32-bit RGBA texture, 8 bits per
TEXTURE_FORMAT_RxGyBzAw, // Normal 32-bit RGBA texture, 8 bits per component // component
/* Don't think these are all directly available on D3D 11 - leaving for now /* Don't think these are all directly available on D3D 11 - leaving for
TEXTURE_FORMAT_R0G0B0Ax, // One 8-bit component mapped to alpha channel, R=G=B=0 now TEXTURE_FORMAT_R0G0B0Ax, // One 8-bit component mapped to
TEXTURE_FORMAT_R1G1B1Ax, // One 8-bit component mapped to alpha channel, R=G=B=1 alpha channel, R=G=B=0 TEXTURE_FORMAT_R1G1B1Ax, // One 8-bit
TEXTURE_FORMAT_RxGxBxAx, // One 8-bit component mapped to all channels component mapped to alpha channel, R=G=B=1 TEXTURE_FORMAT_RxGxBxAx,
*/ // One 8-bit component mapped to all channels
MAX_TEXTURE_FORMATS */
} eTextureFormat; MAX_TEXTURE_FORMATS
} eTextureFormat;
// Textures // Textures
int TextureCreate(); int TextureCreate();
void TextureFree(int idx); void TextureFree(int idx);
void TextureBind(int idx); void TextureBind(int idx);
void TextureBindVertex(int idx, bool scaleLight = false); void TextureBindVertex(int idx, bool scaleLight = false);
void TextureSetTextureLevels(int levels); void TextureSetTextureLevels(int levels);
int TextureGetTextureLevels(); int TextureGetTextureLevels();
void TextureData(int width, int height, void *data, int level, eTextureFormat format = TEXTURE_FORMAT_RxGyBzAw); void TextureData(int width, int height, void* data, int level,
void TextureDataUpdate(int xoffset, int yoffset, int width, int height, void *data, int level); eTextureFormat format = TEXTURE_FORMAT_RxGyBzAw);
void TextureSetParam(int param, int value); void TextureDataUpdate(int xoffset, int yoffset, int width, int height,
void TextureDynamicUpdateStart(); void* data, int level);
void TextureDynamicUpdateEnd(); void TextureSetParam(int param, int value);
HRESULT LoadTextureData(const char *szFilename,D3DXIMAGE_INFO *pSrcInfo, int **ppDataOut); void TextureDynamicUpdateStart();
HRESULT LoadTextureData(BYTE *pbData, DWORD dwBytes,D3DXIMAGE_INFO *pSrcInfo, int **ppDataOut); void TextureDynamicUpdateEnd();
HRESULT SaveTextureData(const char *szFilename, D3DXIMAGE_INFO *pSrcInfo, int *ppDataOut); HRESULT LoadTextureData(const char* szFilename, D3DXIMAGE_INFO* pSrcInfo,
HRESULT SaveTextureDataToMemory(void *pOutput, int outputCapacity, int *outputLength, int width, int height, int *ppDataIn); int** ppDataOut);
void TextureGetStats(); HRESULT LoadTextureData(BYTE* pbData, DWORD dwBytes,
void *TextureGetTexture(int idx); D3DXIMAGE_INFO* pSrcInfo, int** ppDataOut);
HRESULT SaveTextureData(const char* szFilename, D3DXIMAGE_INFO* pSrcInfo,
int* ppDataOut);
HRESULT SaveTextureDataToMemory(void* pOutput, int outputCapacity,
int* outputLength, int width, int height,
int* ppDataIn);
void TextureGetStats();
void* TextureGetTexture(int idx);
// State control // State control
void StateSetColour(float r, float g, float b, float a); void StateSetColour(float r, float g, float b, float a);
void StateSetDepthMask(bool enable); void StateSetDepthMask(bool enable);
void StateSetBlendEnable(bool enable); void StateSetBlendEnable(bool enable);
void StateSetBlendFunc(int src, int dst); void StateSetBlendFunc(int src, int dst);
void StateSetBlendFactor(unsigned int colour); void StateSetBlendFactor(unsigned int colour);
void StateSetAlphaFunc(int func, float param); void StateSetAlphaFunc(int func, float param);
void StateSetDepthFunc(int func); void StateSetDepthFunc(int func);
void StateSetFaceCull(bool enable); void StateSetFaceCull(bool enable);
void StateSetFaceCullCW(bool enable); void StateSetFaceCullCW(bool enable);
void StateSetLineWidth(float width); void StateSetLineWidth(float width);
void StateSetWriteEnable(bool red, bool green, bool blue, bool alpha); void StateSetWriteEnable(bool red, bool green, bool blue, bool alpha);
void StateSetDepthTestEnable(bool enable); void StateSetDepthTestEnable(bool enable);
void StateSetAlphaTestEnable(bool enable); void StateSetAlphaTestEnable(bool enable);
void StateSetDepthSlopeAndBias(float slope, float bias); void StateSetDepthSlopeAndBias(float slope, float bias);
void StateSetFogEnable(bool enable); void StateSetFogEnable(bool enable);
void StateSetFogMode(int mode); void StateSetFogMode(int mode);
void StateSetFogNearDistance(float dist); void StateSetFogNearDistance(float dist);
void StateSetFogFarDistance(float dist); void StateSetFogFarDistance(float dist);
void StateSetFogDensity(float density); void StateSetFogDensity(float density);
void StateSetFogColour(float red, float green, float blue); void StateSetFogColour(float red, float green, float blue);
void StateSetLightingEnable(bool enable); void StateSetLightingEnable(bool enable);
void StateSetVertexTextureUV( float u, float v); void StateSetVertexTextureUV(float u, float v);
void StateSetLightColour(int light, float red, float green, float blue); void StateSetLightColour(int light, float red, float green, float blue);
void StateSetLightAmbientColour(float red, float green, float blue); void StateSetLightAmbientColour(float red, float green, float blue);
void StateSetLightDirection(int light, float x, float y, float z); void StateSetLightDirection(int light, float x, float y, float z);
void StateSetLightEnable(int light, bool enable); void StateSetLightEnable(int light, bool enable);
void StateSetViewport(eViewportType viewportType); void StateSetViewport(eViewportType viewportType);
void StateSetEnableViewportClipPlanes(bool enable); void StateSetEnableViewportClipPlanes(bool enable);
void StateSetTexGenCol(int col, float x, float y, float z, float w, bool eyeSpace); void StateSetTexGenCol(int col, float x, float y, float z, float w,
void StateSetStencil(int Function, uint8_t stencil_ref, uint8_t stencil_func_mask, uint8_t stencil_write_mask); bool eyeSpace);
void StateSetForceLOD(int LOD); void StateSetStencil(int Function, uint8_t stencil_ref,
uint8_t stencil_func_mask, uint8_t stencil_write_mask);
void StateSetForceLOD(int LOD);
// Event tracking // Event tracking
void BeginEvent(LPCWSTR eventName); void BeginEvent(LPCWSTR eventName);
void EndEvent(); void EndEvent();
// PLM event handling // PLM event handling
void Suspend(); void Suspend();
bool Suspended(); bool Suspended();
void Resume(); void Resume();
// Linux window management // Linux window management
bool ShouldClose(); bool ShouldClose();
void Shutdown(); void Shutdown();
}; };
const int GL_MODELVIEW_MATRIX = 0x0BA6; const int GL_MODELVIEW_MATRIX = 0x0BA6;
const int GL_PROJECTION_MATRIX = 0x0BA7; const int GL_PROJECTION_MATRIX = 0x0BA7;
const int GL_MODELVIEW = 0x1700; const int GL_MODELVIEW = 0x1700;
@ -242,8 +254,8 @@ const int GL_EYE_LINEAR = 0x2400;
const int GL_OBJECT_PLANE = 0x2501; const int GL_OBJECT_PLANE = 0x2501;
const int GL_EYE_PLANE = 0x2502; const int GL_EYE_PLANE = 0x2502;
// These things are used by glEnable/glDisable so must be different and non-zero
// These things are used by glEnable/glDisable so must be different and non-zero (zero is used by things we haven't assigned yet) // (zero is used by things we haven't assigned yet)
const int GL_TEXTURE_2D = 0x0DE1; const int GL_TEXTURE_2D = 0x0DE1;
const int GL_BLEND = 0x0BE2; const int GL_BLEND = 0x0BE2;
const int GL_CULL_FACE = 0x0B44; const int GL_CULL_FACE = 0x0B44;
@ -286,7 +298,7 @@ const int GL_TEXTURE_WRAP_T = 0x2803;
const int GL_NEAREST = 0x2600; const int GL_NEAREST = 0x2600;
const int GL_LINEAR = 0x2601; const int GL_LINEAR = 0x2601;
const int GL_EXP = 0x0800; const int GL_EXP = 0x0800;
const int GL_NEAREST_MIPMAP_LINEAR = 0x2702; // TODO - mipmapping bit of this const int GL_NEAREST_MIPMAP_LINEAR = 0x2702; // TODO - mipmapping bit of this
const int GL_CLAMP = 0x2900; const int GL_CLAMP = 0x2900;
const int GL_REPEAT = 0x2901; const int GL_REPEAT = 0x2901;
@ -312,5 +324,3 @@ const int GL_TRIANGLE_STRIP = 0x0005;
// Singleton // Singleton
extern C4JRender RenderManager; extern C4JRender RenderManager;

File diff suppressed because it is too large Load diff

View file

@ -5,4 +5,4 @@
#include "../Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h" #include "../Minecraft.Client/Platform/Linux/Stubs/LinuxStubs.h"
#endif #endif
#endif //_4J_RENDER_STADAFX_H #endif //_4J_RENDER_STADAFX_H

View file

@ -12,66 +12,170 @@ C4JStorage::C4JStorage() : m_pStringTable(nullptr) {}
void C4JStorage::Tick(void) {} void C4JStorage::Tick(void) {}
C4JStorage::EMessageResult C4JStorage::RequestMessageBox(UINT uiTitle, UINT uiText, UINT *uiOptionA, UINT uiOptionC, DWORD dwPad, C4JStorage::EMessageResult C4JStorage::RequestMessageBox(
int(*Func)(void *, int, const C4JStorage::EMessageResult), void *lpParam, C4JStringTable *pStringTable, WCHAR *pwchFormatString, DWORD dwFocusButton) { UINT uiTitle, UINT uiText, UINT* uiOptionA, UINT uiOptionC, DWORD dwPad,
int (*Func)(void*, int, const C4JStorage::EMessageResult), void* lpParam,
C4JStringTable* pStringTable, WCHAR* pwchFormatString,
DWORD dwFocusButton) {
return EMessage_ResultAccept; return EMessage_ResultAccept;
} }
C4JStorage::EMessageResult C4JStorage::GetMessageBoxResult() { return EMessage_Undefined; } C4JStorage::EMessageResult C4JStorage::GetMessageBoxResult() {
return EMessage_Undefined;
}
bool C4JStorage::SetSaveDevice(int(*Func)(void *, const bool), void *lpParam, bool bForceResetOfSaveDevice) { return true; } bool C4JStorage::SetSaveDevice(int (*Func)(void*, const bool), void* lpParam,
bool bForceResetOfSaveDevice) {
return true;
}
void C4JStorage::Init(unsigned int uiSaveVersion, LPCWSTR pwchDefaultSaveName, char *pszSavePackName, int iMinimumSaveSize, int(*Func)(void *, const ESavingMessage, int), void *lpParam, LPCSTR szGroupID) {} void C4JStorage::Init(unsigned int uiSaveVersion, LPCWSTR pwchDefaultSaveName,
char* pszSavePackName, int iMinimumSaveSize,
int (*Func)(void*, const ESavingMessage, int),
void* lpParam, LPCSTR szGroupID) {}
void C4JStorage::ResetSaveData() {} void C4JStorage::ResetSaveData() {}
void C4JStorage::SetDefaultSaveNameForKeyboardDisplay(LPCWSTR pwchDefaultSaveName) {} void C4JStorage::SetDefaultSaveNameForKeyboardDisplay(
LPCWSTR pwchDefaultSaveName) {}
void C4JStorage::SetSaveTitle(LPCWSTR pwchDefaultSaveName) {} void C4JStorage::SetSaveTitle(LPCWSTR pwchDefaultSaveName) {}
bool C4JStorage::GetSaveUniqueNumber(INT *piVal) { if (piVal) *piVal = 0; return true; } bool C4JStorage::GetSaveUniqueNumber(INT* piVal) {
bool C4JStorage::GetSaveUniqueFilename(char *pszName) { if (pszName) pszName[0] = '\0'; return true; } if (piVal) *piVal = 0;
void C4JStorage::SetSaveUniqueFilename(char *szFilename) {} return true;
void C4JStorage::SetState(ESaveGameControlState eControlState, int(*Func)(void *, const bool), void *lpParam) {} }
bool C4JStorage::GetSaveUniqueFilename(char* pszName) {
if (pszName) pszName[0] = '\0';
return true;
}
void C4JStorage::SetSaveUniqueFilename(char* szFilename) {}
void C4JStorage::SetState(ESaveGameControlState eControlState,
int (*Func)(void*, const bool), void* lpParam) {}
void C4JStorage::SetSaveDisabled(bool bDisable) {} void C4JStorage::SetSaveDisabled(bool bDisable) {}
bool C4JStorage::GetSaveDisabled(void) { return false; } bool C4JStorage::GetSaveDisabled(void) { return false; }
unsigned int C4JStorage::GetSaveSize() { return 0; } unsigned int C4JStorage::GetSaveSize() { return 0; }
void C4JStorage::GetSaveData(void *pvData, unsigned int *puiBytes) { if (puiBytes) *puiBytes = 0; } void C4JStorage::GetSaveData(void* pvData, unsigned int* puiBytes) {
PVOID C4JStorage::AllocateSaveData(unsigned int uiBytes) { return malloc(uiBytes); } if (puiBytes) *puiBytes = 0;
void C4JStorage::SetSaveImages(PBYTE pbThumbnail, DWORD dwThumbnailBytes, PBYTE pbImage, DWORD dwImageBytes, PBYTE pbTextData, DWORD dwTextDataBytes) {} }
C4JStorage::ESaveGameState C4JStorage::SaveSaveData(int(*Func)(void *, const bool), void *lpParam) { return ESaveGame_Idle; } PVOID C4JStorage::AllocateSaveData(unsigned int uiBytes) {
void C4JStorage::CopySaveDataToNewSave(PBYTE pbThumbnail, DWORD cbThumbnail, WCHAR *wchNewName, int(*Func)(void *lpParam, bool), void *lpParam) {} return malloc(uiBytes);
}
void C4JStorage::SetSaveImages(PBYTE pbThumbnail, DWORD dwThumbnailBytes,
PBYTE pbImage, DWORD dwImageBytes,
PBYTE pbTextData, DWORD dwTextDataBytes) {}
C4JStorage::ESaveGameState C4JStorage::SaveSaveData(int (*Func)(void*,
const bool),
void* lpParam) {
return ESaveGame_Idle;
}
void C4JStorage::CopySaveDataToNewSave(PBYTE pbThumbnail, DWORD cbThumbnail,
WCHAR* wchNewName,
int (*Func)(void* lpParam, bool),
void* lpParam) {}
void C4JStorage::SetSaveDeviceSelected(unsigned int uiPad, bool bSelected) {} void C4JStorage::SetSaveDeviceSelected(unsigned int uiPad, bool bSelected) {}
bool C4JStorage::GetSaveDeviceSelected(unsigned int iPad) { return true; } bool C4JStorage::GetSaveDeviceSelected(unsigned int iPad) { return true; }
C4JStorage::ESaveGameState C4JStorage::DoesSaveExist(bool *pbExists) { if (pbExists) *pbExists = false; return ESaveGame_Idle; } C4JStorage::ESaveGameState C4JStorage::DoesSaveExist(bool* pbExists) {
if (pbExists) *pbExists = false;
return ESaveGame_Idle;
}
bool C4JStorage::EnoughSpaceForAMinSaveGame() { return true; } bool C4JStorage::EnoughSpaceForAMinSaveGame() { return true; }
void C4JStorage::SetSaveMessageVPosition(float fY) {} void C4JStorage::SetSaveMessageVPosition(float fY) {}
C4JStorage::ESaveGameState C4JStorage::GetSavesInfo(int iPad, int(*Func)(void *lpParam, SAVE_DETAILS *pSaveDetails, const bool), void *lpParam, char *pszSavePackName) { return ESaveGame_Idle; } C4JStorage::ESaveGameState C4JStorage::GetSavesInfo(
int iPad,
int (*Func)(void* lpParam, SAVE_DETAILS* pSaveDetails, const bool),
void* lpParam, char* pszSavePackName) {
return ESaveGame_Idle;
}
PSAVE_DETAILS C4JStorage::ReturnSavesInfo() { return nullptr; } PSAVE_DETAILS C4JStorage::ReturnSavesInfo() { return nullptr; }
void C4JStorage::ClearSavesInfo() {} void C4JStorage::ClearSavesInfo() {}
C4JStorage::ESaveGameState C4JStorage::LoadSaveDataThumbnail(PSAVE_INFO pSaveInfo, int(*Func)(void *lpParam, std::uint8_t *thumbnailData, unsigned int thumbnailBytes), void *lpParam) { return ESaveGame_Idle; } C4JStorage::ESaveGameState C4JStorage::LoadSaveDataThumbnail(
void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, XCONTENT_DATA &xContentData) { memset(&xContentData, 0, sizeof(xContentData)); } PSAVE_INFO pSaveInfo,
void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, PBYTE *ppbImageData, DWORD *pdwImageBytes) { if (ppbImageData) *ppbImageData = nullptr; if (pdwImageBytes) *pdwImageBytes = 0; } int (*Func)(void* lpParam, std::uint8_t* thumbnailData,
C4JStorage::ESaveGameState C4JStorage::LoadSaveData(PSAVE_INFO pSaveInfo, int(*Func)(void *lpParam, const bool, const bool), void *lpParam) { return ESaveGame_Idle; } unsigned int thumbnailBytes),
C4JStorage::ESaveGameState C4JStorage::DeleteSaveData(PSAVE_INFO pSaveInfo, int(*Func)(void *lpParam, const bool), void *lpParam) { return ESaveGame_Idle; } void* lpParam) {
void C4JStorage::RegisterMarketplaceCountsCallback(int(*Func)(void *lpParam, C4JStorage::DLC_TMS_DETAILS *, int), void *lpParam) {} return ESaveGame_Idle;
void C4JStorage::SetDLCPackageRoot(char *pszDLCRoot) {} }
C4JStorage::EDLCStatus C4JStorage::GetDLCOffers(int iPad, int(*Func)(void *, int, std::uint32_t, int), void *lpParam, DWORD dwOfferTypesBitmask) { return EDLC_NoOffers; } void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile,
XCONTENT_DATA& xContentData) {
memset(&xContentData, 0, sizeof(xContentData));
}
void C4JStorage::GetSaveCacheFileInfo(DWORD dwFile, PBYTE* ppbImageData,
DWORD* pdwImageBytes) {
if (ppbImageData) *ppbImageData = nullptr;
if (pdwImageBytes) *pdwImageBytes = 0;
}
C4JStorage::ESaveGameState C4JStorage::LoadSaveData(
PSAVE_INFO pSaveInfo, int (*Func)(void* lpParam, const bool, const bool),
void* lpParam) {
return ESaveGame_Idle;
}
C4JStorage::ESaveGameState C4JStorage::DeleteSaveData(PSAVE_INFO pSaveInfo,
int (*Func)(void* lpParam,
const bool),
void* lpParam) {
return ESaveGame_Idle;
}
void C4JStorage::RegisterMarketplaceCountsCallback(
int (*Func)(void* lpParam, C4JStorage::DLC_TMS_DETAILS*, int),
void* lpParam) {}
void C4JStorage::SetDLCPackageRoot(char* pszDLCRoot) {}
C4JStorage::EDLCStatus C4JStorage::GetDLCOffers(
int iPad, int (*Func)(void*, int, std::uint32_t, int), void* lpParam,
DWORD dwOfferTypesBitmask) {
return EDLC_NoOffers;
}
DWORD C4JStorage::CancelGetDLCOffers() { return 0; } DWORD C4JStorage::CancelGetDLCOffers() { return 0; }
void C4JStorage::ClearDLCOffers() {} void C4JStorage::ClearDLCOffers() {}
XMARKETPLACE_CONTENTOFFER_INFO& C4JStorage::GetOffer(DWORD dw) { return s_dummyOffer; } XMARKETPLACE_CONTENTOFFER_INFO& C4JStorage::GetOffer(DWORD dw) {
return s_dummyOffer;
}
int C4JStorage::GetOfferCount() { return 0; } int C4JStorage::GetOfferCount() { return 0; }
DWORD C4JStorage::InstallOffer(int iOfferIDC, __uint64 *ullOfferIDA, int(*Func)(void *, int, int), void *lpParam, bool bTrial) { return 0; } DWORD C4JStorage::InstallOffer(int iOfferIDC, __uint64* ullOfferIDA,
int (*Func)(void*, int, int), void* lpParam,
bool bTrial) {
return 0;
}
DWORD C4JStorage::GetAvailableDLCCount(int iPad) { return 0; } DWORD C4JStorage::GetAvailableDLCCount(int iPad) { return 0; }
C4JStorage::EDLCStatus C4JStorage::GetInstalledDLC(int iPad, int(*Func)(void *, int, int), void *lpParam) { return EDLC_NoInstalledDLC; } C4JStorage::EDLCStatus C4JStorage::GetInstalledDLC(int iPad,
int (*Func)(void*, int, int),
void* lpParam) {
return EDLC_NoInstalledDLC;
}
XCONTENT_DATA& C4JStorage::GetDLC(DWORD dw) { return s_dummyContentData; } XCONTENT_DATA& C4JStorage::GetDLC(DWORD dw) { return s_dummyContentData; }
std::uint32_t C4JStorage::MountInstalledDLC(int iPad, std::uint32_t dwDLC, int(*Func)(void *, int, std::uint32_t, std::uint32_t), void *lpParam, LPCSTR szMountDrive) { return 0; } std::uint32_t C4JStorage::MountInstalledDLC(
int iPad, std::uint32_t dwDLC,
int (*Func)(void*, int, std::uint32_t, std::uint32_t), void* lpParam,
LPCSTR szMountDrive) {
return 0;
}
DWORD C4JStorage::UnmountInstalledDLC(LPCSTR szMountDrive) { return 0; } DWORD C4JStorage::UnmountInstalledDLC(LPCSTR szMountDrive) { return 0; }
void C4JStorage::GetMountedDLCFileList(const char *szMountDrive, std::vector<std::string> &fileList) { fileList.clear(); } void C4JStorage::GetMountedDLCFileList(const char* szMountDrive,
std::vector<std::string>& fileList) {
fileList.clear();
}
std::string C4JStorage::GetMountedPath(std::string szMount) { return ""; } std::string C4JStorage::GetMountedPath(std::string szMount) { return ""; }
C4JStorage::ETMSStatus C4JStorage::ReadTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, C4JStorage::eTMS_FileType eFileType, C4JStorage::ETMSStatus C4JStorage::ReadTMSFile(
WCHAR *pwchFilename, BYTE **ppBuffer, DWORD *pdwBufferSize, int(*Func)(void *, WCHAR *, int, bool, int), void *lpParam, int iAction) { return ETMSStatus_Fail; } int iQuadrant, eGlobalStorage eStorageFacility,
bool C4JStorage::WriteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, WCHAR *pwchFilename, BYTE *pBuffer, DWORD dwBufferSize) { return false; } C4JStorage::eTMS_FileType eFileType, WCHAR* pwchFilename, BYTE** ppBuffer,
bool C4JStorage::DeleteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility, WCHAR *pwchFilename) { return false; } DWORD* pdwBufferSize, int (*Func)(void*, WCHAR*, int, bool, int),
void C4JStorage::StoreTMSPathName(WCHAR *pwchName) {} void* lpParam, int iAction) {
C4JStorage::ETMSStatus C4JStorage::TMSPP_ReadFile(int iPad, C4JStorage::eGlobalStorage eStorageFacility, C4JStorage::eTMS_FILETYPEVAL eFileTypeVal, LPCSTR szFilename, int(*Func)(void *, int, int, PTMSPP_FILEDATA, LPCSTR), void *lpParam, int iUserData) { return ETMSStatus_Fail; } return ETMSStatus_Fail;
unsigned int C4JStorage::CRC(unsigned char *buf, int len) { }
bool C4JStorage::WriteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility,
WCHAR* pwchFilename, BYTE* pBuffer,
DWORD dwBufferSize) {
return false;
}
bool C4JStorage::DeleteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility,
WCHAR* pwchFilename) {
return false;
}
void C4JStorage::StoreTMSPathName(WCHAR* pwchName) {}
C4JStorage::ETMSStatus C4JStorage::TMSPP_ReadFile(
int iPad, C4JStorage::eGlobalStorage eStorageFacility,
C4JStorage::eTMS_FILETYPEVAL eFileTypeVal, LPCSTR szFilename,
int (*Func)(void*, int, int, PTMSPP_FILEDATA, LPCSTR), void* lpParam,
int iUserData) {
return ETMSStatus_Fail;
}
unsigned int C4JStorage::CRC(unsigned char* buf, int len) {
unsigned int crc = 0xFFFFFFFF; unsigned int crc = 0xFFFFFFFF;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
crc ^= buf[i]; crc ^= buf[i];
@ -82,11 +186,26 @@ unsigned int C4JStorage::CRC(unsigned char *buf, int len) {
return ~crc; return ~crc;
} }
int C4JStorage::AddSubfile(int regionIndex) { (void)regionIndex; return 0; } int C4JStorage::AddSubfile(int regionIndex) {
(void)regionIndex;
return 0;
}
unsigned int C4JStorage::GetSubfileCount() { return 0; } unsigned int C4JStorage::GetSubfileCount() { return 0; }
void C4JStorage::GetSubfileDetails(unsigned int i, int* regionIndex, void** data, unsigned int* size) { (void)i; if(regionIndex) *regionIndex=0; if(data) *data=0; if(size) *size=0; } void C4JStorage::GetSubfileDetails(unsigned int i, int* regionIndex,
void** data, unsigned int* size) {
(void)i;
if (regionIndex) *regionIndex = 0;
if (data) *data = 0;
if (size) *size = 0;
}
void C4JStorage::ResetSubfiles() {} void C4JStorage::ResetSubfiles() {}
void C4JStorage::UpdateSubfile(int index, void* data, unsigned int size) { (void)index; (void)data; (void)size; } void C4JStorage::UpdateSubfile(int index, void* data, unsigned int size) {
void C4JStorage::SaveSubfiles(int (*Func)(void*, const bool), void* param) { if(Func) Func(param, true); } (void)index;
(void)data;
(void)size;
}
void C4JStorage::SaveSubfiles(int (*Func)(void*, const bool), void* param) {
if (Func) Func(param, true);
}
C4JStorage::ESaveGameState C4JStorage::GetSaveState() { return ESaveGame_Idle; } C4JStorage::ESaveGameState C4JStorage::GetSaveState() { return ESaveGame_Idle; }
void C4JStorage::ContinueIncompleteOperation() {} void C4JStorage::ContinueIncompleteOperation() {}

View file

@ -1,354 +1,380 @@
#pragma once #pragma once
#include <cstdint> #include <cstdint>
#include <vector> #include <vector>
//#include <xtms.h> // #include <xtms.h>
class C4JStringTable; class C4JStringTable;
#define MAX_DISPLAYNAME_LENGTH 128 // CELL_SAVEDATA_SYSP_SUBTITLE_SIZE on PS3 #define MAX_DISPLAYNAME_LENGTH 128 // CELL_SAVEDATA_SYSP_SUBTITLE_SIZE on PS3
#define MAX_DETAILS_LENGTH 128 // CELL_SAVEDATA_SYSP_SUBTITLE_SIZE on PS3 #define MAX_DETAILS_LENGTH 128 // CELL_SAVEDATA_SYSP_SUBTITLE_SIZE on PS3
#define MAX_SAVEFILENAME_LENGTH 32 // CELL_SAVEDATA_DIRNAME_SIZE #define MAX_SAVEFILENAME_LENGTH 32 // CELL_SAVEDATA_DIRNAME_SIZE
typedef struct typedef struct {
{ time_t modifiedTime;
time_t modifiedTime; unsigned int dataSize;
unsigned int dataSize; unsigned int thumbnailSize;
unsigned int thumbnailSize; } CONTAINER_METADATA;
}
CONTAINER_METADATA;
typedef struct typedef struct {
{ char UTF8SaveFilename[MAX_SAVEFILENAME_LENGTH];
char UTF8SaveFilename[MAX_SAVEFILENAME_LENGTH]; char UTF8SaveTitle[MAX_DISPLAYNAME_LENGTH];
char UTF8SaveTitle[MAX_DISPLAYNAME_LENGTH]; CONTAINER_METADATA metaData;
CONTAINER_METADATA metaData; PBYTE thumbnailData;
PBYTE thumbnailData; } SAVE_INFO, *PSAVE_INFO;
}
SAVE_INFO,*PSAVE_INFO;
typedef struct typedef struct {
{ int iSaveC;
int iSaveC; PSAVE_INFO SaveInfoA;
PSAVE_INFO SaveInfoA; } SAVE_DETAILS, *PSAVE_DETAILS;
}
SAVE_DETAILS,*PSAVE_DETAILS;
typedef std::vector <PXMARKETPLACE_CONTENTOFFER_INFO> OfferDataArray; typedef std::vector<PXMARKETPLACE_CONTENTOFFER_INFO> OfferDataArray;
typedef std::vector <PXCONTENT_DATA> XContentDataArray; typedef std::vector<PXCONTENT_DATA> XContentDataArray;
//typedef std::vector <PSAVE_DETAILS> SaveDetailsArray; // typedef std::vector <PSAVE_DETAILS> SaveDetailsArray;
// Current version of the dlc data creator // Current version of the dlc data creator
#define CURRENT_DLC_VERSION_NUM 3 #define CURRENT_DLC_VERSION_NUM 3
class C4JStorage class C4JStorage {
{
public: public:
// Structs defined in the DLC_Creator, but added here to be used in the app // Structs defined in the DLC_Creator, but added here to be used in the app
typedef struct typedef struct {
{ unsigned int uiFileSize;
unsigned int uiFileSize; DWORD dwType;
DWORD dwType; DWORD dwWchCount; // count of WCHAR in next array
DWORD dwWchCount; // count of WCHAR in next array WCHAR wchFile[1];
WCHAR wchFile[1]; } DLC_FILE_DETAILS, *PDLC_FILE_DETAILS;
}
DLC_FILE_DETAILS, *PDLC_FILE_DETAILS;
typedef struct typedef struct {
{ DWORD dwType;
DWORD dwType; DWORD dwWchCount; // count of WCHAR in next array;
DWORD dwWchCount; // count of WCHAR in next array; WCHAR wchData[1]; // will be an array of size dwBytes
WCHAR wchData[1]; // will be an array of size dwBytes } DLC_FILE_PARAM, *PDLC_FILE_PARAM;
} // End of DLC_Creator structs
DLC_FILE_PARAM, *PDLC_FILE_PARAM;
// End of DLC_Creator structs
typedef struct typedef struct {
{ WCHAR wchDisplayName[XCONTENT_MAX_DISPLAYNAME_LENGTH];
WCHAR wchDisplayName[XCONTENT_MAX_DISPLAYNAME_LENGTH]; CHAR szFileName[XCONTENT_MAX_FILENAME_LENGTH];
CHAR szFileName[XCONTENT_MAX_FILENAME_LENGTH]; DWORD dwImageOffset;
DWORD dwImageOffset; DWORD dwImageBytes;
DWORD dwImageBytes; } CACHEINFOSTRUCT;
}
CACHEINFOSTRUCT;
// structure to hold DLC info in TMS // structure to hold DLC info in TMS
typedef struct typedef struct {
{ DWORD dwVersion;
DWORD dwVersion; DWORD dwNewOffers;
DWORD dwNewOffers; DWORD dwTotalOffers;
DWORD dwTotalOffers; DWORD dwInstalledTotalOffers;
DWORD dwInstalledTotalOffers; BYTE bPadding[1024 - sizeof(DWORD) * 4]; // future expansion
BYTE bPadding[1024-sizeof(DWORD)*4]; // future expansion } DLC_TMS_DETAILS;
}
DLC_TMS_DETAILS;
enum eGTS_FileTypes enum eGTS_FileTypes { eGTS_Type_Skin = 0, eGTS_Type_Cape, eGTS_Type_MAX };
{
eGTS_Type_Skin=0,
eGTS_Type_Cape,
eGTS_Type_MAX
};
enum eGlobalStorage enum eGlobalStorage {
{ // eGlobalStorage_GameClip=0,
//eGlobalStorage_GameClip=0, eGlobalStorage_Title = 0,
eGlobalStorage_Title=0, eGlobalStorage_TitleUser,
eGlobalStorage_TitleUser, eGlobalStorage_Max
eGlobalStorage_Max };
};
enum EMessageResult enum EMessageResult {
{ EMessage_Undefined = 0,
EMessage_Undefined=0, EMessage_Busy,
EMessage_Busy, EMessage_Pending,
EMessage_Pending, EMessage_Cancelled,
EMessage_Cancelled, EMessage_ResultAccept,
EMessage_ResultAccept, EMessage_ResultDecline,
EMessage_ResultDecline, EMessage_ResultThirdOption,
EMessage_ResultThirdOption, EMessage_ResultFourthOption
EMessage_ResultFourthOption };
};
enum ESaveGameControlState enum ESaveGameControlState {
{ ESaveGameControl_Idle = 0,
ESaveGameControl_Idle=0, ESaveGameControl_Save,
ESaveGameControl_Save, ESaveGameControl_InternalRequestingDevice,
ESaveGameControl_InternalRequestingDevice, ESaveGameControl_InternalGetSaveName,
ESaveGameControl_InternalGetSaveName, ESaveGameControl_InternalSaving,
ESaveGameControl_InternalSaving, ESaveGameControl_CopySave,
ESaveGameControl_CopySave, ESaveGameControl_CopyingSave,
ESaveGameControl_CopyingSave, };
};
enum ESaveGameState enum ESaveGameState {
{ ESaveGame_Idle = 0,
ESaveGame_Idle=0, ESaveGame_Save,
ESaveGame_Save, ESaveGame_InternalRequestingDevice,
ESaveGame_InternalRequestingDevice, ESaveGame_InternalGetSaveName,
ESaveGame_InternalGetSaveName, ESaveGame_InternalSaving,
ESaveGame_InternalSaving, ESaveGame_CopySave,
ESaveGame_CopySave, ESaveGame_CopyingSave,
ESaveGame_CopyingSave, ESaveGame_Load,
ESaveGame_Load, ESaveGame_GetSavesInfo,
ESaveGame_GetSavesInfo, ESaveGame_Rename,
ESaveGame_Rename, ESaveGame_Delete,
ESaveGame_Delete,
ESaveGame_GetSaveThumbnail // Not used as an actual state in the PS4, but the game expects this to be returned to indicate success when getting a thumbnail ESaveGame_GetSaveThumbnail // Not used as an actual state in the PS4,
// but the game expects this to be returned
// to indicate success when getting a
// thumbnail
}; };
enum ELoadGameStatus enum ELoadGameStatus {
{ ELoadGame_Idle = 0,
ELoadGame_Idle=0, ELoadGame_InProgress,
ELoadGame_InProgress, ELoadGame_NoSaves,
ELoadGame_NoSaves, ELoadGame_ChangedDevice,
ELoadGame_ChangedDevice, ELoadGame_DeviceRemoved
ELoadGame_DeviceRemoved };
};
enum EDeleteGameStatus enum EDeleteGameStatus {
{ EDeleteGame_Idle = 0,
EDeleteGame_Idle=0, EDeleteGame_InProgress,
EDeleteGame_InProgress, };
};
enum ESGIStatus {
ESGIStatus_Error = 0,
ESGIStatus_Idle,
ESGIStatus_ReadInProgress,
ESGIStatus_NoSaves,
};
enum ESGIStatus enum EDLCStatus {
{ EDLC_Error = 0,
ESGIStatus_Error=0, EDLC_Idle,
ESGIStatus_Idle, EDLC_NoOffers,
ESGIStatus_ReadInProgress, EDLC_AlreadyEnumeratedAllOffers,
ESGIStatus_NoSaves, EDLC_NoInstalledDLC,
}; EDLC_Pending,
EDLC_LoadInProgress,
EDLC_Loaded,
EDLC_ChangedDevice
};
enum EDLCStatus enum ESavingMessage {
{ ESavingMessage_None = 0,
EDLC_Error=0, ESavingMessage_Short,
EDLC_Idle, ESavingMessage_Long
EDLC_NoOffers, };
EDLC_AlreadyEnumeratedAllOffers,
EDLC_NoInstalledDLC,
EDLC_Pending,
EDLC_LoadInProgress,
EDLC_Loaded,
EDLC_ChangedDevice
};
enum ESavingMessage enum ETMSStatus {
{ ETMSStatus_Idle = 0,
ESavingMessage_None=0, ETMSStatus_Fail,
ESavingMessage_Short, ETMSStatus_Fail_ReadInProgress,
ESavingMessage_Long ETMSStatus_Fail_WriteInProgress,
}; ETMSStatus_Pending,
};
enum ETMSStatus enum eTMS_FileType {
{ eTMS_FileType_Normal = 0,
ETMSStatus_Idle=0, eTMS_FileType_Graphic,
ETMSStatus_Fail, };
ETMSStatus_Fail_ReadInProgress,
ETMSStatus_Fail_WriteInProgress,
ETMSStatus_Pending,
};
enum eTMS_FileType enum eTMS_FILETYPEVAL {
{ TMS_FILETYPE_BINARY,
eTMS_FileType_Normal=0, TMS_FILETYPE_CONFIG,
eTMS_FileType_Graphic, TMS_FILETYPE_JSON,
}; TMS_FILETYPE_MAX
};
enum eTMS_UGCTYPE { TMS_UGCTYPE_NONE, TMS_UGCTYPE_IMAGE, TMS_UGCTYPE_MAX };
enum eTMS_FILETYPEVAL typedef struct {
{ CHAR szFilename[256];
TMS_FILETYPE_BINARY, int iFileSize;
TMS_FILETYPE_CONFIG, eTMS_FILETYPEVAL eFileTypeVal;
TMS_FILETYPE_JSON, } TMSPP_FILE_DETAILS, *PTMSPP_FILE_DETAILS;
TMS_FILETYPE_MAX
};
enum eTMS_UGCTYPE
{
TMS_UGCTYPE_NONE,
TMS_UGCTYPE_IMAGE,
TMS_UGCTYPE_MAX
};
typedef struct {
int iCount;
PTMSPP_FILE_DETAILS FileDetailsA;
} TMSPP_FILE_LIST, *PTMSPP_FILE_LIST;
typedef struct typedef struct {
{ DWORD dwSize;
CHAR szFilename[256]; PBYTE pbData;
int iFileSize; } TMSPP_FILEDATA, *PTMSPP_FILEDATA;
eTMS_FILETYPEVAL eFileTypeVal;
}
TMSPP_FILE_DETAILS, *PTMSPP_FILE_DETAILS;
typedef struct C4JStorage();
{
int iCount;
PTMSPP_FILE_DETAILS FileDetailsA;
}
TMSPP_FILE_LIST, *PTMSPP_FILE_LIST;
typedef struct void Tick(void);
{
DWORD dwSize;
PBYTE pbData;
}
TMSPP_FILEDATA, *PTMSPP_FILEDATA;
// Messages
C4JStorage::EMessageResult RequestMessageBox(
UINT uiTitle, UINT uiText, UINT* uiOptionA, UINT uiOptionC,
DWORD dwPad = XUSER_INDEX_ANY,
int (*Func)(void*, int, const C4JStorage::EMessageResult) = NULL,
void* lpParam = NULL, C4JStringTable* pStringTable = NULL,
WCHAR* pwchFormatString = NULL, DWORD dwFocusButton = 0);
C4JStorage(); C4JStorage::EMessageResult GetMessageBoxResult();
void Tick(void); // save device
bool SetSaveDevice(int (*Func)(void*, const bool), void* lpParam,
bool bForceResetOfSaveDevice = false);
// Messages // savegame
C4JStorage::EMessageResult RequestMessageBox(UINT uiTitle, UINT uiText, UINT *uiOptionA,UINT uiOptionC, DWORD dwPad=XUSER_INDEX_ANY, void Init(unsigned int uiSaveVersion, LPCWSTR pwchDefaultSaveName,
int( *Func)(void *,int,const C4JStorage::EMessageResult)=NULL,void *lpParam=NULL, C4JStringTable *pStringTable=NULL, WCHAR *pwchFormatString=NULL,DWORD dwFocusButton=0); char* pszSavePackName, int iMinimumSaveSize,
int (*Func)(void*, const ESavingMessage, int), void* lpParam,
LPCSTR szGroupID);
void ResetSaveData(); // Call before a new save to clear out stored save
// file name
void SetDefaultSaveNameForKeyboardDisplay(LPCWSTR pwchDefaultSaveName);
void SetSaveTitle(LPCWSTR pwchDefaultSaveName);
bool GetSaveUniqueNumber(INT* piVal);
bool GetSaveUniqueFilename(char* pszName);
void SetSaveUniqueFilename(char* szFilename);
void SetState(ESaveGameControlState eControlState,
int (*Func)(void*, const bool), void* lpParam);
void SetSaveDisabled(bool bDisable);
bool GetSaveDisabled(void);
unsigned int GetSaveSize();
void GetSaveData(void* pvData, unsigned int* puiBytes);
PVOID AllocateSaveData(unsigned int uiBytes);
void SetSaveImages(
PBYTE pbThumbnail, DWORD dwThumbnailBytes, PBYTE pbImage,
DWORD dwImageBytes, PBYTE pbTextData,
DWORD dwTextDataBytes); // Sets the thumbnail & image for the save,
// optionally setting the metadata in the png
C4JStorage::ESaveGameState SaveSaveData(int (*Func)(void*, const bool),
void* lpParam);
void CopySaveDataToNewSave(PBYTE pbThumbnail, DWORD cbThumbnail,
WCHAR* wchNewName,
int (*Func)(void* lpParam, bool), void* lpParam);
void SetSaveDeviceSelected(unsigned int uiPad, bool bSelected);
bool GetSaveDeviceSelected(unsigned int iPad);
C4JStorage::ESaveGameState DoesSaveExist(bool* pbExists);
bool EnoughSpaceForAMinSaveGame();
void SetSaveMessageVPosition(
float fY); // The 'Saving' message will display at a default position
// unless changed
// Get the info for the saves
C4JStorage::ESaveGameState GetSavesInfo(
int iPad,
int (*Func)(void* lpParam, SAVE_DETAILS* pSaveDetails, const bool),
void* lpParam, char* pszSavePackName);
PSAVE_DETAILS ReturnSavesInfo();
void ClearSavesInfo(); // Clears results
C4JStorage::ESaveGameState LoadSaveDataThumbnail(
PSAVE_INFO pSaveInfo,
int (*Func)(void* lpParam, std::uint8_t* thumbnailData,
unsigned int thumbnailBytes),
void* lpParam); // Get the thumbnail for an individual save referenced
// by pSaveInfo
C4JStorage::EMessageResult GetMessageBoxResult(); void GetSaveCacheFileInfo(DWORD dwFile, XCONTENT_DATA& xContentData);
void GetSaveCacheFileInfo(DWORD dwFile, PBYTE* ppbImageData,
DWORD* pdwImageBytes);
// save device // Load the save. Need to call GetSaveData once the callback is called
bool SetSaveDevice(int( *Func)(void *,const bool),void *lpParam, bool bForceResetOfSaveDevice=false); C4JStorage::ESaveGameState LoadSaveData(PSAVE_INFO pSaveInfo,
int (*Func)(void* lpParam,
const bool, const bool),
void* lpParam);
C4JStorage::ESaveGameState DeleteSaveData(PSAVE_INFO pSaveInfo,
int (*Func)(void* lpParam,
const bool),
void* lpParam);
// savegame // DLC
void Init(unsigned int uiSaveVersion,LPCWSTR pwchDefaultSaveName,char *pszSavePackName,int iMinimumSaveSize,int( *Func)(void *, const ESavingMessage, int),void *lpParam,LPCSTR szGroupID); void RegisterMarketplaceCountsCallback(
void ResetSaveData(); // Call before a new save to clear out stored save file name int (*Func)(void* lpParam, C4JStorage::DLC_TMS_DETAILS*, int),
void SetDefaultSaveNameForKeyboardDisplay(LPCWSTR pwchDefaultSaveName); void* lpParam);
void SetSaveTitle(LPCWSTR pwchDefaultSaveName); void SetDLCPackageRoot(char* pszDLCRoot);
bool GetSaveUniqueNumber(INT *piVal); C4JStorage::EDLCStatus GetDLCOffers(
bool GetSaveUniqueFilename(char *pszName); int iPad, int (*Func)(void*, int, std::uint32_t, int), void* lpParam,
void SetSaveUniqueFilename(char *szFilename); DWORD dwOfferTypesBitmask = XMARKETPLACE_OFFERING_TYPE_CONTENT);
void SetState(ESaveGameControlState eControlState,int( *Func)(void *,const bool),void *lpParam); DWORD CancelGetDLCOffers();
void SetSaveDisabled(bool bDisable); void ClearDLCOffers();
bool GetSaveDisabled(void); XMARKETPLACE_CONTENTOFFER_INFO& GetOffer(DWORD dw);
unsigned int GetSaveSize(); int GetOfferCount();
void GetSaveData(void *pvData,unsigned int *puiBytes); DWORD InstallOffer(int iOfferIDC, __uint64* ullOfferIDA,
PVOID AllocateSaveData(unsigned int uiBytes); int (*Func)(void*, int, int), void* lpParam,
void SetSaveImages( PBYTE pbThumbnail,DWORD dwThumbnailBytes,PBYTE pbImage,DWORD dwImageBytes, PBYTE pbTextData ,DWORD dwTextDataBytes); // Sets the thumbnail & image for the save, optionally setting the metadata in the png bool bTrial = false);
C4JStorage::ESaveGameState SaveSaveData(int( *Func)(void * ,const bool),void *lpParam); DWORD GetAvailableDLCCount(int iPad);
void CopySaveDataToNewSave(PBYTE pbThumbnail,DWORD cbThumbnail,WCHAR *wchNewName,int ( *Func)(void *lpParam, bool), void *lpParam);
void SetSaveDeviceSelected(unsigned int uiPad,bool bSelected);
bool GetSaveDeviceSelected(unsigned int iPad);
C4JStorage::ESaveGameState DoesSaveExist(bool *pbExists);
bool EnoughSpaceForAMinSaveGame();
void SetSaveMessageVPosition(float fY); // The 'Saving' message will display at a default position unless changed C4JStorage::EDLCStatus GetInstalledDLC(int iPad,
// Get the info for the saves int (*Func)(void*, int, int),
C4JStorage::ESaveGameState GetSavesInfo(int iPad,int ( *Func)(void *lpParam,SAVE_DETAILS *pSaveDetails,const bool),void *lpParam,char *pszSavePackName); void* lpParam);
PSAVE_DETAILS ReturnSavesInfo(); XCONTENT_DATA& GetDLC(DWORD dw);
void ClearSavesInfo(); // Clears results std::uint32_t MountInstalledDLC(int iPad, std::uint32_t dwDLC,
C4JStorage::ESaveGameState LoadSaveDataThumbnail(PSAVE_INFO pSaveInfo,int( *Func)(void *lpParam,std::uint8_t *thumbnailData,unsigned int thumbnailBytes), void *lpParam); // Get the thumbnail for an individual save referenced by pSaveInfo int (*Func)(void*, int, std::uint32_t,
std::uint32_t),
void* lpParam, LPCSTR szMountDrive = NULL);
DWORD UnmountInstalledDLC(LPCSTR szMountDrive = NULL);
void GetMountedDLCFileList(const char* szMountDrive,
std::vector<std::string>& fileList);
std::string GetMountedPath(std::string szMount);
void GetSaveCacheFileInfo(DWORD dwFile,XCONTENT_DATA &xContentData); // Global title storage
void GetSaveCacheFileInfo(DWORD dwFile, PBYTE *ppbImageData, DWORD *pdwImageBytes); C4JStorage::ETMSStatus ReadTMSFile(
int iQuadrant, eGlobalStorage eStorageFacility,
C4JStorage::eTMS_FileType eFileType, WCHAR* pwchFilename,
BYTE** ppBuffer, DWORD* pdwBufferSize,
int (*Func)(void*, WCHAR*, int, bool, int) = NULL, void* lpParam = NULL,
int iAction = 0);
bool WriteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility,
WCHAR* pwchFilename, BYTE* pBuffer, DWORD dwBufferSize);
bool DeleteTMSFile(int iQuadrant, eGlobalStorage eStorageFacility,
WCHAR* pwchFilename);
void StoreTMSPathName(WCHAR* pwchName = NULL);
// Load the save. Need to call GetSaveData once the callback is called // TMS++
C4JStorage::ESaveGameState LoadSaveData(PSAVE_INFO pSaveInfo,int( *Func)(void *lpParam,const bool, const bool), void *lpParam);
C4JStorage::ESaveGameState DeleteSaveData(PSAVE_INFO pSaveInfo,int( *Func)(void *lpParam,const bool), void *lpParam);
// DLC
void RegisterMarketplaceCountsCallback(int ( *Func)(void *lpParam, C4JStorage::DLC_TMS_DETAILS *, int), void *lpParam );
void SetDLCPackageRoot(char *pszDLCRoot);
C4JStorage::EDLCStatus GetDLCOffers(int iPad,int( *Func)(void *, int, std::uint32_t, int),void *lpParam, DWORD dwOfferTypesBitmask=XMARKETPLACE_OFFERING_TYPE_CONTENT);
DWORD CancelGetDLCOffers();
void ClearDLCOffers();
XMARKETPLACE_CONTENTOFFER_INFO& GetOffer(DWORD dw);
int GetOfferCount();
DWORD InstallOffer(int iOfferIDC, __uint64 *ullOfferIDA,int( *Func)(void *, int, int),void *lpParam, bool bTrial=false);
DWORD GetAvailableDLCCount( int iPad);
C4JStorage::EDLCStatus GetInstalledDLC(int iPad,int( *Func)(void *, int, int),void *lpParam);
XCONTENT_DATA& GetDLC(DWORD dw);
std::uint32_t MountInstalledDLC(int iPad,std::uint32_t dwDLC,int( *Func)(void *, int, std::uint32_t, std::uint32_t),void *lpParam,LPCSTR szMountDrive=NULL);
DWORD UnmountInstalledDLC(LPCSTR szMountDrive = NULL);
void GetMountedDLCFileList(const char* szMountDrive, std::vector<std::string>& fileList);
std::string GetMountedPath(std::string szMount);
// Global title storage
C4JStorage::ETMSStatus ReadTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,C4JStorage::eTMS_FileType eFileType,
WCHAR *pwchFilename,BYTE **ppBuffer,DWORD *pdwBufferSize,int( *Func)(void *, WCHAR *,int, bool, int)=NULL,void *lpParam=NULL, int iAction=0);
bool WriteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename,BYTE *pBuffer,DWORD dwBufferSize);
bool DeleteTMSFile(int iQuadrant,eGlobalStorage eStorageFacility,WCHAR *pwchFilename);
void StoreTMSPathName(WCHAR *pwchName=NULL);
// TMS++
#ifdef _XBOX #ifdef _XBOX
C4JStorage::ETMSStatus WriteTMSFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FileType eFileType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,TMSCLIENT_CALLBACK Func,LPVOID lpParam); C4JStorage::ETMSStatus WriteTMSFile(
HRESULT GetUserQuotaInfo(int iPad,TMSCLIENT_CALLBACK Func,LPVOID lpParam); int iPad, C4JStorage::eGlobalStorage eStorageFacility,
C4JStorage::eTMS_FileType eFileType, CHAR* pchFilePath, CHAR* pchBuffer,
DWORD dwBufferSize, TMSCLIENT_CALLBACK Func, LPVOID lpParam);
HRESULT GetUserQuotaInfo(int iPad, TMSCLIENT_CALLBACK Func, LPVOID lpParam);
#endif #endif
// C4JStorage::ETMSStatus TMSPP_WriteFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=NULL,LPVOID lpParam=NULL, int iUserData=0); // C4JStorage::ETMSStatus TMSPP_WriteFile(int
// C4JStorage::ETMSStatus TMSPP_GetUserQuotaInfo(int iPad,TMSCLIENT_CALLBACK Func,LPVOID lpParam, int iUserData=0); // iPad,C4JStorage::eGlobalStorage
C4JStorage::ETMSStatus TMSPP_ReadFile(int iPad,C4JStorage::eGlobalStorage eStorageFacility,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,LPCSTR szFilename,int( *Func)(void *,int,int,PTMSPP_FILEDATA, LPCSTR)=NULL,void *lpParam=NULL, int iUserData=0); // eStorageFacility,C4JStorage::eTMS_FILETYPEVAL
// C4JStorage::ETMSStatus TMSPP_ReadFileList(int iPad,C4JStorage::eGlobalStorage eStorageFacility,CHAR *pchFilePath,int( *Func)(LPVOID,int,int,PTMSPP_FILE_LIST)=NULL,LPVOID lpParam=NULL, int iUserData=0); // eFileTypeVal,C4JStorage::eTMS_UGCTYPE eUGCType,CHAR *pchFilePath,CHAR
// C4JStorage::ETMSStatus TMSPP_DeleteFile(int iPad,LPCSTR szFilePath,C4JStorage::eTMS_FILETYPEVAL eFileTypeVal,int( *Func)(LPVOID,int,int),LPVOID lpParam=NULL, int iUserData=0); // *pchBuffer,DWORD dwBufferSize,int( *Func)(LPVOID,int,int)=NULL,LPVOID
// bool TMSPP_InFileList(eGlobalStorage eStorageFacility, int iPad,const std::wstring &Filename); // lpParam=NULL, int iUserData=0); C4JStorage::ETMSStatus
// unsigned int CRC(unsigned char *buf, int len); // TMSPP_GetUserQuotaInfo(int iPad,TMSCLIENT_CALLBACK Func,LPVOID lpParam,
// int iUserData=0);
C4JStorage::ETMSStatus TMSPP_ReadFile(
int iPad, C4JStorage::eGlobalStorage eStorageFacility,
C4JStorage::eTMS_FILETYPEVAL eFileTypeVal, LPCSTR szFilename,
int (*Func)(void*, int, int, PTMSPP_FILEDATA, LPCSTR) = NULL,
void* lpParam = NULL, int iUserData = 0);
// C4JStorage::ETMSStatus TMSPP_ReadFileList(int
// iPad,C4JStorage::eGlobalStorage eStorageFacility,CHAR *pchFilePath,int(
// *Func)(LPVOID,int,int,PTMSPP_FILE_LIST)=NULL,LPVOID lpParam=NULL, int
// iUserData=0); C4JStorage::ETMSStatus
// TMSPP_DeleteFile(int iPad,LPCSTR szFilePath,C4JStorage::eTMS_FILETYPEVAL
// eFileTypeVal,int( *Func)(LPVOID,int,int),LPVOID lpParam=NULL, int
// iUserData=0); bool
// TMSPP_InFileList(eGlobalStorage eStorageFacility, int iPad,const
// std::wstring &Filename); unsigned int
// CRC(unsigned char *buf, int len);
// enum eXBLWS // enum eXBLWS
// { // {
// eXBLWS_GET, // eXBLWS_GET,
// eXBLWS_POST, // eXBLWS_POST,
// eXBLWS_PUT, // eXBLWS_PUT,
// eXBLWS_DELETE, // eXBLWS_DELETE,
// }; // };
//bool XBLWS_Command(eXBLWS eCommand); // bool
// XBLWS_Command(eXBLWS eCommand);
unsigned int CRC(unsigned char* buf, int len);
unsigned int CRC(unsigned char *buf, int len); int AddSubfile(int regionIndex);
unsigned int GetSubfileCount();
void GetSubfileDetails(unsigned int i, int* regionIndex, void** data,
unsigned int* size);
void ResetSubfiles();
void UpdateSubfile(int index, void* data, unsigned int size);
void SaveSubfiles(int (*Func)(void*, const bool), void* param);
ESaveGameState GetSaveState();
int AddSubfile(int regionIndex); void ContinueIncompleteOperation();
unsigned int GetSubfileCount();
void GetSubfileDetails(unsigned int i, int* regionIndex, void** data, unsigned int* size);
void ResetSubfiles();
void UpdateSubfile(int index, void* data, unsigned int size);
void SaveSubfiles(int (*Func)(void*, const bool), void* param);
ESaveGameState GetSaveState();
void ContinueIncompleteOperation(); C4JStringTable* m_pStringTable;
C4JStringTable *m_pStringTable;
}; };
extern C4JStorage StorageManager; extern C4JStorage StorageManager;

View file

@ -7,4 +7,4 @@
#include "../Minecraft.World/Platform/x64headers/extraX64.h" #include "../Minecraft.World/Platform/x64headers/extraX64.h"
#endif //_4J_STORAGE_STADAFX_H #endif //_4J_STORAGE_STADAFX_H

View file

@ -32,7 +32,9 @@ Commit names should clearly describe what was changed in the commit. [Convention
### Keep code clean and readable. ### Keep code clean and readable.
At this time, we do not have a style guide or rules for how code should be formatted. In general, code should be readable and try to match the styling and conventions of whatever is around it. Code formatting is defined by the repository's [`.clang-format`](./.clang-format) file. If you are touching C or C++ source, format the files you changed before opening or updating a pull request.
CI checks formatting on changed C and C++ files, so local formatting mismatches will fail the relevant workflow.
### Avoid changing in-game behavior. ### Avoid changing in-game behavior.

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(); return std::shared_ptr<GameCommandPacket>(
new GameCommandPacket(eGameCommand_Teleport, baos.toByteArray()));
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());
// }
//}
}
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);
@ -76,7 +71,8 @@ void GameMode::adjustPlayer(std::shared_ptr<Player> player)
// { // {
// 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;
// } // }
@ -93,92 +89,71 @@ void GameMode::adjustPlayer(std::shared_ptr<Player> player)
// } // }
// 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;
@ -117,15 +107,15 @@ void Options::init()
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""; 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? while ((line = br->readLine()) !=
{ L"") // 4J - was check against NULL - do we need to distinguish
// 4J - removed try/catch // between empty lines and a fail here?
// try { {
std::wstring cmds[2]; // 4J - removed try/catch
int splitpos = (int)line.find(L":"); // try {
if( splitpos == std::wstring::npos ) std::wstring cmds[2];
{ int splitpos = (int)line.find(L":");
cmds[0] = line; if (splitpos == std::wstring::npos) {
cmds[1] = L""; cmds[0] = line;
} cmds[1] = L"";
else } else {
{ cmds[0] = line.substr(0, splitpos);
cmds[0] = line.substr(0,splitpos); cmds[1] = line.substr(splitpos, line.length() - splitpos);
cmds[1] = line.substr(splitpos,line.length()-splitpos);
}
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();
// }
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 LARGE_STATS_COUNT = 8;
static Stat** LARGE_STATS[LARGE_STATS_COUNT];
static const int SAVE_DELAY = 30 * 60;
static const int FLUSH_DELAY = 30 * 60 * 5;
//static const int STAT_DATA_OFFSET = 32; typedef enum {
static const int LARGE_STATS_COUNT = 8; LEADERBOARD_KILLS_PEACEFUL = 0x00000001,
static Stat** LARGE_STATS[LARGE_STATS_COUNT]; LEADERBOARD_KILLS_EASY = 0x00000002,
static const int SAVE_DELAY = 30*60; LEADERBOARD_KILLS_NORMAL = 0x00000004,
static const int FLUSH_DELAY = 30*60*5; LEADERBOARD_KILLS_HARD = 0x00000008,
LEADERBOARD_MININGBLOCKS_PEACEFUL = 0x00000010,
LEADERBOARD_MININGBLOCKS_EASY = 0x00000020,
LEADERBOARD_MININGBLOCKS_NORMAL = 0x00000040,
LEADERBOARD_MININGBLOCKS_HARD = 0x00000080,
LEADERBOARD_MININGORE_PEACEFUL = 0x00000100,
LEADERBOARD_MININGORE_EASY = 0x00000200,
LEADERBOARD_MININGORE_NORMAL = 0x00000400,
LEADERBOARD_MININGORE_HARD = 0x00000800,
LEADERBOARD_FARMING_PEACEFUL = 0x00001000,
LEADERBOARD_FARMING_EASY = 0x00002000,
LEADERBOARD_FARMING_NORMAL = 0x00004000,
LEADERBOARD_FARMING_HARD = 0x00008000,
LEADERBOARD_TRAVELLING_PEACEFUL = 0x00010000,
LEADERBOARD_TRAVELLING_EASY = 0x00020000,
LEADERBOARD_TRAVELLING_NORMAL = 0x00040000,
LEADERBOARD_TRAVELLING_HARD = 0x00080000,
LEADERBOARD_NETHER_PEACEFUL = 0x00100000,
LEADERBOARD_NETHER_EASY = 0x00200000,
LEADERBOARD_NETHER_NORMAL = 0x00400000,
LEADERBOARD_NETHER_HARD = 0x00800000,
LEADERBOARD_TRAVELLING_TOTAL = 0x01000000
} LEADERBOARD_FLAG;
typedef enum { StatsMap stats;
LEADERBOARD_KILLS_PEACEFUL = 0x00000001,
LEADERBOARD_KILLS_EASY = 0x00000002,
LEADERBOARD_KILLS_NORMAL = 0x00000004,
LEADERBOARD_KILLS_HARD = 0x00000008,
LEADERBOARD_MININGBLOCKS_PEACEFUL = 0x00000010,
LEADERBOARD_MININGBLOCKS_EASY = 0x00000020,
LEADERBOARD_MININGBLOCKS_NORMAL = 0x00000040,
LEADERBOARD_MININGBLOCKS_HARD = 0x00000080,
LEADERBOARD_MININGORE_PEACEFUL = 0x00000100,
LEADERBOARD_MININGORE_EASY = 0x00000200,
LEADERBOARD_MININGORE_NORMAL = 0x00000400,
LEADERBOARD_MININGORE_HARD = 0x00000800,
LEADERBOARD_FARMING_PEACEFUL = 0x00001000,
LEADERBOARD_FARMING_EASY = 0x00002000,
LEADERBOARD_FARMING_NORMAL = 0x00004000,
LEADERBOARD_FARMING_HARD = 0x00008000,
LEADERBOARD_TRAVELLING_PEACEFUL = 0x00010000,
LEADERBOARD_TRAVELLING_EASY = 0x00020000,
LEADERBOARD_TRAVELLING_NORMAL = 0x00040000,
LEADERBOARD_TRAVELLING_HARD = 0x00080000,
LEADERBOARD_NETHER_PEACEFUL = 0x00100000,
LEADERBOARD_NETHER_EASY = 0x00200000,
LEADERBOARD_NETHER_NORMAL = 0x00400000,
LEADERBOARD_NETHER_HARD = 0x00800000,
LEADERBOARD_TRAVELLING_TOTAL = 0x01000000
} LEADERBOARD_FLAG;
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);
else
xa = 0.0f;
if( pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_FORWARD) || pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_BACKWARD) ) if (pMinecraft->localgameModes[iPad]->isInputAllowed(
ya = InputManager.GetJoypadStick_LY(iPad); MINECRAFT_ACTION_FORWARD) ||
else pMinecraft->localgameModes[iPad]->isInputAllowed(
ya = 0.0f; 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); // jumping = controller.isButtonPressed(0);
sprintKey = InputManager.GetValue(iPad, MINECRAFT_ACTION_SPRINT) && pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_SPRINT); sprintKey = InputManager.GetValue(iPad, MINECRAFT_ACTION_SPRINT) &&
jumping = InputManager.GetValue(iPad, MINECRAFT_ACTION_JUMP) && pMinecraft->localgameModes[iPad]->isInputAllowed(MINECRAFT_ACTION_JUMP); 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,10 +1,9 @@
#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;
@ -12,13 +11,12 @@ public:
bool sneaking; bool sneaking;
bool sprintKey; bool sprintKey;
Input(); // 4J - added Input(); // 4J - added
virtual ~Input(){} virtual ~Input() {}
virtual void tick(LocalPlayer *player); 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(); void flagEntitiesToBeRemoved(unsigned int* flags,
virtual bool newFallingTileAllowed(); bool* removedFound); // 4J added
void flagEntitiesToBeRemoved(unsigned int *flags, bool *removedFound); // 4J added // 4J added
static const int MAX_UPDATES = 256;
// 4J added // Each of these need to be duplicated for each level in the current game.
static const int MAX_UPDATES = 256; // As we currently only have 2 (over/nether), making this constant
static Level* m_level[3];
static int m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX];
static int m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX];
static int m_updateChunkCount[3];
static int m_updateTileX[3][MAX_UPDATES];
static int m_updateTileY[3][MAX_UPDATES];
static int m_updateTileZ[3][MAX_UPDATES];
static int m_updateTileCount[3];
static int m_randValue[3];
// 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 static C4JThread::EventArray* m_updateTrigger;
static Level *m_level[3]; static CRITICAL_SECTION m_updateCS[3];
static int m_updateChunkX[3][LEVEL_CHUNKS_TO_UPDATE_MAX];
static int m_updateChunkZ[3][LEVEL_CHUNKS_TO_UPDATE_MAX];
static int m_updateChunkCount[3];
static int m_updateTileX[3][MAX_UPDATES];
static int m_updateTileY[3][MAX_UPDATES];
static int m_updateTileZ[3][MAX_UPDATES];
static int m_updateTileCount[3];
static int m_randValue[3];
static C4JThread::EventArray* m_updateTrigger;
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);
}; };

File diff suppressed because it is too large Load diff

View file

@ -46,306 +46,349 @@ class PsPlusUpsellWrapper;
#undef linux #undef linux
#endif #endif
class Minecraft {
class Minecraft
{
private:
enum OS{
linux, solaris, windows, macos, unknown, xbox
};
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];
static const int tickTimes_length = 512;
static __int64 tickTimes[tickTimes_length];
static int frameTimePos;
static __int64 warezTime;
private: private:
static OS getPlatform(); int rightClickDelay;
public: public:
LevelStorageSource *getLevelSource(); // 4J- this should really be in localplayer
void setScreen(Screen *screen); StatsCounter* stats[4];
private: private:
void checkGlError(const std::wstring& string); 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 // 4J Added
virtual void handleChunkVisibilityArea(std::shared_ptr<ChunkVisibilityAreaPacket> packet); virtual void handleChunkVisibilityArea(
std::shared_ptr<ChunkVisibilityAreaPacket> packet);
virtual void handleChunkVisibility(std::shared_ptr<ChunkVisibilityPacket> packet); virtual void handleChunkVisibility(
virtual void handleChunkTilesUpdate(std::shared_ptr<ChunkTilesUpdatePacket> packet); std::shared_ptr<ChunkVisibilityPacket> packet);
virtual void handleBlockRegionUpdate(std::shared_ptr<BlockRegionUpdatePacket> 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
// by virtue of the chunk rebuild
chunk->unload(false); 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; chunk->loaded = true;
LeaveCriticalSection(&m_csLoadCreate); LeaveCriticalSection(&m_csLoadCreate);
#if ( defined _WIN64 || defined __LP64__ ) #if (defined _WIN64 || defined __LP64__)
if( InterlockedCompareExchangeRelease64((LONG64 *)&cache[idx],(LONG64)chunk,(LONG64)lastChunk) == (LONG64)lastChunk ) 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
// care about UGC
// PADDY - this is failing when a local player with chat restrictions joins an online game // PADDY - this is failing when a local player with chat restrictions
// joins an online game
if( player != NULL && player->connection->m_offlineXUID != INVALID_XUID && player->connection->m_onlineXUID != INVALID_XUID ) if (player != NULL &&
{ player->connection->m_offlineXUID != INVALID_XUID &&
if( player->connection->m_friendsOnlyUGC ) player->connection->m_onlineXUID != INVALID_XUID) {
{ if (player->connection->m_friendsOnlyUGC) {
ugcFriendsOnlyBits |= (1<<ugcXuidCount); ugcFriendsOnlyBits |= (1 << ugcXuidCount);
} }
// Need to use the online XUID otherwise friend checks will fail on the client // Need to use the online XUID otherwise friend checks will fail on
ugcXuids[ugcXuidCount] = player->connection->m_onlineXUID; // the client
ugcXuids[ugcXuidCount] = player->connection->m_onlineXUID;
if( player->connection->getNetworkPlayer() != NULL && player->connection->getNetworkPlayer()->IsHost() ) hostIndex = ugcXuidCount; if (player->connection->getNetworkPlayer() != NULL &&
player->connection->getNetworkPlayer()->IsHost())
hostIndex = ugcXuidCount;
++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

@ -178,6 +178,8 @@ void DLCAudioFile::addParameter(EAudioType type, EAudioParameterType ptype, cons
m_parameters[type].push_back(value); m_parameters[type].push_back(value);
//m_parameters[(int)type] = value; //m_parameters[(int)type] = value;
break; break;
default:
break;
} }
} }

View file

@ -237,6 +237,8 @@ DLCFile *DLCPack::addFile(DLCManager::EDLCType type, const std::wstring &path)
case DLCManager::e_DLCType_GameRulesHeader: case DLCManager::e_DLCType_GameRulesHeader:
newFile = new DLCGameRulesHeader(path); newFile = new DLCGameRulesHeader(path);
break; break;
default:
break;
}; };
if( newFile != NULL ) if( newFile != NULL )

View file

@ -70,6 +70,8 @@ void DLCSkinFile::addParameter(DLCManager::EDLCParameterType type, const std::ws
case XC_LANGUAGE_KOREAN: case XC_LANGUAGE_KOREAN:
maximumChars = 35; maximumChars = 35;
break; break;
default:
break;
} }
std::wstring creditValue = value; std::wstring creditValue = value;
while (creditValue.length() > maximumChars) while (creditValue.length() > maximumChars)
@ -155,10 +157,14 @@ void DLCSkinFile::addParameter(DLCManager::EDLCParameterType type, const std::ws
} }
break; break;
case DLCManager::e_DLCParamType_Anim: case DLCManager::e_DLCParamType_Anim:
// 4J Stu - The Xbox version used swscanf_s which isn't available in GCC. {
swscanf(value.c_str(), L"%X", &m_uiAnimOverrideBitmask); // 4J Stu - The Xbox version used swscanf_s which isn't available in GCC.
std::uint32_t skinId = app.getSkinIdFromPath(m_path); swscanf(value.c_str(), L"%X", &m_uiAnimOverrideBitmask);
app.SetAnimOverrideBitmask(skinId, m_uiAnimOverrideBitmask); std::uint32_t skinId = app.getSkinIdFromPath(m_path);
app.SetAnimOverrideBitmask(skinId, m_uiAnimOverrideBitmask);
}
break;
default:
break; break;
} }
} }

View file

@ -32,6 +32,8 @@ void DLCTextureFile::addParameter(DLCManager::EDLCParameterType type, const std:
m_animString = value; m_animString = value;
m_bIsAnim = true; m_bIsAnim = true;
break;
default:
break; break;
} }
} }

View file

@ -164,6 +164,8 @@ bool ConsoleGenerateStructure::postProcess(Level *level, Random *random, Boundin
pPlaceSpawner->placeSpawnerInLevel(this,level,chunkBB); pPlaceSpawner->placeSpawnerInLevel(this,level,chunkBB);
} }
break; break;
default:
break;
}; };
} }

View file

@ -128,6 +128,8 @@ void ChoiceTask::sendTelemetry()
firstPlay = !tutorial->getCompleted( eTutorial_Telemetry_Halfway ); firstPlay = !tutorial->getCompleted( eTutorial_Telemetry_Halfway );
tutorial->setCompleted( eTutorial_Telemetry_Halfway ); tutorial->setCompleted( eTutorial_Telemetry_Halfway );
break; break;
default:
break;
}; };
TelemetryManager->RecordEnemyKilledOrOvercome(pMinecraft->player->GetXboxPad(), 0, 0, 0, 0, 0, 0, m_eTelemetryEvent); TelemetryManager->RecordEnemyKilledOrOvercome(pMinecraft->player->GetXboxPad(), 0, 0, 0, 0, 0, 0, m_eTelemetryEvent);

View file

@ -131,6 +131,8 @@ void InfoTask::sendTelemetry()
firstPlay = !tutorial->getCompleted( eTutorial_Telemetry_Complete ); firstPlay = !tutorial->getCompleted( eTutorial_Telemetry_Complete );
tutorial->setCompleted( eTutorial_Telemetry_Complete ); tutorial->setCompleted( eTutorial_Telemetry_Complete );
break; break;
default:
break;
}; };
TelemetryManager->RecordEnemyKilledOrOvercome(pMinecraft->player->GetXboxPad(), 0, 0, 0, 0, 0, 0, m_eTelemetryEvent); TelemetryManager->RecordEnemyKilledOrOvercome(pMinecraft->player->GetXboxPad(), 0, 0, 0, 0, 0, 0, m_eTelemetryEvent);
} }

View file

@ -123,6 +123,8 @@ int TutorialHint::tick()
case e_Hint_SwimUp: case e_Hint_SwimUp:
if( Minecraft::GetInstance()->localplayers[m_tutorial->getPad()]->isUnderLiquid(Material::water) ) returnVal = m_descriptionId; if( Minecraft::GetInstance()->localplayers[m_tutorial->getPad()]->isUnderLiquid(Material::water) ) returnVal = m_descriptionId;
break; break;
default:
break;
} }
return returnVal; return returnVal;
} }

View file

@ -374,6 +374,8 @@ void IUIScene_AbstractContainerMenu::onMouseTick()
case eTapNone: case eTapNone:
/// Nothing to do, input is not a tap. /// Nothing to do, input is not a tap.
break; break;
default:
break;
} }
#endif // TAP_DETECTION #endif // TAP_DETECTION
@ -632,6 +634,8 @@ void IUIScene_AbstractContainerMenu::onMouseTick()
iDesiredSlotX = m_iCurrSlotX; iDesiredSlotX = m_iCurrSlotX;
iDesiredSlotY = m_iCurrSlotY; iDesiredSlotY = m_iCurrSlotY;
break; break;
default:
break;
} }
int iNumRows; int iNumRows;

View file

@ -176,6 +176,8 @@ void IUIScene_AnvilMenu::handleOtherClicked(int iPad, ESceneSection eSection, in
case eSectionAnvilName: case eSectionAnvilName:
handleEditNamePressed(); handleEditNamePressed();
break; break;
default:
break;
}; };
} }
@ -188,7 +190,9 @@ bool IUIScene_AnvilMenu::IsSectionSlotList( ESceneSection eSection )
case eSectionAnvilItem1: case eSectionAnvilItem1:
case eSectionAnvilItem2: case eSectionAnvilItem2:
case eSectionAnvilResult: case eSectionAnvilResult:
return true; return true;
default:
break;
} }
return false; return false;
} }

View file

@ -955,6 +955,8 @@ bool IUIScene_CreativeMenu::IsSectionSlotList( ESceneSection eSection )
case eSectionInventoryCreativeUsing: case eSectionInventoryCreativeUsing:
case eSectionInventoryCreativeSelector: case eSectionInventoryCreativeSelector:
return true; return true;
default:
break;
} }
return false; return false;
} }
@ -966,6 +968,8 @@ bool IUIScene_CreativeMenu::CanHaveFocus( ESceneSection eSection )
case eSectionInventoryCreativeUsing: case eSectionInventoryCreativeUsing:
case eSectionInventoryCreativeSelector: case eSectionInventoryCreativeSelector:
return true; return true;
default:
break;
} }
return false; return false;
} }

View file

@ -138,6 +138,8 @@ void IUIScene_EnchantingMenu::handleOtherClicked(int iPad, ESceneSection eSectio
case eSectionEnchantButton3: case eSectionEnchantButton3:
index = 2; index = 2;
break; break;
default:
break;
}; };
Minecraft *pMinecraft = Minecraft::GetInstance(); Minecraft *pMinecraft = Minecraft::GetInstance();
if (index >= 0 && m_menu->clickMenuButton(std::dynamic_pointer_cast<Player>(pMinecraft->localplayers[iPad]), index)) if (index >= 0 && m_menu->clickMenuButton(std::dynamic_pointer_cast<Player>(pMinecraft->localplayers[iPad]), index))
@ -175,6 +177,8 @@ bool IUIScene_EnchantingMenu::IsSectionSlotList( ESceneSection eSection )
case eSectionEnchantUsing: case eSectionEnchantUsing:
case eSectionEnchantSlot: case eSectionEnchantSlot:
return true; return true;
default:
break;
} }
return false; return false;
} }

View file

@ -106,6 +106,8 @@ void UIComponent_Chat::render(S32 width, S32 height, C4JRender::eViewportType vi
xPos = (S32)(ui.getScreenWidth() / 2); xPos = (S32)(ui.getScreenWidth() / 2);
yPos = (S32)(ui.getScreenHeight() / 2); yPos = (S32)(ui.getScreenHeight() / 2);
break; break;
default:
break;
} }
ui.setupRenderPosition(xPos, yPos); ui.setupRenderPosition(xPos, yPos);
@ -134,6 +136,8 @@ void UIComponent_Chat::render(S32 width, S32 height, C4JRender::eViewportType vi
case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT:
tileYStart = (S32)(m_movieHeight / 2); tileYStart = (S32)(m_movieHeight / 2);
break; break;
default:
break;
} }
IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight ); IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight );

View file

@ -52,6 +52,8 @@ void UIComponent_MenuBackground::render(S32 width, S32 height, C4JRender::eViewp
xPos = (S32)(ui.getScreenWidth() / 2); xPos = (S32)(ui.getScreenWidth() / 2);
yPos = (S32)(ui.getScreenHeight() / 2); yPos = (S32)(ui.getScreenHeight() / 2);
break; break;
default:
break;
} }
ui.setupRenderPosition(xPos, yPos); ui.setupRenderPosition(xPos, yPos);
@ -80,6 +82,8 @@ void UIComponent_MenuBackground::render(S32 width, S32 height, C4JRender::eViewp
case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT:
tileYStart = (S32)(m_movieHeight / 2); tileYStart = (S32)(m_movieHeight / 2);
break; break;
default:
break;
} }
IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight ); IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight );

View file

@ -90,6 +90,8 @@ void UIComponent_Panorama::render(S32 width, S32 height, C4JRender::eViewportTyp
case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT: case C4JRender::VIEWPORT_TYPE_SPLIT_RIGHT:
xPos = (S32)(ui.getScreenWidth() / 2); xPos = (S32)(ui.getScreenWidth() / 2);
break; break;
default:
break;
} }
ui.setupRenderPosition(xPos, yPos); ui.setupRenderPosition(xPos, yPos);

View file

@ -204,6 +204,8 @@ void UIComponent_Tooltips::render(S32 width, S32 height, C4JRender::eViewportTyp
xPos = (S32)(ui.getScreenWidth() / 2); xPos = (S32)(ui.getScreenWidth() / 2);
yPos = (S32)(ui.getScreenHeight() / 2); yPos = (S32)(ui.getScreenHeight() / 2);
break; break;
default:
break;
} }
ui.setupRenderPosition(xPos, yPos); ui.setupRenderPosition(xPos, yPos);
@ -232,6 +234,8 @@ void UIComponent_Tooltips::render(S32 width, S32 height, C4JRender::eViewportTyp
case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT:
tileYStart = (S32)(m_movieHeight / 2); tileYStart = (S32)(m_movieHeight / 2);
break; break;
default:
break;
} }
IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight ); IggyPlayerSetDisplaySize( getMovie(), m_movieWidth, m_movieHeight );

View file

@ -496,6 +496,8 @@ void UIComponent_TutorialPopup::render(S32 width, S32 height, C4JRender::eViewpo
xPos = (S32)(ui.getScreenWidth() / 2); xPos = (S32)(ui.getScreenWidth() / 2);
yPos = (S32)(ui.getScreenHeight() / 2); yPos = (S32)(ui.getScreenHeight() / 2);
break; break;
default:
break;
} }
//Adjust for safezone //Adjust for safezone
switch( viewport ) switch( viewport )
@ -507,6 +509,8 @@ void UIComponent_TutorialPopup::render(S32 width, S32 height, C4JRender::eViewpo
case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_TOP_RIGHT:
yPos += getSafeZoneHalfHeight(); yPos += getSafeZoneHalfHeight();
break; break;
default:
break;
} }
switch( viewport ) switch( viewport )
{ {
@ -517,6 +521,8 @@ void UIComponent_TutorialPopup::render(S32 width, S32 height, C4JRender::eViewpo
case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT: case C4JRender::VIEWPORT_TYPE_QUADRANT_BOTTOM_RIGHT:
xPos -= getSafeZoneHalfWidth(); xPos -= getSafeZoneHalfWidth();
break; break;
default:
break;
} }
ui.setupRenderPosition(xPos, yPos); ui.setupRenderPosition(xPos, yPos);

View file

@ -526,12 +526,12 @@ IggyLibrary UIController::loadSkin(const std::wstring &skinPath, const std::wstr
rrbool res; rrbool res;
int iteration = 0; int iteration = 0;
__int64 totalStatic = 0; __int64 totalStatic = 0;
while(res = IggyDebugGetMemoryUseInfo ( NULL , while((res = IggyDebugGetMemoryUseInfo ( NULL ,
lib , lib ,
"" , "" ,
0 , 0 ,
iteration , iteration ,
&memoryInfo )) &memoryInfo )))
{ {
totalStatic += memoryInfo.static_allocation_bytes; totalStatic += memoryInfo.static_allocation_bytes;
app.DebugPrintf(app.USER_SR, "%ls - %.*s, static: %dB, dynamic: %dB\n", skinPath.c_str(), memoryInfo.subcategory_stringlen, memoryInfo.subcategory, memoryInfo.static_allocation_bytes, memoryInfo.dynamic_allocation_bytes); app.DebugPrintf(app.USER_SR, "%ls - %.*s, static: %dB, dynamic: %dB\n", skinPath.c_str(), memoryInfo.subcategory_stringlen, memoryInfo.subcategory, memoryInfo.static_allocation_bytes, memoryInfo.dynamic_allocation_bytes);

View file

@ -404,6 +404,8 @@ bool UILayer::NavigateToScene(int iPad, EUIScene scene, void *initData)
case eUIScene_Timer: case eUIScene_Timer:
newScene = new UIScene_Timer(iPad, initData, this); newScene = new UIScene_Timer(iPad, initData, this);
break; break;
default:
break;
}; };
if(newScene == NULL) if(newScene == NULL)
@ -553,6 +555,8 @@ UIScene *UILayer::addComponent(int iPad, EUIScene scene, void *initData)
newScene = new UIComponent_MenuBackground(iPad, initData, this); newScene = new UIComponent_MenuBackground(iPad, initData, this);
m_componentRefCount[scene] = std::pair<int,bool>(1,true); m_componentRefCount[scene] = std::pair<int,bool>(1,true);
break; break;
default:
break;
}; };
if(newScene == NULL) return NULL; if(newScene == NULL) return NULL;
@ -728,6 +732,8 @@ bool UILayer::updateFocusState(bool allowedFocus /* = false */)
case eUIScene_EndPoem: case eUIScene_EndPoem:
m_bIgnoreAutosaveMenuDisplayed = true; m_bIgnoreAutosaveMenuDisplayed = true;
break; break;
default:
break;
} }
switch(sceneType) switch(sceneType)
@ -738,6 +744,8 @@ bool UILayer::updateFocusState(bool allowedFocus /* = false */)
case eUIScene_LeaderboardsMenu: case eUIScene_LeaderboardsMenu:
m_bIgnorePlayerJoinMenuDisplayed = true; m_bIgnorePlayerJoinMenuDisplayed = true;
break; break;
default:
break;
} }
} }
m_hasFocus = layerFocusSet; m_hasFocus = layerFocusSet;

View file

@ -391,12 +391,12 @@ void UIScene::getDebugMemoryUseRecursive(const std::wstring &moviePath, IggyMemo
rrbool res; rrbool res;
IggyMemoryUseInfo internalMemoryInfo; IggyMemoryUseInfo internalMemoryInfo;
int internalIteration = 0; int internalIteration = 0;
while(res = IggyDebugGetMemoryUseInfo ( swf , while((res = IggyDebugGetMemoryUseInfo ( swf ,
0 , 0 ,
memoryInfo.subcategory , memoryInfo.subcategory ,
memoryInfo.subcategory_stringlen , memoryInfo.subcategory_stringlen ,
internalIteration , internalIteration ,
&internalMemoryInfo )) &internalMemoryInfo )))
{ {
app.DebugPrintf(app.USER_SR, "%ls - %.*s static: %d ( %d ) dynamic: %d ( %d )\n", moviePath.c_str(), internalMemoryInfo.subcategory_stringlen, internalMemoryInfo.subcategory, app.DebugPrintf(app.USER_SR, "%ls - %.*s static: %d ( %d ) dynamic: %d ( %d )\n", moviePath.c_str(), internalMemoryInfo.subcategory_stringlen, internalMemoryInfo.subcategory,
internalMemoryInfo.static_allocation_bytes, internalMemoryInfo.static_allocation_count, internalMemoryInfo.dynamic_allocation_bytes, internalMemoryInfo.dynamic_allocation_count); internalMemoryInfo.static_allocation_bytes, internalMemoryInfo.static_allocation_count, internalMemoryInfo.dynamic_allocation_bytes, internalMemoryInfo.dynamic_allocation_count);
@ -414,12 +414,12 @@ void UIScene::PrintTotalMemoryUsage(__int64 &totalStatic, __int64 &totalDynamic)
int iteration = 0; int iteration = 0;
__int64 sceneStatic = 0; __int64 sceneStatic = 0;
__int64 sceneDynamic = 0; __int64 sceneDynamic = 0;
while(res = IggyDebugGetMemoryUseInfo ( swf , while((res = IggyDebugGetMemoryUseInfo ( swf ,
0 , 0 ,
"" , "" ,
0 , 0 ,
iteration , iteration ,
&memoryInfo )) &memoryInfo )))
{ {
sceneStatic += memoryInfo.static_allocation_bytes; sceneStatic += memoryInfo.static_allocation_bytes;
sceneDynamic += memoryInfo.dynamic_allocation_bytes; sceneDynamic += memoryInfo.dynamic_allocation_bytes;

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