2926: clang-format entire repo r=heinrich5991 a=def-



Co-authored-by: def <dennis@felsin9.de>
Co-authored-by: heinrich5991 <heinrich5991@gmail.com>
This commit is contained in:
bors[bot] 2020-09-26 22:10:58 +00:00 committed by GitHub
commit 6bb8cda483
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
337 changed files with 12344 additions and 11737 deletions

View file

@ -2,12 +2,16 @@
Language: Cpp
AccessModifierOffset: -8
AlignAfterOpenBracket: DontAlign
AlignEscapedNewlines: DontAlign
AlignTrailingComments: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AlwaysBreakTemplateDeclarations: true
BasedOnStyle: LLVM
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: false
BreakConstructorInitializers: AfterColon
BreakStringLiterals: true
BraceWrapping:
AfterCaseLabel: true

View file

@ -23,5 +23,5 @@ jobs:
- name: Check style
run: |
clang-format -version
scripts/fix_style.py --dry-run --base origin/master
scripts/fix_style.py --dry-run
scripts/check_header_guards.py

11
formatting-revs.txt Normal file
View file

@ -0,0 +1,11 @@
f7b37eaf6a5dcd20c3bf53c842474129197b585f
3a986fbe529a0b34b4ca968cd8d9e12a07ba3e68
a67a8e36aa81f12b2cac8f5e240228e669fdd11e
f42a5a0431b16cfe3ed7f3f8158606e8fd36d0b1
833e3640b469d5fb98bb431ef834759815d94b55
8ef6a0da169d6eba151d6909a96fb52dc0a47384
4e157c64e3d7e36f23b3dfad0555f3095f31f712
a273969bc198d7259f57286c8a19214d48d22de5
cfd32c357b5aca410c7befb8ae4953fec1fa54ed
d4da82f977abb34cd0ed9a77e707b4c42f26673d
aecc6fb1a59407f84ef5d2b51af9432408cc9563

View file

@ -1,70 +1,41 @@
#!/usr/bin/env python3
from collections import defaultdict
import os
import re
import subprocess
import sys
RE_POSITION=re.compile(rb"^@@ -[0-9]+,[0-9]+ \+(?P<start>[0-9]+),(?P<len>[0-9]+) @@")
def get_line_ranges(git_diff):
new_filename = None
result = defaultdict(list)
for line in git_diff.splitlines():
if line.startswith(b"+++ "):
new_filename = line[6:].decode()
continue
match = RE_POSITION.match(line)
if match:
start = int(match.group("start").decode())
end = start + int(match.group("len").decode()) - 1
result[new_filename].append((start, end))
continue
return dict(result)
os.chdir(os.path.dirname(__file__) + "/..")
def git_get_changed_lines(margin, base):
return get_line_ranges(subprocess.check_output([
"git",
"diff",
base,
"--unified={}".format(margin),
]))
ignore_files = ["src/engine/keys.h", "src/engine/client/keynames.h"]
def filter_cpp(changed_lines):
return {filename: changed_lines[filename] for filename in changed_lines
if any(filename.endswith(ext) for ext in ".c .cpp .h".split())}
def reformat(changed_lines):
for filename in changed_lines:
subprocess.check_call(["clang-format", "-i"] + ["--lines={}:{}".format(start, end) for start, end in changed_lines[filename]] + [filename])
def warn(changed_lines):
result = 0
for filename in changed_lines:
result = subprocess.call(["clang-format", "-Werror", "--dry-run"] + ["--lines={}:{}".format(start, end) for start, end in changed_lines[filename]] + [filename]) or result
def recursive_file_list(path):
result = []
for dirpath, dirnames, filenames in os.walk(path):
result += filter(lambda p: p not in ignore_files, [os.path.join(dirpath, filename) for filename in filenames])
return result
def get_common_base(base):
return subprocess.check_output(["git", "merge-base", "HEAD", base]).decode().strip()
def filter_cpp(filenames):
return [filename for filename in filenames
if any(filename.endswith(ext) for ext in ".c .cpp .h".split())]
def reformat(filenames):
subprocess.check_call(["clang-format", "-i"] + filenames)
def warn(filenames):
return subprocess.call(["clang-format", "-Werror", "--dry-run"] + filenames)
def main():
import argparse
p = argparse.ArgumentParser(description="Check and fix style of changed lines")
p.add_argument("--base", default="HEAD", help="Revision to compare to")
p = argparse.ArgumentParser(description="Check and fix style of changed files")
p.add_argument("-n", "--dry-run", action="store_true", help="Don't fix, only warn")
args = p.parse_args()
filenames = filter_cpp(recursive_file_list("src"))
if not args.dry_run:
last_ranges = None
ranges = filter_cpp(git_get_changed_lines(1, base=args.base))
i = 0
while last_ranges != ranges:
print("Iteration {}".format(i))
reformat(ranges)
last_ranges = ranges
ranges = filter_cpp(git_get_changed_lines(1, base=args.base))
i += 1
print("Done after {} iterations".format(i))
reformat(filenames)
else:
sys.exit(warn(filter_cpp(git_get_changed_lines(1, base=args.base))))
sys.exit(warn(filenames))
if __name__ == "__main__":
main()

View file

@ -6,12 +6,12 @@
enum
{
ANTIBOT_ABI_VERSION=3,
ANTIBOT_ABI_VERSION = 3,
ANTIBOT_MSGFLAG_NONVITAL=1,
ANTIBOT_MSGFLAG_FLUSH=2,
ANTIBOT_MSGFLAG_NONVITAL = 1,
ANTIBOT_MSGFLAG_FLUSH = 2,
ANTIBOT_MAX_CLIENTS=64,
ANTIBOT_MAX_CLIENTS = 64,
};
struct CAntibotMapData
@ -30,9 +30,9 @@ struct CAntibotInputData
// Defined by the network protocol, unlikely to change.
//enum
//{
//TEAM_SPECTATORS=-1,
//TEAM_RED=0,
//TEAM_BLUE=1,
// TEAM_SPECTATORS=-1,
// TEAM_RED=0,
// TEAM_BLUE=1,
//};
struct CAntibotCharacterData
@ -64,15 +64,16 @@ struct CAntibotVersion
int m_SizeRoundData;
};
#define ANTIBOT_VERSION { \
ANTIBOT_ABI_VERSION, \
sizeof(CAntibotVersion), \
sizeof(CAntibotData), \
sizeof(CAntibotCharacterData), \
sizeof(CAntibotInputData), \
sizeof(CAntibotMapData), \
sizeof(CAntibotRoundData), \
}
#define ANTIBOT_VERSION \
{ \
ANTIBOT_ABI_VERSION, \
sizeof(CAntibotVersion), \
sizeof(CAntibotData), \
sizeof(CAntibotCharacterData), \
sizeof(CAntibotInputData), \
sizeof(CAntibotMapData), \
sizeof(CAntibotRoundData), \
}
struct CAntibotData
{

View file

@ -2,8 +2,7 @@
#define ANTIBOT_ANTIBOT_INTERFACE_H
#include "antibot_data.h"
extern "C"
{
extern "C" {
int AntibotAbiVersion();
void AntibotInit(CAntibotData *pCallbackData);
@ -25,7 +24,6 @@ void AntibotOnEngineTick(void);
void AntibotOnEngineClientJoin(int ClientID, bool Sixup);
void AntibotOnEngineClientDrop(int ClientID, const char *pReason);
void AntibotOnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags);
}
#endif // ANTIBOT_ANTIBOT_INTERFACE_H

View file

@ -2,8 +2,7 @@
static CAntibotData *g_pData;
extern "C"
{
extern "C" {
int AntibotAbiVersion()
{
@ -14,26 +13,25 @@ void AntibotInit(CAntibotData *pData)
g_pData = pData;
g_pData->m_pfnLog("null antibot initialized", g_pData->m_pUser);
}
void AntibotRoundStart(CAntibotRoundData *pRoundData) { };
void AntibotRoundEnd(void) { };
void AntibotUpdateData(void) { }
void AntibotRoundStart(CAntibotRoundData *pRoundData){};
void AntibotRoundEnd(void){};
void AntibotUpdateData(void) {}
void AntibotDestroy(void) { g_pData = 0; }
void AntibotDump(void)
{
g_pData->m_pfnLog("null antibot", g_pData->m_pUser);
}
void AntibotOnPlayerInit(int ClientID) { (void)ClientID; }
void AntibotOnPlayerDestroy(int ClientID) { (void)ClientID; }
void AntibotOnSpawn(int ClientID) { (void)ClientID; }
void AntibotOnHammerFireReloading(int ClientID) { (void)ClientID; }
void AntibotOnHammerFire(int ClientID) { (void)ClientID; }
void AntibotOnHammerHit(int ClientID) { (void)ClientID; }
void AntibotOnDirectInput(int ClientID) { (void)ClientID; }
void AntibotOnCharacterTick(int ClientID) { (void)ClientID; }
void AntibotOnHookAttach(int ClientID, bool Player) { (void)ClientID; (void)Player; }
void AntibotOnEngineTick(void) { }
void AntibotOnEngineClientJoin(int ClientID, bool Sixup) { (void)ClientID; (void)Sixup; }
void AntibotOnEngineClientDrop(int ClientID, const char *pReason) { (void)ClientID; (void)pReason; }
void AntibotOnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags) { (void)ClientID; (void)pData; (void)Size; (void)Flags; }
void AntibotOnPlayerInit(int /*ClientID*/) {}
void AntibotOnPlayerDestroy(int /*ClientID*/) {}
void AntibotOnSpawn(int /*ClientID*/) {}
void AntibotOnHammerFireReloading(int /*ClientID*/) {}
void AntibotOnHammerFire(int /*ClientID*/) {}
void AntibotOnHammerHit(int /*ClientID*/) {}
void AntibotOnDirectInput(int /*ClientID*/) {}
void AntibotOnCharacterTick(int /*ClientID*/) {}
void AntibotOnHookAttach(int /*ClientID*/, bool /*Player*/) {}
void AntibotOnEngineTick(void) {}
void AntibotOnEngineClientJoin(int /*ClientID*/, bool /*Sixup*/) {}
void AntibotOnEngineClientDrop(int /*ClientID*/, const char * /*pReason*/) {}
void AntibotOnEngineClientMessage(int /*ClientID*/, const void * /*pData*/, int /*Size*/, int /*Flags*/) {}
}

View file

@ -33,14 +33,26 @@ inline float RgbToHue(float r, float g, float b)
}
// Curiously Recurring Template Pattern for type safety
template <typename DerivedT>
template<typename DerivedT>
class color4_base
{
public:
union { float x, r, h; };
union { float y, g, s; };
union { float z, b, l, v; };
union { float w, a; };
union
{
float x, r, h;
};
union
{
float y, g, s;
};
union
{
float z, b, l, v;
};
union
{
float w, a;
};
color4_base() {}
@ -93,7 +105,7 @@ public:
DerivedT WithAlpha(float alpha)
{
DerivedT col(static_cast<DerivedT&>(*this));
DerivedT col(static_cast<DerivedT &>(*this));
col.a = alpha;
return col;
}
@ -103,7 +115,7 @@ class ColorHSLA : public color4_base<ColorHSLA>
{
public:
using color4_base::color4_base;
ColorHSLA() {};
ColorHSLA(){};
constexpr static const float DARKEST_LGT = 0.5f;
@ -122,7 +134,7 @@ public:
unsigned Pack(float Darkest, bool Alpha = false)
{
ColorHSLA col = *this;
col.l = (l - Darkest)/(1 - Darkest);
col.l = (l - Darkest) / (1 - Darkest);
col.l = clamp(col.l, 0.0f, 1.0f);
return col.Pack(Alpha);
}
@ -132,19 +144,20 @@ class ColorHSVA : public color4_base<ColorHSVA>
{
public:
using color4_base::color4_base;
ColorHSVA() {};
ColorHSVA(){};
};
class ColorRGBA : public color4_base<ColorRGBA>
{
public:
using color4_base::color4_base;
ColorRGBA() {};
ColorRGBA(){};
};
template <typename T, typename F> T color_cast(const F &f) = delete;
template<typename T, typename F>
T color_cast(const F &f) = delete;
template <>
template<>
inline ColorHSLA color_cast(const ColorRGBA &rgb)
{
float Min = minimum(rgb.r, rgb.g, rgb.b);
@ -153,12 +166,12 @@ inline ColorHSLA color_cast(const ColorRGBA &rgb)
float c = Max - Min;
float h = RgbToHue(rgb.r, rgb.g, rgb.b);
float l = 0.5f * (Max + Min);
float s = (Max != 0.0f && Min != 1.0f) ? (c/(1 - (absolute(2 * l - 1)))) : 0;
float s = (Max != 0.0f && Min != 1.0f) ? (c / (1 - (absolute(2 * l - 1)))) : 0;
return ColorHSLA(h, s, l, rgb.a);
}
template <>
template<>
inline ColorRGBA color_cast(const ColorHSLA &hsl)
{
vec3 rgb = vec3(0, 0, 0);
@ -167,7 +180,8 @@ inline ColorRGBA color_cast(const ColorHSLA &hsl)
float c = (1 - absolute(2 * hsl.l - 1)) * hsl.s;
float x = c * (1 - absolute(fmod(h1, 2) - 1));
switch(round_truncate(h1)) {
switch(round_truncate(h1))
{
case 0:
rgb.r = c, rgb.g = x;
break;
@ -189,43 +203,43 @@ inline ColorRGBA color_cast(const ColorHSLA &hsl)
break;
}
float m = hsl.l - (c/2);
float m = hsl.l - (c / 2);
return ColorRGBA(rgb.r + m, rgb.g + m, rgb.b + m, hsl.a);
}
template <>
template<>
inline ColorHSLA color_cast(const ColorHSVA &hsv)
{
float l = hsv.v * (1 - hsv.s * 0.5f);
return ColorHSLA(hsv.h, (l == 0.0f || l == 1.0f) ? 0 : (hsv.v - l)/minimum(l, 1 - l), l);
return ColorHSLA(hsv.h, (l == 0.0f || l == 1.0f) ? 0 : (hsv.v - l) / minimum(l, 1 - l), l);
}
template <>
template<>
inline ColorHSVA color_cast(const ColorHSLA &hsl)
{
float v = hsl.l + hsl.s * minimum(hsl.l, 1 - hsl.l);
return ColorHSVA(hsl.h, v == 0.0f ? 0 : 2 - (2 * hsl.l / v), v);
}
template <>
template<>
inline ColorRGBA color_cast(const ColorHSVA &hsv)
{
return color_cast<ColorRGBA>(color_cast<ColorHSLA>(hsv));
}
template <>
template<>
inline ColorHSVA color_cast(const ColorRGBA &rgb)
{
return color_cast<ColorHSVA>(color_cast<ColorHSLA>(rgb));
}
template <typename T>
template<typename T>
T color_scale(const T &col, float s)
{
return T(col.x * s, col.y * s, col.z * s, col.a * s);
}
template <typename T>
template<typename T>
T color_invert(const T &col)
{
return T(1.0f - col.x, 1.0f - col.y, 1.0f - col.z, 1.0f - col.a);

View file

@ -12,144 +12,142 @@
/* windows Family */
#if defined(WIN64) || defined(_WIN64)
/* Hmm, is this IA64 or x86-64? */
#define CONF_FAMILY_WINDOWS 1
#define CONF_FAMILY_STRING "windows"
#define CONF_PLATFORM_WIN64 1
#define PLATFORM_STRING "win64"
/* Hmm, is this IA64 or x86-64? */
#define CONF_FAMILY_WINDOWS 1
#define CONF_FAMILY_STRING "windows"
#define CONF_PLATFORM_WIN64 1
#define PLATFORM_STRING "win64"
#elif defined(WIN32) || defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__)
#define CONF_FAMILY_WINDOWS 1
#define CONF_FAMILY_STRING "windows"
#define CONF_PLATFORM_WIN32 1
#define PLATFORM_STRING "win32"
#define CONF_FAMILY_WINDOWS 1
#define CONF_FAMILY_STRING "windows"
#define CONF_PLATFORM_WIN32 1
#define PLATFORM_STRING "win32"
#endif
/* unix family */
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_FREEBSD 1
#define PLATFORM_STRING "freebsd"
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_FREEBSD 1
#define PLATFORM_STRING "freebsd"
#endif
#if defined(__NetBSD__)
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_NETBSD 1
#define PLATFORM_STRING "netbsd"
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_NETBSD 1
#define PLATFORM_STRING "netbsd"
#endif
#if defined(__OpenBSD__)
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_OPENBSD 1
#define PLATFORM_STRING "openbsd"
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_OPENBSD 1
#define PLATFORM_STRING "openbsd"
#endif
#if defined(__LINUX__) || defined(__linux__)
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_LINUX 1
#define PLATFORM_STRING "linux"
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_LINUX 1
#define PLATFORM_STRING "linux"
#endif
#if defined(__GNU__) || defined(__gnu__)
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_HURD 1
#define PLATFORM_STRING "gnu"
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_HURD 1
#define PLATFORM_STRING "gnu"
#endif
#if defined(MACOSX) || defined(__APPLE__) || defined(__DARWIN__)
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_MACOSX 1
#define PLATFORM_STRING "macosx"
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_MACOSX 1
#define PLATFORM_STRING "macosx"
#endif
#if defined(__sun)
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_SOLARIS 1
#define PLATFORM_STRING "solaris"
#define CONF_FAMILY_UNIX 1
#define CONF_FAMILY_STRING "unix"
#define CONF_PLATFORM_SOLARIS 1
#define PLATFORM_STRING "solaris"
#endif
/* beos family */
#if defined(__BeOS) || defined(__BEOS__)
#define CONF_FAMILY_BEOS 1
#define CONF_FAMILY_STRING "beos"
#define CONF_PLATFORM_BEOS 1
#define PLATFORM_STRING "beos"
#define CONF_FAMILY_BEOS 1
#define CONF_FAMILY_STRING "beos"
#define CONF_PLATFORM_BEOS 1
#define PLATFORM_STRING "beos"
#endif
/* use gcc endianness definitions when available */
#if defined(__GNUC__) && !defined(__APPLE__) && !defined(__MINGW32__) && !defined(__sun)
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
#include <sys/endian.h>
#else
#include <endian.h>
#endif
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define CONF_ARCH_ENDIAN_LITTLE 1
#elif __BYTE_ORDER == __BIG_ENDIAN
#define CONF_ARCH_ENDIAN_BIG 1
#endif
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
#include <sys/endian.h>
#else
#include <endian.h>
#endif
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define CONF_ARCH_ENDIAN_LITTLE 1
#elif __BYTE_ORDER == __BIG_ENDIAN
#define CONF_ARCH_ENDIAN_BIG 1
#endif
#endif
/* architectures */
#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(CONF_PLATFORM_WIN32)
#define CONF_ARCH_IA32 1
#define CONF_ARCH_STRING "ia32"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_LITTLE 1
#endif
#define CONF_ARCH_IA32 1
#define CONF_ARCH_STRING "ia32"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_LITTLE 1
#endif
#endif
#if defined(__ia64__) || defined(_M_IA64)
#define CONF_ARCH_IA64 1
#define CONF_ARCH_STRING "ia64"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_LITTLE 1
#endif
#define CONF_ARCH_IA64 1
#define CONF_ARCH_STRING "ia64"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_LITTLE 1
#endif
#endif
#if defined(__amd64__) || defined(__x86_64__) || defined(_M_X64)
#define CONF_ARCH_AMD64 1
#define CONF_ARCH_STRING "amd64"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_LITTLE 1
#endif
#define CONF_ARCH_AMD64 1
#define CONF_ARCH_STRING "amd64"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_LITTLE 1
#endif
#endif
#if defined(__powerpc__) || defined(__ppc__)
#define CONF_ARCH_PPC 1
#define CONF_ARCH_STRING "ppc"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_BIG 1
#endif
#define CONF_ARCH_PPC 1
#define CONF_ARCH_STRING "ppc"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_BIG 1
#endif
#endif
#if defined(__sparc__)
#define CONF_ARCH_SPARC 1
#define CONF_ARCH_STRING "sparc"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_BIG 1
#endif
#define CONF_ARCH_SPARC 1
#define CONF_ARCH_STRING "sparc"
#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
#define CONF_ARCH_ENDIAN_BIG 1
#endif
#endif
#if defined(__ARMEB__)
#define CONF_ARCH_ARM 1
#define CONF_ARCH_STRING "arm"
#define CONF_ARCH_ENDIAN_BIG 1
#define CONF_ARCH_ARM 1
#define CONF_ARCH_STRING "arm"
#define CONF_ARCH_ENDIAN_BIG 1
#endif
#if defined(__ARMEL__)
#define CONF_ARCH_ARM 1
#define CONF_ARCH_STRING "arm"
#define CONF_ARCH_ENDIAN_LITTLE 1
#define CONF_ARCH_ARM 1
#define CONF_ARCH_STRING "arm"
#define CONF_ARCH_ENDIAN_LITTLE 1
#endif
#ifndef CONF_FAMILY_STRING

View file

@ -11,5 +11,4 @@
#define DYNAMIC_IMPORT
#endif
#endif // BASE_DYNAMIC_H

View file

@ -9,10 +9,10 @@ extern "C" {
enum
{
SHA256_DIGEST_LENGTH=256/8,
SHA256_MAXSTRSIZE=2*SHA256_DIGEST_LENGTH+1,
MD5_DIGEST_LENGTH=128/8,
MD5_MAXSTRSIZE=2*MD5_DIGEST_LENGTH+1,
SHA256_DIGEST_LENGTH = 256 / 8,
SHA256_MAXSTRSIZE = 2 * SHA256_DIGEST_LENGTH + 1,
MD5_DIGEST_LENGTH = 128 / 8,
MD5_MAXSTRSIZE = 2 * MD5_DIGEST_LENGTH + 1,
};
typedef struct

View file

@ -6,14 +6,14 @@
void md5_update(MD5_CTX *ctxt, const void *data, size_t data_len)
{
md5_append(ctxt, data, data_len);
md5_append(ctxt, data, data_len);
}
MD5_DIGEST md5_finish(MD5_CTX *ctxt)
{
MD5_DIGEST result;
md5_finish_(ctxt, result.data);
return result;
MD5_DIGEST result;
md5_finish_(ctxt, result.data);
return result;
}
#endif

View file

@ -21,10 +21,10 @@ extern "C" {
#else
typedef struct
{
uint64 length;
uint32_t state[8];
uint32_t curlen;
unsigned char buf[64];
uint64 length;
uint32_t state[8];
uint32_t curlen;
unsigned char buf[64];
} SHA256_CTX;
typedef md5_state_t MD5_CTX;
#endif

264
src/base/hash_libtomcrypt.c Executable file → Normal file
View file

@ -14,189 +14,195 @@ typedef uint64_t u64;
typedef SHA256_CTX sha256_state;
static const u32 K[64] =
{
0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
{
0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL};
static u32 minimum(u32 x, u32 y)
{
return x < y ? x : y;
return x < y ? x : y;
}
static u32 load32(const unsigned char* y)
static u32 load32(const unsigned char *y)
{
return ((u32)y[0] << 24) | ((u32)y[1] << 16) | ((u32)y[2] << 8) | ((u32)y[3] << 0);
return ((u32)y[0] << 24) | ((u32)y[1] << 16) | ((u32)y[2] << 8) | ((u32)y[3] << 0);
}
static void store64(u64 x, unsigned char* y)
static void store64(u64 x, unsigned char *y)
{
int i;
for(i = 0; i != 8; ++i)
y[i] = (x >> ((7-i) * 8)) & 255;
int i;
for(i = 0; i != 8; ++i)
y[i] = (x >> ((7 - i) * 8)) & 255;
}
static void store32(u32 x, unsigned char* y)
static void store32(u32 x, unsigned char *y)
{
int i;
for(i = 0; i != 4; ++i)
y[i] = (x >> ((3-i) * 8)) & 255;
int i;
for(i = 0; i != 4; ++i)
y[i] = (x >> ((3 - i) * 8)) & 255;
}
static u32 Ch(u32 x, u32 y, u32 z) { return z ^ (x & (y ^ z)); }
static u32 Ch(u32 x, u32 y, u32 z) { return z ^ (x & (y ^ z)); }
static u32 Maj(u32 x, u32 y, u32 z) { return ((x | y) & z) | (x & y); }
static u32 Rot(u32 x, u32 n) { return (x >> (n & 31)) | (x << (32 - (n & 31))); }
static u32 Sh(u32 x, u32 n) { return x >> n; }
static u32 Sigma0(u32 x) { return Rot(x, 2) ^ Rot(x, 13) ^ Rot(x, 22); }
static u32 Sigma1(u32 x) { return Rot(x, 6) ^ Rot(x, 11) ^ Rot(x, 25); }
static u32 Gamma0(u32 x) { return Rot(x, 7) ^ Rot(x, 18) ^ Sh(x, 3); }
static u32 Gamma1(u32 x) { return Rot(x, 17) ^ Rot(x, 19) ^ Sh(x, 10); }
static u32 Rot(u32 x, u32 n) { return (x >> (n & 31)) | (x << (32 - (n & 31))); }
static u32 Sh(u32 x, u32 n) { return x >> n; }
static u32 Sigma0(u32 x) { return Rot(x, 2) ^ Rot(x, 13) ^ Rot(x, 22); }
static u32 Sigma1(u32 x) { return Rot(x, 6) ^ Rot(x, 11) ^ Rot(x, 25); }
static u32 Gamma0(u32 x) { return Rot(x, 7) ^ Rot(x, 18) ^ Sh(x, 3); }
static u32 Gamma1(u32 x) { return Rot(x, 17) ^ Rot(x, 19) ^ Sh(x, 10); }
static void sha_compress(sha256_state* md, const unsigned char* buf)
static void sha_compress(sha256_state *md, const unsigned char *buf)
{
u32 S[8], W[64], t0, t1, t;
int i;
u32 S[8], W[64], t0, t1, t;
int i;
// Copy state into S
for(i = 0; i < 8; i++)
S[i] = md->state[i];
// Copy state into S
for(i = 0; i < 8; i++)
S[i] = md->state[i];
// Copy the state into 512-bits into W[0..15]
for(i = 0; i < 16; i++)
W[i] = load32(buf + (4*i));
// Copy the state into 512-bits into W[0..15]
for(i = 0; i < 16; i++)
W[i] = load32(buf + (4 * i));
// Fill W[16..63]
for(i = 16; i < 64; i++)
W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
// Fill W[16..63]
for(i = 16; i < 64; i++)
W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
// Compress
#define RND(a, b, c, d, e, f, g, h, i) \
{ \
t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
t1 = Sigma0(a) + Maj(a, b, c); \
d += t0; \
h = t0 + t1; \
}
// Compress
#define RND(a, b, c, d, e, f, g, h, i) \
{ \
t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \
t1 = Sigma0(a) + Maj(a, b, c); \
d += t0; \
h = t0 + t1; \
}
for(i = 0; i < 64; ++i)
{
RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);
t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4];
S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;
}
for(i = 0; i < 64; ++i)
{
RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i);
t = S[7];
S[7] = S[6];
S[6] = S[5];
S[5] = S[4];
S[4] = S[3];
S[3] = S[2];
S[2] = S[1];
S[1] = S[0];
S[0] = t;
}
// Feedback
for(i = 0; i < 8; i++)
md->state[i] = md->state[i] + S[i];
// Feedback
for(i = 0; i < 8; i++)
md->state[i] = md->state[i] + S[i];
}
// Public interface
static void sha_init(sha256_state* md)
static void sha_init(sha256_state *md)
{
md->curlen = 0;
md->length = 0;
md->state[0] = 0x6A09E667UL;
md->state[1] = 0xBB67AE85UL;
md->state[2] = 0x3C6EF372UL;
md->state[3] = 0xA54FF53AUL;
md->state[4] = 0x510E527FUL;
md->state[5] = 0x9B05688CUL;
md->state[6] = 0x1F83D9ABUL;
md->state[7] = 0x5BE0CD19UL;
md->curlen = 0;
md->length = 0;
md->state[0] = 0x6A09E667UL;
md->state[1] = 0xBB67AE85UL;
md->state[2] = 0x3C6EF372UL;
md->state[3] = 0xA54FF53AUL;
md->state[4] = 0x510E527FUL;
md->state[5] = 0x9B05688CUL;
md->state[6] = 0x1F83D9ABUL;
md->state[7] = 0x5BE0CD19UL;
}
static void sha_process(sha256_state* md, const void* src, u32 inlen)
static void sha_process(sha256_state *md, const void *src, u32 inlen)
{
const u32 block_size = 64;
const unsigned char* in = src;
const u32 block_size = 64;
const unsigned char *in = src;
while(inlen > 0)
{
if(md->curlen == 0 && inlen >= block_size)
{
sha_compress(md, in);
md->length += block_size * 8;
in += block_size;
inlen -= block_size;
}
else
{
u32 n = minimum(inlen, (block_size - md->curlen));
memcpy(md->buf + md->curlen, in, n);
md->curlen += n;
in += n;
inlen -= n;
while(inlen > 0)
{
if(md->curlen == 0 && inlen >= block_size)
{
sha_compress(md, in);
md->length += block_size * 8;
in += block_size;
inlen -= block_size;
}
else
{
u32 n = minimum(inlen, (block_size - md->curlen));
memcpy(md->buf + md->curlen, in, n);
md->curlen += n;
in += n;
inlen -= n;
if(md->curlen == block_size)
{
sha_compress(md, md->buf);
md->length += 8*block_size;
md->curlen = 0;
}
}
}
if(md->curlen == block_size)
{
sha_compress(md, md->buf);
md->length += 8 * block_size;
md->curlen = 0;
}
}
}
}
static void sha_done(sha256_state* md, void* out)
static void sha_done(sha256_state *md, void *out)
{
int i;
int i;
// Increase the length of the message
md->length += md->curlen * 8;
// Increase the length of the message
md->length += md->curlen * 8;
// Append the '1' bit
md->buf[md->curlen++] = (unsigned char)0x80;
// Append the '1' bit
md->buf[md->curlen++] = (unsigned char)0x80;
// If the length is currently above 56 bytes we append zeros then compress.
// Then we can fall back to padding zeros and length encoding like normal.
if(md->curlen > 56)
{
while(md->curlen < 64)
md->buf[md->curlen++] = 0;
sha_compress(md, md->buf);
md->curlen = 0;
}
// If the length is currently above 56 bytes we append zeros then compress.
// Then we can fall back to padding zeros and length encoding like normal.
if(md->curlen > 56)
{
while(md->curlen < 64)
md->buf[md->curlen++] = 0;
sha_compress(md, md->buf);
md->curlen = 0;
}
// Pad up to 56 bytes of zeroes
while(md->curlen < 56)
md->buf[md->curlen++] = 0;
// Pad up to 56 bytes of zeroes
while(md->curlen < 56)
md->buf[md->curlen++] = 0;
// Store length
store64(md->length, md->buf+56);
sha_compress(md, md->buf);
// Store length
store64(md->length, md->buf + 56);
sha_compress(md, md->buf);
// Copy output
for(i = 0; i < 8; i++)
store32(md->state[i], (unsigned char *)out+(4*i));
// Copy output
for(i = 0; i < 8; i++)
store32(md->state[i], (unsigned char *)out + (4 * i));
}
void sha256_init(SHA256_CTX *ctxt)
{
sha_init(ctxt);
sha_init(ctxt);
}
void sha256_update(SHA256_CTX *ctxt, const void *data, size_t data_len)
{
sha_process(ctxt, data, data_len);
sha_process(ctxt, data, data_len);
}
SHA256_DIGEST sha256_finish(SHA256_CTX *ctxt)
{
SHA256_DIGEST result;
sha_done(ctxt, result.data);
return result;
SHA256_DIGEST result;
sha_done(ctxt, result.data);
return result;
}
#endif

View file

@ -6,7 +6,7 @@
#include <math.h>
#include <stdlib.h>
template <typename T>
template<typename T>
constexpr inline T clamp(T val, T min, T max)
{
return val < min ? min : (val > max ? max : val);
@ -14,7 +14,7 @@ constexpr inline T clamp(T val, T min, T max)
constexpr inline float sign(float f)
{
return f<0.0f?-1.0f:1.0f;
return f < 0.0f ? -1.0f : 1.0f;
}
constexpr inline int round_to_int(float f)
@ -35,14 +35,14 @@ inline int round_ceil(float f)
template<typename T, typename TB>
constexpr inline T mix(const T a, const T b, TB amount)
{
return a + (b-a)*amount;
return a + (b - a) * amount;
}
inline float frandom() { return rand()/(float)(RAND_MAX); }
inline float frandom() { return rand() / (float)(RAND_MAX); }
// float to fixed
constexpr inline int f2fx(float v) { return (int)(v*(float)(1<<10)); }
constexpr inline float fx2f(int v) { return v*(1.0f/(1<<10)); }
constexpr inline int f2fx(float v) { return (int)(v * (float)(1 << 10)); }
constexpr inline float fx2f(int v) { return v * (1.0f / (1 << 10)); }
// int to fixed
inline int i2fx(int v)
@ -68,23 +68,60 @@ inline int gcd(int a, int b)
class fxp
{
int value;
public:
void set(int v) { value = v; }
int get() const { return value; }
fxp &operator = (int v) { value = v<<10; return *this; }
fxp &operator = (float v) { value = (int)(v*(float)(1<<10)); return *this; }
operator float() const { return value/(float)(1<<10); }
fxp &operator=(int v)
{
value = v << 10;
return *this;
}
fxp &operator=(float v)
{
value = (int)(v * (float)(1 << 10));
return *this;
}
operator float() const { return value / (float)(1 << 10); }
};
constexpr float pi = 3.1415926535897932384626433f;
template <typename T> constexpr inline T minimum(T a, T b) { return a<b?a:b; }
template <typename T> constexpr inline T minimum(T a, T b, T c) { return minimum(minimum(a, b), c); }
template <typename T> constexpr inline T maximum(T a, T b) { return a>b?a:b; }
template <typename T> constexpr inline T maximum(T a, T b, T c) { return maximum(maximum(a, b), c); }
template <typename T> constexpr inline T absolute(T a) { return a<T(0)?-a:a; }
template<typename T>
constexpr inline T minimum(T a, T b)
{
return a < b ? a : b;
}
template<typename T>
constexpr inline T minimum(T a, T b, T c)
{
return minimum(minimum(a, b), c);
}
template<typename T>
constexpr inline T maximum(T a, T b)
{
return a > b ? a : b;
}
template<typename T>
constexpr inline T maximum(T a, T b, T c)
{
return maximum(maximum(a, b), c);
}
template<typename T>
constexpr inline T absolute(T a)
{
return a < T(0) ? -a : a;
}
template <typename T> constexpr inline T in_range(T a, T lower, T upper) { return lower <= a && a <= upper; }
template <typename T> constexpr inline T in_range(T a, T upper) { return in_range(a, 0, upper); }
template<typename T>
constexpr inline T in_range(T a, T lower, T upper)
{
return lower <= a && a <= upper;
}
template<typename T>
constexpr inline T in_range(T a, T upper)
{
return in_range(a, 0, upper);
}
#endif // BASE_MATH_H

File diff suppressed because it is too large Load diff

View file

@ -23,8 +23,8 @@
#endif
#ifdef CONF_PLATFORM_LINUX
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/socket.h>
#endif
#ifdef __cplusplus
@ -47,17 +47,16 @@ extern "C" {
<dbg_break>
*/
#ifdef CONF_DEBUG
#define dbg_assert(test,msg) dbg_assert_imp(__FILE__, __LINE__, test, msg)
#define dbg_assert(test, msg) dbg_assert_imp(__FILE__, __LINE__, test, msg)
#else
#define dbg_assert(test,msg)
#define dbg_assert(test, msg)
#endif
void dbg_assert_imp(const char *filename, int line, int test, const char *msg);
#ifdef __clang_analyzer__
#include <assert.h>
#undef dbg_assert
#define dbg_assert(test,msg) assert(test)
#define dbg_assert(test, msg) assert(test)
#endif
#ifdef __GNUC__
@ -99,7 +98,7 @@ void dbg_break_imp(void);
<dbg_assert>
*/
void dbg_msg(const char *sys, const char *fmt, ...)
GNUC_ATTRIBUTE((format(printf, 2, 3)));
GNUC_ATTRIBUTE((format(printf, 2, 3)));
/* Group: Memory */
@ -166,7 +165,8 @@ void mem_zero(void *block, unsigned size);
int mem_comp(const void *a, const void *b, int size);
/* Group: File IO */
enum {
enum
{
IOFLAG_READ = 1,
IOFLAG_WRITE = 2,
IOFLAG_RANDOM = 4,
@ -321,7 +321,6 @@ int io_flush(IOHANDLE io);
*/
int io_error(IOHANDLE io);
/*
Function: io_stdin
Returns an <IOHANDLE> to the standard input.
@ -532,7 +531,7 @@ void thread_detach(void *thread);
void *thread_init_and_detach(void (*threadfunc)(void *), void *user, const char *name);
/* Group: Locks */
typedef void* LOCK;
typedef void *LOCK;
LOCK lock_create(void);
void lock_destroy(LOCK lock);
@ -541,18 +540,17 @@ int lock_trylock(LOCK lock);
void lock_wait(LOCK lock);
void lock_unlock(LOCK lock);
/* Group: Semaphores */
#if defined(CONF_FAMILY_WINDOWS)
typedef void* SEMAPHORE;
typedef void *SEMAPHORE;
#elif defined(CONF_PLATFORM_MACOSX)
#include <semaphore.h>
typedef sem_t* SEMAPHORE;
#include <semaphore.h>
typedef sem_t *SEMAPHORE;
#elif defined(CONF_FAMILY_UNIX)
#include <semaphore.h>
typedef sem_t SEMAPHORE;
#include <semaphore.h>
typedef sem_t SEMAPHORE;
#else
#error not implemented on this platform
#error not implemented on this platform
#endif
void sphore_init(SEMAPHORE *sem);
@ -663,14 +661,14 @@ typedef struct
enum
{
NETADDR_MAXSTRSIZE = 1+(8*4+7)+1+1+5+1, // [XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]:XXXXX
NETADDR_MAXSTRSIZE = 1 + (8 * 4 + 7) + 1 + 1 + 5 + 1, // [XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]:XXXXX
NETTYPE_INVALID = 0,
NETTYPE_IPV4 = 1,
NETTYPE_IPV6 = 2,
NETTYPE_LINK_BROADCAST = 4,
NETTYPE_WEBSOCKET_IPV4 = 8,
NETTYPE_ALL = NETTYPE_IPV4|NETTYPE_IPV6|NETTYPE_WEBSOCKET_IPV4
NETTYPE_ALL = NETTYPE_IPV4 | NETTYPE_IPV6 | NETTYPE_WEBSOCKET_IPV4
};
typedef struct
@ -813,7 +811,7 @@ typedef struct
#endif
} MMSGS;
void net_init_mmsgs(MMSGS* m);
void net_init_mmsgs(MMSGS *m);
/*
Function: net_udp_recv
@ -830,7 +828,7 @@ void net_init_mmsgs(MMSGS* m);
On success it returns the number of bytes received. Returns -1
on error.
*/
int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS* m, unsigned char **data);
int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS *m, unsigned char **data);
/*
Function: net_udp_close
@ -844,7 +842,6 @@ int net_udp_recv(NETSOCKET sock, NETADDR *addr, void *buffer, int maxsize, MMSGS
*/
int net_udp_close(NETSOCKET sock);
/* Group: Network TCP */
/*
@ -1086,7 +1083,7 @@ int str_length(const char *str);
- Guarantees that dst string will contain zero-termination.
*/
int str_format(char *buffer, int buffer_size, const char *format, ...)
GNUC_ATTRIBUTE((format(printf, 3, 4)));
GNUC_ATTRIBUTE((format(printf, 3, 4)));
/*
Function: str_trim_words
@ -1495,9 +1492,9 @@ int str_hex_decode(void *dst, int dst_size, const char *src);
*/
void str_timestamp(char *buffer, int buffer_size);
void str_timestamp_format(char *buffer, int buffer_size, const char *format)
GNUC_ATTRIBUTE((format(strftime, 3, 0)));
GNUC_ATTRIBUTE((format(strftime, 3, 0)));
void str_timestamp_ex(time_t time, char *buffer, int buffer_size, const char *format)
GNUC_ATTRIBUTE((format(strftime, 4, 0)));
GNUC_ATTRIBUTE((format(strftime, 4, 0)));
#define FORMAT_TIME "%H:%M:%S"
#define FORMAT_SPACE "%Y-%m-%d %H:%M:%S"
@ -1660,7 +1657,6 @@ int fs_rename(const char *oldname, const char *newname);
Group: Undocumented
*/
/*
Function: net_tcp_connect_non_blocking
@ -1715,7 +1711,6 @@ int open_link(const char *link);
void swap_endian(void *data, unsigned elem_size, unsigned num);
typedef void (*DBG_LOGGER)(const char *line, void *user);
typedef void (*DBG_LOGGER_FINISH)(void *user);
void dbg_logger(DBG_LOGGER logger, DBG_LOGGER_FINISH finish, void *user);
@ -1732,7 +1727,6 @@ typedef struct
int recv_bytes;
} NETSTATS;
void net_stats(NETSTATS *stats);
int str_toint(const char *str);

View file

@ -6,7 +6,6 @@
#include "base/tl/range.h"
#include <functional>
/*
insert 4
v
@ -14,7 +13,6 @@
*/
template<class R, class T>
R partition_linear(R range, T value)
{
@ -30,7 +28,6 @@ R partition_linear(R range, T value)
return range;
}
template<class R, class T>
R partition_binary(R range, T value)
{
@ -47,11 +44,11 @@ R partition_binary(R range, T value)
while(range.size() > 1)
{
unsigned pivot = (range.size()-1)/2;
unsigned pivot = (range.size() - 1) / 2;
if(range.index(pivot) < value)
range = range.slice(pivot+1, range.size()-1);
range = range.slice(pivot + 1, range.size() - 1);
else
range = range.slice(0, pivot+1);
range = range.slice(0, pivot + 1);
}
return range;
}
@ -71,12 +68,13 @@ template<class R, class T>
R find_binary(R range, T value)
{
range = partition_linear(range, value);
if(range.empty()) return range;
if(range.front() == value) return range;
if(range.empty())
return range;
if(range.front() == value)
return range;
return R();
}
template<class R>
void sort_bubble(R range)
{
@ -107,14 +105,12 @@ void sort_quick(R range)
concept_index::check(range);
}*/
template<class R>
void sort(R range)
{
sort_bubble(range);
}
template<class R>
bool sort_verify(R range)
{

View file

@ -3,15 +3,15 @@
#ifndef BASE_TL_ALLOCATOR_H
#define BASE_TL_ALLOCATOR_H
template <class T>
template<class T>
class allocator_default
{
public:
static T *alloc() { return new T; }
static void free(T *p) { delete p; }
static T *alloc_array(int size) { return new T [size]; }
static void free_array(T *p) { delete [] p; }
static T *alloc_array(int size) { return new T[size]; }
static void free_array(T *p) { delete[] p; }
};
#endif // TL_FILE_ALLOCATOR_HPP

View file

@ -3,9 +3,8 @@
#ifndef BASE_TL_ARRAY_H
#define BASE_TL_ARRAY_H
#include "base/tl/range.h"
#include "base/tl/allocator.h"
#include "base/tl/range.h"
/*
Class: array
@ -16,7 +15,7 @@
- Use set_size() if you know how many elements
- Use optimize() to reduce the needed space.
*/
template <class T, class ALLOCATOR = allocator_default<T> >
template<class T, class ALLOCATOR = allocator_default<T>>
class array : private ALLOCATOR
{
void init()
@ -47,7 +46,6 @@ public:
(*this)[i] = other[i];
}
/*
Function: array destructor
*/
@ -57,7 +55,6 @@ public:
list = 0x0;
}
/*
Function: delete_all
@ -71,7 +68,6 @@ public:
clear();
}
/*
Function: clear
@ -102,8 +98,8 @@ public:
*/
void remove_index_fast(int index)
{
list[index] = list[num_elements-1];
set_size(size()-1);
list[index] = list[num_elements - 1];
set_size(size() - 1);
}
/*
@ -112,7 +108,7 @@ public:
Remarks:
- Invalidates ranges
*/
void remove_fast(const T& item)
void remove_fast(const T &item)
{
for(int i = 0; i < size(); i++)
if(list[i] == item)
@ -130,10 +126,10 @@ public:
*/
void remove_index(int index)
{
for(int i = index+1; i < num_elements; i++)
list[i-1] = list[i];
for(int i = index + 1; i < num_elements; i++)
list[i - 1] = list[i];
set_size(size()-1);
set_size(size() - 1);
}
/*
@ -142,7 +138,7 @@ public:
Remarks:
- Invalidates ranges
*/
bool remove(const T& item)
bool remove(const T &item)
{
for(int i = 0; i < size(); i++)
if(list[i] == item)
@ -164,12 +160,12 @@ public:
- Invalidates ranges
- See remarks about <array> how the array grows.
*/
int add(const T& item)
int add(const T &item)
{
incsize();
set_size(size()+1);
list[num_elements-1] = item;
return num_elements-1;
set_size(size() + 1);
list[num_elements - 1] = item;
return num_elements - 1;
}
/*
@ -184,27 +180,27 @@ public:
- Invalidates ranges
- See remarks about <array> how the array grows.
*/
int insert(const T& item, range r)
int insert(const T &item, range r)
{
if(r.empty())
return add(item);
int index = (int)(&r.front()-list);
int index = (int)(&r.front() - list);
incsize();
set_size(size()+1);
set_size(size() + 1);
for(int i = num_elements-1; i > index; i--)
list[i] = list[i-1];
for(int i = num_elements - 1; i > index; i--)
list[i] = list[i - 1];
list[index] = item;
return num_elements-1;
return num_elements - 1;
}
/*
Function: operator[]
*/
T& operator[] (int index)
T &operator[](int index)
{
return list[index];
}
@ -212,7 +208,7 @@ public:
/*
Function: const operator[]
*/
const T& operator[] (int index) const
const T &operator[](int index) const
{
return list[index];
}
@ -242,7 +238,7 @@ public:
*/
void set_size(int new_size)
{
if(list_size < new_size)
if(list_size < new_size)
alloc(new_size);
num_elements = new_size;
}
@ -265,7 +261,6 @@ public:
alloc(hint);
}
/*
Function: optimize
Removes unnecessary data, returns how many bytes was earned.
@ -286,7 +281,7 @@ public:
*/
int memusage()
{
return sizeof(array) + sizeof(T)*list_size;
return sizeof(array) + sizeof(T) * list_size;
}
/*
@ -295,7 +290,7 @@ public:
Remarks:
- Invalidates ranges
*/
array &operator = (const array &other)
array &operator=(const array &other)
{
set_size(other.size());
for(int i = 0; i < size(); i++)
@ -307,17 +302,17 @@ public:
Function: all
Returns a range that contains the whole array.
*/
range all() { return range(list, list+num_elements); }
protected:
range all() { return range(list, list + num_elements); }
protected:
void incsize()
{
if(num_elements == list_size)
{
if(list_size < 2)
alloc(list_size+1);
alloc(list_size + 1);
else
alloc(list_size+list_size/2);
alloc(list_size + list_size / 2);
}
}

View file

@ -3,8 +3,8 @@
#ifndef BASE_TL_BASE_H
#define BASE_TL_BASE_H
#include <base/system.h>
#include <algorithm>
#include <base/system.h>
#include <utility>
using std::swap;

View file

@ -20,7 +20,12 @@
*/
struct concept_empty
{
template<typename T> static void check(T &t) { if(0) t.empty(); }
template<typename T>
static void check(T &t)
{
if(0)
t.empty();
}
};
/*
@ -34,7 +39,12 @@ struct concept_empty
*/
struct concept_index
{
template<typename T> static void check(T &t) { if(0) t.index(0); }
template<typename T>
static void check(T &t)
{
if(0)
t.index(0);
}
};
/*
@ -48,7 +58,12 @@ struct concept_index
*/
struct concept_size
{
template<typename T> static void check(T &t) { if(0) t.size(); }
template<typename T>
static void check(T &t)
{
if(0)
t.size();
}
};
/*
@ -62,7 +77,12 @@ struct concept_size
*/
struct concept_slice
{
template<typename T> static void check(T &t) { if(0) t.slice(0, 0); }
template<typename T>
static void check(T &t)
{
if(0)
t.slice(0, 0);
}
};
/*
@ -76,7 +96,12 @@ struct concept_slice
*/
struct concept_sorted
{
template<typename T> static void check(T &t) { if(0) t.sorted(); }
template<typename T>
static void check(T &t)
{
if(0)
t.sorted();
}
};
/*
@ -92,7 +117,15 @@ struct concept_sorted
*/
struct concept_forwarditeration
{
template<typename T> static void check(T &t) { if(0) { t.front(); t.pop_front(); } }
template<typename T>
static void check(T &t)
{
if(0)
{
t.front();
t.pop_front();
}
}
};
/*
@ -108,15 +141,21 @@ struct concept_forwarditeration
*/
struct concept_backwarditeration
{
template<typename T> static void check(T &t) { if(0) { t.back(); t.pop_back(); } }
template<typename T>
static void check(T &t)
{
if(0)
{
t.back();
t.pop_back();
}
}
};
/*
Group: Range classes
*/
/*
Class: plain_range
@ -145,15 +184,35 @@ public:
}
bool empty() const { return begin >= end; }
void pop_front() { tl_assert(!empty()); begin++; }
void pop_back() { tl_assert(!empty()); end--; }
T& front() { tl_assert(!empty()); return *begin; }
T& back() { tl_assert(!empty()); return *(end-1); }
T& index(unsigned i) { tl_assert(i < (unsigned)(end-begin)); return begin[i]; }
unsigned size() const { return (unsigned)(end-begin); }
void pop_front()
{
tl_assert(!empty());
begin++;
}
void pop_back()
{
tl_assert(!empty());
end--;
}
T &front()
{
tl_assert(!empty());
return *begin;
}
T &back()
{
tl_assert(!empty());
return *(end - 1);
}
T &index(unsigned i)
{
tl_assert(i < (unsigned)(end - begin));
return begin[i];
}
unsigned size() const { return (unsigned)(end - begin); }
plain_range slice(unsigned startindex, unsigned endindex)
{
return plain_range(begin+startindex, begin+endindex);
return plain_range(begin + startindex, begin + endindex);
}
protected:
@ -172,20 +231,23 @@ template<class T>
class plain_range_sorted : public plain_range<T>
{
typedef plain_range<T> parent;
public:
/* sorted concept */
void sorted() const { }
void sorted() const {}
plain_range_sorted()
{}
{
}
plain_range_sorted(T *b, T *e)
: parent(b, e)
{}
plain_range_sorted(T *b, T *e) :
parent(b, e)
{
}
plain_range_sorted slice(unsigned start, unsigned count)
{
return plain_range_sorted(parent::begin+start, parent::begin+start+count);
return plain_range_sorted(parent::begin + start, parent::begin + start + count);
}
};
@ -194,6 +256,7 @@ class reverse_range
{
private:
reverse_range() {}
public:
typedef typename R::type type;
@ -204,20 +267,23 @@ public:
reverse_range(const reverse_range &other) { range = other.range; }
bool empty() const { return range.empty(); }
void pop_front() { range.pop_back(); }
void pop_back() { range.pop_front(); }
type& front() { return range.back(); }
type& back() { return range.front(); }
type &front() { return range.back(); }
type &back() { return range.front(); }
R range;
};
template<class R> reverse_range<R> reverse(R range) {
template<class R>
reverse_range<R> reverse(R range)
{
return reverse_range<R>(range);
}
template<class R> R reverse(reverse_range<R> range) {
template<class R>
R reverse(reverse_range<R> range)
{
return range.range;
}

View file

@ -6,24 +6,32 @@
#include "base/tl/algorithm.h"
#include "base/tl/array.h"
template <class T, class ALLOCATOR = allocator_default<T> >
template<class T, class ALLOCATOR = allocator_default<T>>
class sorted_array : public array<T, ALLOCATOR>
{
typedef array<T, ALLOCATOR> parent;
// insert and size is not allowed
int insert(const T& item, typename parent::range r) { dbg_break(); return 0; }
int set_size(int new_size) { dbg_break(); return 0; }
int insert(const T &item, typename parent::range r)
{
dbg_break();
return 0;
}
int set_size(int new_size)
{
dbg_break();
return 0;
}
public:
typedef plain_range_sorted<T> range;
int add(const T& item)
int add(const T &item)
{
return parent::insert(item, partition_binary(all(), item));
}
int add_unsorted(const T& item)
int add_unsorted(const T &item)
{
return parent::add(item);
}
@ -33,12 +41,11 @@ public:
sort(all());
}
/*
Function: all
Returns a sorted range that contains the whole array.
*/
range all() { return range(parent::list, parent::list+parent::num_elements); }
range all() { return range(parent::list, parent::list + parent::num_elements); }
};
#endif // TL_FILE_SORTED_ARRAY_HPP

View file

@ -3,10 +3,10 @@
#ifndef BASE_TL_STRING_H
#define BASE_TL_STRING_H
#include "base/tl/base.h"
#include "base/tl/allocator.h"
#include "base/tl/base.h"
template<class ALLOCATOR >
template<class ALLOCATOR>
class string_base : private ALLOCATOR
{
char *str;
@ -14,7 +14,8 @@ class string_base : private ALLOCATOR
void reset()
{
str = 0; length = 0;
str = 0;
length = 0;
}
void free()
@ -26,8 +27,8 @@ class string_base : private ALLOCATOR
void copy(const char *other_str, int other_length)
{
length = other_length;
str = ALLOCATOR::alloc_array(length+1);
mem_copy(str, other_str, length+1);
str = ALLOCATOR::alloc_array(length + 1);
mem_copy(str, other_str, length + 1);
}
void copy(const string_base &other)
@ -40,10 +41,14 @@ class string_base : private ALLOCATOR
public:
string_base() { reset(); }
string_base(const char *other_str) { copy(other_str, str_length(other_str)); }
string_base(const string_base &other) { reset(); copy(other); }
string_base(const string_base &other)
{
reset();
copy(other);
}
~string_base() { free(); }
string_base &operator = (const char *other)
string_base &operator=(const char *other)
{
free();
if(other)
@ -51,20 +56,20 @@ public:
return *this;
}
string_base &operator = (const string_base &other)
string_base &operator=(const string_base &other)
{
free();
copy(other);
return *this;
}
bool operator < (const char *other_str) const { return str_comp(str, other_str) < 0; }
bool operator<(const char *other_str) const { return str_comp(str, other_str) < 0; }
operator const char *() const { return str; }
const char *cstr() const { return str; }
};
/* normal allocated string */
typedef string_base<allocator_default<char> > string;
typedef string_base<allocator_default<char>> string;
#endif // TL_FILE_STRING_HPP

View file

@ -6,10 +6,11 @@
class semaphore
{
SEMAPHORE sem;
public:
semaphore() { sphore_init(&sem); }
~semaphore() { sphore_destroy(&sem); }
semaphore(const semaphore&) = delete;
semaphore(const semaphore &) = delete;
void wait() { sphore_wait(&sem); }
void signal() { sphore_signal(&sem); }
};
@ -29,7 +30,7 @@ public:
lock_destroy(var);
}
lock(const lock&) = delete;
lock(const lock &) = delete;
void take() { lock_wait(var); }
void release() { lock_unlock(var); }
@ -38,6 +39,7 @@ public:
class scope_lock
{
lock *var;
public:
scope_lock(lock *l)
{
@ -50,7 +52,7 @@ public:
var->release();
}
scope_lock(const scope_lock&) = delete;
scope_lock(const scope_lock &) = delete;
};
#endif // BASE_TL_THREADING_H

View file

@ -8,8 +8,8 @@ struct DECOMP_SLICE
enum
{
NUM_DECOMP_LENGTHS=8,
NUM_DECOMPS=9563,
NUM_DECOMP_LENGTHS = 8,
NUM_DECOMPS = 9563,
};
static const uint8_t decomp_lengths[NUM_DECOMP_LENGTHS] = {

View file

@ -4,19 +4,19 @@
static int compul(const void *a, const void *b)
{
struct UPPER_LOWER *ul_a = (struct UPPER_LOWER *) a;
struct UPPER_LOWER *ul_b = (struct UPPER_LOWER *) b;
return ul_a->upper - ul_b->upper;
struct UPPER_LOWER *ul_a = (struct UPPER_LOWER *)a;
struct UPPER_LOWER *ul_b = (struct UPPER_LOWER *)b;
return ul_a->upper - ul_b->upper;
}
int str_utf8_tolower(int code)
{
struct UPPER_LOWER key;
struct UPPER_LOWER *res;
key.upper = code;
res = bsearch(&key, tolower, NUM_TOLOWER, sizeof(struct UPPER_LOWER), compul);
struct UPPER_LOWER key;
struct UPPER_LOWER *res;
key.upper = code;
res = bsearch(&key, tolower, NUM_TOLOWER, sizeof(struct UPPER_LOWER), compul);
if(res == NULL)
return code;
return res->lower;
if(res == NULL)
return code;
return res->lower;
}

View file

@ -8,7 +8,7 @@ struct UPPER_LOWER
enum
{
NUM_TOLOWER=1390,
NUM_TOLOWER = 1390,
};
static const struct UPPER_LOWER tolower[] = {

View file

@ -13,8 +13,14 @@ template<typename T>
class vector2_base
{
public:
union { T x,u; };
union { T y,v; };
union
{
T x, u;
};
union
{
T y, v;
};
vector2_base() {}
vector2_base(T nx, T ny)
@ -23,53 +29,82 @@ public:
y = ny;
}
vector2_base operator -() const { return vector2_base(-x, -y); }
vector2_base operator -(const vector2_base &v) const { return vector2_base(x-v.x, y-v.y); }
vector2_base operator +(const vector2_base &v) const { return vector2_base(x+v.x, y+v.y); }
vector2_base operator *(const T v) const { return vector2_base(x*v, y*v); }
vector2_base operator *(const vector2_base &v) const { return vector2_base(x*v.x, y*v.y); }
vector2_base operator /(const T v) const { return vector2_base(x/v, y/v); }
vector2_base operator /(const vector2_base &v) const { return vector2_base(x/v.x, y/v.y); }
vector2_base operator-() const { return vector2_base(-x, -y); }
vector2_base operator-(const vector2_base &v) const { return vector2_base(x - v.x, y - v.y); }
vector2_base operator+(const vector2_base &v) const { return vector2_base(x + v.x, y + v.y); }
vector2_base operator*(const T v) const { return vector2_base(x * v, y * v); }
vector2_base operator*(const vector2_base &v) const { return vector2_base(x * v.x, y * v.y); }
vector2_base operator/(const T v) const { return vector2_base(x / v, y / v); }
vector2_base operator/(const vector2_base &v) const { return vector2_base(x / v.x, y / v.y); }
const vector2_base &operator +=(const vector2_base &v) { x += v.x; y += v.y; return *this; }
const vector2_base &operator -=(const vector2_base &v) { x -= v.x; y -= v.y; return *this; }
const vector2_base &operator *=(const T v) { x *= v; y *= v; return *this; }
const vector2_base &operator *=(const vector2_base &v) { x *= v.x; y *= v.y; return *this; }
const vector2_base &operator /=(const T v) { x /= v; y /= v; return *this; }
const vector2_base &operator /=(const vector2_base &v) { x /= v.x; y /= v.y; return *this; }
const vector2_base &operator+=(const vector2_base &v)
{
x += v.x;
y += v.y;
return *this;
}
const vector2_base &operator-=(const vector2_base &v)
{
x -= v.x;
y -= v.y;
return *this;
}
const vector2_base &operator*=(const T v)
{
x *= v;
y *= v;
return *this;
}
const vector2_base &operator*=(const vector2_base &v)
{
x *= v.x;
y *= v.y;
return *this;
}
const vector2_base &operator/=(const T v)
{
x /= v;
y /= v;
return *this;
}
const vector2_base &operator/=(const vector2_base &v)
{
x /= v.x;
y /= v.y;
return *this;
}
bool operator ==(const vector2_base &v) const { return x == v.x && y == v.y; } //TODO: do this with an eps instead
bool operator !=(const vector2_base &v) const { return x != v.x || y != v.y; }
bool operator==(const vector2_base &v) const { return x == v.x && y == v.y; } //TODO: do this with an eps instead
bool operator!=(const vector2_base &v) const { return x != v.x || y != v.y; }
operator const T* () { return &x; }
operator const T *() { return &x; }
T &operator[](const int index) { return index ? y : x; }
};
template<typename T>
inline T length(const vector2_base<T> &a)
{
return sqrtf(a.x*a.x + a.y*a.y);
return sqrtf(a.x * a.x + a.y * a.y);
}
template<typename T>
inline T distance(const vector2_base<T> a, const vector2_base<T> &b)
{
return length(a-b);
return length(a - b);
}
template<typename T>
inline T dot(const vector2_base<T> a, const vector2_base<T> &b)
{
return a.x*b.x + a.y*b.y;
return a.x * b.x + a.y * b.y;
}
template<typename T>
inline vector2_base<T> normalize(const vector2_base<T> &v)
{
T l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y));
return vector2_base<T>(v.x*l, v.y*l);
T l = (T)(1.0f / sqrtf(v.x * v.x + v.y * v.y));
return vector2_base<T>(v.x * l, v.y * l);
}
typedef vector2_base<float> vec2;
@ -82,8 +117,8 @@ inline vector2_base<T> closest_point_on_line(vector2_base<T> line_point0, vector
vector2_base<T> c = target_point - line_point0;
vector2_base<T> v = (line_point1 - line_point0);
v = normalize(v);
T d = length(line_point0-line_point1);
T t = dot(v, c)/d;
T d = length(line_point0 - line_point1);
T t = dot(v, c) / d;
return mix(line_point0, line_point1, clamp(t, (T)0, (T)1));
/*
if (t < 0) t = 0;
@ -96,9 +131,18 @@ template<typename T>
class vector3_base
{
public:
union { T x,r,h; };
union { T y,g,s; };
union { T z,b,v,l; };
union
{
T x, r, h;
};
union
{
T y, g, s;
};
union
{
T z, b, v, l;
};
vector3_base() {}
vector3_base(T nx, T ny, T nz)
@ -108,30 +152,66 @@ public:
z = nz;
}
vector3_base operator -(const vector3_base &v) const { return vector3_base(x-v.x, y-v.y, z-v.z); }
vector3_base operator -() const { return vector3_base(-x, -y, -z); }
vector3_base operator +(const vector3_base &v) const { return vector3_base(x+v.x, y+v.y, z+v.z); }
vector3_base operator *(const T v) const { return vector3_base(x*v, y*v, z*v); }
vector3_base operator *(const vector3_base &v) const { return vector3_base(x*v.x, y*v.y, z*v.z); }
vector3_base operator /(const T v) const { return vector3_base(x/v, y/v, z/v); }
vector3_base operator /(const vector3_base &v) const { return vector3_base(x/v.x, y/v.y, z/v.z); }
vector3_base operator-(const vector3_base &v) const { return vector3_base(x - v.x, y - v.y, z - v.z); }
vector3_base operator-() const { return vector3_base(-x, -y, -z); }
vector3_base operator+(const vector3_base &v) const { return vector3_base(x + v.x, y + v.y, z + v.z); }
vector3_base operator*(const T v) const { return vector3_base(x * v, y * v, z * v); }
vector3_base operator*(const vector3_base &v) const { return vector3_base(x * v.x, y * v.y, z * v.z); }
vector3_base operator/(const T v) const { return vector3_base(x / v, y / v, z / v); }
vector3_base operator/(const vector3_base &v) const { return vector3_base(x / v.x, y / v.y, z / v.z); }
const vector3_base &operator +=(const vector3_base &v) { x += v.x; y += v.y; z += v.z; return *this; }
const vector3_base &operator -=(const vector3_base &v) { x -= v.x; y -= v.y; z -= v.z; return *this; }
const vector3_base &operator *=(const T v) { x *= v; y *= v; z *= v; return *this; }
const vector3_base &operator *=(const vector3_base &v) { x *= v.x; y *= v.y; z *= v.z; return *this; }
const vector3_base &operator /=(const T v) { x /= v; y /= v; z /= v; return *this; }
const vector3_base &operator /=(const vector3_base &v) { x /= v.x; y /= v.y; z /= v.z; return *this; }
const vector3_base &operator+=(const vector3_base &v)
{
x += v.x;
y += v.y;
z += v.z;
return *this;
}
const vector3_base &operator-=(const vector3_base &v)
{
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
const vector3_base &operator*=(const T v)
{
x *= v;
y *= v;
z *= v;
return *this;
}
const vector3_base &operator*=(const vector3_base &v)
{
x *= v.x;
y *= v.y;
z *= v.z;
return *this;
}
const vector3_base &operator/=(const T v)
{
x /= v;
y /= v;
z /= v;
return *this;
}
const vector3_base &operator/=(const vector3_base &v)
{
x /= v.x;
y /= v.y;
z /= v.z;
return *this;
}
bool operator ==(const vector3_base &v) const { return x == v.x && y == v.y && z == v.z; } //TODO: do this with an eps instead
bool operator==(const vector3_base &v) const { return x == v.x && y == v.y && z == v.z; } //TODO: do this with an eps instead
operator const T* () { return &x; }
operator const T *() { return &x; }
};
template<typename T>
inline T length(const vector3_base<T> &a)
{
return sqrtf(a.x*a.x + a.y*a.y + a.z*a.z);
return sqrtf(a.x * a.x + a.y * a.y + a.z * a.z);
}
template<typename T>
@ -146,29 +226,29 @@ inline vector2_base<T> rotate(const vector2_base<T> &a, float angle)
template<typename T>
inline T distance(const vector3_base<T> &a, const vector3_base<T> &b)
{
return length(a-b);
return length(a - b);
}
template<typename T>
inline T dot(const vector3_base<T> &a, const vector3_base<T> &b)
{
return a.x*b.x + a.y*b.y + a.z*b.z;
return a.x * b.x + a.y * b.y + a.z * b.z;
}
template<typename T>
inline vector3_base<T> normalize(const vector3_base<T> &v)
{
T l = (T)(1.0f/sqrtf(v.x*v.x + v.y*v.y + v.z*v.z));
return vector3_base<T>(v.x*l, v.y*l, v.z*l);
T l = (T)(1.0f / sqrtf(v.x * v.x + v.y * v.y + v.z * v.z));
return vector3_base<T>(v.x * l, v.y * l, v.z * l);
}
template<typename T>
inline vector3_base<T> cross(const vector3_base<T> &a, const vector3_base<T> &b)
{
return vector3_base<T>(
a.y*b.z - a.z*b.y,
a.z*b.x - a.x*b.z,
a.x*b.y - a.y*b.x);
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x);
}
typedef vector3_base<float> vec3;
@ -181,10 +261,22 @@ template<typename T>
class vector4_base
{
public:
union { T x,r,h; };
union { T y,g,s; };
union { T z,b,l; };
union { T w,a; };
union
{
T x, r, h;
};
union
{
T y, g, s;
};
union
{
T z, b, l;
};
union
{
T w, a;
};
vector4_base() {}
vector4_base(T nx, T ny, T nz, T nw)
@ -195,24 +287,66 @@ public:
w = nw;
}
vector4_base operator +(const vector4_base &v) const { return vector4_base(x+v.x, y+v.y, z+v.z, w+v.w); }
vector4_base operator -(const vector4_base &v) const { return vector4_base(x-v.x, y-v.y, z-v.z, w-v.w); }
vector4_base operator -() const { return vector4_base(-x, -y, -z, -w); }
vector4_base operator *(const vector4_base &v) const { return vector4_base(x*v.x, y*v.y, z*v.z, w*v.w); }
vector4_base operator *(const T v) const { return vector4_base(x*v, y*v, z*v, w*v); }
vector4_base operator /(const vector4_base &v) const { return vector4_base(x/v.x, y/v.y, z/v.z, w/v.w); }
vector4_base operator /(const T v) const { return vector4_base(x/v, y/v, z/v, w/v); }
vector4_base operator+(const vector4_base &v) const { return vector4_base(x + v.x, y + v.y, z + v.z, w + v.w); }
vector4_base operator-(const vector4_base &v) const { return vector4_base(x - v.x, y - v.y, z - v.z, w - v.w); }
vector4_base operator-() const { return vector4_base(-x, -y, -z, -w); }
vector4_base operator*(const vector4_base &v) const { return vector4_base(x * v.x, y * v.y, z * v.z, w * v.w); }
vector4_base operator*(const T v) const { return vector4_base(x * v, y * v, z * v, w * v); }
vector4_base operator/(const vector4_base &v) const { return vector4_base(x / v.x, y / v.y, z / v.z, w / v.w); }
vector4_base operator/(const T v) const { return vector4_base(x / v, y / v, z / v, w / v); }
const vector4_base &operator +=(const vector4_base &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; }
const vector4_base &operator -=(const vector4_base &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; }
const vector4_base &operator *=(const T v) { x *= v; y *= v; z *= v; w *= v; return *this; }
const vector4_base &operator *=(const vector4_base &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; }
const vector4_base &operator /=(const T v) { x /= v; y /= v; z /= v; w /= v; return *this; }
const vector4_base &operator /=(const vector4_base &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; }
const vector4_base &operator+=(const vector4_base &v)
{
x += v.x;
y += v.y;
z += v.z;
w += v.w;
return *this;
}
const vector4_base &operator-=(const vector4_base &v)
{
x -= v.x;
y -= v.y;
z -= v.z;
w -= v.w;
return *this;
}
const vector4_base &operator*=(const T v)
{
x *= v;
y *= v;
z *= v;
w *= v;
return *this;
}
const vector4_base &operator*=(const vector4_base &v)
{
x *= v.x;
y *= v.y;
z *= v.z;
w *= v.w;
return *this;
}
const vector4_base &operator/=(const T v)
{
x /= v;
y /= v;
z /= v;
w /= v;
return *this;
}
const vector4_base &operator/=(const vector4_base &v)
{
x /= v.x;
y /= v.y;
z /= v.z;
w /= v.w;
return *this;
}
bool operator ==(const vector4_base &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } //TODO: do this with an eps instead
bool operator==(const vector4_base &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } //TODO: do this with an eps instead
operator const T* () { return &x; }
operator const T *() { return &x; }
};
typedef vector4_base<float> vec4;

View file

@ -24,7 +24,7 @@ public:
// Commands
virtual void Dump() = 0;
virtual ~IAntibot() { };
virtual ~IAntibot(){};
};
class IEngineAntibot : public IAntibot
@ -39,7 +39,7 @@ public:
virtual void OnEngineClientDrop(int ClientID, const char *pReason) = 0;
virtual void OnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags) = 0;
virtual ~IEngineAntibot() { };
virtual ~IEngineAntibot(){};
};
#endif //ENGINE_ANTIBOT_H

View file

@ -4,17 +4,17 @@
#define ENGINE_CLIENT_H
#include "kernel.h"
#include "message.h"
#include "graphics.h"
#include "message.h"
#include <engine/friends.h>
enum
{
RECORDER_MANUAL=0,
RECORDER_AUTO=1,
RECORDER_RACE=2,
RECORDER_REPLAYS=3,
RECORDER_MAX=4,
RECORDER_MANUAL = 0,
RECORDER_AUTO = 1,
RECORDER_RACE = 2,
RECORDER_REPLAYS = 3,
RECORDER_MAX = 4,
};
typedef bool (*CLIENTFUNC_FILTER)(const void *pData, int DataSize, void *pUser);
@ -41,6 +41,7 @@ protected:
int m_GameTickSpeed;
float m_FrameTimeAvg;
public:
char m_aNews[3000];
int64 m_ReconnectTime;
@ -64,7 +65,7 @@ public:
enum
{
STATE_OFFLINE=0,
STATE_OFFLINE = 0,
STATE_CONNECTING,
STATE_LOADING,
STATE_ONLINE,
@ -103,9 +104,9 @@ public:
virtual void Restart() = 0;
virtual void Quit() = 0;
virtual const char *DemoPlayer_Play(const char *pFilename, int StorageType) = 0;
#if defined(CONF_VIDEORECORDER)
#if defined(CONF_VIDEORECORDER)
virtual const char *DemoPlayer_Render(const char *pFilename, int StorageType, const char *pVideoName, int SpeedIndex) = 0;
#endif
#endif
virtual void DemoRecorder_Start(const char *pFilename, bool WithTimestamp, int Recorder) = 0;
virtual void DemoRecorder_HandleAutoStart() = 0;
virtual void DemoRecorder_Stop(int Recorder, bool RemoveFile = false) = 0;
@ -150,8 +151,8 @@ public:
enum
{
SNAP_CURRENT=0,
SNAP_PREV=1
SNAP_CURRENT = 0,
SNAP_PREV = 1
};
// TODO: Refactor: should redo this a bit i think, too many virtual calls
@ -164,7 +165,7 @@ public:
virtual void SnapSetStaticsize(int ItemType, int Size) = 0;
virtual int SendMsg(CMsgPacker *pMsg, int Flags) = 0;
virtual int SendMsgY(CMsgPacker *pMsg, int Flags, int NetClient=1) = 0;
virtual int SendMsgY(CMsgPacker *pMsg, int Flags, int NetClient = 1) = 0;
template<class T>
int SendPackMsg(T *pMsg, int Flags)
@ -207,10 +208,9 @@ public:
virtual void GenerateTimeoutSeed() = 0;
virtual IFriends* Foes() = 0;
virtual IFriends *Foes() = 0;
virtual void GetSmoothTick(int *pSmoothTick, float *pSmoothIntraTick, float MixAmount) = 0;
};
class IGameClient : public IInterface

File diff suppressed because it is too large Load diff

View file

@ -2,37 +2,39 @@
#define ENGINE_CLIENT_BACKEND_SDL_H
#include "SDL.h"
#include "SDL_opengl.h"
#include "graphics_threaded.h"
#include <base/tl/threading.h>
#include <atomic>
# if defined(CONF_PLATFORM_MACOSX)
#include <objc/objc-runtime.h>
#if defined(CONF_PLATFORM_MACOSX)
#include <objc/objc-runtime.h>
class CAutoreleasePool
class CAutoreleasePool
{
private:
id m_Pool;
public:
CAutoreleasePool()
{
private:
id m_Pool;
Class NSAutoreleasePoolClass = (Class)objc_getClass("NSAutoreleasePool");
m_Pool = class_createInstance(NSAutoreleasePoolClass, 0);
SEL selector = sel_registerName("init");
((id(*)(id, SEL))objc_msgSend)(m_Pool, selector);
}
public:
CAutoreleasePool()
{
Class NSAutoreleasePoolClass = (Class) objc_getClass("NSAutoreleasePool");
m_Pool = class_createInstance(NSAutoreleasePoolClass, 0);
SEL selector = sel_registerName("init");
((id (*)(id, SEL))objc_msgSend)(m_Pool, selector);
}
~CAutoreleasePool()
{
SEL selector = sel_registerName("drain");
((id (*)(id, SEL))objc_msgSend)(m_Pool, selector);
}
};
~CAutoreleasePool()
{
SEL selector = sel_registerName("drain");
((id(*)(id, SEL))objc_msgSend)(m_Pool, selector);
}
};
#endif
// basic threaded backend, abstract, missing init and shutdown functions
class CGraphicsBackend_Threaded : public IGraphicsBackend
{
@ -57,7 +59,7 @@ protected:
private:
ICommandProcessor *m_pProcessor;
CCommandBuffer * volatile m_pBuffer;
CCommandBuffer *volatile m_pBuffer;
volatile bool m_Shutdown;
semaphore m_Activity;
semaphore m_BufferDone;
@ -71,10 +73,10 @@ class CCommandProcessorFragment_General
{
void Cmd_Nop();
void Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand);
public:
bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand);
};
public:
bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand);
};
struct SBackendCapabilites
{
@ -110,7 +112,8 @@ class CCommandProcessorFragment_OpenGL
protected:
struct CTexture
{
CTexture() : m_Tex(0), m_Tex2DArray(0), m_Sampler(0), m_Sampler2DArray(0) {}
CTexture() :
m_Tex(0), m_Tex2DArray(0), m_Sampler(0), m_Sampler2DArray(0) {}
GLuint m_Tex;
GLuint m_Tex2DArray; //or 3D texture as fallback
GLuint m_Sampler;
@ -140,6 +143,7 @@ protected:
bool m_HasShaders;
int m_LastBlendMode; //avoid all possible opengl state changes
bool m_LastClipEnable;
public:
enum
{
@ -149,7 +153,8 @@ public:
struct SCommand_Init : public CCommandBuffer::SCommand
{
SCommand_Init() : SCommand(CMD_INIT) {}
SCommand_Init() :
SCommand(CMD_INIT) {}
class IStorage *m_pStorage;
std::atomic<int> *m_pTextureMemoryUsage;
SBackendCapabilites *m_pCapabilities;
@ -158,7 +163,8 @@ public:
struct SCommand_Shutdown : public CCommandBuffer::SCommand
{
SCommand_Shutdown() : SCommand(CMD_SHUTDOWN) {}
SCommand_Shutdown() :
SCommand(CMD_SHUTDOWN) {}
};
protected:
@ -190,7 +196,7 @@ protected:
virtual void Cmd_UpdateBufferContainer(const CCommandBuffer::SCommand_UpdateBufferContainer *pCommand) {}
virtual void Cmd_DeleteBufferContainer(const CCommandBuffer::SCommand_DeleteBufferContainer *pCommand) {}
virtual void Cmd_IndicesRequiredNumNotify(const CCommandBuffer::SCommand_IndicesRequiredNumNotify *pCommand) {}
virtual void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) {}
virtual void Cmd_RenderBorderTile(const CCommandBuffer::SCommand_RenderBorderTile *pCommand) {}
virtual void Cmd_RenderBorderTileLine(const CCommandBuffer::SCommand_RenderBorderTileLine *pCommand) {}
@ -200,13 +206,15 @@ protected:
virtual void Cmd_RenderQuadContainer(const CCommandBuffer::SCommand_RenderQuadContainer *pCommand) {}
virtual void Cmd_RenderQuadContainerAsSprite(const CCommandBuffer::SCommand_RenderQuadContainerAsSprite *pCommand) {}
virtual void Cmd_RenderQuadContainerAsSpriteMultiple(const CCommandBuffer::SCommand_RenderQuadContainerAsSpriteMultiple *pCommand) {}
public:
CCommandProcessorFragment_OpenGL();
bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand);
bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand);
};
class CCommandProcessorFragment_OpenGL2 : public CCommandProcessorFragment_OpenGL {
class CCommandProcessorFragment_OpenGL2 : public CCommandProcessorFragment_OpenGL
{
struct SBufferContainer
{
SBufferContainer() {}
@ -218,13 +226,14 @@ class CCommandProcessorFragment_OpenGL2 : public CCommandProcessorFragment_OpenG
struct SBufferObject
{
SBufferObject(GLuint BufferObjectID) : m_BufferObjectID(BufferObjectID)
SBufferObject(GLuint BufferObjectID) :
m_BufferObjectID(BufferObjectID)
{
m_pData = NULL;
m_DataSize = 0;
}
GLuint m_BufferObjectID;
void* m_pData;
void *m_pData;
size_t m_DataSize;
};
@ -233,10 +242,11 @@ class CCommandProcessorFragment_OpenGL2 : public CCommandProcessorFragment_OpenG
bool DoAnalyzeStep(size_t StepN, size_t CheckCount, size_t VerticesCount, uint8_t aFakeTexture[], size_t SingleImageSize);
bool IsTileMapAnalysisSucceeded();
void RenderBorderTileEmulation(SBufferContainer& BufferContainer, const CCommandBuffer::SState& State, const float* pColor, const char *pBuffOffset, unsigned int DrawNum, const float* pOffset, const float* pDir, int JumpIndex);
void RenderBorderTileLineEmulation(SBufferContainer& BufferContainer, const CCommandBuffer::SState& State, const float* pColor, const char *pBuffOffset, unsigned int IndexDrawNum, unsigned int DrawNum, const float* pOffset, const float* pDir);
void RenderBorderTileEmulation(SBufferContainer &BufferContainer, const CCommandBuffer::SState &State, const float *pColor, const char *pBuffOffset, unsigned int DrawNum, const float *pOffset, const float *pDir, int JumpIndex);
void RenderBorderTileLineEmulation(SBufferContainer &BufferContainer, const CCommandBuffer::SState &State, const float *pColor, const char *pBuffOffset, unsigned int IndexDrawNum, unsigned int DrawNum, const float *pOffset, const float *pDir);
void UseProgram(CGLSLTWProgram *pProgram);
protected:
void SetState(const CCommandBuffer::SState &State, CGLSLTWProgram *pProgram, bool Use2DArrayTextures = false);
@ -254,8 +264,8 @@ protected:
void Cmd_UpdateBufferContainer(const CCommandBuffer::SCommand_UpdateBufferContainer *pCommand) override;
void Cmd_DeleteBufferContainer(const CCommandBuffer::SCommand_DeleteBufferContainer *pCommand) override;
void Cmd_IndicesRequiredNumNotify(const CCommandBuffer::SCommand_IndicesRequiredNumNotify *pCommand) override;
void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) override;
void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) override;
void Cmd_RenderBorderTile(const CCommandBuffer::SCommand_RenderBorderTile *pCommand) override;
void Cmd_RenderBorderTileLine(const CCommandBuffer::SCommand_RenderBorderTileLine *pCommand) override;
@ -263,24 +273,27 @@ protected:
CGLSLTileProgram *m_pTileProgramTextured;
CGLSLPrimitiveProgram *m_pPrimitive3DProgram;
CGLSLPrimitiveProgram *m_pPrimitive3DProgramTextured;
bool m_UseMultipleTextureUnits;
GLint m_MaxTextureUnits;
struct STextureBound{
struct STextureBound
{
int m_TextureSlot;
bool m_Is2DArray;
};
std::vector<STextureBound> m_TextureSlotBoundToUnit; //the texture index generated by loadtextureraw is stored in an index calculated by max texture units
bool IsAndUpdateTextureSlotBound(int IDX, int Slot, bool Is2DArray = false);
public:
CCommandProcessorFragment_OpenGL2() : CCommandProcessorFragment_OpenGL(), m_UseMultipleTextureUnits(false) {}
CCommandProcessorFragment_OpenGL2() :
CCommandProcessorFragment_OpenGL(), m_UseMultipleTextureUnits(false) {}
};
class CCommandProcessorFragment_OpenGL3 : public CCommandProcessorFragment_OpenGL2 {
class CCommandProcessorFragment_OpenGL3 : public CCommandProcessorFragment_OpenGL2
{
};
#define MAX_STREAM_BUFFER_COUNT 30
@ -314,17 +327,18 @@ class CCommandProcessorFragment_OpenGL3_3 : public CCommandProcessorFragment_Ope
GLuint m_LastIndexBufferBound[MAX_STREAM_BUFFER_COUNT];
int m_LastStreamBuffer;
GLuint m_QuadDrawIndexBufferID;
unsigned int m_CurrentIndicesInBuffer;
void DestroyBufferContainer(int Index, bool DeleteBOs = true);
void AppendIndices(unsigned int NewIndicesCount);
struct SBufferContainer
{
SBufferContainer() : m_VertArrayID(0), m_LastIndexBufferBound(0) {}
SBufferContainer() :
m_VertArrayID(0), m_LastIndexBufferBound(0) {}
GLuint m_VertArrayID;
GLuint m_LastIndexBufferBound;
SBufferContainerInfo m_ContainerInfo;
@ -332,8 +346,9 @@ class CCommandProcessorFragment_OpenGL3_3 : public CCommandProcessorFragment_Ope
std::vector<SBufferContainer> m_BufferContainers;
std::vector<GLuint> m_BufferObjectIndices;
CCommandBuffer::SColorf m_ClearColor;
protected:
static int TexFormatToNewOpenGLFormat(int TexFormat);
bool IsNewApi() override { return true; }
@ -362,8 +377,8 @@ protected:
void Cmd_UpdateBufferContainer(const CCommandBuffer::SCommand_UpdateBufferContainer *pCommand) override;
void Cmd_DeleteBufferContainer(const CCommandBuffer::SCommand_DeleteBufferContainer *pCommand) override;
void Cmd_IndicesRequiredNumNotify(const CCommandBuffer::SCommand_IndicesRequiredNumNotify *pCommand) override;
void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) override;
void Cmd_RenderTileLayer(const CCommandBuffer::SCommand_RenderTileLayer *pCommand) override;
void Cmd_RenderBorderTile(const CCommandBuffer::SCommand_RenderBorderTile *pCommand) override;
void Cmd_RenderBorderTileLine(const CCommandBuffer::SCommand_RenderBorderTileLine *pCommand) override;
void Cmd_RenderQuadLayer(const CCommandBuffer::SCommand_RenderQuadLayer *pCommand) override;
@ -372,6 +387,7 @@ protected:
void Cmd_RenderQuadContainer(const CCommandBuffer::SCommand_RenderQuadContainer *pCommand) override;
void Cmd_RenderQuadContainerAsSprite(const CCommandBuffer::SCommand_RenderQuadContainerAsSprite *pCommand) override;
void Cmd_RenderQuadContainerAsSpriteMultiple(const CCommandBuffer::SCommand_RenderQuadContainerAsSpriteMultiple *pCommand) override;
public:
CCommandProcessorFragment_OpenGL3_3() = default;
};
@ -382,6 +398,7 @@ class CCommandProcessorFragment_SDL
// SDL stuff
SDL_Window *m_pWindow;
SDL_GLContext m_GLContext;
public:
enum
{
@ -392,7 +409,8 @@ public:
struct SCommand_Init : public CCommandBuffer::SCommand
{
SCommand_Init() : SCommand(CMD_INIT) {}
SCommand_Init() :
SCommand(CMD_INIT) {}
SDL_Window *m_pWindow;
SDL_GLContext m_GLContext;
SBackendCapabilites *m_pCapabilities;
@ -410,7 +428,8 @@ public:
struct SCommand_Update_Viewport : public CCommandBuffer::SCommand
{
SCommand_Update_Viewport() : SCommand(CMD_UPDATE_VIEWPORT) {}
SCommand_Update_Viewport() :
SCommand(CMD_UPDATE_VIEWPORT) {}
int m_X;
int m_Y;
int m_Width;
@ -419,7 +438,8 @@ public:
struct SCommand_Shutdown : public CCommandBuffer::SCommand
{
SCommand_Shutdown() : SCommand(CMD_SHUTDOWN) {}
SCommand_Shutdown() :
SCommand(CMD_SHUTDOWN) {}
};
private:
@ -430,6 +450,7 @@ private:
void Cmd_VSync(const CCommandBuffer::SCommand_VSync *pCommand);
void Cmd_Resize(const CCommandBuffer::SCommand_Resize *pCommand);
void Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand);
public:
CCommandProcessorFragment_SDL();
@ -442,6 +463,7 @@ class CCommandProcessor_SDL_OpenGL : public CGraphicsBackend_Threaded::ICommandP
CCommandProcessorFragment_OpenGL *m_pOpenGL;
CCommandProcessorFragment_SDL m_SDL;
CCommandProcessorFragment_General m_General;
public:
CCommandProcessor_SDL_OpenGL(int OpenGLMajor, int OpenGLMinor, int OpenGLPatch);
virtual void RunBuffer(CCommandBuffer *pBuffer);
@ -457,8 +479,9 @@ class CGraphicsBackend_SDL_OpenGL : public CGraphicsBackend_Threaded
int m_NumScreens;
SBackendCapabilites m_Capabilites;
bool m_UseNewOpenGL;
public:
virtual int Init(const char *pName, int *Screen, int *pWidth, int *pHeight, int FsaaSamples, int Flags, int *pDesktopWidth, int *pDesktopHeight, int *pCurrentWidth, int *pCurrentHeight, class IStorage *pStorage);
virtual int Shutdown();
@ -470,14 +493,14 @@ public:
virtual void Minimize();
virtual void Maximize();
virtual bool Fullscreen(bool State);
virtual void SetWindowBordered(bool State); // on=true/off=false
virtual void SetWindowBordered(bool State); // on=true/off=false
virtual bool SetWindowScreen(int Index);
virtual int GetWindowScreen();
virtual int WindowActive();
virtual int WindowOpen();
virtual void SetWindowGrab(bool Grab);
virtual void NotifyWindow();
virtual bool IsNewOpenGL() { return m_UseNewOpenGL; }
virtual bool HasTileBuffering() { return m_Capabilites.m_TileBuffering; }
virtual bool HasQuadBuffering() { return m_Capabilites.m_QuadBuffering; }

File diff suppressed because it is too large Load diff

View file

@ -3,12 +3,29 @@
#ifndef ENGINE_CLIENT_CLIENT_H
#define ENGINE_CLIENT_CLIENT_H
#include <list>
#include <memory>
#include <base/hash.h>
#include <engine/client.h>
#include <engine/client/demoedit.h>
#include <engine/client/friends.h>
#include <engine/client/http.h>
#include <engine/client/serverbrowser.h>
#include <engine/client/updater.h>
#include <engine/editor.h>
#include <engine/engine.h>
#include <engine/graphics.h>
#include <engine/input.h>
#include <engine/map.h>
#include <engine/masterserver.h>
#include <engine/shared/config.h>
#include <engine/shared/demo.h>
#include <engine/shared/fifo.h>
#include <engine/shared/ghost.h>
#include <engine/shared/network.h>
#include <engine/sound.h>
#include <engine/steam.h>
#define CONNECTLINK "ddnet:"
@ -18,7 +35,7 @@ public:
enum
{
// restrictions: Must be power of two
MAX_VALUES=128,
MAX_VALUES = 128,
};
float m_Min, m_Max;
@ -35,7 +52,6 @@ public:
void Render(IGraphics *pGraphics, IGraphics::CTextureHandle FontTexture, float x, float y, float w, float h, const char *pDescription);
};
class CSmoothTime
{
int64 m_Snap;
@ -81,8 +97,8 @@ class CClient : public IClient, public CDemoPlayer::IListener
enum
{
NUM_SNAPSHOT_TYPES=2,
PREDICTION_MARGIN=1000/50/2, // magic network prediction value
NUM_SNAPSHOT_TYPES = 2,
PREDICTION_MARGIN = 1000 / 50 / 2, // magic network prediction value
};
enum
@ -135,7 +151,7 @@ class CClient : public IClient, public CDemoPlayer::IListener
int m_UseTempRconCommands;
char m_Password[32];
bool m_SendPassword;
bool m_ButtonRender=false;
bool m_ButtonRender = false;
// version-checking
char m_aVersionStr[10];
@ -228,7 +244,7 @@ class CClient : public IClient, public CDemoPlayer::IListener
{
enum
{
STATE_INIT=0,
STATE_INIT = 0,
STATE_START,
STATE_READY,
};
@ -238,7 +254,7 @@ class CClient : public IClient, public CDemoPlayer::IListener
} m_VersionInfo;
volatile int m_GfxState;
static void GraphicsThreadProxy(void *pThis) { ((CClient*)pThis)->GraphicsThread(); }
static void GraphicsThreadProxy(void *pThis) { ((CClient *)pThis)->GraphicsThread(); }
void GraphicsThread();
#if defined(CONF_FAMILY_UNIX)
@ -260,7 +276,7 @@ public:
// ----- send functions -----
virtual int SendMsg(CMsgPacker *pMsg, int Flags);
virtual int SendMsgY(CMsgPacker *pMsg, int Flags, int NetClient=1);
virtual int SendMsgY(CMsgPacker *pMsg, int Flags, int NetClient = 1);
void SendInfo();
void SendEnterGame();
@ -465,7 +481,7 @@ public:
bool EditorHasUnsavedData() { return m_pEditor->HasUnsavedData(); }
virtual IFriends* Foes() { return &m_Foes; }
virtual IFriends *Foes() { return &m_Foes; }
void GetSmoothTick(int *pSmoothTick, float *pSmoothIntraTick, float MixAmount);
};

View file

@ -1,5 +1,5 @@
#include <engine/shared/demo.h>
#include "demoedit.h"
#include <engine/shared/demo.h>
CDemoEdit::CDemoEdit(const char *pNetVersion, class CSnapshotDelta *pSnapshotDelta, IStorage *pStorage, const char *pDemo, const char *pDst, int StartTick, int EndTick) :
m_SnapshotDelta(*pSnapshotDelta),

View file

@ -2,6 +2,8 @@
#define ENGINE_CLIENT_DEMOEDIT_H
#include <engine/client/http.h>
#include <engine/shared/demo.h>
#include <engine/shared/snapshot.h>
#define CONNECTLINK "ddnet:"

View file

@ -62,7 +62,7 @@ void CFriends::Init(bool Foes)
const CFriendInfo *CFriends::GetFriend(int Index) const
{
return &m_aFriends[maximum(0, Index%m_NumFriends)];
return &m_aFriends[maximum(0, Index % m_NumFriends)];
}
int CFriends::GetFriendState(const char *pName, const char *pClan) const
@ -139,7 +139,7 @@ void CFriends::RemoveFriend(int Index)
{
if(Index >= 0 && Index < m_NumFriends)
{
mem_move(&m_aFriends[Index], &m_aFriends[Index+1], sizeof(CFriendInfo)*(m_NumFriends-(Index+1)));
mem_move(&m_aFriends[Index], &m_aFriends[Index + 1], sizeof(CFriendInfo) * (m_NumFriends - (Index + 1)));
--m_NumFriends;
}
}
@ -153,7 +153,7 @@ void CFriends::Friends()
for(int i = 0; i < m_NumFriends; ++i)
{
str_format(aBuf, sizeof(aBuf), "Name: %s, Clan: %s", m_aFriends[i].m_aName, m_aFriends[i].m_aClan);
pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, m_Foes?"foes":"friends", aBuf, true);
pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, m_Foes ? "foes" : "friends", aBuf, true);
}
}
}
@ -162,7 +162,7 @@ void CFriends::ConfigSaveCallback(IConfig *pConfig, void *pUserData)
{
CFriends *pSelf = (CFriends *)pUserData;
char aBuf[128];
const char *pEnd = aBuf+sizeof(aBuf)-4;
const char *pEnd = aBuf + sizeof(aBuf) - 4;
for(int i = 0; i < pSelf->m_NumFriends; ++i)
{
str_copy(aBuf, pSelf->m_Foes ? "add_foe " : "add_friend ", sizeof(aBuf));

View file

@ -3,6 +3,8 @@
#ifndef ENGINE_CLIENT_FRIENDS_H
#define ENGINE_CLIENT_FRIENDS_H
#include <engine/config.h>
#include <engine/console.h>
#include <engine/friends.h>
class CFriends : public IFriends

View file

@ -13,44 +13,43 @@
#include <pnglite.h>
#include <engine/shared/config.h>
#include <engine/graphics.h>
#include <engine/storage.h>
#include <engine/keys.h>
#include <engine/console.h>
#include <engine/graphics.h>
#include <engine/keys.h>
#include <engine/shared/config.h>
#include <engine/storage.h>
#include <game/localization.h>
#include <math.h> // cosf, sinf, log2f
#if defined(CONF_VIDEORECORDER)
#include "video.h"
#include "video.h"
#endif
#include "graphics_threaded.h"
static CVideoMode g_aFakeModes[] = {
{320,240,8,8,8}, {400,300,8,8,8}, {640,480,8,8,8},
{720,400,8,8,8}, {768,576,8,8,8}, {800,600,8,8,8},
{1024,600,8,8,8}, {1024,768,8,8,8}, {1152,864,8,8,8},
{1280,768,8,8,8}, {1280,800,8,8,8}, {1280,960,8,8,8},
{1280,1024,8,8,8}, {1368,768,8,8,8}, {1400,1050,8,8,8},
{1440,900,8,8,8}, {1440,1050,8,8,8}, {1600,1000,8,8,8},
{1600,1200,8,8,8}, {1680,1050,8,8,8}, {1792,1344,8,8,8},
{1800,1440,8,8,8}, {1856,1392,8,8,8}, {1920,1080,8,8,8},
{1920,1200,8,8,8}, {1920,1440,8,8,8}, {1920,2400,8,8,8},
{2048,1536,8,8,8},
{320, 240, 8, 8, 8}, {400, 300, 8, 8, 8}, {640, 480, 8, 8, 8},
{720, 400, 8, 8, 8}, {768, 576, 8, 8, 8}, {800, 600, 8, 8, 8},
{1024, 600, 8, 8, 8}, {1024, 768, 8, 8, 8}, {1152, 864, 8, 8, 8},
{1280, 768, 8, 8, 8}, {1280, 800, 8, 8, 8}, {1280, 960, 8, 8, 8},
{1280, 1024, 8, 8, 8}, {1368, 768, 8, 8, 8}, {1400, 1050, 8, 8, 8},
{1440, 900, 8, 8, 8}, {1440, 1050, 8, 8, 8}, {1600, 1000, 8, 8, 8},
{1600, 1200, 8, 8, 8}, {1680, 1050, 8, 8, 8}, {1792, 1344, 8, 8, 8},
{1800, 1440, 8, 8, 8}, {1856, 1392, 8, 8, 8}, {1920, 1080, 8, 8, 8},
{1920, 1200, 8, 8, 8}, {1920, 1440, 8, 8, 8}, {1920, 2400, 8, 8, 8},
{2048, 1536, 8, 8, 8},
{320,240,5,6,5}, {400,300,5,6,5}, {640,480,5,6,5},
{720,400,5,6,5}, {768,576,5,6,5}, {800,600,5,6,5},
{1024,600,5,6,5}, {1024,768,5,6,5}, {1152,864,5,6,5},
{1280,768,5,6,5}, {1280,800,5,6,5}, {1280,960,5,6,5},
{1280,1024,5,6,5}, {1368,768,5,6,5}, {1400,1050,5,6,5},
{1440,900,5,6,5}, {1440,1050,5,6,5}, {1600,1000,5,6,5},
{1600,1200,5,6,5}, {1680,1050,5,6,5}, {1792,1344,5,6,5},
{1800,1440,5,6,5}, {1856,1392,5,6,5}, {1920,1080,5,6,5},
{1920,1200,5,6,5}, {1920,1440,5,6,5}, {1920,2400,5,6,5},
{2048,1536,5,6,5}
};
{320, 240, 5, 6, 5}, {400, 300, 5, 6, 5}, {640, 480, 5, 6, 5},
{720, 400, 5, 6, 5}, {768, 576, 5, 6, 5}, {800, 600, 5, 6, 5},
{1024, 600, 5, 6, 5}, {1024, 768, 5, 6, 5}, {1152, 864, 5, 6, 5},
{1280, 768, 5, 6, 5}, {1280, 800, 5, 6, 5}, {1280, 960, 5, 6, 5},
{1280, 1024, 5, 6, 5}, {1368, 768, 5, 6, 5}, {1400, 1050, 5, 6, 5},
{1440, 900, 5, 6, 5}, {1440, 1050, 5, 6, 5}, {1600, 1000, 5, 6, 5},
{1600, 1200, 5, 6, 5}, {1680, 1050, 5, 6, 5}, {1792, 1344, 5, 6, 5},
{1800, 1440, 5, 6, 5}, {1856, 1392, 5, 6, 5}, {1920, 1080, 5, 6, 5},
{1920, 1200, 5, 6, 5}, {1920, 1440, 5, 6, 5}, {1920, 2400, 5, 6, 5},
{2048, 1536, 5, 6, 5}};
void CGraphics_Threaded::FlushVertices(bool KeepVertices)
{
@ -65,7 +64,7 @@ void CGraphics_Threaded::FlushVertices(bool KeepVertices)
}
}
void CGraphics_Threaded::FlushTextVertices(int TextureSize, int TextTextureIndex, int TextOutlineTextureIndex, float* pOutlineTextColor)
void CGraphics_Threaded::FlushTextVertices(int TextureSize, int TextTextureIndex, int TextOutlineTextureIndex, float *pOutlineTextColor)
{
CCommandBuffer::SCommand_RenderTextStream Cmd;
int PrimType, PrimCount, NumVerts;
@ -158,12 +157,12 @@ void CGraphics_Threaded::ClipEnable(int x, int y, int w, int h)
x = clamp(x, 0, ScreenWidth());
y = clamp(y, 0, ScreenHeight());
w = clamp(w, 0, ScreenWidth()-x);
h = clamp(h, 0, ScreenHeight()-y);
w = clamp(w, 0, ScreenWidth() - x);
h = clamp(h, 0, ScreenHeight() - y);
m_State.m_ClipEnable = true;
m_State.m_ClipX = x;
m_State.m_ClipY = ScreenHeight()-(y+h);
m_State.m_ClipY = ScreenHeight() - (y + h);
m_State.m_ClipW = w;
m_State.m_ClipH = h;
}
@ -223,7 +222,7 @@ void CGraphics_Threaded::LinesBegin()
{
dbg_assert(m_Drawing == 0, "called Graphics()->LinesBegin twice");
m_Drawing = DRAWING_LINES;
SetColor(1,1,1,1);
SetColor(1, 1, 1, 1);
}
void CGraphics_Threaded::LinesEnd()
@ -239,18 +238,18 @@ void CGraphics_Threaded::LinesDraw(const CLineItem *pArray, int Num)
for(int i = 0; i < Num; ++i)
{
m_aVertices[m_NumVertices + 2*i].m_Pos.x = pArray[i].m_X0;
m_aVertices[m_NumVertices + 2*i].m_Pos.y = pArray[i].m_Y0;
m_aVertices[m_NumVertices + 2*i].m_Tex = m_aTexture[0];
SetColor(&m_aVertices[m_NumVertices + 2*i], 0);
m_aVertices[m_NumVertices + 2 * i].m_Pos.x = pArray[i].m_X0;
m_aVertices[m_NumVertices + 2 * i].m_Pos.y = pArray[i].m_Y0;
m_aVertices[m_NumVertices + 2 * i].m_Tex = m_aTexture[0];
SetColor(&m_aVertices[m_NumVertices + 2 * i], 0);
m_aVertices[m_NumVertices + 2*i + 1].m_Pos.x = pArray[i].m_X1;
m_aVertices[m_NumVertices + 2*i + 1].m_Pos.y = pArray[i].m_Y1;
m_aVertices[m_NumVertices + 2*i + 1].m_Tex = m_aTexture[1];
SetColor(&m_aVertices[m_NumVertices + 2*i + 1], 1);
m_aVertices[m_NumVertices + 2 * i + 1].m_Pos.x = pArray[i].m_X1;
m_aVertices[m_NumVertices + 2 * i + 1].m_Pos.y = pArray[i].m_Y1;
m_aVertices[m_NumVertices + 2 * i + 1].m_Tex = m_aTexture[1];
SetColor(&m_aVertices[m_NumVertices + 2 * i + 1], 1);
}
AddVertices(2*Num);
AddVertices(2 * Num);
}
int CGraphics_Threaded::UnloadTexture(CTextureHandle Index)
@ -272,9 +271,12 @@ int CGraphics_Threaded::UnloadTexture(CTextureHandle Index)
static int ImageFormatToTexFormat(int Format)
{
if(Format == CImageInfo::FORMAT_RGB) return CCommandBuffer::TEXFORMAT_RGB;
if(Format == CImageInfo::FORMAT_RGBA) return CCommandBuffer::TEXFORMAT_RGBA;
if(Format == CImageInfo::FORMAT_ALPHA) return CCommandBuffer::TEXFORMAT_ALPHA;
if(Format == CImageInfo::FORMAT_RGB)
return CCommandBuffer::TEXFORMAT_RGB;
if(Format == CImageInfo::FORMAT_RGBA)
return CCommandBuffer::TEXFORMAT_RGBA;
if(Format == CImageInfo::FORMAT_ALPHA)
return CCommandBuffer::TEXFORMAT_ALPHA;
return CCommandBuffer::TEXFORMAT_RGBA;
}
@ -288,7 +290,6 @@ static int ImageFormatToPixelSize(int Format)
}
}
int CGraphics_Threaded::LoadTextureRawSub(CTextureHandle TextureID, int x, int y, int Width, int Height, int Format, const void *pData)
{
CCommandBuffer::SCommand_Texture_Update Cmd;
@ -300,7 +301,7 @@ int CGraphics_Threaded::LoadTextureRawSub(CTextureHandle TextureID, int x, int y
Cmd.m_Format = ImageFormatToTexFormat(Format);
// calculate memory usage
int MemSize = Width*Height*ImageFormatToPixelSize(Format);
int MemSize = Width * Height * ImageFormatToPixelSize(Format);
// copy texture data
void *pTmpData = malloc(MemSize);
@ -360,25 +361,25 @@ IGraphics::CTextureHandle CGraphics_Threaded::LoadTextureRaw(int Width, int Heig
// flags
Cmd.m_Flags = 0;
if(Flags&IGraphics::TEXLOAD_NOMIPMAPS)
if(Flags & IGraphics::TEXLOAD_NOMIPMAPS)
Cmd.m_Flags |= CCommandBuffer::TEXFLAG_NOMIPMAPS;
if(g_Config.m_GfxTextureCompressionOld && ((Flags & IGraphics::TEXLOAD_NO_COMPRESSION) == 0))
Cmd.m_Flags |= CCommandBuffer::TEXFLAG_COMPRESSED;
if(g_Config.m_GfxTextureQualityOld || Flags & TEXLOAD_NORESAMPLE)
Cmd.m_Flags |= CCommandBuffer::TEXFLAG_QUALITY;
if((Flags&IGraphics::TEXLOAD_TO_2D_ARRAY_TEXTURE) != 0)
if((Flags & IGraphics::TEXLOAD_TO_2D_ARRAY_TEXTURE) != 0)
Cmd.m_Flags |= CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE;
if((Flags&IGraphics::TEXLOAD_TO_3D_TEXTURE) != 0)
if((Flags & IGraphics::TEXLOAD_TO_3D_TEXTURE) != 0)
Cmd.m_Flags |= CCommandBuffer::TEXFLAG_TO_3D_TEXTURE;
if((Flags&IGraphics::TEXLOAD_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER) != 0)
if((Flags & IGraphics::TEXLOAD_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER) != 0)
Cmd.m_Flags |= CCommandBuffer::TEXFLAG_TO_2D_ARRAY_TEXTURE_SINGLE_LAYER;
if((Flags&IGraphics::TEXLOAD_TO_3D_TEXTURE_SINGLE_LAYER) != 0)
if((Flags & IGraphics::TEXLOAD_TO_3D_TEXTURE_SINGLE_LAYER) != 0)
Cmd.m_Flags |= CCommandBuffer::TEXFLAG_TO_3D_TEXTURE_SINGLE_LAYER;
if((Flags&IGraphics::TEXLOAD_NO_2D_TEXTURE) != 0)
if((Flags & IGraphics::TEXLOAD_NO_2D_TEXTURE) != 0)
Cmd.m_Flags |= CCommandBuffer::TEXFLAG_NO_2D_TEXTURE;
// copy texture data
int MemSize = Width*Height*Cmd.m_PixelSize;
int MemSize = Width * Height * Cmd.m_PixelSize;
void *pTmpData = malloc(MemSize);
mem_copy(pTmpData, pData, MemSize);
Cmd.m_pData = pTmpData;
@ -425,7 +426,7 @@ int CGraphics_Threaded::LoadPNG(CImageInfo *pImg, const char *pFilename, int Sto
png_t Png; // ignore_convention
// open file for reading
png_init(0,0); // ignore_convention
png_init(0, 0); // ignore_convention
IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType, aCompleteFilename, sizeof(aCompleteFilename));
if(File)
@ -560,7 +561,7 @@ void CGraphics_Threaded::TextQuadsBegin()
QuadsBegin();
}
void CGraphics_Threaded::TextQuadsEnd(int TextureSize, int TextTextureIndex, int TextOutlineTextureIndex, float* pOutlineTextColor)
void CGraphics_Threaded::TextQuadsEnd(int TextureSize, int TextTextureIndex, int TextOutlineTextureIndex, float *pOutlineTextColor)
{
dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->TextQuadsEnd without begin");
FlushTextVertices(TextureSize, TextTextureIndex, TextOutlineTextureIndex, pOutlineTextColor);
@ -598,10 +599,12 @@ void CGraphics_Threaded::QuadsSetRotation(float Angle)
m_Rotation = Angle;
}
inline void clampf(float& Value, float Min, float Max)
inline void clampf(float &Value, float Min, float Max)
{
if(Value > Max) Value = Max;
else if(Value < Min) Value = Min;
if(Value > Max)
Value = Max;
else if(Value < Min)
Value = Min;
}
void CGraphics_Threaded::SetColorVertex(const CColorVertex *pArray, int Num)
@ -615,10 +618,10 @@ void CGraphics_Threaded::SetColorVertex(const CColorVertex *pArray, int Num)
clampf(g, 0.f, 1.f);
clampf(b, 0.f, 1.f);
clampf(a, 0.f, 1.f);
m_aColor[pArray[i].m_Index].r = (unsigned char)(r*255.f);
m_aColor[pArray[i].m_Index].g = (unsigned char)(g*255.f);
m_aColor[pArray[i].m_Index].b = (unsigned char)(b*255.f);
m_aColor[pArray[i].m_Index].a = (unsigned char)(a*255.f);
m_aColor[pArray[i].m_Index].r = (unsigned char)(r * 255.f);
m_aColor[pArray[i].m_Index].g = (unsigned char)(g * 255.f);
m_aColor[pArray[i].m_Index].b = (unsigned char)(b * 255.f);
m_aColor[pArray[i].m_Index].a = (unsigned char)(a * 255.f);
}
}
@ -664,10 +667,10 @@ void CGraphics_Threaded::ChangeColorOfCurrentQuadVertices(float r, float g, floa
clampf(g, 0.f, 1.f);
clampf(b, 0.f, 1.f);
clampf(a, 0.f, 1.f);
m_aColor[0].r = (unsigned char)(r*255.f);
m_aColor[0].g = (unsigned char)(g*255.f);
m_aColor[0].b = (unsigned char)(b*255.f);
m_aColor[0].a = (unsigned char)(a*255.f);
m_aColor[0].r = (unsigned char)(r * 255.f);
m_aColor[0].g = (unsigned char)(g * 255.f);
m_aColor[0].b = (unsigned char)(b * 255.f);
m_aColor[0].a = (unsigned char)(a * 255.f);
for(int i = 0; i < m_NumVertices; ++i)
{
@ -735,11 +738,15 @@ void CGraphics_Threaded::ChangeColorOfQuadVertices(int QuadOffset, unsigned char
void CGraphics_Threaded::QuadsSetSubset(float TlU, float TlV, float BrU, float BrV)
{
m_aTexture[0].u = TlU; m_aTexture[1].u = BrU;
m_aTexture[0].v = TlV; m_aTexture[1].v = TlV;
m_aTexture[0].u = TlU;
m_aTexture[1].u = BrU;
m_aTexture[0].v = TlV;
m_aTexture[1].v = TlV;
m_aTexture[3].u = TlU; m_aTexture[2].u = BrU;
m_aTexture[3].v = BrV; m_aTexture[2].v = BrV;
m_aTexture[3].u = TlU;
m_aTexture[2].u = BrU;
m_aTexture[3].v = BrV;
m_aTexture[2].v = BrV;
}
void CGraphics_Threaded::QuadsSetSubsetFree(
@ -761,8 +768,8 @@ void CGraphics_Threaded::QuadsDraw(CQuadItem *pArray, int Num)
{
for(int i = 0; i < Num; ++i)
{
pArray[i].m_X -= pArray[i].m_Width/2;
pArray[i].m_Y -= pArray[i].m_Height/2;
pArray[i].m_X -= pArray[i].m_Width / 2;
pArray[i].m_Y -= pArray[i].m_Height / 2;
}
QuadsDrawTL(pArray, Num);
@ -809,65 +816,65 @@ void CGraphics_Threaded::QuadsDrawFreeform(const CFreeformItem *pArray, int Num)
{
for(int i = 0; i < Num; ++i)
{
m_aVertices[m_NumVertices + 6*i].m_Pos.x = pArray[i].m_X0;
m_aVertices[m_NumVertices + 6*i].m_Pos.y = pArray[i].m_Y0;
m_aVertices[m_NumVertices + 6*i].m_Tex = m_aTexture[0];
SetColor(&m_aVertices[m_NumVertices + 6*i], 0);
m_aVertices[m_NumVertices + 6 * i].m_Pos.x = pArray[i].m_X0;
m_aVertices[m_NumVertices + 6 * i].m_Pos.y = pArray[i].m_Y0;
m_aVertices[m_NumVertices + 6 * i].m_Tex = m_aTexture[0];
SetColor(&m_aVertices[m_NumVertices + 6 * i], 0);
m_aVertices[m_NumVertices + 6*i + 1].m_Pos.x = pArray[i].m_X1;
m_aVertices[m_NumVertices + 6*i + 1].m_Pos.y = pArray[i].m_Y1;
m_aVertices[m_NumVertices + 6*i + 1].m_Tex = m_aTexture[1];
SetColor(&m_aVertices[m_NumVertices + 6*i + 1], 1);
m_aVertices[m_NumVertices + 6 * i + 1].m_Pos.x = pArray[i].m_X1;
m_aVertices[m_NumVertices + 6 * i + 1].m_Pos.y = pArray[i].m_Y1;
m_aVertices[m_NumVertices + 6 * i + 1].m_Tex = m_aTexture[1];
SetColor(&m_aVertices[m_NumVertices + 6 * i + 1], 1);
m_aVertices[m_NumVertices + 6*i + 2].m_Pos.x = pArray[i].m_X3;
m_aVertices[m_NumVertices + 6*i + 2].m_Pos.y = pArray[i].m_Y3;
m_aVertices[m_NumVertices + 6*i + 2].m_Tex = m_aTexture[3];
SetColor(&m_aVertices[m_NumVertices + 6*i + 2], 3);
m_aVertices[m_NumVertices + 6 * i + 2].m_Pos.x = pArray[i].m_X3;
m_aVertices[m_NumVertices + 6 * i + 2].m_Pos.y = pArray[i].m_Y3;
m_aVertices[m_NumVertices + 6 * i + 2].m_Tex = m_aTexture[3];
SetColor(&m_aVertices[m_NumVertices + 6 * i + 2], 3);
m_aVertices[m_NumVertices + 6*i + 3].m_Pos.x = pArray[i].m_X0;
m_aVertices[m_NumVertices + 6*i + 3].m_Pos.y = pArray[i].m_Y0;
m_aVertices[m_NumVertices + 6*i + 3].m_Tex = m_aTexture[0];
SetColor(&m_aVertices[m_NumVertices + 6*i + 3], 0);
m_aVertices[m_NumVertices + 6 * i + 3].m_Pos.x = pArray[i].m_X0;
m_aVertices[m_NumVertices + 6 * i + 3].m_Pos.y = pArray[i].m_Y0;
m_aVertices[m_NumVertices + 6 * i + 3].m_Tex = m_aTexture[0];
SetColor(&m_aVertices[m_NumVertices + 6 * i + 3], 0);
m_aVertices[m_NumVertices + 6*i + 4].m_Pos.x = pArray[i].m_X3;
m_aVertices[m_NumVertices + 6*i + 4].m_Pos.y = pArray[i].m_Y3;
m_aVertices[m_NumVertices + 6*i + 4].m_Tex = m_aTexture[3];
SetColor(&m_aVertices[m_NumVertices + 6*i + 4], 3);
m_aVertices[m_NumVertices + 6 * i + 4].m_Pos.x = pArray[i].m_X3;
m_aVertices[m_NumVertices + 6 * i + 4].m_Pos.y = pArray[i].m_Y3;
m_aVertices[m_NumVertices + 6 * i + 4].m_Tex = m_aTexture[3];
SetColor(&m_aVertices[m_NumVertices + 6 * i + 4], 3);
m_aVertices[m_NumVertices + 6*i + 5].m_Pos.x = pArray[i].m_X2;
m_aVertices[m_NumVertices + 6*i + 5].m_Pos.y = pArray[i].m_Y2;
m_aVertices[m_NumVertices + 6*i + 5].m_Tex = m_aTexture[2];
SetColor(&m_aVertices[m_NumVertices + 6*i + 5], 2);
m_aVertices[m_NumVertices + 6 * i + 5].m_Pos.x = pArray[i].m_X2;
m_aVertices[m_NumVertices + 6 * i + 5].m_Pos.y = pArray[i].m_Y2;
m_aVertices[m_NumVertices + 6 * i + 5].m_Tex = m_aTexture[2];
SetColor(&m_aVertices[m_NumVertices + 6 * i + 5], 2);
}
AddVertices(3*2*Num);
AddVertices(3 * 2 * Num);
}
else
{
for(int i = 0; i < Num; ++i)
{
m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X0;
m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y0;
m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0];
SetColor(&m_aVertices[m_NumVertices + 4*i], 0);
m_aVertices[m_NumVertices + 4 * i].m_Pos.x = pArray[i].m_X0;
m_aVertices[m_NumVertices + 4 * i].m_Pos.y = pArray[i].m_Y0;
m_aVertices[m_NumVertices + 4 * i].m_Tex = m_aTexture[0];
SetColor(&m_aVertices[m_NumVertices + 4 * i], 0);
m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X1;
m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y1;
m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1];
SetColor(&m_aVertices[m_NumVertices + 4*i + 1], 1);
m_aVertices[m_NumVertices + 4 * i + 1].m_Pos.x = pArray[i].m_X1;
m_aVertices[m_NumVertices + 4 * i + 1].m_Pos.y = pArray[i].m_Y1;
m_aVertices[m_NumVertices + 4 * i + 1].m_Tex = m_aTexture[1];
SetColor(&m_aVertices[m_NumVertices + 4 * i + 1], 1);
m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X3;
m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y3;
m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[3];
SetColor(&m_aVertices[m_NumVertices + 4*i + 2], 3);
m_aVertices[m_NumVertices + 4 * i + 2].m_Pos.x = pArray[i].m_X3;
m_aVertices[m_NumVertices + 4 * i + 2].m_Pos.y = pArray[i].m_Y3;
m_aVertices[m_NumVertices + 4 * i + 2].m_Tex = m_aTexture[3];
SetColor(&m_aVertices[m_NumVertices + 4 * i + 2], 3);
m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X2;
m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y2;
m_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[2];
SetColor(&m_aVertices[m_NumVertices + 4*i + 3], 2);
m_aVertices[m_NumVertices + 4 * i + 3].m_Pos.x = pArray[i].m_X2;
m_aVertices[m_NumVertices + 4 * i + 3].m_Pos.y = pArray[i].m_Y2;
m_aVertices[m_NumVertices + 4 * i + 3].m_Tex = m_aTexture[2];
SetColor(&m_aVertices[m_NumVertices + 4 * i + 3], 2);
}
AddVertices(4*Num);
AddVertices(4 * Num);
}
}
@ -888,19 +895,19 @@ void CGraphics_Threaded::QuadsText(float x, float y, float Size, const char *pTe
else
{
QuadsSetSubset(
(c%16)/16.0f,
(c/16)/16.0f,
(c%16)/16.0f+1.0f/16.0f,
(c/16)/16.0f+1.0f/16.0f);
(c % 16) / 16.0f,
(c / 16) / 16.0f,
(c % 16) / 16.0f + 1.0f / 16.0f,
(c / 16) / 16.0f + 1.0f / 16.0f);
CQuadItem QuadItem(x, y, Size, Size);
QuadsDrawTL(&QuadItem, 1);
x += Size/2;
x += Size / 2;
}
}
}
void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor, char** pOffsets, unsigned int *IndicedVertexDrawNum, size_t NumIndicesOffet)
void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor, char **pOffsets, unsigned int *IndicedVertexDrawNum, size_t NumIndicesOffet)
{
if(NumIndicesOffet == 0)
return;
@ -912,21 +919,21 @@ void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor
Cmd.m_BufferContainerIndex = BufferContainerIndex;
mem_copy(&Cmd.m_Color, pColor, sizeof(Cmd.m_Color));
void *Data = m_pCommandBuffer->AllocData((sizeof(char*) + sizeof(unsigned int))*NumIndicesOffet);
void *Data = m_pCommandBuffer->AllocData((sizeof(char *) + sizeof(unsigned int)) * NumIndicesOffet);
if(Data == 0x0)
{
// kick command buffer and try again
KickCommandBuffer();
void *Data = m_pCommandBuffer->AllocData((sizeof(char*) + sizeof(unsigned int))*NumIndicesOffet);
void *Data = m_pCommandBuffer->AllocData((sizeof(char *) + sizeof(unsigned int)) * NumIndicesOffet);
if(Data == 0x0)
{
dbg_msg("graphics", "failed to allocate data for vertices");
return;
}
}
Cmd.m_pIndicesOffsets = (char**)Data;
Cmd.m_pDrawCount = (unsigned int*)(((char*)Data) + (sizeof(char*)*NumIndicesOffet));
Cmd.m_pIndicesOffsets = (char **)Data;
Cmd.m_pDrawCount = (unsigned int *)(((char *)Data) + (sizeof(char *) * NumIndicesOffet));
// check if we have enough free memory in the commandbuffer
if(!m_pCommandBuffer->AddCommand(Cmd))
@ -934,14 +941,14 @@ void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor
// kick command buffer and try again
KickCommandBuffer();
Data = m_pCommandBuffer->AllocData((sizeof(char*) + sizeof(unsigned int))*NumIndicesOffet);
Data = m_pCommandBuffer->AllocData((sizeof(char *) + sizeof(unsigned int)) * NumIndicesOffet);
if(Data == 0x0)
{
dbg_msg("graphics", "failed to allocate data for vertices");
return;
}
Cmd.m_pIndicesOffsets = (char**)Data;
Cmd.m_pDrawCount = (unsigned int*)(((char*)Data) + (sizeof(char*)*NumIndicesOffet));
Cmd.m_pIndicesOffsets = (char **)Data;
Cmd.m_pDrawCount = (unsigned int *)(((char *)Data) + (sizeof(char *) * NumIndicesOffet));
if(!m_pCommandBuffer->AddCommand(Cmd))
{
@ -950,9 +957,8 @@ void CGraphics_Threaded::RenderTileLayer(int BufferContainerIndex, float *pColor
}
}
mem_copy(Cmd.m_pIndicesOffsets, pOffsets, sizeof(char*)*NumIndicesOffet);
mem_copy(Cmd.m_pDrawCount, IndicedVertexDrawNum, sizeof(unsigned int)*NumIndicesOffet);
mem_copy(Cmd.m_pIndicesOffsets, pOffsets, sizeof(char *) * NumIndicesOffet);
mem_copy(Cmd.m_pDrawCount, IndicedVertexDrawNum, sizeof(unsigned int) * NumIndicesOffet);
//todo max indices group check!!
}
@ -1023,7 +1029,7 @@ void CGraphics_Threaded::RenderBorderTileLines(int BufferContainerIndex, float *
}
}
void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderInfo* pQuadInfo, int QuadNum)
void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderInfo *pQuadInfo, int QuadNum)
{
if(QuadNum == 0)
return;
@ -1034,7 +1040,7 @@ void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderIn
Cmd.m_QuadNum = QuadNum;
Cmd.m_BufferContainerIndex = BufferContainerIndex;
Cmd.m_pQuadInfo = (SQuadRenderInfo*)AllocCommandBufferData(QuadNum * sizeof(SQuadRenderInfo));
Cmd.m_pQuadInfo = (SQuadRenderInfo *)AllocCommandBufferData(QuadNum * sizeof(SQuadRenderInfo));
if(Cmd.m_pQuadInfo == 0x0)
return;
@ -1044,7 +1050,7 @@ void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderIn
// kick command buffer and try again
KickCommandBuffer();
Cmd.m_pQuadInfo = (SQuadRenderInfo*)m_pCommandBuffer->AllocData(QuadNum * sizeof(SQuadRenderInfo));
Cmd.m_pQuadInfo = (SQuadRenderInfo *)m_pCommandBuffer->AllocData(QuadNum * sizeof(SQuadRenderInfo));
if(Cmd.m_pQuadInfo == 0x0)
{
dbg_msg("graphics", "failed to allocate data for the quad info");
@ -1061,7 +1067,7 @@ void CGraphics_Threaded::RenderQuadLayer(int BufferContainerIndex, SQuadRenderIn
mem_copy(Cmd.m_pQuadInfo, pQuadInfo, sizeof(SQuadRenderInfo) * QuadNum);
}
void CGraphics_Threaded::RenderText(int BufferContainerIndex, int TextQuadNum, int TextureSize, int TextureTextIndex, int TextureTextOutlineIndex, float* pTextColor, float* pTextoutlineColor)
void CGraphics_Threaded::RenderText(int BufferContainerIndex, int TextQuadNum, int TextureSize, int TextureTextIndex, int TextureTextOutlineIndex, float *pTextColor, float *pTextoutlineColor)
{
if(BufferContainerIndex == -1)
return;
@ -1112,7 +1118,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex)
{
if(IsQuadContainerBufferingEnabled())
{
SQuadContainer& Container = m_QuadContainers[ContainerIndex];
SQuadContainer &Container = m_QuadContainers[ContainerIndex];
if(Container.m_Quads.size() > 0)
{
if(Container.m_QuadBufferObjectIndex == -1)
@ -1132,7 +1138,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex)
Info.m_Stride = sizeof(CCommandBuffer::SVertex);
Info.m_Attributes.push_back(SBufferContainerInfo::SAttribute());
SBufferContainerInfo::SAttribute* pAttr = &Info.m_Attributes.back();
SBufferContainerInfo::SAttribute *pAttr = &Info.m_Attributes.back();
pAttr->m_DataTypeCount = 2;
pAttr->m_FuncType = 0;
pAttr->m_Normalized = false;
@ -1144,7 +1150,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex)
pAttr->m_DataTypeCount = 2;
pAttr->m_FuncType = 0;
pAttr->m_Normalized = false;
pAttr->m_pOffset = (void*)(sizeof(float) * 2);
pAttr->m_pOffset = (void *)(sizeof(float) * 2);
pAttr->m_Type = GRAPHICS_TYPE_FLOAT;
pAttr->m_VertBufferBindingIndex = Container.m_QuadBufferObjectIndex;
Info.m_Attributes.push_back(SBufferContainerInfo::SAttribute());
@ -1152,7 +1158,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex)
pAttr->m_DataTypeCount = 4;
pAttr->m_FuncType = 0;
pAttr->m_Normalized = true;
pAttr->m_pOffset = (void*)(sizeof(float) * 2 + sizeof(float) * 2);
pAttr->m_pOffset = (void *)(sizeof(float) * 2 + sizeof(float) * 2);
pAttr->m_Type = GRAPHICS_TYPE_UNSIGNED_BYTE;
pAttr->m_VertBufferBindingIndex = Container.m_QuadBufferObjectIndex;
@ -1164,7 +1170,7 @@ void CGraphics_Threaded::QuadContainerUpload(int ContainerIndex)
void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CQuadItem *pArray, int Num)
{
SQuadContainer& Container = m_QuadContainers[ContainerIndex];
SQuadContainer &Container = m_QuadContainers[ContainerIndex];
if((int)Container.m_Quads.size() > Num + CCommandBuffer::MAX_VERTICES)
return;
@ -1172,7 +1178,7 @@ void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CQuadItem *pA
for(int i = 0; i < Num; ++i)
{
Container.m_Quads.push_back(SQuadContainer::SQuad());
SQuadContainer::SQuad& Quad = Container.m_Quads.back();
SQuadContainer::SQuad &Quad = Container.m_Quads.back();
Quad.m_aVertices[0].m_Pos.x = pArray[i].m_X;
Quad.m_aVertices[0].m_Pos.y = pArray[i].m_Y;
@ -1209,7 +1215,7 @@ void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CQuadItem *pA
void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CFreeformItem *pArray, int Num)
{
SQuadContainer& Container = m_QuadContainers[ContainerIndex];
SQuadContainer &Container = m_QuadContainers[ContainerIndex];
if((int)Container.m_Quads.size() > Num + CCommandBuffer::MAX_VERTICES)
return;
@ -1217,7 +1223,7 @@ void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CFreeformItem
for(int i = 0; i < Num; ++i)
{
Container.m_Quads.push_back(SQuadContainer::SQuad());
SQuadContainer::SQuad& Quad = Container.m_Quads.back();
SQuadContainer::SQuad &Quad = Container.m_Quads.back();
Quad.m_aVertices[0].m_Pos.x = pArray[i].m_X0;
Quad.m_aVertices[0].m_Pos.y = pArray[i].m_Y0;
@ -1245,7 +1251,7 @@ void CGraphics_Threaded::QuadContainerAddQuads(int ContainerIndex, CFreeformItem
void CGraphics_Threaded::QuadContainerReset(int ContainerIndex)
{
SQuadContainer& Container = m_QuadContainers[ContainerIndex];
SQuadContainer &Container = m_QuadContainers[ContainerIndex];
if(IsQuadContainerBufferingEnabled())
{
if(Container.m_QuadBufferContainerIndex != -1)
@ -1271,7 +1277,7 @@ void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadDrawNum
void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadOffset, int QuadDrawNum)
{
SQuadContainer& Container = m_QuadContainers[ContainerIndex];
SQuadContainer &Container = m_QuadContainers[ContainerIndex];
if(QuadDrawNum == -1)
QuadDrawNum = (int)Container.m_Quads.size() - QuadOffset;
@ -1287,7 +1293,7 @@ void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadOffset,
CCommandBuffer::SCommand_RenderQuadContainer Cmd;
Cmd.m_State = m_State;
Cmd.m_DrawNum = (unsigned int)QuadDrawNum * 6;
Cmd.m_pOffset = (void*)(QuadOffset * 6 * sizeof(unsigned int));
Cmd.m_pOffset = (void *)(QuadOffset * 6 * sizeof(unsigned int));
Cmd.m_BufferContainerIndex = Container.m_QuadBufferContainerIndex;
// check if we have enough free memory in the commandbuffer
@ -1309,7 +1315,7 @@ void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadOffset,
{
for(int i = 0; i < QuadDrawNum; ++i)
{
SQuadContainer::SQuad& Quad = Container.m_Quads[QuadOffset + i];
SQuadContainer::SQuad &Quad = Container.m_Quads[QuadOffset + i];
m_aVertices[i * 6] = Quad.m_aVertices[0];
m_aVertices[i * 6 + 1] = Quad.m_aVertices[1];
m_aVertices[i * 6 + 2] = Quad.m_aVertices[2];
@ -1332,7 +1338,7 @@ void CGraphics_Threaded::RenderQuadContainer(int ContainerIndex, int QuadOffset,
void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int QuadOffset, float X, float Y, float ScaleX, float ScaleY)
{
SQuadContainer& Container = m_QuadContainers[ContainerIndex];
SQuadContainer &Container = m_QuadContainers[ContainerIndex];
if((int)Container.m_Quads.size() < QuadOffset + 1)
return;
@ -1342,7 +1348,7 @@ void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int Qua
if(Container.m_QuadBufferContainerIndex == -1)
return;
SQuadContainer::SQuad& Quad = Container.m_Quads[QuadOffset];
SQuadContainer::SQuad &Quad = Container.m_Quads[QuadOffset];
CCommandBuffer::SCommand_RenderQuadContainerAsSprite Cmd;
float ScreenX0, ScreenY0, ScreenX1, ScreenY1;
@ -1352,7 +1358,7 @@ void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int Qua
MapScreen(ScreenX0, ScreenY0, ScreenX1, ScreenY1);
Cmd.m_DrawNum = 1 * 6;
Cmd.m_pOffset = (void*)(QuadOffset * 6 * sizeof(unsigned int));
Cmd.m_pOffset = (void *)(QuadOffset * 6 * sizeof(unsigned int));
Cmd.m_BufferContainerIndex = Container.m_QuadBufferContainerIndex;
Cmd.m_VertexColor.r = (float)m_aColor[0].r / 255.f;
@ -1383,7 +1389,7 @@ void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int Qua
{
if(g_Config.m_GfxQuadAsTriangle)
{
SQuadContainer::SQuad& Quad = Container.m_Quads[QuadOffset];
SQuadContainer::SQuad &Quad = Container.m_Quads[QuadOffset];
m_aVertices[0] = Quad.m_aVertices[0];
m_aVertices[1] = Quad.m_aVertices[1];
m_aVertices[2] = Quad.m_aVertices[2];
@ -1458,7 +1464,7 @@ void CGraphics_Threaded::RenderQuadContainerAsSprite(int ContainerIndex, int Qua
void CGraphics_Threaded::RenderQuadContainerAsSpriteMultiple(int ContainerIndex, int QuadOffset, int DrawCount, SRenderSpriteInfo *pRenderInfo)
{
SQuadContainer& Container = m_QuadContainers[ContainerIndex];
SQuadContainer &Container = m_QuadContainers[ContainerIndex];
if(DrawCount == 0)
return;
@ -1468,14 +1474,14 @@ void CGraphics_Threaded::RenderQuadContainerAsSpriteMultiple(int ContainerIndex,
if(Container.m_QuadBufferContainerIndex == -1)
return;
SQuadContainer::SQuad& Quad = Container.m_Quads[0];
SQuadContainer::SQuad &Quad = Container.m_Quads[0];
CCommandBuffer::SCommand_RenderQuadContainerAsSpriteMultiple Cmd;
Cmd.m_State = m_State;
Cmd.m_DrawNum = 1 * 6;
Cmd.m_DrawCount = DrawCount;
Cmd.m_pOffset = (void*)(QuadOffset * 6 * sizeof(unsigned int));
Cmd.m_pOffset = (void *)(QuadOffset * 6 * sizeof(unsigned int));
Cmd.m_BufferContainerIndex = Container.m_QuadBufferContainerIndex;
Cmd.m_VertexColor.r = (float)m_aColor[0].r / 255.f;
@ -1533,9 +1539,9 @@ void CGraphics_Threaded::RenderQuadContainerAsSpriteMultiple(int ContainerIndex,
}
}
void* CGraphics_Threaded::AllocCommandBufferData(unsigned AllocSize)
void *CGraphics_Threaded::AllocCommandBufferData(unsigned AllocSize)
{
void* pData = m_pCommandBuffer->AllocData(AllocSize);
void *pData = m_pCommandBuffer->AllocData(AllocSize);
if(pData == 0x0)
{
// kick command buffer and try again
@ -1597,7 +1603,8 @@ int CGraphics_Threaded::CreateBufferObject(size_t UploadDataSize, void *pUploadD
}
mem_copy(Cmd.m_pUploadData, pUploadData, UploadDataSize);
}
else {
else
{
Cmd.m_pUploadData = NULL;
// check if we have enough free memory in the commandbuffer
if(!m_pCommandBuffer->AddCommand(Cmd))
@ -1613,10 +1620,11 @@ int CGraphics_Threaded::CreateBufferObject(size_t UploadDataSize, void *pUploadD
// update the buffer instead
size_t UploadDataOffset = 0;
while(UploadDataSize > 0) {
while(UploadDataSize > 0)
{
size_t UpdateSize = (UploadDataSize > CMD_BUFFER_DATA_BUFFER_SIZE ? CMD_BUFFER_DATA_BUFFER_SIZE : UploadDataSize);
UpdateBufferObject(Index, UpdateSize, (((char*)pUploadData) + UploadDataOffset), (void*)UploadDataOffset);
UpdateBufferObject(Index, UpdateSize, (((char *)pUploadData) + UploadDataOffset), (void *)UploadDataOffset);
UploadDataOffset += UpdateSize;
UploadDataSize -= UpdateSize;
@ -1626,7 +1634,7 @@ int CGraphics_Threaded::CreateBufferObject(size_t UploadDataSize, void *pUploadD
return Index;
}
void CGraphics_Threaded::RecreateBufferObject(int BufferIndex, size_t UploadDataSize, void* pUploadData)
void CGraphics_Threaded::RecreateBufferObject(int BufferIndex, size_t UploadDataSize, void *pUploadData)
{
CCommandBuffer::SCommand_RecreateBufferObject Cmd;
Cmd.m_BufferIndex = BufferIndex;
@ -1660,7 +1668,8 @@ void CGraphics_Threaded::RecreateBufferObject(int BufferIndex, size_t UploadData
mem_copy(Cmd.m_pUploadData, pUploadData, UploadDataSize);
}
else {
else
{
Cmd.m_pUploadData = NULL;
// check if we have enough free memory in the commandbuffer
if(!m_pCommandBuffer->AddCommand(Cmd))
@ -1676,10 +1685,11 @@ void CGraphics_Threaded::RecreateBufferObject(int BufferIndex, size_t UploadData
// update the buffer instead
size_t UploadDataOffset = 0;
while(UploadDataSize > 0) {
while(UploadDataSize > 0)
{
size_t UpdateSize = (UploadDataSize > CMD_BUFFER_DATA_BUFFER_SIZE ? CMD_BUFFER_DATA_BUFFER_SIZE : UploadDataSize);
UpdateBufferObject(BufferIndex, UpdateSize, (((char*)pUploadData) + UploadDataOffset), (void*)UploadDataOffset);
UpdateBufferObject(BufferIndex, UpdateSize, (((char *)pUploadData) + UploadDataOffset), (void *)UploadDataOffset);
UploadDataOffset += UpdateSize;
UploadDataSize -= UpdateSize;
@ -1790,7 +1800,7 @@ int CGraphics_Threaded::CreateBufferContainer(SBufferContainerInfo *pContainerIn
Cmd.m_AttrCount = (int)pContainerInfo->m_Attributes.size();
Cmd.m_Stride = pContainerInfo->m_Stride;
Cmd.m_Attributes = (SBufferContainerInfo::SAttribute*)AllocCommandBufferData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute));
Cmd.m_Attributes = (SBufferContainerInfo::SAttribute *)AllocCommandBufferData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute));
if(Cmd.m_Attributes == NULL)
return -1;
@ -1800,7 +1810,7 @@ int CGraphics_Threaded::CreateBufferContainer(SBufferContainerInfo *pContainerIn
// kick command buffer and try again
KickCommandBuffer();
Cmd.m_Attributes = (SBufferContainerInfo::SAttribute*)m_pCommandBuffer->AllocData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute));
Cmd.m_Attributes = (SBufferContainerInfo::SAttribute *)m_pCommandBuffer->AllocData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute));
if(Cmd.m_Attributes == 0x0)
{
dbg_msg("graphics", "failed to allocate data for upload data");
@ -1865,7 +1875,6 @@ void CGraphics_Threaded::DeleteBufferContainer(int ContainerIndex, bool DestroyA
}
m_VertexArrayInfo[ContainerIndex].m_AssociatedBufferObjectIndices.clear();
// also clear the buffer object index
m_VertexArrayInfo[ContainerIndex].m_FreeIndex = m_FirstFreeVertexArrayInfo;
m_FirstFreeVertexArrayInfo = ContainerIndex;
@ -1878,7 +1887,7 @@ void CGraphics_Threaded::UpdateBufferContainer(int ContainerIndex, SBufferContai
Cmd.m_AttrCount = (int)pContainerInfo->m_Attributes.size();
Cmd.m_Stride = pContainerInfo->m_Stride;
Cmd.m_Attributes = (SBufferContainerInfo::SAttribute*)AllocCommandBufferData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute));
Cmd.m_Attributes = (SBufferContainerInfo::SAttribute *)AllocCommandBufferData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute));
if(Cmd.m_Attributes == NULL)
return;
@ -1888,7 +1897,7 @@ void CGraphics_Threaded::UpdateBufferContainer(int ContainerIndex, SBufferContai
// kick command buffer and try again
KickCommandBuffer();
Cmd.m_Attributes = (SBufferContainerInfo::SAttribute*)m_pCommandBuffer->AllocData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute));
Cmd.m_Attributes = (SBufferContainerInfo::SAttribute *)m_pCommandBuffer->AllocData(Cmd.m_AttrCount * sizeof(SBufferContainerInfo::SAttribute));
if(Cmd.m_Attributes == 0x0)
{
dbg_msg("graphics", "failed to allocate data for upload data");
@ -1932,11 +1941,16 @@ int CGraphics_Threaded::IssueInit()
{
int Flags = 0;
if(g_Config.m_GfxBorderless) Flags |= IGraphicsBackend::INITFLAG_BORDERLESS;
if(g_Config.m_GfxFullscreen) Flags |= IGraphicsBackend::INITFLAG_FULLSCREEN;
if(g_Config.m_GfxVsync) Flags |= IGraphicsBackend::INITFLAG_VSYNC;
if(g_Config.m_GfxHighdpi) Flags |= IGraphicsBackend::INITFLAG_HIGHDPI;
if(g_Config.m_GfxResizable) Flags |= IGraphicsBackend::INITFLAG_RESIZABLE;
if(g_Config.m_GfxBorderless)
Flags |= IGraphicsBackend::INITFLAG_BORDERLESS;
if(g_Config.m_GfxFullscreen)
Flags |= IGraphicsBackend::INITFLAG_FULLSCREEN;
if(g_Config.m_GfxVsync)
Flags |= IGraphicsBackend::INITFLAG_VSYNC;
if(g_Config.m_GfxHighdpi)
Flags |= IGraphicsBackend::INITFLAG_HIGHDPI;
if(g_Config.m_GfxResizable)
Flags |= IGraphicsBackend::INITFLAG_RESIZABLE;
int r = m_pBackend->Init("DDNet Client", &g_Config.m_GfxScreen, &g_Config.m_GfxScreenWidth, &g_Config.m_GfxScreenHeight, g_Config.m_GfxFsaaSamples, Flags, &m_DesktopScreenWidth, &m_DesktopScreenHeight, &m_ScreenWidth, &m_ScreenHeight, m_pStorage);
m_IsNewOpenGL = m_pBackend->IsNewOpenGL();
@ -2069,9 +2083,9 @@ int CGraphics_Threaded::Init()
// init textures
m_FirstFreeTexture = 0;
for(int i = 0; i < MAX_TEXTURES-1; i++)
m_aTextureIndices[i] = i+1;
m_aTextureIndices[MAX_TEXTURES-1] = -1;
for(int i = 0; i < MAX_TEXTURES - 1; i++)
m_aTextureIndices[i] = i + 1;
m_aTextureIndices[MAX_TEXTURES - 1] = -1;
m_FirstFreeVertexArrayInfo = -1;
m_FirstFreeBufferObjectIndex = -1;
@ -2088,13 +2102,12 @@ int CGraphics_Threaded::Init()
// create null texture, will get id=0
static const unsigned char s_aNullTextureData[] = {
0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff,
0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff,
0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff,
0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff,
};
0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff,
0xff, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff,
0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0xff,
0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0xff};
m_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,s_aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE);
m_InvalidTexture = LoadTextureRaw(4, 4, CImageInfo::FORMAT_RGBA, s_aNullTextureData, CImageInfo::FORMAT_RGBA, TEXLOAD_NORESAMPLE);
return 0;
}
@ -2144,17 +2157,17 @@ bool CGraphics_Threaded::SetWindowScreen(int Index)
void CGraphics_Threaded::Resize(int w, int h)
{
#if defined(CONF_VIDEORECORDER)
if (IVideo::Current() && IVideo::Current()->IsRecording())
if(IVideo::Current() && IVideo::Current()->IsRecording())
return;
#endif
if(m_ScreenWidth == w && m_ScreenHeight == h)
return;
if(h > 4*w/5)
h = 4*w/5;
if(w > 21*h/9)
w = 21*h/9;
if(h > 4 * w / 5)
h = 4 * w / 5;
if(w > 21 * h / 9)
w = 21 * h / 9;
m_ScreenWidth = w;
m_ScreenHeight = h;
@ -2207,7 +2220,7 @@ void CGraphics_Threaded::TakeScreenshot(const char *pFilename)
// TODO: screenshot support
char aDate[20];
str_timestamp(aDate, sizeof(aDate));
str_format(m_aScreenshotName, sizeof(m_aScreenshotName), "screenshots/%s_%s.png", pFilename?pFilename:"screenshot", aDate);
str_format(m_aScreenshotName, sizeof(m_aScreenshotName), "screenshots/%s_%s.png", pFilename ? pFilename : "screenshot", aDate);
m_DoScreenshot = true;
}
@ -2221,7 +2234,7 @@ void CGraphics_Threaded::Swap()
{
if(!m_Warnings.empty())
{
SGraphicsWarning* pCurWarning = GetCurWarning();
SGraphicsWarning *pCurWarning = GetCurWarning();
if(pCurWarning->m_WasShown)
{
m_Warnings.erase(m_Warnings.begin());
@ -2287,7 +2300,7 @@ SGraphicsWarning *CGraphics_Threaded::GetCurWarning()
return NULL;
else
{
SGraphicsWarning* pCurWarning = &m_Warnings[0];
SGraphicsWarning *pCurWarning = &m_Warnings[0];
return pCurWarning;
}
}
@ -2296,7 +2309,7 @@ int CGraphics_Threaded::GetVideoModes(CVideoMode *pModes, int MaxModes, int Scre
{
if(g_Config.m_GfxDisplayAllModes)
{
int Count = sizeof(g_aFakeModes)/sizeof(CVideoMode);
int Count = sizeof(g_aFakeModes) / sizeof(CVideoMode);
mem_copy(pModes, g_aFakeModes, sizeof(g_aFakeModes));
if(MaxModes < Count)
Count = MaxModes;

View file

@ -2,11 +2,12 @@
#define ENGINE_CLIENT_GRAPHICS_THREADED_H
#include <engine/graphics.h>
#include <engine/shared/config.h>
#include <vector>
#define CMD_BUFFER_DATA_BUFFER_SIZE 1024*1024*2
#define CMD_BUFFER_CMD_BUFFER_SIZE 1024*256
#define CMD_BUFFER_DATA_BUFFER_SIZE 1024 * 1024 * 2
#define CMD_BUFFER_CMD_BUFFER_SIZE 1024 * 256
class CCommandBuffer
{
@ -15,6 +16,7 @@ class CCommandBuffer
unsigned char *m_pData;
unsigned m_Size;
unsigned m_Used;
public:
CBuffer(unsigned BufferSize)
{
@ -25,7 +27,7 @@ class CCommandBuffer
~CBuffer()
{
delete [] m_pData;
delete[] m_pData;
m_pData = 0x0;
m_Used = 0;
m_Size = 0;
@ -56,8 +58,8 @@ public:
enum
{
MAX_TEXTURES=1024*4,
MAX_VERTICES=32*1024,
MAX_TEXTURES = 1024 * 4,
MAX_VERTICES = 32 * 1024,
};
enum
@ -170,7 +172,8 @@ public:
struct SCommand
{
public:
SCommand(unsigned Cmd) : m_Cmd(Cmd), m_Size(0) {}
SCommand(unsigned Cmd) :
m_Cmd(Cmd), m_Size(0) {}
unsigned m_Cmd;
unsigned m_Size;
};
@ -193,25 +196,29 @@ public:
struct SCommand_Clear : public SCommand
{
SCommand_Clear() : SCommand(CMD_CLEAR) {}
SCommand_Clear() :
SCommand(CMD_CLEAR) {}
SColorf m_Color;
};
struct SCommand_Signal : public SCommand
{
SCommand_Signal() : SCommand(CMD_SIGNAL) {}
SCommand_Signal() :
SCommand(CMD_SIGNAL) {}
semaphore *m_pSemaphore;
};
struct SCommand_RunBuffer : public SCommand
{
SCommand_RunBuffer() : SCommand(CMD_RUNBUFFER) {}
SCommand_RunBuffer() :
SCommand(CMD_RUNBUFFER) {}
CCommandBuffer *m_pOtherBuffer;
};
struct SCommand_Render : public SCommand
{
SCommand_Render() : SCommand(CMD_RENDER) {}
SCommand_Render() :
SCommand(CMD_RENDER) {}
SState m_State;
unsigned m_PrimType;
unsigned m_PrimCount;
@ -220,8 +227,8 @@ public:
struct SCommand_RenderTex3D : public SCommand
{
SCommand_RenderTex3D()
: SCommand(CMD_RENDER_TEX3D) {}
SCommand_RenderTex3D() :
SCommand(CMD_RENDER_TEX3D) {}
SState m_State;
unsigned m_PrimType;
unsigned m_PrimCount;
@ -230,7 +237,8 @@ public:
struct SCommand_CreateBufferObject : public SCommand
{
SCommand_CreateBufferObject() : SCommand(CMD_CREATE_BUFFER_OBJECT) {}
SCommand_CreateBufferObject() :
SCommand(CMD_CREATE_BUFFER_OBJECT) {}
int m_BufferIndex;
@ -238,10 +246,10 @@ public:
size_t m_DataSize;
};
struct SCommand_RecreateBufferObject : public SCommand
{
SCommand_RecreateBufferObject() : SCommand(CMD_RECREATE_BUFFER_OBJECT) {}
SCommand_RecreateBufferObject() :
SCommand(CMD_RECREATE_BUFFER_OBJECT) {}
int m_BufferIndex;
@ -251,7 +259,8 @@ public:
struct SCommand_UpdateBufferObject : public SCommand
{
SCommand_UpdateBufferObject() : SCommand(CMD_UPDATE_BUFFER_OBJECT) {}
SCommand_UpdateBufferObject() :
SCommand(CMD_UPDATE_BUFFER_OBJECT) {}
int m_BufferIndex;
@ -262,7 +271,8 @@ public:
struct SCommand_CopyBufferObject : public SCommand
{
SCommand_CopyBufferObject() : SCommand(CMD_COPY_BUFFER_OBJECT) {}
SCommand_CopyBufferObject() :
SCommand(CMD_COPY_BUFFER_OBJECT) {}
int m_WriteBufferIndex;
int m_ReadBufferIndex;
@ -274,38 +284,42 @@ public:
struct SCommand_DeleteBufferObject : public SCommand
{
SCommand_DeleteBufferObject() : SCommand(CMD_DELETE_BUFFER_OBJECT) {}
SCommand_DeleteBufferObject() :
SCommand(CMD_DELETE_BUFFER_OBJECT) {}
int m_BufferIndex;
};
struct SCommand_CreateBufferContainer : public SCommand
{
SCommand_CreateBufferContainer() : SCommand(CMD_CREATE_BUFFER_CONTAINER) {}
SCommand_CreateBufferContainer() :
SCommand(CMD_CREATE_BUFFER_CONTAINER) {}
int m_BufferContainerIndex;
int m_Stride;
int m_AttrCount;
SBufferContainerInfo::SAttribute* m_Attributes;
SBufferContainerInfo::SAttribute *m_Attributes;
};
struct SCommand_UpdateBufferContainer : public SCommand
{
SCommand_UpdateBufferContainer() : SCommand(CMD_UPDATE_BUFFER_CONTAINER) {}
SCommand_UpdateBufferContainer() :
SCommand(CMD_UPDATE_BUFFER_CONTAINER) {}
int m_BufferContainerIndex;
int m_Stride;
int m_AttrCount;
SBufferContainerInfo::SAttribute* m_Attributes;
SBufferContainerInfo::SAttribute *m_Attributes;
};
struct SCommand_DeleteBufferContainer : public SCommand
{
SCommand_DeleteBufferContainer() : SCommand(CMD_DELETE_BUFFER_CONTAINER) {}
SCommand_DeleteBufferContainer() :
SCommand(CMD_DELETE_BUFFER_CONTAINER) {}
int m_BufferContainerIndex;
bool m_DestroyAllBO;
@ -313,19 +327,21 @@ public:
struct SCommand_IndicesRequiredNumNotify : public SCommand
{
SCommand_IndicesRequiredNumNotify() : SCommand(CMD_INDICES_REQUIRED_NUM_NOTIFY) {}
SCommand_IndicesRequiredNumNotify() :
SCommand(CMD_INDICES_REQUIRED_NUM_NOTIFY) {}
unsigned int m_RequiredIndicesNum;
};
struct SCommand_RenderTileLayer : public SCommand
{
SCommand_RenderTileLayer() : SCommand(CMD_RENDER_TILE_LAYER) {}
SCommand_RenderTileLayer() :
SCommand(CMD_RENDER_TILE_LAYER) {}
SState m_State;
SColorf m_Color; //the color of the whole tilelayer -- already envelopped
//the char offset of all indices that should be rendered, and the amount of renders
char** m_pIndicesOffsets;
char **m_pIndicesOffsets;
unsigned int *m_pDrawCount;
int m_IndicesDrawNum;
@ -334,7 +350,8 @@ public:
struct SCommand_RenderBorderTile : public SCommand
{
SCommand_RenderBorderTile() : SCommand(CMD_RENDER_BORDER_TILE) {}
SCommand_RenderBorderTile() :
SCommand(CMD_RENDER_BORDER_TILE) {}
SState m_State;
SColorf m_Color; //the color of the whole tilelayer -- already envelopped
char *m_pIndicesOffset; // you should use the command buffer data to allocate vertices for this command
@ -348,7 +365,8 @@ public:
struct SCommand_RenderBorderTileLine : public SCommand
{
SCommand_RenderBorderTileLine() : SCommand(CMD_RENDER_BORDER_TILE_LINE) {}
SCommand_RenderBorderTileLine() :
SCommand(CMD_RENDER_BORDER_TILE_LINE) {}
SState m_State;
SColorf m_Color; //the color of the whole tilelayer -- already envelopped
char *m_pIndicesOffset; // you should use the command buffer data to allocate vertices for this command
@ -362,17 +380,19 @@ public:
struct SCommand_RenderQuadLayer : public SCommand
{
SCommand_RenderQuadLayer() : SCommand(CMD_RENDER_QUAD_LAYER) {}
SCommand_RenderQuadLayer() :
SCommand(CMD_RENDER_QUAD_LAYER) {}
SState m_State;
int m_BufferContainerIndex;
SQuadRenderInfo* m_pQuadInfo;
SQuadRenderInfo *m_pQuadInfo;
int m_QuadNum;
};
struct SCommand_RenderText : public SCommand
{
SCommand_RenderText() : SCommand(CMD_RENDER_TEXT) {}
SCommand_RenderText() :
SCommand(CMD_RENDER_TEXT) {}
SState m_State;
int m_BufferContainerIndex;
@ -388,7 +408,8 @@ public:
struct SCommand_RenderTextStream : public SCommand
{
SCommand_RenderTextStream() : SCommand(CMD_RENDER_TEXT_STREAM) {}
SCommand_RenderTextStream() :
SCommand(CMD_RENDER_TEXT_STREAM) {}
SState m_State;
SVertex *m_pVertices;
@ -405,7 +426,8 @@ public:
struct SCommand_RenderQuadContainer : public SCommand
{
SCommand_RenderQuadContainer() : SCommand(CMD_RENDER_QUAD_CONTAINER) {}
SCommand_RenderQuadContainer() :
SCommand(CMD_RENDER_QUAD_CONTAINER) {}
SState m_State;
int m_BufferContainerIndex;
@ -416,7 +438,8 @@ public:
struct SCommand_RenderQuadContainerAsSprite : public SCommand
{
SCommand_RenderQuadContainerAsSprite() : SCommand(CMD_RENDER_QUAD_CONTAINER_SPRITE) {}
SCommand_RenderQuadContainerAsSprite() :
SCommand(CMD_RENDER_QUAD_CONTAINER_SPRITE) {}
SState m_State;
int m_BufferContainerIndex;
@ -432,7 +455,8 @@ public:
struct SCommand_RenderQuadContainerAsSpriteMultiple : public SCommand
{
SCommand_RenderQuadContainerAsSpriteMultiple() : SCommand(CMD_RENDER_QUAD_CONTAINER_SPRITE_MULTIPLE) {}
SCommand_RenderQuadContainerAsSpriteMultiple() :
SCommand(CMD_RENDER_QUAD_CONTAINER_SPRITE_MULTIPLE) {}
SState m_State;
int m_BufferContainerIndex;
@ -449,13 +473,15 @@ public:
struct SCommand_Screenshot : public SCommand
{
SCommand_Screenshot() : SCommand(CMD_SCREENSHOT) {}
SCommand_Screenshot() :
SCommand(CMD_SCREENSHOT) {}
CImageInfo *m_pImage; // processor will fill this out, the one who adds this command must free the data as well
};
struct SCommand_VideoModes : public SCommand
{
SCommand_VideoModes() : SCommand(CMD_VIDEOMODES) {}
SCommand_VideoModes() :
SCommand(CMD_VIDEOMODES) {}
CVideoMode *m_pModes; // processor will fill this in
int m_MaxModes; // maximum of modes the processor can write to the m_pModes
@ -465,14 +491,16 @@ public:
struct SCommand_Swap : public SCommand
{
SCommand_Swap() : SCommand(CMD_SWAP) {}
SCommand_Swap() :
SCommand(CMD_SWAP) {}
int m_Finish;
};
struct SCommand_VSync : public SCommand
{
SCommand_VSync() : SCommand(CMD_VSYNC) {}
SCommand_VSync() :
SCommand(CMD_VSYNC) {}
int m_VSync;
bool *m_pRetOk;
@ -480,7 +508,8 @@ public:
struct SCommand_Resize : public SCommand
{
SCommand_Resize() : SCommand(CMD_RESIZE) {}
SCommand_Resize() :
SCommand(CMD_RESIZE) {}
int m_Width;
int m_Height;
@ -488,7 +517,8 @@ public:
struct SCommand_Texture_Create : public SCommand
{
SCommand_Texture_Create() : SCommand(CMD_TEXTURE_CREATE) {}
SCommand_Texture_Create() :
SCommand(CMD_TEXTURE_CREATE) {}
// texture information
int m_Slot;
@ -504,7 +534,8 @@ public:
struct SCommand_Texture_Update : public SCommand
{
SCommand_Texture_Update() : SCommand(CMD_TEXTURE_UPDATE) {}
SCommand_Texture_Update() :
SCommand(CMD_TEXTURE_UPDATE) {}
// texture information
int m_Slot;
@ -517,18 +548,18 @@ public:
void *m_pData; // will be freed by the command processor
};
struct SCommand_Texture_Destroy : public SCommand
{
SCommand_Texture_Destroy() : SCommand(CMD_TEXTURE_DESTROY) {}
SCommand_Texture_Destroy() :
SCommand(CMD_TEXTURE_DESTROY) {}
// texture information
int m_Slot;
};
//
CCommandBuffer(unsigned CmdBufferSize, unsigned DataBufferSize)
: m_CmdBuffer(CmdBufferSize), m_DataBuffer(DataBufferSize)
CCommandBuffer(unsigned CmdBufferSize, unsigned DataBufferSize) :
m_CmdBuffer(CmdBufferSize), m_DataBuffer(DataBufferSize)
{
}
@ -589,11 +620,11 @@ class IGraphicsBackend
public:
enum
{
INITFLAG_FULLSCREEN = 1<<0,
INITFLAG_VSYNC = 1<<1,
INITFLAG_RESIZABLE = 1<<2,
INITFLAG_BORDERLESS = 1<<3,
INITFLAG_HIGHDPI = 1<<4,
INITFLAG_FULLSCREEN = 1 << 0,
INITFLAG_VSYNC = 1 << 1,
INITFLAG_RESIZABLE = 1 << 2,
INITFLAG_BORDERLESS = 1 << 3,
INITFLAG_HIGHDPI = 1 << 4,
};
virtual ~IGraphicsBackend() {}
@ -634,11 +665,11 @@ class CGraphics_Threaded : public IEngineGraphics
{
NUM_CMDBUFFERS = 2,
MAX_VERTICES = 32*1024,
MAX_TEXTURES = 1024*4,
MAX_VERTICES = 32 * 1024,
MAX_TEXTURES = 1024 * 4,
DRAWING_QUADS=1,
DRAWING_LINES=2
DRAWING_QUADS = 1,
DRAWING_LINES = 2
};
CCommandBuffer::SState m_State;
@ -684,7 +715,8 @@ class CGraphics_Threaded : public IEngineGraphics
struct SVertexArrayInfo
{
SVertexArrayInfo() : m_FreeIndex(-1) {}
SVertexArrayInfo() :
m_FreeIndex(-1) {}
// keep a reference to them, so we can free their IDs
std::vector<int> m_AssociatedBufferObjectIndices;
@ -710,7 +742,6 @@ class CGraphics_Threaded : public IEngineGraphics
CCommandBuffer::SVertex m_aVertices[4];
};
std::vector<SQuad> m_Quads;
int m_QuadBufferObjectIndex;
@ -723,13 +754,14 @@ class CGraphics_Threaded : public IEngineGraphics
struct SWindowResizeListener
{
SWindowResizeListener(WINDOW_RESIZE_FUNC pFunc, void *pUser) : m_pFunc(pFunc), m_pUser(pUser) {}
SWindowResizeListener(WINDOW_RESIZE_FUNC pFunc, void *pUser) :
m_pFunc(pFunc), m_pUser(pUser) {}
WINDOW_RESIZE_FUNC m_pFunc;
void *m_pUser;
};
std::vector<SWindowResizeListener> m_ResizeListeners;
void* AllocCommandBufferData(unsigned AllocSize);
void *AllocCommandBufferData(unsigned AllocSize);
void AddVertices(int Count);
void AddVertices(int Count, CCommandBuffer::SVertex *pVertices);
@ -757,6 +789,7 @@ class CGraphics_Threaded : public IEngineGraphics
int IssueInit();
int InitWindow();
public:
CGraphics_Threaded();

View file

@ -13,7 +13,7 @@
// TODO: Non-global pls?
static CURLSH *gs_Share;
static LOCK gs_aLocks[CURL_LOCK_DATA_LAST+1];
static LOCK gs_aLocks[CURL_LOCK_DATA_LAST + 1];
static int GetLockIndex(int Data)
{
@ -75,13 +75,13 @@ void EscapeUrl(char *pBuf, int Size, const char *pStr)
curl_free(pEsc);
}
CRequest::CRequest(const char *pUrl, CTimeout Timeout, bool LogProgress)
: m_Timeout(Timeout),
m_Size(0),
m_Progress(0),
m_LogProgress(LogProgress),
m_State(HTTP_QUEUED),
m_Abort(false)
CRequest::CRequest(const char *pUrl, CTimeout Timeout, bool LogProgress) :
m_Timeout(Timeout),
m_Size(0),
m_Progress(0),
m_LogProgress(LogProgress),
m_State(HTTP_QUEUED),
m_Abort(false)
{
str_copy(m_aUrl, pUrl, sizeof(m_aUrl));
}
@ -247,11 +247,11 @@ size_t CGet::OnData(char *pData, size_t DataSize)
return DataSize;
}
CGetFile::CGetFile(IStorage *pStorage, const char *pUrl, const char *pDest, int StorageType, CTimeout Timeout, bool LogProgress)
: CRequest(pUrl, Timeout, LogProgress),
m_pStorage(pStorage),
m_StorageType(StorageType),
m_File(0)
CGetFile::CGetFile(IStorage *pStorage, const char *pUrl, const char *pDest, int StorageType, CTimeout Timeout, bool LogProgress) :
CRequest(pUrl, Timeout, LogProgress),
m_pStorage(pStorage),
m_StorageType(StorageType),
m_File(0)
{
str_copy(m_aDest, pDest, sizeof(m_aDest));
@ -298,8 +298,8 @@ int CGetFile::OnCompletion(int State)
return State;
}
CPostJson::CPostJson(const char *pUrl, CTimeout Timeout, const char *pJson)
: CRequest(pUrl, Timeout)
CPostJson::CPostJson(const char *pUrl, CTimeout Timeout, const char *pJson) :
CRequest(pUrl, Timeout)
{
str_copy(m_aJson, pJson, sizeof(m_aJson));
}

View file

@ -1,9 +1,9 @@
#ifndef ENGINE_CLIENT_HTTP_H
#define ENGINE_CLIENT_HTTP_H
#include <engine/kernel.h>
#include <engine/shared/jobs.h>
#include <engine/storage.h>
#include <engine/kernel.h>
typedef struct _json_value json_value;
typedef void CURL;
@ -78,7 +78,17 @@ public:
CGet(const char *pUrl, CTimeout Timeout);
~CGet();
size_t ResultSize() const { if(!Result()) { return 0; } else { return m_BufferSize; } }
size_t ResultSize() const
{
if(!Result())
{
return 0;
}
else
{
return m_BufferSize;
}
}
unsigned char *Result() const;
unsigned char *TakeResult();
json_value *ResultJson() const;
@ -105,7 +115,6 @@ public:
const char *Dest() const { return m_aDest; }
};
class CPostJson : public CRequest
{
virtual size_t OnData(char *pData, size_t DataSize) { return DataSize; }

View file

@ -3,6 +3,11 @@
#ifndef ENGINE_CLIENT_INPUT_H
#define ENGINE_CLIENT_INPUT_H
#include <engine/graphics.h>
#include <engine/input.h>
#include <stddef.h>
class CInput : public IEngineInput
{
IEngineGraphics *m_pGraphics;

View file

@ -1,18 +1,18 @@
#include "opengl_sl.h"
#include <engine/shared/linereader.h>
#include <engine/storage.h>
#include <vector>
#include <stdio.h>
#include <string>
#include <vector>
bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char *pFile, int Type)
bool CGLSL::LoadShader(CGLSLCompiler *pCompiler, IStorage *pStorage, const char *pFile, int Type)
{
if (m_IsLoaded)
if(m_IsLoaded)
return true;
IOHANDLE f = pStorage->OpenFile(pFile, IOFLAG_READ, IStorage::TYPE_ALL);
std::vector<std::string> Lines;
if (f)
if(f)
{
bool IsNewOpenGL = pCompiler->m_OpenGLVersionMajor >= 4 || (pCompiler->m_OpenGLVersionMajor == 3 && pCompiler->m_OpenGLVersionMinor == 3);
//add compiler specific values
@ -38,7 +38,7 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char
}
}
for(CGLSLCompiler::SGLSLCompilerDefine& Define : pCompiler->m_Defines)
for(CGLSLCompiler::SGLSLCompilerDefine &Define : pCompiler->m_Defines)
{
Lines.push_back(std::string("#define ") + Define.m_DefineName + std::string(" ") + Define.m_DefineValue + std::string("\r\n"));
}
@ -50,8 +50,8 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char
CLineReader LineReader;
LineReader.Init(f);
char* ReadLine = NULL;
while ((ReadLine = LineReader.Get()))
char *ReadLine = NULL;
while((ReadLine = LineReader.Get()))
{
std::string Line;
pCompiler->ParseLine(Line, ReadLine, Type);
@ -60,9 +60,9 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char
}
io_close(f);
const char** ShaderCode = new const char*[Lines.size()];
const char **ShaderCode = new const char *[Lines.size()];
for (size_t i = 0; i < Lines.size(); ++i)
for(size_t i = 0; i < Lines.size(); ++i)
{
ShaderCode[i] = Lines[i].c_str();
}
@ -77,7 +77,7 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char
int CompilationStatus;
glGetShaderiv(shader, GL_COMPILE_STATUS, &CompilationStatus);
if (CompilationStatus == GL_FALSE)
if(CompilationStatus == GL_FALSE)
{
char buff[3000];
@ -97,13 +97,14 @@ bool CGLSL::LoadShader(CGLSLCompiler* pCompiler, IStorage *pStorage, const char
return true;
}
else return false;
else
return false;
}
void CGLSL::DeleteShader()
{
if (!IsLoaded()) return;
if(!IsLoaded())
return;
m_IsLoaded = false;
glDeleteShader(m_ShaderID);
}
@ -138,12 +139,12 @@ CGLSLCompiler::CGLSLCompiler(int OpenGLVersionMajor, int OpenGLVersionMinor, int
m_TextureReplaceType = 0;
}
void CGLSLCompiler::AddDefine(const std::string& DefineName, const std::string& DefineValue)
void CGLSLCompiler::AddDefine(const std::string &DefineName, const std::string &DefineValue)
{
m_Defines.emplace_back(SGLSLCompilerDefine(DefineName, DefineValue));
}
void CGLSLCompiler::AddDefine(const char* pDefineName, const char* pDefineValue)
void CGLSLCompiler::AddDefine(const char *pDefineName, const char *pDefineValue)
{
AddDefine(std::string(pDefineName), std::string(pDefineValue));
}
@ -153,12 +154,12 @@ void CGLSLCompiler::ClearDefines()
m_Defines.clear();
}
void CGLSLCompiler::ParseLine(std::string& Line, const char* pReadLine, int Type)
void CGLSLCompiler::ParseLine(std::string &Line, const char *pReadLine, int Type)
{
bool IsNewOpenGL = m_OpenGLVersionMajor >= 4 || (m_OpenGLVersionMajor == 3 && m_OpenGLVersionMinor == 3);
if(!IsNewOpenGL)
{
const char* pBuff = pReadLine;
const char *pBuff = pReadLine;
char aTmpStr[1024];
size_t TmpStrSize = 0;
while(*pBuff)
@ -168,13 +169,13 @@ void CGLSLCompiler::ParseLine(std::string& Line, const char* pReadLine, int Type
Line.append(1, *pBuff);
++pBuff;
}
while(*pBuff && !str_isspace(*pBuff) && *pBuff != '(' && *pBuff != '.')
{
aTmpStr[TmpStrSize++] = *pBuff;
++pBuff;
}
if(TmpStrSize > 0)
{
aTmpStr[TmpStrSize] = 0;
@ -221,7 +222,7 @@ void CGLSLCompiler::ParseLine(std::string& Line, const char* pReadLine, int Type
Found = true;
}
}
if(!Found)
{
dbg_msg("Shader compiler", "Fix shader for older OpenGL versions.");
@ -261,9 +262,9 @@ void CGLSLCompiler::ParseLine(std::string& Line, const char* pReadLine, int Type
else
{
Line.append(aTmpStr);
}
}
}
if(*pBuff)
{
Line.append(1, *pBuff);

View file

@ -2,21 +2,23 @@
#define ENGINE_CLIENT_OPENGL_SL_H
#include <GL/glew.h>
#include <vector>
#include <string>
#include <vector>
class CGLSLCompiler;
class CGLSL {
class CGLSL
{
public:
bool LoadShader(CGLSLCompiler* pCompiler, class IStorage *pStorage, const char *pFile, int Type);
bool LoadShader(CGLSLCompiler *pCompiler, class IStorage *pStorage, const char *pFile, int Type);
void DeleteShader();
bool IsLoaded();
GLuint GetShaderID();
CGLSL();
virtual ~CGLSL();
private:
GLuint m_ShaderID;
int m_Type;
@ -30,7 +32,7 @@ private:
struct SGLSLCompilerDefine
{
SGLSLCompilerDefine(const std::string& DefineName, const std::string& DefineValue)
SGLSLCompilerDefine(const std::string &DefineName, const std::string &DefineValue)
{
m_DefineName = DefineName;
m_DefineValue = DefineValue;
@ -52,11 +54,11 @@ public:
void SetHasTextureArray(bool TextureArray) { m_HasTextureArray = TextureArray; }
void SetTextureReplaceType(int TextureReplaceType) { m_TextureReplaceType = TextureReplaceType; }
void AddDefine(const std::string& DefineName, const std::string& DefineValue);
void AddDefine(const char* pDefineName, const char* pDefineValue);
void AddDefine(const std::string &DefineName, const std::string &DefineValue);
void AddDefine(const char *pDefineName, const char *pDefineValue);
void ClearDefines();
void ParseLine(std::string& Line, const char* pReadLine, int Type);
void ParseLine(std::string &Line, const char *pReadLine, int Type);
enum EGLSLCompilerTextureReplaceType
{

View file

@ -9,14 +9,15 @@ void CGLSLProgram::CreateProgram()
void CGLSLProgram::DeleteProgram()
{
if (!m_IsLinked) return;
if(!m_IsLinked)
return;
m_IsLinked = false;
glDeleteProgram(m_ProgramID);
}
bool CGLSLProgram::AddShader(CGLSL* pShader)
bool CGLSLProgram::AddShader(CGLSL *pShader)
{
if (pShader->IsLoaded())
if(pShader->IsLoaded())
{
glAttachShader(m_ProgramID, pShader->GetShaderID());
return true;
@ -24,9 +25,9 @@ bool CGLSLProgram::AddShader(CGLSL* pShader)
return false;
}
void CGLSLProgram::DetachShader(CGLSL* pShader)
void CGLSLProgram::DetachShader(CGLSL *pShader)
{
if (pShader->IsLoaded())
if(pShader->IsLoaded())
{
DetachShaderByID(pShader->GetShaderID());
}
@ -43,7 +44,7 @@ void CGLSLProgram::LinkProgram()
int LinkStatus;
glGetProgramiv(m_ProgramID, GL_LINK_STATUS, &LinkStatus);
m_IsLinked = LinkStatus == GL_TRUE;
if (!m_IsLinked)
if(!m_IsLinked)
{
char sInfoLog[1024];
char sFinalMessage[1536];
@ -52,7 +53,7 @@ void CGLSLProgram::LinkProgram()
str_format(sFinalMessage, 1536, "Error! Shader program wasn't linked! The linker returned:\n\n%s", sInfoLog);
dbg_msg("GLSL Program", "%s", sFinalMessage);
}
//detach all shaders attached to this program
DetachAllShaders();
}
@ -64,7 +65,7 @@ void CGLSLProgram::DetachAllShaders()
while(1)
{
glGetAttachedShaders(m_ProgramID, 100, &ReturnedCount, aShaders);
if(ReturnedCount > 0)
{
for(GLsizei i = 0; i < ReturnedCount; ++i)
@ -72,8 +73,9 @@ void CGLSLProgram::DetachAllShaders()
DetachShaderByID(aShaders[i]);
}
}
if(ReturnedCount < 100) break;
if(ReturnedCount < 100)
break;
}
}
@ -112,14 +114,15 @@ void CGLSLProgram::SetUniform(int Loc, const bool Value)
glUniform1i(Loc, (int)Value);
}
int CGLSLProgram::GetUniformLoc(const char* Name)
int CGLSLProgram::GetUniformLoc(const char *Name)
{
return glGetUniformLocation(m_ProgramID, Name);
}
void CGLSLProgram::UseProgram()
{
if(m_IsLinked) glUseProgram(m_ProgramID);
if(m_IsLinked)
glUseProgram(m_ProgramID);
}
GLuint CGLSLProgram::GetProgramID()

View file

@ -5,22 +5,23 @@
class CGLSL;
class CGLSLProgram {
class CGLSLProgram
{
public:
void CreateProgram();
void DeleteProgram();
bool AddShader(CGLSL* pShader);
bool AddShader(CGLSL *pShader);
void LinkProgram();
void UseProgram();
GLuint GetProgramID();
void DetachShader(CGLSL* pShader);
void DetachShader(CGLSL *pShader);
void DetachShaderByID(GLuint ShaderID);
void DetachAllShaders();
//Support various types
//Support various types
void SetUniformVec2(int Loc, int Count, const float *pValue);
void SetUniformVec4(int Loc, int Count, const float *pValue);
void SetUniform(int Loc, const int Value);
@ -28,21 +29,23 @@ public:
void SetUniform(int Loc, const bool Value);
void SetUniform(int Loc, const float Value);
void SetUniform(int Loc, int Count, const float *pValues);
//for performance reason we do not use SetUniform with using strings... save the Locations of the variables instead
int GetUniformLoc(const char* Name);
int GetUniformLoc(const char *Name);
CGLSLProgram();
virtual ~CGLSLProgram();
protected:
GLuint m_ProgramID;
bool m_IsLinked;
};
class CGLSLTWProgram : public CGLSLProgram {
class CGLSLTWProgram : public CGLSLProgram
{
public:
CGLSLTWProgram() : m_LocPos(-1), m_LocIsTextured(-1), m_LocTextureSampler(-1), m_LastTextureSampler(-1), m_LastIsTextured(-1)
CGLSLTWProgram() :
m_LocPos(-1), m_LocIsTextured(-1), m_LocTextureSampler(-1), m_LastTextureSampler(-1), m_LastIsTextured(-1)
{
m_LastScreen[0] = m_LastScreen[1] = m_LastScreen[2] = m_LastScreen[3] = -1.f;
}
@ -56,9 +59,11 @@ public:
float m_LastScreen[4];
};
class CGLSLTextProgram : public CGLSLTWProgram {
class CGLSLTextProgram : public CGLSLTWProgram
{
public:
CGLSLTextProgram() : CGLSLTWProgram()
CGLSLTextProgram() :
CGLSLTWProgram()
{
m_LastColor[0] = m_LastColor[1] = m_LastColor[2] = m_LastColor[3] = -1.f;
m_LastOutlineColor[0] = m_LastOutlineColor[1] = m_LastOutlineColor[2] = m_LastOutlineColor[3] = -1.f;
@ -79,13 +84,16 @@ public:
int m_LastTextureSize;
};
class CGLSLPrimitiveProgram : public CGLSLTWProgram {
class CGLSLPrimitiveProgram : public CGLSLTWProgram
{
public:
};
class CGLSLSpriteProgram : public CGLSLTWProgram {
class CGLSLSpriteProgram : public CGLSLTWProgram
{
public:
CGLSLSpriteProgram() : CGLSLTWProgram()
CGLSLSpriteProgram() :
CGLSLTWProgram()
{
m_LastRotation = 0.f;
m_LastCenter[0] = m_LastCenter[1] = 0.f;
@ -101,9 +109,11 @@ public:
float m_LastVertciesColor[4];
};
class CGLSLSpriteMultipleProgram : public CGLSLTWProgram {
class CGLSLSpriteMultipleProgram : public CGLSLTWProgram
{
public:
CGLSLSpriteMultipleProgram() : CGLSLTWProgram()
CGLSLSpriteMultipleProgram() :
CGLSLTWProgram()
{
m_LastCenter[0] = m_LastCenter[1] = 0.f;
m_LastVertciesColor[0] = m_LastVertciesColor[1] = m_LastVertciesColor[2] = m_LastVertciesColor[3] = -1.f;
@ -117,16 +127,19 @@ public:
float m_LastVertciesColor[4];
};
class CGLSLQuadProgram : public CGLSLTWProgram {
class CGLSLQuadProgram : public CGLSLTWProgram
{
public:
int m_LocColors;
int m_LocOffsets;
int m_LocRotations;
};
class CGLSLTileProgram : public CGLSLTWProgram {
class CGLSLTileProgram : public CGLSLTWProgram
{
public:
CGLSLTileProgram() : m_LocColor(-1), m_LocOffset(-1), m_LocDir(-1), m_LocNum(-1), m_LocJumpIndex(-1) {}
CGLSLTileProgram() :
m_LocColor(-1), m_LocOffset(-1), m_LocDir(-1), m_LocNum(-1), m_LocJumpIndex(-1) {}
int m_LocColor;
int m_LocOffset;

View file

@ -28,8 +28,10 @@ class SortWrap
typedef bool (CServerBrowser::*SortFunc)(int, int) const;
SortFunc m_pfnSort;
CServerBrowser *m_pThis;
public:
SortWrap(CServerBrowser *t, SortFunc f) : m_pfnSort(f), m_pThis(t) {}
SortWrap(CServerBrowser *t, SortFunc f) :
m_pfnSort(f), m_pThis(t) {}
bool operator()(int a, int b) { return (g_Config.m_BrSortOrder ? (m_pThis->*m_pfnSort)(b, a) : (m_pThis->*m_pfnSort)(a, b)); }
};
@ -117,7 +119,7 @@ bool CServerBrowser::SortCompareName(int Index1, int Index2) const
CServerEntry *b = m_ppServerlist[Index2];
// make sure empty entries are listed last
return (a->m_GotInfo && b->m_GotInfo) || (!a->m_GotInfo && !b->m_GotInfo) ? str_comp(a->m_Info.m_aName, b->m_Info.m_aName) < 0 :
a->m_GotInfo ? true : false;
a->m_GotInfo ? true : false;
}
bool CServerBrowser::SortCompareMap(int Index1, int Index2) const
@ -165,7 +167,7 @@ bool CServerBrowser::SortCompareNumPlayersAndPing(int Index1, int Index2) const
if(a->m_Info.m_NumFilteredPlayers == 0 || b->m_Info.m_NumFilteredPlayers == 0)
return a->m_Info.m_NumFilteredPlayers == 0;
else
return a->m_Info.m_NumFilteredPlayers - (a->m_Info.m_Latency/100)*MAX_CLIENTS < b->m_Info.m_NumFilteredPlayers - (b->m_Info.m_Latency/100)*MAX_CLIENTS;
return a->m_Info.m_NumFilteredPlayers - (a->m_Info.m_Latency / 100) * MAX_CLIENTS < b->m_Info.m_NumFilteredPlayers - (b->m_Info.m_Latency / 100) * MAX_CLIENTS;
}
void CServerBrowser::Filter()
@ -191,7 +193,7 @@ void CServerBrowser::Filter()
Filtered = 1;
else if(g_Config.m_BrFilterFull && Players(m_ppServerlist[i]->m_Info) == Max(m_ppServerlist[i]->m_Info))
Filtered = 1;
else if(g_Config.m_BrFilterPw && m_ppServerlist[i]->m_Info.m_Flags&SERVER_FLAG_PASSWORD)
else if(g_Config.m_BrFilterPw && m_ppServerlist[i]->m_Info.m_Flags & SERVER_FLAG_PASSWORD)
Filtered = 1;
else if(g_Config.m_BrFilterPing && g_Config.m_BrFilterPing < m_ppServerlist[i]->m_Info.m_Latency)
Filtered = 1;
@ -320,17 +322,17 @@ int CServerBrowser::SortHash() const
void SetFilteredPlayers(const CServerInfo &Item)
{
if (g_Config.m_BrFilterSpectators)
if(g_Config.m_BrFilterSpectators)
Item.m_NumFilteredPlayers = Item.m_NumPlayers;
else
Item.m_NumFilteredPlayers = Item.m_NumClients;
if (g_Config.m_BrFilterConnectingPlayers)
if(g_Config.m_BrFilterConnectingPlayers)
{
for (int i = 0; i < MAX_CLIENTS; i++)
for(int i = 0; i < MAX_CLIENTS; i++)
{
const CServerInfo::CClient &Client = Item.m_aClients[i];
if (str_comp(Client.m_aName, "(connecting)") == 0 && Client.m_aClan[0] == '\0' && Client.m_Country == -1 && Client.m_Score == 0)
if(str_comp(Client.m_aName, "(connecting)") == 0 && Client.m_aClan[0] == '\0' && Client.m_Country == -1 && Client.m_Score == 0)
Item.m_NumFilteredPlayers--;
}
}
@ -350,18 +352,18 @@ void CServerBrowser::Sort()
Filter();
// sort
if(g_Config.m_BrSortOrder == 2 && (g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS ||g_Config.m_BrSort == IServerBrowser::SORT_PING))
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareNumPlayersAndPing));
if(g_Config.m_BrSortOrder == 2 && (g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS || g_Config.m_BrSort == IServerBrowser::SORT_PING))
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareNumPlayersAndPing));
else if(g_Config.m_BrSort == IServerBrowser::SORT_NAME)
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareName));
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareName));
else if(g_Config.m_BrSort == IServerBrowser::SORT_PING)
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortComparePing));
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortComparePing));
else if(g_Config.m_BrSort == IServerBrowser::SORT_MAP)
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareMap));
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareMap));
else if(g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS)
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareNumPlayers));
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareNumPlayers));
else if(g_Config.m_BrSort == IServerBrowser::SORT_GAMETYPE)
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareGametype));
std::stable_sort(m_pSortedServerlist, m_pSortedServerlist + m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareGametype));
// set indexes
for(i = 0; i < m_NumSortedServers; i++)
@ -401,7 +403,7 @@ CServerBrowser::CServerEntry *CServerBrowser::Find(const NETADDR &Addr)
if(net_addr_comp(&pEntry->m_Addr, &Addr) == 0)
return pEntry;
}
return (CServerEntry*)0;
return (CServerEntry *)0;
}
void CServerBrowser::QueueRequest(CServerEntry *pEntry)
@ -498,7 +500,7 @@ CServerBrowser::CServerEntry *CServerBrowser::Add(const NETADDR &Addr)
CServerEntry **ppNewlist;
m_NumServerCapacity += 100;
ppNewlist = (CServerEntry **)calloc(m_NumServerCapacity, sizeof(CServerEntry *));
mem_copy(ppNewlist, m_ppServerlist, m_NumServers*sizeof(CServerEntry*));
mem_copy(ppNewlist, m_ppServerlist, m_NumServers * sizeof(CServerEntry *));
free(m_ppServerlist);
m_ppServerlist = ppNewlist;
}
@ -569,12 +571,12 @@ void CServerBrowser::Set(const NETADDR &Addr, int Type, int Token, const CServer
}
pEntry = Find(Addr);
if(m_ServerlistType == IServerBrowser::TYPE_LAN)
{
NETADDR Broadcast;
mem_zero(&Broadcast, sizeof(Broadcast));
Broadcast.type = m_pNetClient->NetType()|NETTYPE_LINK_BROADCAST;
Broadcast.type = m_pNetClient->NetType() | NETTYPE_LINK_BROADCAST;
int Token = GenerateToken(Broadcast);
bool Drop = false;
Drop = Drop || BasicToken != GetBasicToken(Token);
@ -602,13 +604,13 @@ void CServerBrowser::Set(const NETADDR &Addr, int Type, int Token, const CServer
return;
}
}
SetInfo(pEntry, *pInfo);
if (m_ServerlistType == IServerBrowser::TYPE_LAN)
pEntry->m_Info.m_Latency = minimum(static_cast<int>((time_get()-m_BroadcastTime)*1000/time_freq()), 999);
else if (pEntry->m_RequestTime > 0)
if(m_ServerlistType == IServerBrowser::TYPE_LAN)
pEntry->m_Info.m_Latency = minimum(static_cast<int>((time_get() - m_BroadcastTime) * 1000 / time_freq()), 999);
else if(pEntry->m_RequestTime > 0)
{
pEntry->m_Info.m_Latency = minimum(static_cast<int>((time_get()-pEntry->m_RequestTime)*1000/time_freq()), 999);
pEntry->m_Info.m_Latency = minimum(static_cast<int>((time_get() - pEntry->m_RequestTime) * 1000 / time_freq()), 999);
pEntry->m_RequestTime = -1; // Request has been answered
}
RemoveRequest(pEntry);
@ -635,15 +637,15 @@ void CServerBrowser::Refresh(int Type)
if(Type == IServerBrowser::TYPE_LAN)
{
unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1];
unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO) + 1];
CNetChunk Packet;
int i;
/* do the broadcast version */
Packet.m_ClientID = -1;
mem_zero(&Packet, sizeof(Packet));
Packet.m_Address.type = m_pNetClient->NetType()|NETTYPE_LINK_BROADCAST;
Packet.m_Flags = NETSENDFLAG_CONNLESS|NETSENDFLAG_EXTENDED;
Packet.m_Address.type = m_pNetClient->NetType() | NETTYPE_LINK_BROADCAST;
Packet.m_Flags = NETSENDFLAG_CONNLESS | NETSENDFLAG_EXTENDED;
Packet.m_DataSize = sizeof(Buffer);
Packet.m_pData = Buffer;
mem_zero(&Packet.m_aExtraData, sizeof(Packet.m_aExtraData));
@ -739,7 +741,7 @@ void CServerBrowser::Refresh(int Type)
void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) const
{
unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO)+1];
unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO) + 1];
CNetChunk Packet;
if(g_Config.m_Debug)
@ -747,7 +749,7 @@ void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) cons
char aAddrStr[NETADDR_MAXSTRSIZE];
net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true);
char aBuf[256];
str_format(aBuf, sizeof(aBuf),"requesting server info from %s", aAddrStr);
str_format(aBuf, sizeof(aBuf), "requesting server info from %s", aAddrStr);
m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf);
}
@ -758,7 +760,7 @@ void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) cons
Packet.m_ClientID = -1;
Packet.m_Address = Addr;
Packet.m_Flags = NETSENDFLAG_CONNLESS|NETSENDFLAG_EXTENDED;
Packet.m_Flags = NETSENDFLAG_CONNLESS | NETSENDFLAG_EXTENDED;
Packet.m_DataSize = sizeof(Buffer);
Packet.m_pData = Buffer;
mem_zero(&Packet.m_aExtraData, sizeof(Packet.m_aExtraData));
@ -773,7 +775,7 @@ void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry) cons
void CServerBrowser::RequestImpl64(const NETADDR &Addr, CServerEntry *pEntry) const
{
unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO_64_LEGACY)+1];
unsigned char Buffer[sizeof(SERVERBROWSE_GETINFO_64_LEGACY) + 1];
CNetChunk Packet;
if(g_Config.m_Debug)
@ -781,7 +783,7 @@ void CServerBrowser::RequestImpl64(const NETADDR &Addr, CServerEntry *pEntry) co
char aAddrStr[NETADDR_MAXSTRSIZE];
net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true);
char aBuf[256];
str_format(aBuf, sizeof(aBuf),"requesting server info 64 from %s", aAddrStr);
str_format(aBuf, sizeof(aBuf), "requesting server info 64 from %s", aAddrStr);
m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf);
}
@ -805,7 +807,6 @@ void CServerBrowser::RequestCurrentServer(const NETADDR &Addr) const
RequestImpl(Addr, 0);
}
void CServerBrowser::Update(bool ForceResort)
{
int64 Timeout = time_freq();
@ -849,21 +850,21 @@ void CServerBrowser::Update(bool ForceResort)
{
m_MasterServerCount = 0;
for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++)
{
if(!m_pMasterServer->IsValid(i))
continue;
int Count = m_pMasterServer->GetCount(i);
if(Count == -1)
{
if(!m_pMasterServer->IsValid(i))
continue;
int Count = m_pMasterServer->GetCount(i);
if(Count == -1)
{
/* ignore Server
m_MasterServerCount = -1;
return;
// we don't have the required server information
*/
}
else
m_MasterServerCount += Count;
}
else
m_MasterServerCount += Count;
}
//request Server-List
NETADDR Addr;
CNetChunk Packet;
@ -892,27 +893,27 @@ void CServerBrowser::Update(bool ForceResort)
{
m_MasterServerCount = 0;
for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++)
{
if(!m_pMasterServer->IsValid(i))
continue;
int Count = m_pMasterServer->GetCount(i);
if(Count == -1)
{
if(!m_pMasterServer->IsValid(i))
continue;
int Count = m_pMasterServer->GetCount(i);
if(Count == -1)
{
/* ignore Server
m_MasterServerCount = -1;
return;
// we don't have the required server information
*/
}
else
m_MasterServerCount += Count;
}
//if(g_Config.m_Debug)
//{
// dbg_msg("client_srvbrowse", "ServerCount2: %d", m_MasterServerCount);
//}
else
m_MasterServerCount += Count;
}
//if(g_Config.m_Debug)
//{
// dbg_msg("client_srvbrowse", "ServerCount2: %d", m_MasterServerCount);
//}
}
if(m_MasterServerCount > m_NumRequests + m_LastPacketTick)
if(m_MasterServerCount > m_NumRequests + m_LastPacketTick)
{
++m_LastPacketTick;
return; //wait for more packets
@ -923,7 +924,7 @@ void CServerBrowser::Update(bool ForceResort)
{
if(!pEntry) // no more entries
break;
if(pEntry->m_RequestTime && pEntry->m_RequestTime+Timeout < Now)
if(pEntry->m_RequestTime && pEntry->m_RequestTime + Timeout < Now)
{
pEntry = pEntry->m_pNextReq;
continue;
@ -934,7 +935,7 @@ void CServerBrowser::Update(bool ForceResort)
if(pEntry->m_RequestTime == 0)
{
if (pEntry->m_Request64Legacy)
if(pEntry->m_Request64Legacy)
RequestImpl64(pEntry->m_Addr, pEntry);
else
RequestImpl(pEntry->m_Addr, pEntry);
@ -957,7 +958,7 @@ void CServerBrowser::Update(bool ForceResort)
}
//update max-requests
m_CurrentMaxRequests = m_CurrentMaxRequests/2;
m_CurrentMaxRequests = m_CurrentMaxRequests / 2;
if(m_CurrentMaxRequests < 1)
m_CurrentMaxRequests = 1;
}
@ -969,7 +970,7 @@ void CServerBrowser::Update(bool ForceResort)
if(!pEntry) // no more entries
break;
pNext = pEntry->m_pNextReq;
RemoveRequest(pEntry); //release request
RemoveRequest(pEntry); //release request
pEntry = pNext;
}
}
@ -979,7 +980,6 @@ void CServerBrowser::Update(bool ForceResort)
Sort();
}
bool CServerBrowser::IsFavorite(const NETADDR &Addr) const
{
// search for the address
@ -1031,7 +1031,7 @@ void CServerBrowser::RemoveFavorite(const NETADDR &Addr)
{
if(net_addr_comp(&Addr, &m_aFavoriteServers[i]) == 0)
{
mem_move(&m_aFavoriteServers[i], &m_aFavoriteServers[i+1], sizeof(NETADDR)*(m_NumFavoriteServers-(i+1)));
mem_move(&m_aFavoriteServers[i], &m_aFavoriteServers[i + 1], sizeof(NETADDR) * (m_NumFavoriteServers - (i + 1)));
m_NumFavoriteServers--;
pEntry = Find(Addr);
@ -1045,24 +1045,24 @@ void CServerBrowser::RemoveFavorite(const NETADDR &Addr)
void CServerBrowser::LoadDDNetServers()
{
if (!m_pDDNetInfo)
if(!m_pDDNetInfo)
return;
// reset servers / countries
for (int Network = 0; Network < NUM_NETWORKS; Network++)
for(int Network = 0; Network < NUM_NETWORKS; Network++)
{
CNetwork *pNet = &m_aNetworks[Network];
// parse JSON
const json_value *pServers = json_object_get(m_pDDNetInfo, Network == NETWORK_DDNET ? "servers" : "servers-kog");
if (!pServers || pServers->type != json_array)
if(!pServers || pServers->type != json_array)
return;
pNet->m_NumCountries = 0;
pNet->m_NumTypes = 0;
for (int i = 0; i < json_array_length(pServers) && pNet->m_NumCountries < MAX_COUNTRIES; i++)
for(int i = 0; i < json_array_length(pServers) && pNet->m_NumCountries < MAX_COUNTRIES; i++)
{
// pSrv - { name, flagId, servers }
const json_value *pSrv = json_array_get(pServers, i);
@ -1070,7 +1070,7 @@ void CServerBrowser::LoadDDNetServers()
const json_value *pName = json_object_get(pSrv, "name");
const json_value *pFlagID = json_object_get(pSrv, "flagId");
if (pSrv->type != json_object || pTypes->type != json_object || pName->type != json_string || pFlagID->type != json_integer)
if(pSrv->type != json_object || pTypes->type != json_object || pName->type != json_string || pFlagID->type != json_integer)
{
dbg_msg("client_srvbrowse", "invalid attributes");
continue;
@ -1085,12 +1085,12 @@ void CServerBrowser::LoadDDNetServers()
pCntr->m_FlagID = json_int_get(pFlagID);
// add country
for (unsigned int t = 0; t < pTypes->u.object.length; t++)
for(unsigned int t = 0; t < pTypes->u.object.length; t++)
{
const char *pType = pTypes->u.object.values[t].name;
const json_value *pAddrs = pTypes->u.object.values[t].value;
if (pAddrs->type != json_array)
if(pAddrs->type != json_array)
{
dbg_msg("client_srvbrowse", "invalid attributes");
continue;
@ -1113,10 +1113,10 @@ void CServerBrowser::LoadDDNetServers()
}
// add addresses
for (int g = 0; g < json_array_length(pAddrs); g++, pCntr->m_NumServers++)
for(int g = 0; g < json_array_length(pAddrs); g++, pCntr->m_NumServers++)
{
const json_value *pAddr = json_array_get(pAddrs, g);
if (pAddr->type != json_string)
if(pAddr->type != json_string)
{
dbg_msg("client_srvbrowse", "invalid attributes");
continue;
@ -1170,7 +1170,7 @@ int CServerBrowser::HasRank(const char *pMap)
if(!pDDNetRanks || pDDNetRanks->type != json_array)
return -1;
for (int i = 0; i < json_array_length(pDDNetRanks); i++)
for(int i = 0; i < json_array_length(pDDNetRanks); i++)
{
const json_value *pJson = json_array_get(pDDNetRanks, i);
if(!pJson || pJson->type != json_string)
@ -1248,18 +1248,16 @@ bool CServerBrowser::IsRefreshingMasters() const
return m_pMasterServer->IsRefreshing();
}
int CServerBrowser::LoadingProgression() const
{
if(m_NumServers == 0)
return 0;
int Servers = m_NumServers;
int Loaded = m_NumServers-m_NumRequests;
return 100.0f * Loaded/Servers;
int Loaded = m_NumServers - m_NumRequests;
return 100.0f * Loaded / Servers;
}
void CServerBrowser::ConfigSaveCallback(IConfig *pConfig, void *pUserData)
{
CServerBrowser *pSelf = (CServerBrowser *)pUserData;
@ -1276,7 +1274,7 @@ void CServerBrowser::ConfigSaveCallback(IConfig *pConfig, void *pUserData)
void CServerBrowser::DDNetFilterAdd(char *pFilter, const char *pName)
{
if (DDNetFiltered(pFilter, pName))
if(DDNetFiltered(pFilter, pName))
return;
char aBuf[128];
@ -1286,7 +1284,7 @@ void CServerBrowser::DDNetFilterAdd(char *pFilter, const char *pName)
void CServerBrowser::DDNetFilterRem(char *pFilter, const char *pName)
{
if (!DDNetFiltered(pFilter, pName))
if(!DDNetFiltered(pFilter, pName))
return;
// rewrite exclude/filter list

View file

@ -3,9 +3,12 @@
#ifndef ENGINE_CLIENT_SERVERBROWSER_H
#define ENGINE_CLIENT_SERVERBROWSER_H
#include <engine/serverbrowser.h>
#include <engine/shared/memheap.h>
#include <engine/config.h>
#include <engine/external/json-parser/json.h>
#include <engine/masterserver.h>
#include <engine/serverbrowser.h>
#include <engine/shared/config.h>
#include <engine/shared/memheap.h>
class CServerBrowser : public IServerBrowser
{
@ -38,7 +41,12 @@ public:
char m_aTypes[MAX_SERVERS][32];
int m_NumServers;
void Reset() { m_NumServers = 0; m_FlagID = -1; m_aName[0] = '\0'; };
void Reset()
{
m_NumServers = 0;
m_FlagID = -1;
m_aName[0] = '\0';
};
/*void Add(NETADDR Addr, char* pType) {
if (m_NumServers < MAX_SERVERS)
{
@ -51,9 +59,9 @@ public:
enum
{
MAX_FAVORITES=2048,
MAX_COUNTRIES=16,
MAX_TYPES=32,
MAX_FAVORITES = 2048,
MAX_COUNTRIES = 16,
MAX_TYPES = 32,
};
struct CNetwork
@ -65,7 +73,6 @@ public:
int m_NumTypes;
};
CServerBrowser();
virtual ~CServerBrowser();

View file

@ -12,13 +12,12 @@
#include "sound.h"
extern "C"
{
extern "C" {
#if defined(CONF_VIDEORECORDER)
#include <engine/shared/video.h>
#include <engine/shared/video.h>
#endif
#include <opusfile.h>
#include <wavpack.h>
#include <opusfile.h>
#include <wavpack.h>
}
#include <math.h>
@ -65,9 +64,9 @@ struct CVoice
};
};
static CSample m_aSamples[NUM_SAMPLES] = { {0} };
static CVoice m_aVoices[NUM_VOICES] = { {0} };
static CChannel m_aChannels[NUM_CHANNELS] = { {255, 0} };
static CSample m_aSamples[NUM_SAMPLES] = {{0}};
static CVoice m_aVoices[NUM_VOICES] = {{0}};
static CChannel m_aChannels[NUM_CHANNELS] = {{255, 0}};
static LOCK m_SoundLock = 0;
@ -78,7 +77,7 @@ static int m_MixingRate = 48000;
static volatile int m_SoundVolume = 100;
static int m_NextVoice = 0;
static int *m_pMixBuffer = 0; // buffer only used by the thread callback function
static int *m_pMixBuffer = 0; // buffer only used by the thread callback function
static unsigned m_MaxFrames = 0;
static const void *s_pWVBuffer = 0x0;
@ -100,7 +99,7 @@ static short Int2Short(int i)
static int IntAbs(int i)
{
if(i<0)
if(i < 0)
return -i;
return i;
}
@ -108,7 +107,7 @@ static int IntAbs(int i)
static void Mix(short *pFinalOut, unsigned Frames)
{
int MasterVol;
mem_zero(m_pMixBuffer, m_MaxFrames*2*sizeof(int));
mem_zero(m_pMixBuffer, m_MaxFrames * 2 * sizeof(int));
Frames = minimum(Frames, m_MaxFrames);
// acquire lock while we are mixing
@ -125,13 +124,13 @@ static void Mix(short *pFinalOut, unsigned Frames)
int *pOut = m_pMixBuffer;
int Step = v->m_pSample->m_Channels; // setup input sources
short *pInL = &v->m_pSample->m_pData[v->m_Tick*Step];
short *pInR = &v->m_pSample->m_pData[v->m_Tick*Step+1];
short *pInL = &v->m_pSample->m_pData[v->m_Tick * Step];
short *pInR = &v->m_pSample->m_pData[v->m_Tick * Step + 1];
unsigned End = v->m_pSample->m_NumFrames-v->m_Tick;
unsigned End = v->m_pSample->m_NumFrames - v->m_Tick;
int Rvol = (int)(v->m_pChannel->m_Vol*(v->m_Vol/255.0f));
int Lvol = (int)(v->m_pChannel->m_Vol*(v->m_Vol/255.0f));
int Rvol = (int)(v->m_pChannel->m_Vol * (v->m_Vol / 255.0f));
int Lvol = (int)(v->m_pChannel->m_Vol * (v->m_Vol / 255.0f));
// make sure that we don't go outside the sound data
if(Frames < End)
@ -142,7 +141,7 @@ static void Mix(short *pFinalOut, unsigned Frames)
pInR = pInL;
// volume calculation
if(v->m_Flags&ISound::FLAG_POS && v->m_pChannel->m_Pan)
if(v->m_Flags & ISound::FLAG_POS && v->m_pChannel->m_Pan)
{
// TODO: we should respect the channel panning value
int dx = v->m_X - m_CenterX;
@ -158,65 +157,65 @@ static void Mix(short *pFinalOut, unsigned Frames)
switch(v->m_Shape)
{
case ISound::SHAPE_CIRCLE:
{
float r = v->m_Circle.m_Radius;
RangeX = r;
int Dist = (int)sqrtf((float)dx * dx + dy * dy); // nasty float
if(Dist < r)
{
float r = v->m_Circle.m_Radius;
RangeX = r;
InVoiceField = true;
int Dist = (int)sqrtf((float)dx*dx+dy*dy); // nasty float
if(Dist < r)
{
InVoiceField = true;
// falloff
int FalloffDistance = r*v->m_Falloff;
if(Dist > FalloffDistance)
FalloffX = FalloffY = (r-Dist)/(r-FalloffDistance);
else
FalloffX = FalloffY = 1.0f;
}
// falloff
int FalloffDistance = r * v->m_Falloff;
if(Dist > FalloffDistance)
FalloffX = FalloffY = (r - Dist) / (r - FalloffDistance);
else
InVoiceField = false;
break;
FalloffX = FalloffY = 1.0f;
}
else
InVoiceField = false;
break;
}
case ISound::SHAPE_RECTANGLE:
{
RangeX = v->m_Rectangle.m_Width / 2.0f;
int abs_dx = abs(dx);
int abs_dy = abs(dy);
int w = v->m_Rectangle.m_Width / 2.0f;
int h = v->m_Rectangle.m_Height / 2.0f;
if(abs_dx < w && abs_dy < h)
{
RangeX = v->m_Rectangle.m_Width/2.0f;
InVoiceField = true;
int abs_dx = abs(dx);
int abs_dy = abs(dy);
// falloff
int fx = v->m_Falloff * w;
int fy = v->m_Falloff * h;
int w = v->m_Rectangle.m_Width/2.0f;
int h = v->m_Rectangle.m_Height/2.0f;
if(abs_dx < w && abs_dy < h)
{
InVoiceField = true;
// falloff
int fx = v->m_Falloff * w;
int fy = v->m_Falloff * h;
FalloffX = abs_dx > fx ? (float)(w-abs_dx)/(w-fx) : 1.0f;
FalloffY = abs_dy > fy ? (float)(h-abs_dy)/(h-fy) : 1.0f;
}
else
InVoiceField = false;
break;
FalloffX = abs_dx > fx ? (float)(w - abs_dx) / (w - fx) : 1.0f;
FalloffY = abs_dy > fy ? (float)(h - abs_dy) / (h - fy) : 1.0f;
}
else
InVoiceField = false;
break;
}
};
if(InVoiceField)
{
// panning
if(!(v->m_Flags&ISound::FLAG_NO_PANNING))
if(!(v->m_Flags & ISound::FLAG_NO_PANNING))
{
if(dx > 0)
Lvol = ((RangeX-p)*Lvol)/RangeX;
Lvol = ((RangeX - p) * Lvol) / RangeX;
else
Rvol = ((RangeX-p)*Rvol)/RangeX;
Rvol = ((RangeX - p) * Rvol) / RangeX;
}
{
@ -234,8 +233,8 @@ static void Mix(short *pFinalOut, unsigned Frames)
// process all frames
for(unsigned s = 0; s < End; s++)
{
*pOut++ += (*pInL)*Lvol;
*pOut++ += (*pInR)*Rvol;
*pOut++ += (*pInL) * Lvol;
*pOut++ += (*pInR) * Rvol;
pInL += Step;
pInR += Step;
v->m_Tick++;
@ -244,7 +243,7 @@ static void Mix(short *pFinalOut, unsigned Frames)
// free voice if not used any more
if(v->m_Tick == v->m_pSample->m_NumFrames)
{
if(v->m_Flags&ISound::FLAG_LOOP)
if(v->m_Flags & ISound::FLAG_LOOP)
v->m_Tick = 0;
else
{
@ -255,7 +254,6 @@ static void Mix(short *pFinalOut, unsigned Frames)
}
}
// release the lock
lock_unlock(m_SoundLock);
@ -264,12 +262,12 @@ static void Mix(short *pFinalOut, unsigned Frames)
// TODO: this seams slow
for(unsigned i = 0; i < Frames; i++)
{
int j = i<<1;
int vl = ((m_pMixBuffer[j]*MasterVol)/101)>>8;
int vr = ((m_pMixBuffer[j+1]*MasterVol)/101)>>8;
int j = i << 1;
int vl = ((m_pMixBuffer[j] * MasterVol) / 101) >> 8;
int vr = ((m_pMixBuffer[j + 1] * MasterVol) / 101) >> 8;
pFinalOut[j] = Int2Short(vl);
pFinalOut[j+1] = Int2Short(vr);
pFinalOut[j + 1] = Int2Short(vr);
// dbg_msg("sound", "the real shit: %d %d", pFinalOut[j], pFinalOut[j+1]);
}
@ -278,23 +276,21 @@ static void Mix(short *pFinalOut, unsigned Frames)
#if defined(CONF_ARCH_ENDIAN_BIG)
swap_endian(pFinalOut, sizeof(short), Frames * 2);
#endif
}
static void SdlCallback(void *pUnused, Uint8 *pStream, int Len)
{
(void)pUnused;
#if defined(CONF_VIDEORECORDER)
if (!(IVideo::Current() && g_Config.m_ClVideoSndEnable))
Mix((short *)pStream, Len/2/2);
if(!(IVideo::Current() && g_Config.m_ClVideoSndEnable))
Mix((short *)pStream, Len / 2 / 2);
else
IVideo::Current()->NextAudioFrame(Mix);
#else
Mix((short *)pStream, Len/2/2);
Mix((short *)pStream, Len / 2 / 2);
#endif
}
int CSound::Init()
{
m_SoundEnabled = 0;
@ -327,7 +323,7 @@ int CSound::Init()
// Open the audio device and start playing sound!
m_Device = SDL_OpenAudioDevice(NULL, 0, &Format, &FormatOut, 0);
if (m_Device == 0)
if(m_Device == 0)
{
dbg_msg("client/sound", "unable to open audio: %s", SDL_GetError());
return -1;
@ -335,7 +331,7 @@ int CSound::Init()
else
dbg_msg("client/sound", "sound init successful using audio driver '%s'", SDL_GetCurrentAudioDriver());
m_MaxFrames = FormatOut.samples*2;
m_MaxFrames = FormatOut.samples * 2;
m_pMixBuffer = (int *)calloc(m_MaxFrames * 2, sizeof(int));
SDL_PauseAudioDevice(m_Device, 0);
@ -359,10 +355,10 @@ int CSound::Update()
m_SoundVolume = WantedVolume;
lock_unlock(m_SoundLock);
}
//#if defined(CONF_VIDEORECORDER)
// if(IVideo::Current() && g_Config.m_ClVideoSndEnable)
// IVideo::Current()->NextAudioFrame(Mix);
//#endif
//#if defined(CONF_VIDEORECORDER)
// if(IVideo::Current() && g_Config.m_ClVideoSndEnable)
// IVideo::Current()->NextAudioFrame(Mix);
//#endif
return 0;
}
@ -404,24 +400,24 @@ void CSound::RateConvert(int SampleID)
return;
// allocate new data
NumFrames = (int)((pSample->m_NumFrames/(float)pSample->m_Rate)*m_MixingRate);
NumFrames = (int)((pSample->m_NumFrames / (float)pSample->m_Rate) * m_MixingRate);
pNewData = (short *)calloc(NumFrames * pSample->m_Channels, sizeof(short));
for(int i = 0; i < NumFrames; i++)
{
// resample TODO: this should be done better, like linear at least
float a = i/(float)NumFrames;
int f = (int)(a*pSample->m_NumFrames);
float a = i / (float)NumFrames;
int f = (int)(a * pSample->m_NumFrames);
if(f >= pSample->m_NumFrames)
f = pSample->m_NumFrames-1;
f = pSample->m_NumFrames - 1;
// set new data
if(pSample->m_Channels == 1)
pNewData[i] = pSample->m_pData[f];
else if(pSample->m_Channels == 2)
{
pNewData[i*2] = pSample->m_pData[f*2];
pNewData[i*2+1] = pSample->m_pData[f*2+1];
pNewData[i * 2] = pSample->m_pData[f * 2];
pNewData[i * 2 + 1] = pSample->m_pData[f * 2 + 1];
}
}
@ -439,8 +435,8 @@ int CSound::DecodeOpus(int SampleID, const void *pData, unsigned DataSize)
CSample *pSample = &m_aSamples[SampleID];
OggOpusFile *OpusFile = op_open_memory((const unsigned char *) pData, DataSize, NULL);
if (OpusFile)
OggOpusFile *OpusFile = op_open_memory((const unsigned char *)pData, DataSize, NULL);
if(OpusFile)
{
int NumChannels = op_channel_count(OpusFile, -1);
int NumSamples = op_pcm_total(OpusFile, -1); // per channel!
@ -457,9 +453,9 @@ int CSound::DecodeOpus(int SampleID, const void *pData, unsigned DataSize)
int Read;
int Pos = 0;
while (Pos < NumSamples)
while(Pos < NumSamples)
{
Read = op_read(OpusFile, pSample->m_pData + Pos*NumChannels, NumSamples*NumChannels, NULL);
Read = op_read(OpusFile, pSample->m_pData + Pos * NumChannels, NumSamples * NumChannels, NULL);
Pos += Read;
}
@ -574,11 +570,11 @@ int CSound::DecodeWV(int SampleID, const void *pData, unsigned DataSize)
pSample->m_pData = (short *)calloc(NumSamples * NumChannels, sizeof(short));
pDst = pSample->m_pData;
for (i = 0; i < NumSamples*NumChannels; i++)
for(i = 0; i < NumSamples * NumChannels; i++)
*pDst++ = (short)*pSrc++;
free(pBuffer);
#ifdef CONF_WAVPACK_CLOSE_FILE
#ifdef CONF_WAVPACK_CLOSE_FILE
WavpackCloseFile(pContext);
#endif
@ -645,7 +641,6 @@ int CSound::LoadOpus(const char *pFilename)
return SampleID;
}
int CSound::LoadWV(const char *pFilename)
{
// don't waste memory on sound when we are stress testing
@ -761,7 +756,7 @@ float CSound::GetSampleDuration(int SampleID)
if(SampleID == -1 || SampleID >= NUM_SAMPLES)
return 0.0f;
return (m_aSamples[SampleID].m_NumFrames/m_aSamples[SampleID].m_Rate);
return (m_aSamples[SampleID].m_NumFrames / m_aSamples[SampleID].m_Rate);
}
void CSound::SetListenerPos(float x, float y)
@ -781,7 +776,7 @@ void CSound::SetVoiceVolume(CVoiceHandle Voice, float Volume)
return;
Volume = clamp(Volume, 0.0f, 1.0f);
m_aVoices[VoiceID].m_Vol = (int)(Volume*255.0f);
m_aVoices[VoiceID].m_Vol = (int)(Volume * 255.0f);
}
void CSound::SetVoiceFalloff(CVoiceHandle Voice, float Falloff)
@ -827,7 +822,7 @@ void CSound::SetVoiceTimeOffset(CVoiceHandle Voice, float offset)
if(m_aVoices[VoiceID].m_pSample)
{
int Tick = 0;
bool IsLooping = m_aVoices[VoiceID].m_Flags&ISound::FLAG_LOOP;
bool IsLooping = m_aVoices[VoiceID].m_Flags & ISound::FLAG_LOOP;
uint64 TickOffset = m_aVoices[VoiceID].m_pSample->m_Rate * offset;
if(m_aVoices[VoiceID].m_pSample->m_NumFrames > 0 && IsLooping)
Tick = TickOffset % m_aVoices[VoiceID].m_pSample->m_NumFrames;
@ -836,10 +831,10 @@ void CSound::SetVoiceTimeOffset(CVoiceHandle Voice, float offset)
// at least 200msec off, else depend on buffer size
float Threshold = maximum(0.2f * m_aVoices[VoiceID].m_pSample->m_Rate, (float)m_MaxFrames);
if(abs(m_aVoices[VoiceID].m_Tick-Tick) > Threshold)
if(abs(m_aVoices[VoiceID].m_Tick - Tick) > Threshold)
{
// take care of looping (modulo!)
if( !(IsLooping && (minimum(m_aVoices[VoiceID].m_Tick, Tick) + m_aVoices[VoiceID].m_pSample->m_NumFrames - maximum(m_aVoices[VoiceID].m_Tick, Tick)) <= Threshold))
if(!(IsLooping && (minimum(m_aVoices[VoiceID].m_Tick, Tick) + m_aVoices[VoiceID].m_pSample->m_NumFrames - maximum(m_aVoices[VoiceID].m_Tick, Tick)) <= Threshold))
{
m_aVoices[VoiceID].m_Tick = Tick;
}
@ -880,8 +875,8 @@ void CSound::SetVoiceRectangle(CVoiceHandle Voice, float Width, float Height)
void CSound::SetChannel(int ChannelID, float Vol, float Pan)
{
m_aChannels[ChannelID].m_Vol = (int)(Vol*255.0f);
m_aChannels[ChannelID].m_Pan = (int)(Pan*255.0f); // TODO: this is only on and off right now
m_aChannels[ChannelID].m_Vol = (int)(Vol * 255.0f);
m_aChannels[ChannelID].m_Pan = (int)(Pan * 255.0f); // TODO: this is only on and off right now
}
ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags, float x, float y)
@ -899,7 +894,7 @@ ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags, float
if(!m_aVoices[id].m_pSample)
{
VoiceID = id;
m_NextVoice = id+1;
m_NextVoice = id + 1;
break;
}
}
@ -929,7 +924,7 @@ ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags, float
ISound::CVoiceHandle CSound::PlayAt(int ChannelID, int SampleID, int Flags, float x, float y)
{
return Play(ChannelID, SampleID, Flags|ISound::FLAG_POS, x, y);
return Play(ChannelID, SampleID, Flags | ISound::FLAG_POS, x, y);
}
ISound::CVoiceHandle CSound::Play(int ChannelID, int SampleID, int Flags)
@ -992,5 +987,4 @@ void CSound::StopVoice(CVoiceHandle Voice)
lock_unlock(m_SoundLock);
}
IEngineSound *CreateEngineSound() { return new CSound; }

View file

@ -3,7 +3,9 @@
#ifndef ENGINE_CLIENT_SOUND_H
#define ENGINE_CLIENT_SOUND_H
#include <engine/graphics.h>
#include <engine/sound.h>
#include <engine/storage.h>
#include "SDL.h"

View file

@ -129,10 +129,10 @@ class CSteamStub : public ISteam
{
const char *GetPlayerName() { return 0; }
const NETADDR *GetConnectAddress() { return 0; }
void ClearConnectAddress() { }
void Update() { }
void ClearGameInfo() { }
void SetGameInfo(NETADDR ServerAddr, const char *pMapName) { }
void ClearConnectAddress() {}
void Update() {}
void ClearGameInfo() {}
void SetGameInfo(NETADDR ServerAddr, const char *pMapName) {}
};
ISteam *CreateSteam()

View file

@ -1,11 +1,11 @@
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <base/system.h>
#include <base/math.h>
#include <base/system.h>
#include <engine/graphics.h>
#include <engine/textrender.h>
#include <engine/shared/config.h>
#include <engine/storage.h>
#include <engine/textrender.h>
// ft2 texture
#include <ft2build.h>
@ -17,8 +17,8 @@ enum
MAX_CHARACTERS = 64,
};
#include <vector>
#include <map>
#include <vector>
struct SFontSizeChar
{
@ -71,7 +71,6 @@ struct CFontSizeData
FT_Face *m_pFace;
std::map<int, SFontSizeChar> m_Chars;
};
#define MIN_FONT_SIZE 6
@ -135,7 +134,7 @@ struct STextContainer
{
STextContainer() { Reset(); }
CFont* m_pFont;
CFont *m_pFont;
int m_FontSize;
STextString m_StringInfo;
@ -178,7 +177,6 @@ struct STextContainer
}
};
class CTextRender : public IEngineTextRender
{
IGraphics *m_pGraphics;
@ -192,7 +190,7 @@ class CTextRender : public IEngineTextRender
SBufferContainerInfo m_DefaultTextContainerInfo;
std::vector<CFont*> m_Fonts;
std::vector<CFont *> m_Fonts;
CFont *m_pCurFont;
int GetFreeTextContainerIndex()
@ -218,7 +216,7 @@ class CTextRender : public IEngineTextRender
m_FirstFreeTextContainerIndex = Index;
}
STextContainer& GetTextContainer(int Index)
STextContainer &GetTextContainer(int Index)
{
if(Index >= (int)m_TextContainers.size())
{
@ -245,7 +243,7 @@ class CTextRender : public IEngineTextRender
if(*pCursor == 0)
return Length;
if(*pCursor == '\n' || *pCursor == '\t' || *pCursor == ' ')
return Length+1;
return Length + 1;
Length = str_utf8_forward(pText, Length);
}
}
@ -266,22 +264,22 @@ class CTextRender : public IEngineTextRender
for(int y = 0; y < h; y++)
for(int x = 0; x < w; x++)
{
int c = pIn[y*w+x];
int c = pIn[y * w + x];
for(int sy = -OutlineCount; sy <= OutlineCount; sy++)
for(int sx = -OutlineCount; sx <= OutlineCount; sx++)
{
int GetX = x+sx;
int GetY = y+sy;
int GetX = x + sx;
int GetY = y + sy;
if(GetX >= 0 && GetY >= 0 && GetX < w && GetY < h)
{
int Index = GetY*w+GetX;
int Index = GetY * w + GetX;
if(pIn[Index] > c)
c = pIn[Index];
}
}
pOut[y*w+x] = c;
pOut[y * w + x] = c;
}
}
@ -314,7 +312,7 @@ class CTextRender : public IEngineTextRender
{
int NewDimensions = pFont->m_CurTextureDimensions[TextureIndex] * 2;
unsigned char *pTmpTexBuffer = new unsigned char[NewDimensions*NewDimensions];
unsigned char *pTmpTexBuffer = new unsigned char[NewDimensions * NewDimensions];
mem_zero(pTmpTexBuffer, NewDimensions * NewDimensions * sizeof(unsigned char));
for(int y = 0; y < pFont->m_CurTextureDimensions[TextureIndex]; ++y)
@ -355,11 +353,10 @@ class CTextRender : public IEngineTextRender
}
// 128k * 2 of data used for rendering glyphs
unsigned char ms_aGlyphData[(1024/4) * (1024/4)];
unsigned char ms_aGlyphDataOutlined[(1024/4) * (1024/4)];
unsigned char ms_aGlyphData[(1024 / 4) * (1024 / 4)];
unsigned char ms_aGlyphDataOutlined[(1024 / 4) * (1024 / 4)];
bool GetCharacterSpace(CFont *pFont, int TextureIndex, int Width, int Height, int& PosX, int& PosY)
bool GetCharacterSpace(CFont *pFont, int TextureIndex, int Width, int Height, int &PosX, int &PosY)
{
if(pFont->m_CurTextureDimensions[TextureIndex] < Width)
return false;
@ -367,7 +364,7 @@ class CTextRender : public IEngineTextRender
return false;
// skyline bottom left algorithm
std::vector<int>& SkylineHeights = pFont->m_TextureSkyline[TextureIndex].m_CurHeightOfPixelColumn;
std::vector<int> &SkylineHeights = pFont->m_TextureSkyline[TextureIndex].m_CurHeightOfPixelColumn;
// search a fitting area with less pixel loss
int SmallestPixelLossAreaX = 0;
@ -453,7 +450,7 @@ class CTextRender : public IEngineTextRender
if(GlyphIndex == 0)
{
for(CFont::SFontFallBack& FallbackFont : pFont->m_FtFallbackFonts)
for(CFont::SFontFallBack &FallbackFont : pFont->m_FtFallbackFonts)
{
FtFace = FallbackFont.m_FtFace;
FT_Set_Pixel_Sizes(FtFace, 0, pSizeData->m_FontSize);
@ -479,7 +476,7 @@ class CTextRender : public IEngineTextRender
}
}
if(FT_Load_Glyph(FtFace, GlyphIndex, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP))
if(FT_Load_Glyph(FtFace, GlyphIndex, FT_LOAD_RENDER | FT_LOAD_NO_BITMAP))
{
dbg_msg("pFont", "error loading glyph %d", Chr);
return;
@ -500,7 +497,7 @@ class CTextRender : public IEngineTextRender
for(py = 0; py < pBitmap->rows; py++) // ignore_convention
for(px = 0; px < pBitmap->width; px++) // ignore_convention
ms_aGlyphData[(py+y)*Width+px+x] = pBitmap->buffer[py*pBitmap->width+px]; // ignore_convention
ms_aGlyphData[(py + y) * Width + px + x] = pBitmap->buffer[py * pBitmap->width + px]; // ignore_convention
// upload the glyph
int X = 0;
@ -530,7 +527,7 @@ class CTextRender : public IEngineTextRender
pFontchr->m_Width = Width;
pFontchr->m_OffsetX = (FtFace->glyph->metrics.horiBearingX >> 6); // ignore_convention
pFontchr->m_OffsetY = -((FtFace->glyph->metrics.height >> 6) - (FtFace->glyph->metrics.horiBearingY >> 6));
pFontchr->m_AdvanceX = (FtFace->glyph->advance.x>>6); // ignore_convention
pFontchr->m_AdvanceX = (FtFace->glyph->advance.x >> 6); // ignore_convention
pFontchr->m_aUVs[0] = X;
pFontchr->m_aUVs[1] = Y;
@ -546,7 +543,7 @@ class CTextRender : public IEngineTextRender
if(it == pSizeData->m_Chars.end())
{
// render and add character
SFontSizeChar& FontSizeChr = pSizeData->m_Chars[Chr];
SFontSizeChar &FontSizeChr = pSizeData->m_Chars[Chr];
RenderGlyph(pFont, pSizeData, Chr);
@ -560,18 +557,17 @@ class CTextRender : public IEngineTextRender
float Kerning(CFont *pFont, FT_UInt GlyphIndexLeft, FT_UInt GlyphIndexRight)
{
FT_Vector Kerning = {0,0};
FT_Vector Kerning = {0, 0};
FT_Get_Kerning(pFont->m_FtFace, GlyphIndexLeft, GlyphIndexRight, FT_KERNING_DEFAULT, &Kerning);
return (Kerning.x>>6);
return (Kerning.x >> 6);
}
public:
CTextRender()
{
m_pGraphics = 0;
m_Color = ColorRGBA(1,1,1,1);
m_Color = ColorRGBA(1, 1, 1, 1);
m_OutlineColor = ColorRGBA(0, 0, 0, 0.3f);
m_pCurFont = 0;
@ -612,7 +608,7 @@ public:
m_DefaultTextContainerInfo.m_Stride = sizeof(STextCharQuadVertex);
m_DefaultTextContainerInfo.m_Attributes.push_back(SBufferContainerInfo::SAttribute());
SBufferContainerInfo::SAttribute* pAttr = &m_DefaultTextContainerInfo.m_Attributes.back();
SBufferContainerInfo::SAttribute *pAttr = &m_DefaultTextContainerInfo.m_Attributes.back();
pAttr->m_DataTypeCount = 2;
pAttr->m_FuncType = 0;
pAttr->m_Normalized = false;
@ -624,7 +620,7 @@ public:
pAttr->m_DataTypeCount = 2;
pAttr->m_FuncType = 0;
pAttr->m_Normalized = false;
pAttr->m_pOffset = (void*)(sizeof(float) * 2);
pAttr->m_pOffset = (void *)(sizeof(float) * 2);
pAttr->m_Type = GRAPHICS_TYPE_FLOAT;
pAttr->m_VertBufferBindingIndex = -1;
m_DefaultTextContainerInfo.m_Attributes.push_back(SBufferContainerInfo::SAttribute());
@ -632,7 +628,7 @@ public:
pAttr->m_DataTypeCount = 4;
pAttr->m_FuncType = 0;
pAttr->m_Normalized = true;
pAttr->m_pOffset = (void*)(sizeof(float) * 2 + sizeof(float) * 2);
pAttr->m_pOffset = (void *)(sizeof(float) * 2 + sizeof(float) * 2);
pAttr->m_Type = GRAPHICS_TYPE_UNSIGNED_BYTE;
pAttr->m_VertBufferBindingIndex = -1;
@ -730,7 +726,7 @@ public:
FT_Done_Face(pFont->m_FtFace);
for(CFont::SFontFallBack& FallbackFont : pFont->m_FtFallbackFonts)
for(CFont::SFontFallBack &FallbackFont : pFont->m_FtFallbackFonts)
{
FT_Done_Face(FallbackFont.m_FtFace);
}
@ -873,9 +869,9 @@ public:
float UVScale = 1.0f / pFont->m_CurTextureDimensions[0];
const char *pCurrent = (char *)pText;
const char *pEnd = pCurrent+Length;
const char *pEnd = pCurrent + Length;
if((m_RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0)
if((m_RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0)
{
DrawX = pCursor->m_X;
DrawY = pCursor->m_Y;
@ -888,7 +884,7 @@ public:
LineCount = pCursor->m_LineCount;
if(pCursor->m_Flags&TEXTFLAG_RENDER)
if(pCursor->m_Flags & TEXTFLAG_RENDER)
{
// make sure there are no vertices
Graphics()->FlushVertices();
@ -903,7 +899,7 @@ public:
{
Graphics()->TextureSet(pFont->m_aTextures[1]);
Graphics()->QuadsBegin();
Graphics()->SetColor(m_OutlineColor.r, m_OutlineColor.g, m_OutlineColor.b, m_OutlineColor.a*m_Color.a);
Graphics()->SetColor(m_OutlineColor.r, m_OutlineColor.g, m_OutlineColor.b, m_OutlineColor.a * m_Color.a);
}
}
@ -914,9 +910,9 @@ public:
{
int NewLine = 0;
const char *pBatchEnd = pEnd;
if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags&TEXTFLAG_STOP_AT_END))
if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags & TEXTFLAG_STOP_AT_END))
{
int Wlen = minimum(WordLength((char *)pCurrent), (int)(pEnd-pCurrent));
int Wlen = minimum(WordLength((char *)pCurrent), (int)(pEnd - pCurrent));
CTextCursor Compare = *pCursor;
Compare.m_X = DrawX;
Compare.m_Y = DrawY;
@ -924,7 +920,7 @@ public:
Compare.m_LineWidth = -1;
TextEx(&Compare, pCurrent, Wlen);
if(Compare.m_X-DrawX > pCursor->m_LineWidth)
if(Compare.m_X - DrawX > pCursor->m_LineWidth)
{
// word can't be fitted in one line, cut it
CTextCursor Cutter = *pCursor;
@ -943,7 +939,7 @@ public:
if(WordGlyphs <= 3) // if we can't place 3 chars of the word on this line, take the next
Wlen = 0;
}
else if(Compare.m_X-pCursor->m_StartX > pCursor->m_LineWidth)
else if(Compare.m_X - pCursor->m_StartX > pCursor->m_LineWidth)
{
NewLine = 1;
Wlen = 0;
@ -956,7 +952,7 @@ public:
int NextCharacter = str_utf8_decode(&pTmp);
while(pCurrent < pBatchEnd)
{
pCursor->m_CharCount += pTmp-pCurrent;
pCursor->m_CharCount += pTmp - pCurrent;
int Character = NextCharacter;
pCurrent = pTmp;
NextCharacter = str_utf8_decode(&pTmp);
@ -968,7 +964,7 @@ public:
DrawX = pCursor->m_StartX;
DrawY += Size;
if((m_RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
if((m_RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
{
DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign
DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY;
@ -982,25 +978,25 @@ public:
SFontSizeChar *pChr = GetChar(pFont, pSizeData, Character);
if(pChr)
{
bool ApplyBearingX = !(((m_RenderFlags&TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (m_RenderFlags&TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0));
float Advance = ((((m_RenderFlags&TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + ((!ApplyBearingX) ? (-pChr->m_OffsetX) : 0.f)))) * Scale;
bool ApplyBearingX = !(((m_RenderFlags & TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (m_RenderFlags & TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0));
float Advance = ((((m_RenderFlags & TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + ((!ApplyBearingX) ? (-pChr->m_OffsetX) : 0.f)))) * Scale;
float CharKerning = 0.f;
if((m_RenderFlags&TEXT_RENDER_FLAG_KERNING) != 0)
CharKerning = Kerning(pFont, LastCharGlyphIndex, pChr->m_GlyphIndex)*Scale*Size;
if((m_RenderFlags & TEXT_RENDER_FLAG_KERNING) != 0)
CharKerning = Kerning(pFont, LastCharGlyphIndex, pChr->m_GlyphIndex) * Scale * Size;
LastCharGlyphIndex = pChr->m_GlyphIndex;
if(pCursor->m_Flags&TEXTFLAG_STOP_AT_END && (DrawX + CharKerning)+Advance*Size-pCursor->m_StartX > pCursor->m_LineWidth)
if(pCursor->m_Flags & TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - pCursor->m_StartX > pCursor->m_LineWidth)
{
// we hit the end of the line, no more to render or count
pCurrent = pEnd;
break;
}
float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX)*Scale*Size;
float CharWidth = pChr->m_Width*Scale*Size;
float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX) * Scale * Size;
float CharWidth = pChr->m_Width * Scale * Size;
if(pCursor->m_Flags&TEXTFLAG_RENDER && m_Color.a != 0.f)
if(pCursor->m_Flags & TEXTFLAG_RENDER && m_Color.a != 0.f)
{
if(Graphics()->IsTextBufferingEnabled())
Graphics()->QuadsSetSubset(pChr->m_aUVs[0], pChr->m_aUVs[3], pChr->m_aUVs[2], pChr->m_aUVs[1]);
@ -1009,22 +1005,22 @@ public:
float Y = (DrawY + Size);
float BearingY = 0.f;
BearingY = (((m_RenderFlags&TEXT_RENDER_FLAG_NO_Y_BEARING) != 0) ? 0.f : (pChr->m_OffsetY*Scale*Size));
BearingY = (((m_RenderFlags & TEXT_RENDER_FLAG_NO_Y_BEARING) != 0) ? 0.f : (pChr->m_OffsetY * Scale * Size));
if((m_RenderFlags&TEXT_RENDER_FLAG_NO_OVERSIZE) != 0)
if((m_RenderFlags & TEXT_RENDER_FLAG_NO_OVERSIZE) != 0)
{
if(pChr->m_Height*Scale*Size + BearingY > Size)
BearingY -= pChr->m_Height*Scale*Size - Size;
if(pChr->m_Height * Scale * Size + BearingY > Size)
BearingY -= pChr->m_Height * Scale * Size - Size;
}
IGraphics::CQuadItem QuadItem((DrawX + CharKerning) + BearingX, Y - BearingY, CharWidth, -pChr->m_Height*Scale*Size);
IGraphics::CQuadItem QuadItem((DrawX + CharKerning) + BearingX, Y - BearingY, CharWidth, -pChr->m_Height * Scale * Size);
Graphics()->QuadsDrawTL(&QuadItem, 1);
}
if(NextCharacter == 0 && (m_RenderFlags&TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0)
if(NextCharacter == 0 && (m_RenderFlags & TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0)
DrawX += BearingX + CharKerning + CharWidth;
else
DrawX += Advance*Size + CharKerning;
DrawX += Advance * Size + CharKerning;
pCursor->m_GlyphCount++;
++CharacterCounter;
@ -1035,7 +1031,7 @@ public:
{
DrawX = pCursor->m_StartX;
DrawY += Size;
if((m_RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
if((m_RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
{
DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign
DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY;
@ -1045,11 +1041,11 @@ public:
}
}
if(pCursor->m_Flags&TEXTFLAG_RENDER)
if(pCursor->m_Flags & TEXTFLAG_RENDER)
{
if(Graphics()->IsTextBufferingEnabled())
{
float OutlineColor[4] = { m_OutlineColor.r, m_OutlineColor.g, m_OutlineColor.b, m_OutlineColor.a*m_Color.a };
float OutlineColor[4] = {m_OutlineColor.r, m_OutlineColor.g, m_OutlineColor.b, m_OutlineColor.a * m_Color.a};
Graphics()->TextQuadsEnd(pFont->m_CurTextureDimensions[0], pFont->m_aTextures[0], pFont->m_aTextures[1], OutlineColor);
}
else
@ -1083,7 +1079,7 @@ public:
return -1;
int ContainerIndex = GetFreeTextContainerIndex();
STextContainer& TextContainer = GetTextContainer(ContainerIndex);
STextContainer &TextContainer = GetTextContainer(ContainerIndex);
TextContainer.m_pFont = pFont;
CFontSizeData *pSizeData = NULL;
@ -1159,7 +1155,7 @@ public:
virtual void AppendTextContainer(CTextCursor *pCursor, int TextContainerIndex, const char *pText)
{
STextContainer& TextContainer = GetTextContainer(TextContainerIndex);
STextContainer &TextContainer = GetTextContainer(TextContainerIndex);
CFontSizeData *pSizeData = NULL;
@ -1203,7 +1199,7 @@ public:
int RenderFlags = TextContainer.m_RenderFlags;
if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0)
if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0)
{
DrawX = pCursor->m_X;
DrawY = pCursor->m_Y;
@ -1223,7 +1219,7 @@ public:
{
int NewLine = 0;
const char *pBatchEnd = pEnd;
if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags&TEXTFLAG_STOP_AT_END))
if(pCursor->m_LineWidth > 0 && !(pCursor->m_Flags & TEXTFLAG_STOP_AT_END))
{
int Wlen = minimum(WordLength((char *)pCurrent), (int)(pEnd - pCurrent));
CTextCursor Compare = *pCursor;
@ -1265,7 +1261,7 @@ public:
int NextCharacter = str_utf8_decode(&pTmp);
while(pCurrent < pBatchEnd)
{
TextContainer.m_CharCount += pTmp-pCurrent;
TextContainer.m_CharCount += pTmp - pCurrent;
int Character = NextCharacter;
pCurrent = pTmp;
NextCharacter = str_utf8_decode(&pTmp);
@ -1277,7 +1273,7 @@ public:
DrawX = pCursor->m_StartX;
DrawY += Size;
if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
{
DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign
DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY;
@ -1291,38 +1287,38 @@ public:
SFontSizeChar *pChr = GetChar(TextContainer.m_pFont, pSizeData, Character);
if(pChr)
{
bool ApplyBearingX = !(((RenderFlags&TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (RenderFlags&TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0));
float Advance = ((((RenderFlags&TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + ((!ApplyBearingX) ? (-pChr->m_OffsetX) : 0.f)))) * Scale;
bool ApplyBearingX = !(((RenderFlags & TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (RenderFlags & TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0));
float Advance = ((((RenderFlags & TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + ((!ApplyBearingX) ? (-pChr->m_OffsetX) : 0.f)))) * Scale;
float CharKerning = 0.f;
if((RenderFlags&TEXT_RENDER_FLAG_KERNING) != 0)
CharKerning = Kerning(TextContainer.m_pFont, LastCharGlyphIndex, pChr->m_GlyphIndex)*Scale*Size;
if((RenderFlags & TEXT_RENDER_FLAG_KERNING) != 0)
CharKerning = Kerning(TextContainer.m_pFont, LastCharGlyphIndex, pChr->m_GlyphIndex) * Scale * Size;
LastCharGlyphIndex = pChr->m_GlyphIndex;
if(pCursor->m_Flags&TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - pCursor->m_StartX > pCursor->m_LineWidth)
if(pCursor->m_Flags & TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - pCursor->m_StartX > pCursor->m_LineWidth)
{
// we hit the end of the line, no more to render or count
pCurrent = pEnd;
break;
}
float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX)*Scale*Size;
float CharWidth = pChr->m_Width*Scale*Size;
float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX) * Scale * Size;
float CharWidth = pChr->m_Width * Scale * Size;
// don't add text that isn't drawn, the color overwrite is used for that
if(m_Color.a != 0.f)
{
TextContainer.m_StringInfo.m_CharacterQuads.push_back(STextCharQuad());
STextCharQuad& TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads.back();
STextCharQuad &TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads.back();
float Y = (DrawY + Size);
float BearingY = (((RenderFlags&TEXT_RENDER_FLAG_NO_Y_BEARING) != 0) ? 0.f : (pChr->m_OffsetY*Scale*Size));
float BearingY = (((RenderFlags & TEXT_RENDER_FLAG_NO_Y_BEARING) != 0) ? 0.f : (pChr->m_OffsetY * Scale * Size));
if((RenderFlags&TEXT_RENDER_FLAG_NO_OVERSIZE) != 0)
if((RenderFlags & TEXT_RENDER_FLAG_NO_OVERSIZE) != 0)
{
if(pChr->m_Height*Scale*Size + BearingY > Size)
BearingY -= pChr->m_Height*Scale*Size - Size;
if(pChr->m_Height * Scale * Size + BearingY > Size)
BearingY -= pChr->m_Height * Scale * Size - Size;
}
TextCharQuad.m_Vertices[0].m_X = (DrawX + CharKerning) + BearingX;
@ -1344,7 +1340,7 @@ public:
TextCharQuad.m_Vertices[1].m_Color.m_A = (unsigned char)(m_Color.a * 255.f);
TextCharQuad.m_Vertices[2].m_X = (DrawX + CharKerning) + BearingX + CharWidth;
TextCharQuad.m_Vertices[2].m_Y = Y - BearingY - pChr->m_Height*Scale*Size;
TextCharQuad.m_Vertices[2].m_Y = Y - BearingY - pChr->m_Height * Scale * Size;
TextCharQuad.m_Vertices[2].m_U = pChr->m_aUVs[2];
TextCharQuad.m_Vertices[2].m_V = pChr->m_aUVs[1];
TextCharQuad.m_Vertices[2].m_Color.m_R = (unsigned char)(m_Color.r * 255.f);
@ -1353,7 +1349,7 @@ public:
TextCharQuad.m_Vertices[2].m_Color.m_A = (unsigned char)(m_Color.a * 255.f);
TextCharQuad.m_Vertices[3].m_X = (DrawX + CharKerning) + BearingX;
TextCharQuad.m_Vertices[3].m_Y = Y - BearingY - pChr->m_Height*Scale*Size;
TextCharQuad.m_Vertices[3].m_Y = Y - BearingY - pChr->m_Height * Scale * Size;
TextCharQuad.m_Vertices[3].m_U = pChr->m_aUVs[0];
TextCharQuad.m_Vertices[3].m_V = pChr->m_aUVs[1];
TextCharQuad.m_Vertices[3].m_Color.m_R = (unsigned char)(m_Color.r * 255.f);
@ -1362,7 +1358,7 @@ public:
TextCharQuad.m_Vertices[3].m_Color.m_A = (unsigned char)(m_Color.a * 255.f);
}
if(NextCharacter == 0 && (RenderFlags&TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0)
if(NextCharacter == 0 && (RenderFlags & TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0)
DrawX += BearingX + CharKerning + CharWidth;
else
DrawX += Advance * Size + CharKerning;
@ -1375,7 +1371,7 @@ public:
{
DrawX = pCursor->m_StartX;
DrawY += Size;
if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
{
DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign
DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY;
@ -1419,7 +1415,7 @@ public:
virtual void RecreateTextContainerSoft(CTextCursor *pCursor, int TextContainerIndex, const char *pText)
{
STextContainer& TextContainer = GetTextContainer(TextContainerIndex);
STextContainer &TextContainer = GetTextContainer(TextContainerIndex);
TextContainer.m_StringInfo.m_CharacterQuads.clear();
TextContainer.m_StringInfo.m_QuadNum = 0;
// the text buffer gets then recreated by the appended quads
@ -1428,7 +1424,7 @@ public:
virtual void SetTextContainerSelection(int TextContainerIndex, const char *pText, int CursorPos, int SelectionStart, int SelectionEnd)
{
STextContainer& TextContainer = GetTextContainer(TextContainerIndex);
STextContainer &TextContainer = GetTextContainer(TextContainerIndex);
CFontSizeData *pSizeData = NULL;
@ -1467,7 +1463,7 @@ public:
int RenderFlags = TextContainer.m_RenderFlags;
if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0)
if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) != 0)
{
DrawX = TextContainer.m_X;
DrawY = TextContainer.m_Y;
@ -1497,7 +1493,7 @@ public:
{
int NewLine = 0;
const char *pBatchEnd = pEnd;
if(TextContainer.m_LineWidth > 0 && !(TextContainer.m_Flags&TEXTFLAG_STOP_AT_END))
if(TextContainer.m_LineWidth > 0 && !(TextContainer.m_Flags & TEXTFLAG_STOP_AT_END))
{
CTextCursor FakeCursor;
SetCursor(&FakeCursor, DrawX, DrawY, TextContainer.m_UnscaledFontSize, TextContainer.m_Flags);
@ -1551,7 +1547,7 @@ public:
int NextCharacter = str_utf8_decode(&pTmp);
while(pCurrent < pBatchEnd)
{
TextContainer.m_CharCount += pTmp-pCurrent;
TextContainer.m_CharCount += pTmp - pCurrent;
int Character = NextCharacter;
pCurrent = pTmp;
NextCharacter = str_utf8_decode(&pTmp);
@ -1563,7 +1559,7 @@ public:
DrawX = TextContainer.m_StartX;
DrawY += Size;
if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
{
DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign
DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY;
@ -1577,15 +1573,15 @@ public:
SFontSizeChar *pChr = GetChar(TextContainer.m_pFont, pSizeData, Character);
if(pChr)
{
bool ApplyBearingX = !(((RenderFlags&TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (RenderFlags&TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0));
float Advance = ((((RenderFlags&TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + (!ApplyBearingX ? (-pChr->m_OffsetX) : 0.f)))) * Scale;
bool ApplyBearingX = !(((RenderFlags & TEXT_RENDER_FLAG_NO_X_BEARING) != 0) || (CharacterCounter == 0 && (RenderFlags & TEXT_RENDER_FLAG_NO_FIRST_CHARACTER_X_BEARING) != 0));
float Advance = ((((RenderFlags & TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH) != 0) ? (pChr->m_Width) : (pChr->m_AdvanceX + (!ApplyBearingX ? (-pChr->m_OffsetX) : 0.f)))) * Scale;
float CharKerning = 0.f;
if((RenderFlags&TEXT_RENDER_FLAG_KERNING) != 0)
CharKerning = Kerning(TextContainer.m_pFont, LastCharGlyphIndex, pChr->m_GlyphIndex)*Scale*Size;
if((RenderFlags & TEXT_RENDER_FLAG_KERNING) != 0)
CharKerning = Kerning(TextContainer.m_pFont, LastCharGlyphIndex, pChr->m_GlyphIndex) * Scale * Size;
LastCharGlyphIndex = pChr->m_GlyphIndex;
if(TextContainer.m_Flags&TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - TextContainer.m_StartX > TextContainer.m_LineWidth)
if(TextContainer.m_Flags & TEXTFLAG_STOP_AT_END && (DrawX + CharKerning) + Advance * Size - TextContainer.m_StartX > TextContainer.m_LineWidth)
{
// we hit the end of the line, no more to render or count
pCurrent = pEnd;
@ -1604,10 +1600,10 @@ public:
SelectionQuads.push_back(IGraphics::CQuadItem((DrawX + CharKerning), DrawY, Advance * Size, MaxRowHeight));
}
float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX)*Scale*Size;
float CharWidth = pChr->m_Width*Scale*Size;
float BearingX = (!ApplyBearingX ? 0.f : pChr->m_OffsetX) * Scale * Size;
float CharWidth = pChr->m_Width * Scale * Size;
if(NextCharacter == 0 && (RenderFlags&TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0)
if(NextCharacter == 0 && (RenderFlags & TEXT_RENDER_FLAG_NO_LAST_CHARACTER_ADVANCE) != 0)
DrawX += BearingX + CharKerning + CharWidth;
else
DrawX += Advance * Size + CharKerning;
@ -1622,7 +1618,7 @@ public:
{
DrawX = TextContainer.m_StartX;
DrawY += Size;
if((RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
if((RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
{
DrawX = (int)(DrawX * FakeToScreenX) / FakeToScreenX; // realign
DrawY = (int)(DrawY * FakeToScreenY) / FakeToScreenY;
@ -1647,7 +1643,7 @@ public:
virtual void DeleteTextContainer(int TextContainerIndex)
{
STextContainer& TextContainer = GetTextContainer(TextContainerIndex);
STextContainer &TextContainer = GetTextContainer(TextContainerIndex);
if(Graphics()->IsTextBufferingEnabled())
{
if(TextContainer.m_StringInfo.m_QuadBufferContainerIndex != -1)
@ -1660,7 +1656,7 @@ public:
virtual void RenderTextContainer(int TextContainerIndex, STextRenderColor *pTextColor, STextRenderColor *pTextOutlineColor)
{
STextContainer& TextContainer = GetTextContainer(TextContainerIndex);
STextContainer &TextContainer = GetTextContainer(TextContainerIndex);
CFont *pFont = TextContainer.m_pFont;
if(TextContainer.m_StringInfo.m_SelectionQuadContainerIndex != -1)
@ -1680,7 +1676,7 @@ public:
{
Graphics()->TextureClear();
// render buffered text
Graphics()->RenderText(TextContainer.m_StringInfo.m_QuadBufferContainerIndex, TextContainer.m_StringInfo.m_QuadNum, pFont->m_CurTextureDimensions[0], pFont->m_aTextures[0], pFont->m_aTextures[1], (float*)pTextColor, (float*)pTextOutlineColor);
Graphics()->RenderText(TextContainer.m_StringInfo.m_QuadBufferContainerIndex, TextContainer.m_StringInfo.m_QuadNum, pFont->m_CurTextureDimensions[0], pFont->m_aTextures[0], pFont->m_aTextures[1], (float *)pTextColor, (float *)pTextOutlineColor);
}
else
{
@ -1694,7 +1690,7 @@ public:
for(size_t i = 0; i < TextContainer.m_StringInfo.m_QuadNum; ++i)
{
STextCharQuad& TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads[i];
STextCharQuad &TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads[i];
Graphics()->SetColor(TextCharQuad.m_Vertices[0].m_Color.m_R / 255.f * pTextOutlineColor->m_R, TextCharQuad.m_Vertices[0].m_Color.m_G / 255.f * pTextOutlineColor->m_G, TextCharQuad.m_Vertices[0].m_Color.m_B / 255.f * pTextOutlineColor->m_B, TextCharQuad.m_Vertices[0].m_Color.m_A / 255.f * pTextOutlineColor->m_A);
@ -1711,7 +1707,7 @@ public:
for(size_t i = 0; i < TextContainer.m_StringInfo.m_QuadNum; ++i)
{
STextCharQuad& TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads[i];
STextCharQuad &TextCharQuad = TextContainer.m_StringInfo.m_CharacterQuads[i];
unsigned char CR = (unsigned char)((float)(TextCharQuad.m_Vertices[0].m_Color.m_R) * pTextColor->m_R);
unsigned char CG = (unsigned char)((float)(TextCharQuad.m_Vertices[0].m_Color.m_G) * pTextColor->m_G);
unsigned char CB = (unsigned char)((float)(TextCharQuad.m_Vertices[0].m_Color.m_B) * pTextColor->m_B);
@ -1725,7 +1721,6 @@ public:
else
Graphics()->QuadsEnd();
// reset
Graphics()->SetColor(1.f, 1.f, 1.f, 1.f);
}
@ -1733,13 +1728,13 @@ public:
virtual void RenderTextContainer(int TextContainerIndex, STextRenderColor *pTextColor, STextRenderColor *pTextOutlineColor, float X, float Y)
{
STextContainer& TextContainer = GetTextContainer(TextContainerIndex);
STextContainer &TextContainer = GetTextContainer(TextContainerIndex);
// remap the current screen, after render revert the change again
float ScreenX0, ScreenY0, ScreenX1, ScreenY1;
Graphics()->GetScreen(&ScreenX0, &ScreenY0, &ScreenX1, &ScreenY1);
if((TextContainer.m_RenderFlags&TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
if((TextContainer.m_RenderFlags & TEXT_RENDER_FLAG_NO_PIXEL_ALIGMENT) == 0)
{
float FakeToScreenX = (Graphics()->ScreenWidth() / (ScreenX1 - ScreenX0));
float FakeToScreenY = (Graphics()->ScreenHeight() / (ScreenY1 - ScreenY0));
@ -1758,7 +1753,7 @@ public:
virtual void UploadEntityLayerText(void *pTexBuff, int ImageColorChannelCount, int TexWidth, int TexHeight, int TexSubWidth, int TexSubHeight, const char *pText, int Length, float x, float y, int FontSize)
{
if (FontSize < 1)
if(FontSize < 1)
return;
const char *pCurrent = (char *)pText;
@ -1778,7 +1773,7 @@ public:
FT_Set_Pixel_Sizes(pFont->m_FtFace, 0, FontSize);
if(FT_Load_Char(pFont->m_FtFace, NextCharacter, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP))
if(FT_Load_Char(pFont->m_FtFace, NextCharacter, FT_LOAD_RENDER | FT_LOAD_NO_BITMAP))
{
dbg_msg("pFont", "error loading glyph %d", NextCharacter);
pCurrent = pTmp;
@ -1789,7 +1784,7 @@ public:
int SlotW = pBitmap->width;
int SlotH = pBitmap->rows;
int SlotSize = SlotW*SlotH;
int SlotSize = SlotW * SlotH;
// prepare glyph data
mem_zero(ms_aGlyphData, SlotSize);
@ -1799,11 +1794,11 @@ public:
for(py = 0; py < (unsigned)SlotH; py++) // ignore_convention
for(px = 0; px < (unsigned)SlotW; px++)
{
ms_aGlyphData[(py)*SlotW + px] = pBitmap->buffer[py*pBitmap->width + px]; // ignore_convention
ms_aGlyphData[(py)*SlotW + px] = pBitmap->buffer[py * pBitmap->width + px]; // ignore_convention
}
}
uint8_t* pImageBuff = (uint8_t*)pTexBuff;
uint8_t *pImageBuff = (uint8_t *)pTexBuff;
for(int OffY = 0; OffY < SlotH; ++OffY)
{
for(int OffX = 0; OffX < SlotW; ++OffX)
@ -1838,7 +1833,7 @@ public:
int FontSize = 100.f / ((float)WidthOfText / (float)MaxWidth);
if (MaxSize > 0 && FontSize > MaxSize)
if(MaxSize > 0 && FontSize > MaxSize)
FontSize = MaxSize;
return FontSize;
@ -1852,7 +1847,7 @@ public:
int WidthOfText = 0;
FT_Set_Pixel_Sizes(pFont->m_FtFace, FontWidth, FontHeight);
while (pCurrent < pEnd)
while(pCurrent < pEnd)
{
const char *pTmp = pCurrent;
int NextCharacter = str_utf8_decode(&pTmp);
@ -1886,7 +1881,7 @@ public:
for(size_t i = 0; i < m_TextContainers.size(); ++i)
if(m_TextContainers[i].m_StringInfo.m_QuadBufferContainerIndex != -1)
FoundTextContainer = true;
if (FoundTextContainer)
if(FoundTextContainer)
{
dbg_msg("text render", "%s", "Found non empty text container");
dbg_assert(false, "text container was not empty");

View file

@ -1,16 +1,16 @@
#include "updater.h"
#include <base/system.h>
#include <engine/engine.h>
#include <engine/storage.h>
#include <engine/client.h>
#include <engine/engine.h>
#include <engine/external/json-parser/json.h>
#include <engine/shared/json.h>
#include <engine/storage.h>
#include <game/version.h>
#include <stdlib.h> // system
using std::string;
using std::map;
using std::string;
class CUpdaterFetchTask : public CGetFile
{
@ -176,14 +176,14 @@ void CUpdater::Update()
{
switch(m_State)
{
case IUpdater::GOT_MANIFEST:
PerformUpdate();
break;
case IUpdater::MOVE_FILES:
CommitUpdate();
break;
default:
return;
case IUpdater::GOT_MANIFEST:
PerformUpdate();
break;
case IUpdater::MOVE_FILES:
CommitUpdate();
break;
default:
return;
}
}
@ -206,16 +206,16 @@ bool CUpdater::ReplaceClient()
str_format(aPath, sizeof(aPath), "update/%s", m_aClientExecTmp);
Success &= m_pStorage->RenameBinaryFile(aPath, PLAT_CLIENT_EXEC);
}
#if !defined(CONF_FAMILY_WINDOWS)
m_pStorage->GetBinaryPath(PLAT_CLIENT_EXEC, aPath, sizeof aPath);
char aBuf[512];
str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath);
if(system(aBuf))
{
dbg_msg("updater", "ERROR: failed to set client executable bit");
Success = false;
}
#endif
#if !defined(CONF_FAMILY_WINDOWS)
m_pStorage->GetBinaryPath(PLAT_CLIENT_EXEC, aPath, sizeof aPath);
char aBuf[512];
str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath);
if(system(aBuf))
{
dbg_msg("updater", "ERROR: failed to set client executable bit");
Success = false;
}
#endif
return Success;
}
@ -230,16 +230,16 @@ bool CUpdater::ReplaceServer()
Success &= m_pStorage->RenameBinaryFile(PLAT_SERVER_EXEC, SERVER_EXEC ".old");
str_format(aPath, sizeof(aPath), "update/%s", m_aServerExecTmp);
Success &= m_pStorage->RenameBinaryFile(aPath, PLAT_SERVER_EXEC);
#if !defined(CONF_FAMILY_WINDOWS)
m_pStorage->GetBinaryPath(PLAT_SERVER_EXEC, aPath, sizeof aPath);
char aBuf[512];
str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath);
if (system(aBuf))
{
dbg_msg("updater", "ERROR: failed to set server executable bit");
Success = false;
}
#endif
#if !defined(CONF_FAMILY_WINDOWS)
m_pStorage->GetBinaryPath(PLAT_SERVER_EXEC, aPath, sizeof aPath);
char aBuf[512];
str_format(aBuf, sizeof aBuf, "chmod +x %s", aPath);
if(system(aBuf))
{
dbg_msg("updater", "ERROR: failed to set server executable bit");
Success = false;
}
#endif
return Success;
}
@ -391,14 +391,14 @@ void CUpdater::CommitUpdate()
void CUpdater::WinXpRestart()
{
char aBuf[512];
IOHANDLE bhFile = io_open(m_pStorage->GetBinaryPath("du.bat", aBuf, sizeof aBuf), IOFLAG_WRITE);
if(!bhFile)
return;
char bBuf[512];
str_format(bBuf, sizeof(bBuf), ":_R\r\ndel \"" PLAT_CLIENT_EXEC "\"\r\nif exist \"" PLAT_CLIENT_EXEC "\" goto _R\r\n:_T\r\nmove /y \"update\\%s\" \"" PLAT_CLIENT_EXEC "\"\r\nif not exist \"" PLAT_CLIENT_EXEC "\" goto _T\r\nstart " PLAT_CLIENT_EXEC "\r\ndel \"du.bat\"\r\n", m_aClientExecTmp);
io_write(bhFile, bBuf, str_length(bBuf));
io_close(bhFile);
shell_execute(aBuf);
m_pClient->Quit();
char aBuf[512];
IOHANDLE bhFile = io_open(m_pStorage->GetBinaryPath("du.bat", aBuf, sizeof aBuf), IOFLAG_WRITE);
if(!bhFile)
return;
char bBuf[512];
str_format(bBuf, sizeof(bBuf), ":_R\r\ndel \"" PLAT_CLIENT_EXEC "\"\r\nif exist \"" PLAT_CLIENT_EXEC "\" goto _R\r\n:_T\r\nmove /y \"update\\%s\" \"" PLAT_CLIENT_EXEC "\"\r\nif not exist \"" PLAT_CLIENT_EXEC "\" goto _T\r\nstart " PLAT_CLIENT_EXEC "\r\ndel \"du.bat\"\r\n", m_aClientExecTmp);
io_write(bhFile, bBuf, str_length(bBuf));
io_close(bhFile);
shell_execute(aBuf);
m_pClient->Quit();
}

View file

@ -1,8 +1,8 @@
#ifndef ENGINE_CLIENT_UPDATER_H
#define ENGINE_CLIENT_UPDATER_H
#include <engine/updater.h>
#include <engine/client/http.h>
#include <engine/updater.h>
#include <map>
#include <string>
@ -10,20 +10,20 @@
#define SERVER_EXEC "DDNet-Server"
#if defined(CONF_FAMILY_WINDOWS)
#define PLAT_EXT ".exe"
#define PLAT_NAME CONF_PLATFORM_STRING
#define PLAT_EXT ".exe"
#define PLAT_NAME CONF_PLATFORM_STRING
#elif defined(CONF_FAMILY_UNIX)
#define PLAT_EXT ""
#if defined(CONF_ARCH_IA32)
#define PLAT_NAME CONF_PLATFORM_STRING "-x86"
#elif defined(CONF_ARCH_AMD64)
#define PLAT_NAME CONF_PLATFORM_STRING "-x86_64"
#else
#define PLAT_NAME CONF_PLATFORM_STRING "-unsupported"
#endif
#define PLAT_EXT ""
#if defined(CONF_ARCH_IA32)
#define PLAT_NAME CONF_PLATFORM_STRING "-x86"
#elif defined(CONF_ARCH_AMD64)
#define PLAT_NAME CONF_PLATFORM_STRING "-x86_64"
#else
#define PLAT_EXT ""
#define PLAT_NAME "unsupported-unsupported"
#define PLAT_NAME CONF_PLATFORM_STRING "-unsupported"
#endif
#else
#define PLAT_EXT ""
#define PLAT_NAME "unsupported-unsupported"
#endif
#define PLAT_CLIENT_DOWN CLIENT_EXEC "-" PLAT_NAME PLAT_EXT

View file

@ -1,8 +1,8 @@
#if defined(CONF_VIDEORECORDER)
#include <engine/storage.h>
#include <engine/console.h>
#include <engine/shared/config.h>
#include <engine/storage.h>
#include "video.h"
@ -13,7 +13,7 @@
const size_t FORMAT_NCHANNELS = 3;
static LOCK g_WriteLock = 0;
CVideo::CVideo(CGraphics_Threaded* pGraphics, IStorage* pStorage, IConsole *pConsole, int Width, int Height, const char *pName) :
CVideo::CVideo(CGraphics_Threaded *pGraphics, IStorage *pStorage, IConsole *pConsole, int Width, int Height, const char *pName) :
m_pGraphics(pGraphics),
m_pStorage(pStorage),
m_pConsole(pConsole),
@ -47,7 +47,7 @@ CVideo::CVideo(CGraphics_Threaded* pGraphics, IStorage* pStorage, IConsole *pCon
// TODO:
m_HasAudio = g_Config.m_ClVideoSndEnable;
m_SndBufferSize = g_Config.m_SndBufferSize;
m_SndBufferSize = g_Config.m_SndBufferSize;
dbg_assert(ms_pCurrentVideo == 0, "ms_pCurrentVideo is NOT set to NULL while creating a new Video.");
@ -98,7 +98,6 @@ void CVideo::Start()
m_pPixels = (uint8_t *)malloc(NVals * sizeof(GLubyte));
m_pRGB = (uint8_t *)malloc(NVals * sizeof(uint8_t));
/* Add the audio and video streams using the default format codecs
* and initialize the codecs. */
if(m_pFormat->video_codec != AV_CODEC_ID_NONE)
@ -152,8 +151,7 @@ void CVideo::Start()
m_VideoStream.pSwsCtx,
m_VideoStream.pEnc->width, m_VideoStream.pEnc->height, AV_PIX_FMT_RGB24,
m_VideoStream.pEnc->width, m_VideoStream.pEnc->height, AV_PIX_FMT_YUV420P,
0, 0, 0, 0
);
0, 0, 0, 0);
}
/* Write the stream header, if any. */
@ -195,7 +193,7 @@ void CVideo::Stop()
if(m_HasAudio)
CloseStream(&m_AudioStream);
//fclose(m_dbgfile);
//fclose(m_dbgfile);
if(!(m_pFormat->flags & AVFMT_NOFILE))
avio_closep(&m_pFormatContext->pb);
@ -252,7 +250,7 @@ void CVideo::NextVideoFrame()
//dbg_msg("video_recorder", "called");
ms_Time += ms_TickTime;
ms_LocalTime = (ms_Time-ms_LocalStartTime)/(float)time_freq();
ms_LocalTime = (ms_Time - ms_LocalStartTime) / (float)time_freq();
m_NextFrame = true;
m_Vframe += 1;
@ -268,7 +266,7 @@ void CVideo::NextAudioFrameTimeline()
if(m_Recording && m_HasAudio)
{
//if(m_Vframe * m_AudioStream.pEnc->sample_rate / m_FPS >= m_AudioStream.pEnc->frame_number*m_AudioStream.pEnc->frame_size)
if(m_VideoStream.pEnc->frame_number * (double)m_AudioStream.pEnc->sample_rate / m_FPS >= (double)m_AudioStream.pEnc->frame_number*m_AudioStream.pEnc->frame_size)
if(m_VideoStream.pEnc->frame_number * (double)m_AudioStream.pEnc->sample_rate / m_FPS >= (double)m_AudioStream.pEnc->frame_number * m_AudioStream.pEnc->frame_size)
{
m_NextAudioFrame = true;
}
@ -282,7 +280,7 @@ void CVideo::NextAudioFrame(void (*Mix)(short *pFinalOut, unsigned Frames))
m_ProcessingAudioFrame = true;
//dbg_msg("video recorder", "video_frame: %lf", (double)(m_Vframe/m_FPS));
//if((double)(m_Vframe/m_FPS) < m_AudioStream.pEnc->frame_number*m_AudioStream.pEnc->frame_size/m_AudioStream.pEnc->sample_rate)
//return;
//return;
Mix(m_aBuffer, ALEN);
//m_AudioStream.pFrame->pts = m_AudioStream.pEnc->frame_number;
//dbg_msg("video_recorder", "aframe: %d", m_AudioStream.pEnc->frame_number);
@ -297,9 +295,9 @@ void CVideo::NextAudioFrame(void (*Mix)(short *pFinalOut, unsigned Frames))
int DstNbSamples;
av_samples_fill_arrays(
(uint8_t**)m_AudioStream.pTmpFrame->data,
(uint8_t **)m_AudioStream.pTmpFrame->data,
0, // pointer to linesize (int*)
(const uint8_t*)m_aBuffer,
(const uint8_t *)m_aBuffer,
2, // channels
m_AudioStream.pTmpFrame->nb_samples,
AV_SAMPLE_FMT_S16,
@ -309,17 +307,15 @@ void CVideo::NextAudioFrame(void (*Mix)(short *pFinalOut, unsigned Frames))
DstNbSamples = av_rescale_rnd(
swr_get_delay(
m_AudioStream.pSwrCtx,
m_AudioStream.pEnc->sample_rate
) + m_AudioStream.pTmpFrame->nb_samples,
m_AudioStream.pEnc->sample_rate) +
m_AudioStream.pTmpFrame->nb_samples,
m_AudioStream.pEnc->sample_rate,
m_AudioStream.pEnc->sample_rate, AV_ROUND_UP
);
m_AudioStream.pEnc->sample_rate, AV_ROUND_UP);
// dbg_msg("video_recorder", "DstNbSamples: %d", DstNbSamples);
// fwrite(m_aBuffer, sizeof(short), 2048, m_dbgfile);
int Ret = av_frame_make_writable(m_AudioStream.pFrame);
if(Ret < 0)
{
@ -333,8 +329,7 @@ void CVideo::NextAudioFrame(void (*Mix)(short *pFinalOut, unsigned Frames))
m_AudioStream.pFrame->data,
m_AudioStream.pFrame->nb_samples,
(const uint8_t **)m_AudioStream.pTmpFrame->data,
m_AudioStream.pTmpFrame->nb_samples
);
m_AudioStream.pTmpFrame->nb_samples);
if(Ret < 0)
{
@ -363,9 +358,9 @@ void CVideo::FillAudioFrame()
void CVideo::FillVideoFrame()
{
const int InLinesize[1] = { 3 * m_VideoStream.pEnc->width };
sws_scale(m_VideoStream.pSwsCtx, (const uint8_t * const *)&m_pRGB, InLinesize, 0,
m_VideoStream.pEnc->height, m_VideoStream.pFrame->data, m_VideoStream.pFrame->linesize);
const int InLinesize[1] = {3 * m_VideoStream.pEnc->width};
sws_scale(m_VideoStream.pSwsCtx, (const uint8_t *const *)&m_pRGB, InLinesize, 0,
m_VideoStream.pEnc->height, m_VideoStream.pFrame->data, m_VideoStream.pFrame->linesize);
}
void CVideo::ReadRGBFromGL()
@ -389,10 +384,9 @@ void CVideo::ReadRGBFromGL()
}
}
AVFrame* CVideo::AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height)
AVFrame *CVideo::AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height)
{
AVFrame* pPicture;
AVFrame *pPicture;
int Ret;
pPicture = av_frame_alloc();
@ -400,7 +394,7 @@ AVFrame* CVideo::AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height)
return NULL;
pPicture->format = PixFmt;
pPicture->width = Width;
pPicture->width = Width;
pPicture->height = Height;
/* allocate the buffers for the frame data */
@ -414,8 +408,7 @@ AVFrame* CVideo::AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height)
return pPicture;
}
AVFrame* CVideo::AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLayout, int SampleRate, int NbSamples)
AVFrame *CVideo::AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLayout, int SampleRate, int NbSamples)
{
AVFrame *Frame = av_frame_alloc();
int Ret;
@ -447,8 +440,8 @@ AVFrame* CVideo::AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLa
bool CVideo::OpenVideo()
{
int Ret;
AVCodecContext* c = m_VideoStream.pEnc;
AVDictionary* opt = 0;
AVCodecContext *c = m_VideoStream.pEnc;
AVDictionary *opt = 0;
av_dict_copy(&opt, m_pOptDict, 0);
@ -543,22 +536,22 @@ bool CVideo::OpenAudio()
return false;
}
/* set options */
av_opt_set_int(m_AudioStream.pSwrCtx, "in_channel_count", 2, 0);
av_opt_set_int(m_AudioStream.pSwrCtx, "in_sample_rate", g_Config.m_SndRate, 0);
av_opt_set_sample_fmt(m_AudioStream.pSwrCtx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
av_opt_set_int(m_AudioStream.pSwrCtx, "out_channel_count", c->channels, 0);
av_opt_set_int(m_AudioStream.pSwrCtx, "out_sample_rate", c->sample_rate, 0);
av_opt_set_sample_fmt(m_AudioStream.pSwrCtx, "out_sample_fmt", c->sample_fmt, 0);
/* set options */
av_opt_set_int(m_AudioStream.pSwrCtx, "in_channel_count", 2, 0);
av_opt_set_int(m_AudioStream.pSwrCtx, "in_sample_rate", g_Config.m_SndRate, 0);
av_opt_set_sample_fmt(m_AudioStream.pSwrCtx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
av_opt_set_int(m_AudioStream.pSwrCtx, "out_channel_count", c->channels, 0);
av_opt_set_int(m_AudioStream.pSwrCtx, "out_sample_rate", c->sample_rate, 0);
av_opt_set_sample_fmt(m_AudioStream.pSwrCtx, "out_sample_fmt", c->sample_fmt, 0);
/* initialize the resampling context */
if((Ret = swr_init(m_AudioStream.pSwrCtx)) < 0)
{
dbg_msg("video_recorder", "Failed to initialize the resampling context");
return false;
}
/* initialize the resampling context */
if((Ret = swr_init(m_AudioStream.pSwrCtx)) < 0)
{
dbg_msg("video_recorder", "Failed to initialize the resampling context");
return false;
}
return true;
return true;
}
/* Add an output stream. */
@ -567,7 +560,7 @@ bool CVideo::AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **pp
AVCodecContext *c;
/* find the encoder */
*ppCodec= avcodec_find_encoder(CodecId);
*ppCodec = avcodec_find_encoder(CodecId);
if(!(*ppCodec))
{
dbg_msg("video_recorder", "Could not find encoder for '%s'",
@ -581,7 +574,7 @@ bool CVideo::AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **pp
dbg_msg("video_recorder", "Could not allocate stream");
return false;
}
pStream->pSt->id = pOC->nb_streams-1;
pStream->pSt->id = pOC->nb_streams - 1;
c = avcodec_alloc_context3(*ppCodec);
if(!c)
{
@ -590,79 +583,79 @@ bool CVideo::AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **pp
}
pStream->pEnc = c;
switch ((*ppCodec)->type)
switch((*ppCodec)->type)
{
case AVMEDIA_TYPE_AUDIO:
case AVMEDIA_TYPE_AUDIO:
// m_MixingRate = g_Config.m_SndRate;
//
// // Set 16-bit stereo audio at 22Khz
// Format.freq = g_Config.m_SndRate; // ignore_convention
// Format.format = AUDIO_S16; // ignore_convention
// Format.channels = 2; // ignore_convention
// Format.samples = g_Config.m_SndBufferSize; // ignore_convention
// m_MixingRate = g_Config.m_SndRate;
//
// // Set 16-bit stereo audio at 22Khz
// Format.freq = g_Config.m_SndRate; // ignore_convention
// Format.format = AUDIO_S16; // ignore_convention
// Format.channels = 2; // ignore_convention
// Format.samples = g_Config.m_SndBufferSize; // ignore_convention
c->sample_fmt = (*ppCodec)->sample_fmts ? (*ppCodec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
c->bit_rate = g_Config.m_SndRate * 2 * 16;
c->frame_size = m_SndBufferSize;
c->sample_rate = g_Config.m_SndRate;
if((*ppCodec)->supported_samplerates)
c->sample_fmt = (*ppCodec)->sample_fmts ? (*ppCodec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
c->bit_rate = g_Config.m_SndRate * 2 * 16;
c->frame_size = m_SndBufferSize;
c->sample_rate = g_Config.m_SndRate;
if((*ppCodec)->supported_samplerates)
{
c->sample_rate = (*ppCodec)->supported_samplerates[0];
for(int i = 0; (*ppCodec)->supported_samplerates[i]; i++)
{
c->sample_rate = (*ppCodec)->supported_samplerates[0];
for(int i = 0; (*ppCodec)->supported_samplerates[i]; i++)
{
if((*ppCodec)->supported_samplerates[i] == g_Config.m_SndRate)
c->sample_rate = g_Config.m_SndRate;
}
if((*ppCodec)->supported_samplerates[i] == g_Config.m_SndRate)
c->sample_rate = g_Config.m_SndRate;
}
c->channels = 2;
c->channel_layout = AV_CH_LAYOUT_STEREO;
}
c->channels = 2;
c->channel_layout = AV_CH_LAYOUT_STEREO;
pStream->pSt->time_base.num = 1;
pStream->pSt->time_base.den = c->sample_rate;
break;
pStream->pSt->time_base.num = 1;
pStream->pSt->time_base.den = c->sample_rate;
break;
case AVMEDIA_TYPE_VIDEO:
c->codec_id = CodecId;
case AVMEDIA_TYPE_VIDEO:
c->codec_id = CodecId;
c->bit_rate = 400000;
/* Resolution must be a multiple of two. */
c->width = m_Width;
c->height = m_Height%2==0?m_Height:m_Height-1;
/* timebase: This is the fundamental unit of time (in seconds) in terms
c->bit_rate = 400000;
/* Resolution must be a multiple of two. */
c->width = m_Width;
c->height = m_Height % 2 == 0 ? m_Height : m_Height - 1;
/* timebase: This is the fundamental unit of time (in seconds) in terms
* of which frame timestamps are represented. For fixed-fps content,
* timebase should be 1/framerate and timestamp increments should be
* identical to 1. */
pStream->pSt->time_base.num = 1;
pStream->pSt->time_base.den = m_FPS;
c->time_base = pStream->pSt->time_base;
pStream->pSt->time_base.num = 1;
pStream->pSt->time_base.den = m_FPS;
c->time_base = pStream->pSt->time_base;
c->gop_size = 12; /* emit one intra frame every twelve frames at most */
c->pix_fmt = STREAM_PIX_FMT;
if(c->codec_id == AV_CODEC_ID_MPEG2VIDEO)
{
/* just for testing, we also add B-frames */
c->max_b_frames = 2;
}
if(c->codec_id == AV_CODEC_ID_MPEG1VIDEO)
{
/* Needed to avoid using macroblocks in which some coeffs overflow.
c->gop_size = 12; /* emit one intra frame every twelve frames at most */
c->pix_fmt = STREAM_PIX_FMT;
if(c->codec_id == AV_CODEC_ID_MPEG2VIDEO)
{
/* just for testing, we also add B-frames */
c->max_b_frames = 2;
}
if(c->codec_id == AV_CODEC_ID_MPEG1VIDEO)
{
/* Needed to avoid using macroblocks in which some coeffs overflow.
* This does not happen with normal video, it just happens here as
* the motion of the chroma plane does not match the luma plane. */
c->mb_decision = 2;
}
if(CodecId == AV_CODEC_ID_H264)
{
const char *presets[10] = {"ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow", "placebo"};
//av_opt_set(c->priv_data, "preset", "slow", 0);
//av_opt_set_int(c->priv_data, "crf", 22, 0);
av_opt_set(c->priv_data, "preset", presets[g_Config.m_ClVideoX264Preset], 0);
av_opt_set_int(c->priv_data, "crf", g_Config.m_ClVideoX264Crf, 0);
}
c->mb_decision = 2;
}
if(CodecId == AV_CODEC_ID_H264)
{
const char *presets[10] = {"ultrafast", "superfast", "veryfast", "faster", "fast", "medium", "slow", "slower", "veryslow", "placebo"};
//av_opt_set(c->priv_data, "preset", "slow", 0);
//av_opt_set_int(c->priv_data, "crf", 22, 0);
av_opt_set(c->priv_data, "preset", presets[g_Config.m_ClVideoX264Preset], 0);
av_opt_set_int(c->priv_data, "crf", g_Config.m_ClVideoX264Crf, 0);
}
break;
default:
break;
default:
break;
}
/* Some formats want stream headers to be separate. */
@ -672,12 +665,12 @@ bool CVideo::AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **pp
return true;
}
void CVideo::WriteFrame(OutputStream* pStream)
void CVideo::WriteFrame(OutputStream *pStream)
{
//lock_wait(g_WriteLock);
int RetRecv = 0;
AVPacket Packet = { 0 };
AVPacket Packet = {0};
av_init_packet(&Packet);
Packet.data = 0;
@ -711,12 +704,12 @@ void CVideo::WriteFrame(OutputStream* pStream)
//lock_unlock(g_WriteLock);
}
void CVideo::FinishFrames(OutputStream* pStream)
void CVideo::FinishFrames(OutputStream *pStream)
{
dbg_msg("video_recorder", "------------");
int RetRecv = 0;
AVPacket Packet = { 0 };
AVPacket Packet = {0};
av_init_packet(&Packet);
Packet.data = 0;
@ -750,7 +743,7 @@ void CVideo::FinishFrames(OutputStream* pStream)
}
}
void CVideo::CloseStream(OutputStream* pStream)
void CVideo::CloseStream(OutputStream *pStream)
{
avcodec_free_context(&pStream->pEnc);
av_frame_free(&pStream->pFrame);

View file

@ -2,41 +2,39 @@
#define ENGINE_CLIENT_VIDEO_H
#if defined(__ANDROID__)
#define GL_GLEXT_PROTOTYPES
#include <GLES/gl.h>
#include <GLES/glext.h>
#include <GL/glu.h>
#define glOrtho glOrthof
#define GL_GLEXT_PROTOTYPES
#include <GL/glu.h>
#include <GLES/gl.h>
#include <GLES/glext.h>
#define glOrtho glOrthof
#else
#include "SDL_opengl.h"
#include "SDL_opengl.h"
#if defined(CONF_PLATFORM_MACOSX)
#include "OpenGL/glu.h"
#else
#include "GL/glu.h"
#endif
#if defined(CONF_PLATFORM_MACOSX)
#include "OpenGL/glu.h"
#else
#include "GL/glu.h"
#endif
#endif
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
};
#include <base/system.h>
#include <engine/shared/video.h>
#include <engine/shared/demo.h>
#include <engine/shared/video.h>
#define ALEN 2048
// a wrapper around a single output AVStream
typedef struct OutputStream {
typedef struct OutputStream
{
AVStream *pSt;
AVCodecContext *pEnc;
@ -54,7 +52,7 @@ typedef struct OutputStream {
class CVideo : public IVideo
{
public:
CVideo(class CGraphics_Threaded* pGraphics, class IStorage* pStorage, class IConsole *pConsole, int width, int height, const char *name);
CVideo(class CGraphics_Threaded *pGraphics, class IStorage *pStorage, class IConsole *pConsole, int width, int height, const char *name);
~CVideo();
virtual void Start();
@ -70,7 +68,7 @@ public:
virtual void NextAudioFrameTimeline();
virtual bool AudioFrameRendered() { return !m_NextAudioFrame; }
static IVideo* Current() { return IVideo::ms_pCurrentVideo; }
static IVideo *Current() { return IVideo::ms_pCurrentVideo; }
static void Init() { av_log_set_level(AV_LOG_DEBUG); }
@ -83,24 +81,24 @@ private:
bool OpenVideo();
bool OpenAudio();
AVFrame *AllocPicture(enum AVPixelFormat PixFmt, int Width, int Height);
AVFrame* AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLayout, int SampleRate, int NbSamples);
AVFrame *AllocAudioFrame(enum AVSampleFormat SampleFmt, uint64 ChannelLayout, int SampleRate, int NbSamples);
void WriteFrame(OutputStream* pStream);
void FinishFrames(OutputStream* pStream);
void WriteFrame(OutputStream *pStream);
void FinishFrames(OutputStream *pStream);
void CloseStream(OutputStream *pStream);
bool AddStream(OutputStream *pStream, AVFormatContext *pOC, AVCodec **ppCodec, enum AVCodecID CodecId);
class CGraphics_Threaded* m_pGraphics;
class IStorage* m_pStorage;
class IConsole* m_pConsole;
class CGraphics_Threaded *m_pGraphics;
class IStorage *m_pStorage;
class IConsole *m_pConsole;
int m_Width;
int m_Height;
char m_Name[256];
//FILE *m_dbgfile;
int m_Vseq;
short m_aBuffer[ALEN*2];
short m_aBuffer[ALEN * 2];
int m_Vframe;
int m_FPS;
@ -116,23 +114,22 @@ private:
bool m_HasAudio;
GLubyte* m_pPixels;
GLubyte *m_pPixels;
OutputStream m_VideoStream;
OutputStream m_AudioStream;
AVCodec* m_VideoCodec;
AVCodec* m_AudioCodec;
AVCodec *m_VideoCodec;
AVCodec *m_AudioCodec;
AVDictionary* m_pOptDict;
AVDictionary *m_pOptDict;
AVFormatContext* m_pFormatContext;
AVOutputFormat* m_pFormat;
AVFormatContext *m_pFormatContext;
AVOutputFormat *m_pFormat;
uint8_t* m_pRGB;
uint8_t *m_pRGB;
int m_SndBufferSize;
};
#endif

View file

@ -3,35 +3,34 @@
#ifndef ENGINE_CONSOLE_H
#define ENGINE_CONSOLE_H
#include "kernel.h"
#include <base/color.h>
#include <engine/storage.h>
#include "kernel.h"
class IConsole : public IInterface
{
MACRO_INTERFACE("console", 0)
public:
// TODO: rework/cleanup
enum
{
OUTPUT_LEVEL_STANDARD=0,
OUTPUT_LEVEL_STANDARD = 0,
OUTPUT_LEVEL_ADDINFO,
OUTPUT_LEVEL_DEBUG,
ACCESS_LEVEL_ADMIN=0,
ACCESS_LEVEL_ADMIN = 0,
ACCESS_LEVEL_MOD,
ACCESS_LEVEL_HELPER,
ACCESS_LEVEL_USER,
TEMPCMD_NAME_LENGTH=32,
TEMPCMD_HELP_LENGTH=96,
TEMPCMD_PARAMS_LENGTH=96,
TEMPCMD_NAME_LENGTH = 32,
TEMPCMD_HELP_LENGTH = 96,
TEMPCMD_PARAMS_LENGTH = 96,
MAX_PRINT_CB=4,
MAX_PRINT_CB = 4,
CLIENT_ID_GAME=-2,
CLIENT_ID_NO_GAME=-3,
CLIENT_ID_GAME = -2,
CLIENT_ID_NO_GAME = -3,
};
// TODO: rework this interface to reduce the amount of virtual calls
@ -39,6 +38,7 @@ public:
{
protected:
unsigned m_NumArgs;
public:
IResult() { m_NumArgs = 0; }
virtual ~IResult() {}
@ -62,6 +62,7 @@ public:
{
protected:
int m_AccessLevel;
public:
CCommandInfo() { m_AccessLevel = ACCESS_LEVEL_ADMIN; }
virtual ~CCommandInfo() {}

View file

@ -3,14 +3,14 @@
#ifndef ENGINE_DEMO_H
#define ENGINE_DEMO_H
#include "kernel.h"
#include <base/hash.h>
#include <engine/map.h>
#include <engine/shared/uuid_manager.h>
#include "kernel.h"
enum
{
MAX_TIMELINE_MARKERS=64
MAX_TIMELINE_MARKERS = 64
};
const double g_aSpeeds[] = {0.1, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 20.0, 24.0, 28.0, 32.0, 40.0, 48.0, 56.0, 64.0};
@ -18,12 +18,11 @@ const double g_aSpeeds[] = {0.1, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0,
typedef bool (*DEMOFUNC_FILTER)(const void *pData, int DataSize, void *pUser);
// TODO: Properly extend demo format using uuids
static const CUuid SHA256_EXTENSION = {{
// "6be6da4a-cebd-380c-9b5b-1289c842d780"
// "demoitem-sha256@ddnet.tw"
0x6b, 0xe6, 0xda, 0x4a, 0xce, 0xbd, 0x38, 0x0c,
0x9b, 0x5b, 0x12, 0x89, 0xc8, 0x42, 0xd7, 0x80
}};
// "6be6da4a-cebd-380c-9b5b-1289c842d780"
// "demoitem-sha256@ddnet.tw"
static const CUuid SHA256_EXTENSION =
{{0x6b, 0xe6, 0xda, 0x4a, 0xce, 0xbd, 0x38, 0x0c,
0x9b, 0x5b, 0x12, 0x89, 0xc8, 0x42, 0xd7, 0x80}};
struct CDemoHeader
{
@ -72,7 +71,7 @@ public:
enum
{
DEMOTYPE_INVALID=0,
DEMOTYPE_INVALID = 0,
DEMOTYPE_CLIENT,
DEMOTYPE_SERVER,
};
@ -107,7 +106,6 @@ class IDemoEditor : public IInterface
{
MACRO_INTERFACE("demoeditor", 0)
public:
virtual void Slice(const char *pDemo, const char *pDst, int StartTick, int EndTick, DEMOFUNC_FILTER pfnFilter, void *pUser) = 0;
};

View file

@ -8,7 +8,6 @@ class IEditor : public IInterface
{
MACRO_INTERFACE("editor", 0)
public:
virtual ~IEditor() {}
virtual void Init() = 0;
virtual void UpdateAndRender() = 0;

3
src/engine/external/.clang-format vendored Normal file
View file

@ -0,0 +1,3 @@
DisableFormat: true
# clang-format bug: still sorts includes even if disabled
SortIncludes: false

View file

@ -21,11 +21,11 @@ class IFriends : public IInterface
public:
enum
{
FRIEND_NO=0,
FRIEND_NO = 0,
FRIEND_CLAN,
FRIEND_PLAYER,
MAX_FRIENDS=1024,
MAX_FRIENDS = 1024,
};
virtual void Init(bool Foes = false) = 0;

View file

@ -63,10 +63,10 @@ class CImageInfo
public:
enum
{
FORMAT_AUTO=-1,
FORMAT_RGB=0,
FORMAT_RGBA=1,
FORMAT_ALPHA=2,
FORMAT_AUTO = -1,
FORMAT_RGB = 0,
FORMAT_RGBA = 1,
FORMAT_ALPHA = 2,
};
/* Variable: width
@ -120,7 +120,10 @@ struct GL_SColorf
};
//use normalized color values
struct GL_SColor { unsigned char r, g, b, a; };
struct GL_SColor
{
unsigned char r, g, b, a;
};
struct GL_SVertex
{
@ -145,12 +148,13 @@ struct GL_SVertexTex3DStream
struct SGraphicsWarning
{
SGraphicsWarning() : m_WasShown(false) {}
SGraphicsWarning() :
m_WasShown(false) {}
char m_aWarningMsg[128];
bool m_WasShown;
};
typedef void(*WINDOW_RESIZE_FUNC)(void *pUser);
typedef void (*WINDOW_RESIZE_FUNC)(void *pUser);
class IGraphics : public IInterface
{
@ -160,15 +164,16 @@ protected:
int m_ScreenHeight;
int m_DesktopScreenWidth;
int m_DesktopScreenHeight;
public:
/* Constants: Texture Loading Flags
TEXLOAD_NORESAMPLE - Prevents the texture from any resampling
*/
enum
{
TEXLOAD_NORESAMPLE = 1<<0,
TEXLOAD_NOMIPMAPS = 1<<1,
TEXLOAD_NO_COMPRESSION = 1<<2,
TEXLOAD_NORESAMPLE = 1 << 0,
TEXLOAD_NOMIPMAPS = 1 << 1,
TEXLOAD_NO_COMPRESSION = 1 << 2,
TEXLOAD_TO_3D_TEXTURE = (1 << 3),
TEXLOAD_TO_2D_ARRAY_TEXTURE = (1 << 4),
TEXLOAD_TO_3D_TEXTURE_SINGLE_LAYER = (1 << 5),
@ -176,22 +181,23 @@ public:
TEXLOAD_NO_2D_TEXTURE = (1 << 7),
};
class CTextureHandle
{
friend class IGraphics;
int m_Id;
public:
CTextureHandle()
: m_Id(-1)
{}
CTextureHandle() :
m_Id(-1)
{
}
operator int() const { return m_Id; }
};
int ScreenWidth() const { return m_ScreenWidth; }
int ScreenHeight() const { return m_ScreenHeight; }
float ScreenAspect() const { return (float)ScreenWidth()/(float)ScreenHeight(); }
float ScreenAspect() const { return (float)ScreenWidth() / (float)ScreenHeight(); }
virtual bool Fullscreen(bool State) = 0;
virtual void SetWindowBordered(bool State) = 0;
@ -263,7 +269,8 @@ public:
{
float m_X0, m_Y0, m_X1, m_Y1;
CLineItem() {}
CLineItem(float x0, float y0, float x1, float y1) : m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1) {}
CLineItem(float x0, float y0, float x1, float y1) :
m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1) {}
};
virtual void LinesBegin() = 0;
virtual void LinesEnd() = 0;
@ -285,8 +292,15 @@ public:
{
float m_X, m_Y, m_Width, m_Height;
CQuadItem() {}
CQuadItem(float x, float y, float w, float h) : m_X(x), m_Y(y), m_Width(w), m_Height(h) {}
void Set(float x, float y, float w, float h) { m_X = x; m_Y = y; m_Width = w; m_Height = h; }
CQuadItem(float x, float y, float w, float h) :
m_X(x), m_Y(y), m_Width(w), m_Height(h) {}
void Set(float x, float y, float w, float h)
{
m_X = x;
m_Y = y;
m_Width = w;
m_Height = h;
}
};
virtual void QuadsDraw(CQuadItem *pArray, int Num) = 0;
virtual void QuadsDrawTL(const CQuadItem *pArray, int Num) = 0;
@ -297,8 +311,8 @@ public:
{
float m_X0, m_Y0, m_X1, m_Y1, m_X2, m_Y2, m_X3, m_Y3;
CFreeformItem() {}
CFreeformItem(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3)
: m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1), m_X2(x2), m_Y2(y2), m_X3(x3), m_Y3(y3) {}
CFreeformItem(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) :
m_X0(x0), m_Y0(y0), m_X1(x1), m_Y1(y1), m_X2(x2), m_Y2(y2), m_X3(x3), m_Y3(y3) {}
};
virtual int CreateQuadContainer() = 0;
@ -328,7 +342,8 @@ public:
int m_Index;
float m_R, m_G, m_B, m_A;
CColorVertex() {}
CColorVertex(int i, float r, float g, float b, float a) : m_Index(i), m_R(r), m_G(g), m_B(b), m_A(a) {}
CColorVertex(int i, float r, float g, float b, float a) :
m_Index(i), m_R(r), m_G(g), m_B(b), m_A(a) {}
};
virtual void SetColorVertex(const CColorVertex *pArray, int Num) = 0;
virtual void SetColor(float r, float g, float b, float a) = 0;
@ -353,6 +368,7 @@ public:
virtual void NotifyWindow() = 0;
virtual SGraphicsWarning *GetCurWarning() = 0;
protected:
inline CTextureHandle CreateTextureHandle(int Index)
{

View file

@ -13,24 +13,21 @@ class IInterface
// friend with the kernel implementation
friend class CKernel;
IKernel *m_pKernel;
protected:
IKernel *Kernel() { return m_pKernel; }
public:
IInterface() : m_pKernel(0) {}
virtual ~IInterface() {}
//virtual unsigned InterfaceID() = 0;
//virtual const char *InterfaceName() = 0;
public:
IInterface() :
m_pKernel(0) {}
virtual ~IInterface() {}
};
#define MACRO_INTERFACE(Name, ver) \
public: \
static const char *InterfaceName() { return Name; } \
private:
//virtual unsigned InterfaceID() { return INTERFACE_ID; }
//virtual const char *InterfaceName() { return name; }
public: \
static const char *InterfaceName() { return Name; } \
\
private:
// This kernel thingie makes the structure very flat and basiclly singletons.
// I'm not sure if this is a good idea but it works for now.
@ -40,6 +37,7 @@ class IKernel
virtual bool RegisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface, bool Destroy) = 0;
virtual bool ReregisterInterfaceImpl(const char *InterfaceName, IInterface *pInterface) = 0;
virtual IInterface *RequestInterfaceImpl(const char *InterfaceName) = 0;
public:
static IKernel *Create();
virtual ~IKernel() {}

View file

@ -3,8 +3,8 @@
#ifndef ENGINE_MAP_H
#define ENGINE_MAP_H
#include <base/hash.h>
#include "kernel.h"
#include <base/hash.h>
enum
{
@ -26,7 +26,6 @@ public:
virtual int NumItems() = 0;
};
class IEngineMap : public IMap
{
MACRO_INTERFACE("enginemap", 0)

View file

@ -9,10 +9,9 @@ class IMasterServer : public IInterface
{
MACRO_INTERFACE("masterserver", 0)
public:
enum
{
MAX_MASTERSERVERS=4
MAX_MASTERSERVERS = 4
};
virtual void Init() = 0;

View file

@ -12,7 +12,8 @@ public:
int m_MsgID;
bool m_System;
bool m_NoTranslate;
CMsgPacker(int Type, bool System = false, bool NoTranslate = false) : m_MsgID(Type), m_System(System), m_NoTranslate(NoTranslate)
CMsgPacker(int Type, bool System = false, bool NoTranslate = false) :
m_MsgID(Type), m_System(System), m_NoTranslate(NoTranslate)
{
Reset();
}

View file

@ -10,10 +10,10 @@
#include "kernel.h"
#include "message.h"
#include <engine/shared/protocol.h>
#include <game/generated/protocol.h>
#include <game/generated/protocol7.h>
#include <game/generated/protocolglue.h>
#include <engine/shared/protocol.h>
struct CAntibotRoundData;
@ -62,7 +62,7 @@ public:
{
int Result = 0;
T tmp;
if (ClientID == -1)
if(ClientID == -1)
{
for(int i = 0; i < MAX_CLIENTS; i++)
if(ClientIngame(i))
@ -70,7 +70,9 @@ public:
mem_copy(&tmp, pMsg, sizeof(T));
Result = SendPackMsgTranslate(&tmp, Flags, i);
}
} else {
}
else
{
mem_copy(&tmp, pMsg, sizeof(T));
Result = SendPackMsgTranslate(&tmp, Flags, ClientID);
}
@ -130,8 +132,10 @@ public:
int SendPackMsgTranslate(CNetMsg_Sv_KillMsg *pMsg, int Flags, int ClientID)
{
if (!Translate(pMsg->m_Victim, ClientID)) return 0;
if (!Translate(pMsg->m_Killer, ClientID)) pMsg->m_Killer = pMsg->m_Victim;
if(!Translate(pMsg->m_Victim, ClientID))
return 0;
if(!Translate(pMsg->m_Killer, ClientID))
pMsg->m_Killer = pMsg->m_Victim;
return SendPackMsgOne(pMsg, Flags, ClientID);
}
@ -146,19 +150,19 @@ public:
return SendMsg(&Packer, Flags, ClientID);
}
bool Translate(int& Target, int Client)
bool Translate(int &Target, int Client)
{
if(IsSixup(Client))
return true;
CClientInfo Info;
GetClientInfo(Client, &Info);
if (Info.m_DDNetVersion >= VERSION_DDNET_OLD)
if(Info.m_DDNetVersion >= VERSION_DDNET_OLD)
return true;
int *pMap = GetIdMap(Client);
bool Found = false;
for (int i = 0; i < VANILLA_MAX_CLIENTS; i++)
for(int i = 0; i < VANILLA_MAX_CLIENTS; i++)
{
if (Target == pMap[i])
if(Target == pMap[i])
{
Target = i;
Found = true;
@ -168,17 +172,17 @@ public:
return Found;
}
bool ReverseTranslate(int& Target, int Client)
bool ReverseTranslate(int &Target, int Client)
{
if(IsSixup(Client))
return true;
CClientInfo Info;
GetClientInfo(Client, &Info);
if (Info.m_DDNetVersion >= VERSION_DDNET_OLD)
if(Info.m_DDNetVersion >= VERSION_DDNET_OLD)
return true;
Target = clamp(Target, 0, VANILLA_MAX_CLIENTS-1);
Target = clamp(Target, 0, VANILLA_MAX_CLIENTS - 1);
int *pMap = GetIdMap(Client);
if (pMap[Target] == -1)
if(pMap[Target] == -1)
return false;
Target = pMap[Target];
return true;
@ -198,9 +202,10 @@ public:
virtual void SnapSetStaticsize(int ItemType, int Size) = 0;
enum {
RCON_CID_SERV=-1,
RCON_CID_VOTE=-2,
enum
{
RCON_CID_SERV = -1,
RCON_CID_VOTE = -2,
};
virtual void SetRconCID(int ClientID) = 0;
virtual int GetAuthedState(int ClientID) = 0;
@ -208,7 +213,6 @@ public:
virtual void Kick(int ClientID, const char *pReason) = 0;
virtual void Ban(int ClientID, int Seconds, const char *pReason) = 0;
virtual void DemoRecorder_HandleAutoStart() = 0;
virtual bool DemoRecorder_IsRecording() = 0;
@ -221,7 +225,7 @@ public:
virtual void GetClientAddr(int ClientID, NETADDR *pAddr) = 0;
virtual int* GetIdMap(int ClientID) = 0;
virtual int *GetIdMap(int ClientID) = 0;
virtual bool DnsblWhite(int ClientID) = 0;
virtual bool DnsblPending(int ClientID) = 0;

View file

@ -1,13 +1,13 @@
#include "antibot.h"
#include <antibot/antibot_interface.h>
#include <engine/kernel.h>
#include <engine/console.h>
#include <engine/kernel.h>
#include <engine/server.h>
#ifdef CONF_ANTIBOT
CAntibot::CAntibot()
: m_pServer(0), m_pConsole(0), m_pGameServer(0), m_Initialized(false)
CAntibot::CAntibot() :
m_pServer(0), m_pConsole(0), m_pGameServer(0), m_Initialized(false)
{
}
CAntibot::~CAntibot()
@ -23,11 +23,11 @@ void CAntibot::Send(int ClientID, const void *pData, int Size, int Flags, void *
CAntibot *pAntibot = (CAntibot *)pUser;
int RealFlags = MSGFLAG_VITAL;
if(Flags&ANTIBOT_MSGFLAG_NONVITAL)
if(Flags & ANTIBOT_MSGFLAG_NONVITAL)
{
RealFlags &= ~MSGFLAG_VITAL;
}
if(Flags&ANTIBOT_MSGFLAG_FLUSH)
if(Flags & ANTIBOT_MSGFLAG_FLUSH)
{
RealFlags |= MSGFLAG_FLUSH;
}
@ -95,32 +95,80 @@ void CAntibot::Update()
}
}
void CAntibot::OnPlayerInit(int ClientID) { Update(); AntibotOnPlayerInit(ClientID); }
void CAntibot::OnPlayerDestroy(int ClientID) { Update(); AntibotOnPlayerDestroy(ClientID); }
void CAntibot::OnSpawn(int ClientID) { Update(); AntibotOnSpawn(ClientID); }
void CAntibot::OnHammerFireReloading(int ClientID) { Update(); AntibotOnHammerFireReloading(ClientID); }
void CAntibot::OnHammerFire(int ClientID) { Update(); AntibotOnHammerFire(ClientID); }
void CAntibot::OnHammerHit(int ClientID) { Update(); AntibotOnHammerHit(ClientID); }
void CAntibot::OnDirectInput(int ClientID) { Update(); AntibotOnDirectInput(ClientID); }
void CAntibot::OnCharacterTick(int ClientID) { Update(); AntibotOnCharacterTick(ClientID); }
void CAntibot::OnHookAttach(int ClientID, bool Player) { Update(); AntibotOnHookAttach(ClientID, Player); }
void CAntibot::OnPlayerInit(int ClientID)
{
Update();
AntibotOnPlayerInit(ClientID);
}
void CAntibot::OnPlayerDestroy(int ClientID)
{
Update();
AntibotOnPlayerDestroy(ClientID);
}
void CAntibot::OnSpawn(int ClientID)
{
Update();
AntibotOnSpawn(ClientID);
}
void CAntibot::OnHammerFireReloading(int ClientID)
{
Update();
AntibotOnHammerFireReloading(ClientID);
}
void CAntibot::OnHammerFire(int ClientID)
{
Update();
AntibotOnHammerFire(ClientID);
}
void CAntibot::OnHammerHit(int ClientID)
{
Update();
AntibotOnHammerHit(ClientID);
}
void CAntibot::OnDirectInput(int ClientID)
{
Update();
AntibotOnDirectInput(ClientID);
}
void CAntibot::OnCharacterTick(int ClientID)
{
Update();
AntibotOnCharacterTick(ClientID);
}
void CAntibot::OnHookAttach(int ClientID, bool Player)
{
Update();
AntibotOnHookAttach(ClientID, Player);
}
void CAntibot::OnEngineTick() { Update(); AntibotOnEngineTick(); }
void CAntibot::OnEngineClientJoin(int ClientID, bool Sixup) { Update(); AntibotOnEngineClientJoin(ClientID, Sixup); }
void CAntibot::OnEngineClientDrop(int ClientID, const char *pReason) { Update(); AntibotOnEngineClientDrop(ClientID, pReason); }
void CAntibot::OnEngineTick()
{
Update();
AntibotOnEngineTick();
}
void CAntibot::OnEngineClientJoin(int ClientID, bool Sixup)
{
Update();
AntibotOnEngineClientJoin(ClientID, Sixup);
}
void CAntibot::OnEngineClientDrop(int ClientID, const char *pReason)
{
Update();
AntibotOnEngineClientDrop(ClientID, pReason);
}
void CAntibot::OnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags)
{
Update();
int AntibotFlags = 0;
if((Flags&MSGFLAG_VITAL) == 0)
if((Flags & MSGFLAG_VITAL) == 0)
{
AntibotFlags |= ANTIBOT_MSGFLAG_NONVITAL;
}
AntibotOnEngineClientMessage(ClientID, pData, Size, Flags);
}
#else
CAntibot::CAntibot()
: m_pServer(0), m_pConsole(0), m_pGameServer(0), m_Initialized(false)
CAntibot::CAntibot() :
m_pServer(0), m_pConsole(0), m_pGameServer(0), m_Initialized(false)
{
}
CAntibot::~CAntibot()
@ -148,20 +196,23 @@ void CAntibot::Update()
{
}
void CAntibot::OnPlayerInit(int ClientID) { }
void CAntibot::OnPlayerDestroy(int ClientID) { }
void CAntibot::OnSpawn(int ClientID) { }
void CAntibot::OnHammerFireReloading(int ClientID) { }
void CAntibot::OnHammerFire(int ClientID) { }
void CAntibot::OnHammerHit(int ClientID) { }
void CAntibot::OnDirectInput(int ClientID) { }
void CAntibot::OnCharacterTick(int ClientID) { }
void CAntibot::OnHookAttach(int ClientID, bool Player) { }
void CAntibot::OnPlayerInit(int ClientID) {}
void CAntibot::OnPlayerDestroy(int ClientID) {}
void CAntibot::OnSpawn(int ClientID) {}
void CAntibot::OnHammerFireReloading(int ClientID) {}
void CAntibot::OnHammerFire(int ClientID) {}
void CAntibot::OnHammerHit(int ClientID) {}
void CAntibot::OnDirectInput(int ClientID) {}
void CAntibot::OnCharacterTick(int ClientID) {}
void CAntibot::OnHookAttach(int ClientID, bool Player) {}
void CAntibot::OnEngineTick() { }
void CAntibot::OnEngineClientJoin(int ClientID, bool Sixup) { }
void CAntibot::OnEngineClientDrop(int ClientID, const char *pReason) { }
void CAntibot::OnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags) { }
void CAntibot::OnEngineTick() {}
void CAntibot::OnEngineClientJoin(int ClientID, bool Sixup) {}
void CAntibot::OnEngineClientDrop(int ClientID, const char *pReason) {}
void CAntibot::OnEngineClientMessage(int ClientID, const void *pData, int Size, int Flags) {}
#endif
IEngineAntibot *CreateEngineAntibot() { return new CAntibot; }
IEngineAntibot *CreateEngineAntibot()
{
return new CAntibot;
}

View file

@ -22,6 +22,7 @@ class CAntibot : public IEngineAntibot
static void Send(int ClientID, const void *pData, int Size, int Flags, void *pUser);
static void Log(const char *pMessage, void *pUser);
static void Report(int ClientID, const char *pMessage, void *pUser);
public:
CAntibot();
virtual ~CAntibot();

View file

@ -1,6 +1,6 @@
#include "authmanager.h"
#include <base/hash_ctxt.h>
#include <engine/shared/config.h>
#include "authmanager.h"
#define ADMIN_IDENT "default_admin"
#define MOD_IDENT "default_mod"

View file

@ -27,6 +27,7 @@ private:
int m_aDefault[3];
bool m_Generated;
public:
typedef void (*FListCallback)(const char *pIdent, int Level, void *pUser);

View file

@ -5,82 +5,82 @@
void IDbConnection::FormatCreateRace(char *aBuf, unsigned int BufferSize)
{
str_format(aBuf, BufferSize,
"CREATE TABLE IF NOT EXISTS %s_race ("
"Map VARCHAR(128) COLLATE %s NOT NULL, "
"Name VARCHAR(%d) COLLATE %s NOT NULL, "
"Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"Time FLOAT DEFAULT 0, "
"Server CHAR(4), "
"cp1 FLOAT DEFAULT 0, cp2 FLOAT DEFAULT 0, cp3 FLOAT DEFAULT 0, "
"cp4 FLOAT DEFAULT 0, cp5 FLOAT DEFAULT 0, cp6 FLOAT DEFAULT 0, "
"cp7 FLOAT DEFAULT 0, cp8 FLOAT DEFAULT 0, cp9 FLOAT DEFAULT 0, "
"cp10 FLOAT DEFAULT 0, cp11 FLOAT DEFAULT 0, cp12 FLOAT DEFAULT 0, "
"cp13 FLOAT DEFAULT 0, cp14 FLOAT DEFAULT 0, cp15 FLOAT DEFAULT 0, "
"cp16 FLOAT DEFAULT 0, cp17 FLOAT DEFAULT 0, cp18 FLOAT DEFAULT 0, "
"cp19 FLOAT DEFAULT 0, cp20 FLOAT DEFAULT 0, cp21 FLOAT DEFAULT 0, "
"cp22 FLOAT DEFAULT 0, cp23 FLOAT DEFAULT 0, cp24 FLOAT DEFAULT 0, "
"cp25 FLOAT DEFAULT 0, "
"GameID VARCHAR(64), "
"DDNet7 BOOL DEFAULT FALSE, "
"PRIMARY KEY (Map, Name, Time, Timestamp, Server)"
");",
GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate());
"CREATE TABLE IF NOT EXISTS %s_race ("
" Map VARCHAR(128) COLLATE %s NOT NULL, "
" Name VARCHAR(%d) COLLATE %s NOT NULL, "
" Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
" Time FLOAT DEFAULT 0, "
" Server CHAR(4), "
" cp1 FLOAT DEFAULT 0, cp2 FLOAT DEFAULT 0, cp3 FLOAT DEFAULT 0, "
" cp4 FLOAT DEFAULT 0, cp5 FLOAT DEFAULT 0, cp6 FLOAT DEFAULT 0, "
" cp7 FLOAT DEFAULT 0, cp8 FLOAT DEFAULT 0, cp9 FLOAT DEFAULT 0, "
" cp10 FLOAT DEFAULT 0, cp11 FLOAT DEFAULT 0, cp12 FLOAT DEFAULT 0, "
" cp13 FLOAT DEFAULT 0, cp14 FLOAT DEFAULT 0, cp15 FLOAT DEFAULT 0, "
" cp16 FLOAT DEFAULT 0, cp17 FLOAT DEFAULT 0, cp18 FLOAT DEFAULT 0, "
" cp19 FLOAT DEFAULT 0, cp20 FLOAT DEFAULT 0, cp21 FLOAT DEFAULT 0, "
" cp22 FLOAT DEFAULT 0, cp23 FLOAT DEFAULT 0, cp24 FLOAT DEFAULT 0, "
" cp25 FLOAT DEFAULT 0, "
" GameID VARCHAR(64), "
" DDNet7 BOOL DEFAULT FALSE, "
" PRIMARY KEY (Map, Name, Time, Timestamp, Server)"
");",
GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate());
}
void IDbConnection::FormatCreateTeamrace(char *aBuf, unsigned int BufferSize, const char *pIdType)
{
str_format(aBuf, BufferSize,
"CREATE TABLE IF NOT EXISTS %s_teamrace ("
"Map VARCHAR(128) COLLATE %s NOT NULL, "
"Name VARCHAR(%d) COLLATE %s NOT NULL, "
"Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"Time FLOAT DEFAULT 0, "
"ID %s NOT NULL, " // VARBINARY(16) for MySQL and BLOB for SQLite
"GameID VARCHAR(64), "
"DDNet7 BOOL DEFAULT FALSE, "
"PRIMARY KEY (ID, Name)"
");",
GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate(), pIdType);
"CREATE TABLE IF NOT EXISTS %s_teamrace ("
" Map VARCHAR(128) COLLATE %s NOT NULL, "
" Name VARCHAR(%d) COLLATE %s NOT NULL, "
" Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
" Time FLOAT DEFAULT 0, "
" ID %s NOT NULL, " // VARBINARY(16) for MySQL and BLOB for SQLite
" GameID VARCHAR(64), "
" DDNet7 BOOL DEFAULT FALSE, "
" PRIMARY KEY (ID, Name)"
");",
GetPrefix(), BinaryCollate(), MAX_NAME_LENGTH, BinaryCollate(), pIdType);
}
void IDbConnection::FormatCreateMaps(char *aBuf, unsigned int BufferSize)
{
str_format(aBuf, BufferSize,
"CREATE TABLE IF NOT EXISTS %s_maps ("
"Map VARCHAR(128) COLLATE %s NOT NULL, "
"Server VARCHAR(32) COLLATE %s NOT NULL, "
"Mapper VARCHAR(128) COLLATE %s NOT NULL, "
"Points INT DEFAULT 0, "
"Stars INT DEFAULT 0, "
"Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
"PRIMARY KEY (Map)"
");",
GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate());
"CREATE TABLE IF NOT EXISTS %s_maps ("
" Map VARCHAR(128) COLLATE %s NOT NULL, "
" Server VARCHAR(32) COLLATE %s NOT NULL, "
" Mapper VARCHAR(128) COLLATE %s NOT NULL, "
" Points INT DEFAULT 0, "
" Stars INT DEFAULT 0, "
" Timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, "
" PRIMARY KEY (Map)"
");",
GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate());
}
void IDbConnection::FormatCreateSaves(char *aBuf, unsigned int BufferSize)
{
str_format(aBuf, BufferSize,
"CREATE TABLE IF NOT EXISTS %s_saves ("
"Savegame TEXT COLLATE %s NOT NULL, "
"Map VARCHAR(128) COLLATE %s NOT NULL, "
"Code VARCHAR(128) COLLATE %s NOT NULL, "
"Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
"Server CHAR(4), "
"DDNet7 BOOL DEFAULT FALSE, "
"SaveID VARCHAR(36) DEFAULT NULL, "
"PRIMARY KEY (Map, Code)"
");",
GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate());
"CREATE TABLE IF NOT EXISTS %s_saves ("
" Savegame TEXT COLLATE %s NOT NULL, "
" Map VARCHAR(128) COLLATE %s NOT NULL, "
" Code VARCHAR(128) COLLATE %s NOT NULL, "
" Timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, "
" Server CHAR(4), "
" DDNet7 BOOL DEFAULT FALSE, "
" SaveID VARCHAR(36) DEFAULT NULL, "
" PRIMARY KEY (Map, Code)"
");",
GetPrefix(), BinaryCollate(), BinaryCollate(), BinaryCollate());
}
void IDbConnection::FormatCreatePoints(char *aBuf, unsigned int BufferSize)
{
str_format(aBuf, BufferSize,
"CREATE TABLE IF NOT EXISTS %s_points ("
"Name VARCHAR(%d) COLLATE %s NOT NULL, "
"Points INT DEFAULT 0, "
"PRIMARY KEY (Name)"
");",
GetPrefix(), MAX_NAME_LENGTH, BinaryCollate());
"CREATE TABLE IF NOT EXISTS %s_points ("
" Name VARCHAR(%d) COLLATE %s NOT NULL, "
" Points INT DEFAULT 0, "
" PRIMARY KEY (Name)"
");",
GetPrefix(), MAX_NAME_LENGTH, BinaryCollate());
}

View file

@ -14,7 +14,7 @@ public:
str_copy(m_aPrefix, pPrefix, sizeof(m_aPrefix));
}
virtual ~IDbConnection() {}
IDbConnection& operator=(const IDbConnection&) = delete;
IDbConnection &operator=(const IDbConnection &) = delete;
virtual void Print(IConsole *pConsole, const char *Mode) = 0;
// copies the credentials, not the active connection

View file

@ -11,13 +11,13 @@
struct CSqlExecData
{
CSqlExecData(
CDbConnectionPool::FRead pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName);
CDbConnectionPool::FRead pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName);
CSqlExecData(
CDbConnectionPool::FWrite pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName);
CDbConnectionPool::FWrite pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName);
~CSqlExecData() {}
enum
@ -39,9 +39,9 @@ CSqlExecData::CSqlExecData(
CDbConnectionPool::FRead pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName) :
m_Mode(READ_ACCESS),
m_pThreadData(std::move(pThreadData)),
m_pName(pName)
m_Mode(READ_ACCESS),
m_pThreadData(std::move(pThreadData)),
m_pName(pName)
{
m_Ptr.m_pReadFunc = pFunc;
}
@ -50,9 +50,9 @@ CSqlExecData::CSqlExecData(
CDbConnectionPool::FWrite pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName) :
m_Mode(WRITE_ACCESS),
m_pThreadData(std::move(pThreadData)),
m_pName(pName)
m_Mode(WRITE_ACCESS),
m_pThreadData(std::move(pThreadData)),
m_pName(pName)
{
m_Ptr.m_pWriteFunc = pFunc;
}
@ -86,9 +86,9 @@ void CDbConnectionPool::RegisterDatabase(std::unique_ptr<IDbConnection> pDatabas
}
void CDbConnectionPool::Execute(
FRead pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName)
FRead pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName)
{
m_aTasks[FirstElem++].reset(new CSqlExecData(pFunc, std::move(pThreadData), pName));
FirstElem %= sizeof(m_aTasks) / sizeof(m_aTasks[0]);
@ -96,9 +96,9 @@ void CDbConnectionPool::Execute(
}
void CDbConnectionPool::ExecuteWrite(
FWrite pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName)
FWrite pFunc,
std::unique_ptr<const ISqlData> pThreadData,
const char *pName)
{
m_aTasks[FirstElem++].reset(new CSqlExecData(pFunc, std::move(pThreadData), pName));
FirstElem %= sizeof(m_aTasks) / sizeof(m_aTasks[0]);
@ -112,13 +112,14 @@ void CDbConnectionPool::OnShutdown()
int i = 0;
while(m_Shutdown.load())
{
if (i > 600) {
if(i > 600)
{
dbg_msg("sql", "Waited 60 seconds for score-threads to complete, quitting anyway");
break;
}
// print a log about every two seconds
if (i % 20 == 0)
if(i % 20 == 0)
dbg_msg("sql", "Waiting for score-threads to complete (%ds)", i / 10);
++i;
thread_sleep(100000);
@ -163,7 +164,8 @@ void CDbConnectionPool::Worker()
break;
}
}
} break;
}
break;
case CSqlExecData::WRITE_ACCESS:
{
for(int i = 0; i < (int)m_aapDbConnections[Mode::WRITE].size(); i++)
@ -189,7 +191,8 @@ void CDbConnectionPool::Worker()
}
}
}
} break;
}
break;
}
if(!Success)
dbg_msg("sql", "%s failed on all databases", pThreadData->m_pName);
@ -216,16 +219,16 @@ bool CDbConnectionPool::ExecSqlFunc(IDbConnection *pConnection, CSqlExecData *pD
}
}
#if defined(CONF_SQL)
catch (sql::SQLException &e)
catch(sql::SQLException &e)
{
dbg_msg("sql", "%s MySQL Error: %s", pData->m_pName, e.what());
}
#endif
catch (std::runtime_error &e)
catch(std::runtime_error &e)
{
dbg_msg("sql", "%s SQLite Error: %s", pData->m_pName, e.what());
}
catch (...)
catch(...)
{
dbg_msg("sql", "%s Unexpected exception caught", pData->m_pName);
}
@ -234,16 +237,16 @@ bool CDbConnectionPool::ExecSqlFunc(IDbConnection *pConnection, CSqlExecData *pD
pConnection->Unlock();
}
#if defined(CONF_SQL)
catch (sql::SQLException &e)
catch(sql::SQLException &e)
{
dbg_msg("sql", "%s MySQL Error during unlock: %s", pData->m_pName, e.what());
}
#endif
catch (std::runtime_error &e)
catch(std::runtime_error &e)
{
dbg_msg("sql", "%s SQLite Error during unlock: %s", pData->m_pName, e.what());
}
catch (...)
catch(...)
{
dbg_msg("sql", "%s Unexpected exception caught during unlock", pData->m_pName);
}
@ -252,4 +255,3 @@ bool CDbConnectionPool::ExecSqlFunc(IDbConnection *pConnection, CSqlExecData *pD
dbg_msg("sql", "%s failed", pData->m_pName);
return Success;
}

View file

@ -1,8 +1,8 @@
#ifndef ENGINE_SERVER_DATABASES_CONNECTION_POOL_H
#define ENGINE_SERVER_DATABASES_CONNECTION_POOL_H
#include <base/tl/threading.h>
#include <atomic>
#include <base/tl/threading.h>
#include <memory>
#include <vector>
@ -10,7 +10,7 @@ class IDbConnection;
struct ISqlData
{
virtual ~ISqlData() {};
virtual ~ISqlData(){};
};
class IConsole;
@ -20,7 +20,7 @@ class CDbConnectionPool
public:
CDbConnectionPool();
~CDbConnectionPool();
CDbConnectionPool& operator=(const CDbConnectionPool&) = delete;
CDbConnectionPool &operator=(const CDbConnectionPool &) = delete;
typedef bool (*FRead)(IDbConnection *, const ISqlData *);
typedef bool (*FWrite)(IDbConnection *, const ISqlData *, bool);
@ -38,14 +38,14 @@ public:
void RegisterDatabase(std::unique_ptr<IDbConnection> pDatabase, Mode DatabaseMode);
void Execute(
FRead pFunc,
std::unique_ptr<const ISqlData> pSqlRequestData,
const char *pName);
FRead pFunc,
std::unique_ptr<const ISqlData> pSqlRequestData,
const char *pName);
// writes to WRITE_BACKUP server in case of failure
void ExecuteWrite(
FWrite pFunc,
std::unique_ptr<const ISqlData> pSqlRequestData,
const char *pName);
FWrite pFunc,
std::unique_ptr<const ISqlData> pSqlRequestData,
const char *pName);
void OnShutdown();

View file

@ -14,13 +14,13 @@
lock CMysqlConnection::m_SqlDriverLock;
CMysqlConnection::CMysqlConnection(
const char *pDatabase,
const char *pPrefix,
const char *pUser,
const char *pPass,
const char *pIp,
int Port,
bool Setup) :
const char *pDatabase,
const char *pPrefix,
const char *pUser,
const char *pPass,
const char *pIp,
int Port,
bool Setup) :
IDbConnection(pPrefix),
#if defined(CONF_SQL)
m_NewQuery(false),
@ -52,8 +52,8 @@ void CMysqlConnection::Print(IConsole *pConsole, const char *Mode)
{
char aBuf[512];
str_format(aBuf, sizeof(aBuf),
"MySQL-%s: DB: '%s' Prefix: '%s' User: '%s' IP: <{'%s'}> Port: %d",
Mode, m_aDatabase, GetPrefix(), m_aUser, m_aIp, m_Port);
"MySQL-%s: DB: '%s' Prefix: '%s' User: '%s' IP: <{'%s'}> Port: %d",
Mode, m_aDatabase, GetPrefix(), m_aUser, m_aIp, m_Port);
pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
}
@ -82,19 +82,19 @@ IDbConnection::Status CMysqlConnection::Connect()
m_pConnection->setSchema(m_aDatabase);
return Status::SUCCESS;
}
catch (sql::SQLException &e)
catch(sql::SQLException &e)
{
dbg_msg("sql", "MySQL Error: %s", e.what());
}
catch (const std::exception& ex)
catch(const std::exception &ex)
{
dbg_msg("sql", "MySQL Error: %s", ex.what());
}
catch (const std::string& ex)
catch(const std::string &ex)
{
dbg_msg("sql", "MySQL Error: %s", ex.c_str());
}
catch (...)
catch(...)
{
dbg_msg("sql", "Unknown Error cause by the MySQL/C++ Connector");
}
@ -109,10 +109,10 @@ IDbConnection::Status CMysqlConnection::Connect()
m_pResults.release();
sql::ConnectOptionsMap connection_properties;
connection_properties["hostName"] = sql::SQLString(m_aIp);
connection_properties["port"] = m_Port;
connection_properties["userName"] = sql::SQLString(m_aUser);
connection_properties["password"] = sql::SQLString(m_aPass);
connection_properties["hostName"] = sql::SQLString(m_aIp);
connection_properties["port"] = m_Port;
connection_properties["userName"] = sql::SQLString(m_aUser);
connection_properties["password"] = sql::SQLString(m_aPass);
connection_properties["OPT_CONNECT_TIMEOUT"] = 60;
connection_properties["OPT_READ_TIMEOUT"] = 60;
connection_properties["OPT_WRITE_TIMEOUT"] = 120;
@ -161,19 +161,19 @@ IDbConnection::Status CMysqlConnection::Connect()
dbg_msg("sql", "sql connection established");
return Status::SUCCESS;
}
catch (sql::SQLException &e)
catch(sql::SQLException &e)
{
dbg_msg("sql", "MySQL Error: %s", e.what());
}
catch (const std::exception& ex)
catch(const std::exception &ex)
{
dbg_msg("sql", "MySQL Error: %s", ex.what());
}
catch (const std::string& ex)
catch(const std::string &ex)
{
dbg_msg("sql", "MySQL Error: %s", ex.c_str());
}
catch (...)
catch(...)
{
dbg_msg("sql", "Unknown Error cause by the MySQL/C++ Connector");
}
@ -230,7 +230,7 @@ void CMysqlConnection::BindBlob(int Idx, unsigned char *pBlob, int Size)
{
#if defined(CONF_SQL)
// copy blob into string
auto Blob = std::string(pBlob, pBlob+Size);
auto Blob = std::string(pBlob, pBlob + Size);
m_pPreparedStmt->setString(Idx, Blob);
m_NewQuery = true;
#endif
@ -316,10 +316,10 @@ void CMysqlConnection::AddPoints(const char *pPlayer, int Points)
{
char aBuf[512];
str_format(aBuf, sizeof(aBuf),
"INSERT INTO %s_points(Name, Points) "
"VALUES (?, ?) "
"ON DUPLICATE KEY UPDATE Points=Points+?;",
GetPrefix());
"INSERT INTO %s_points(Name, Points) "
"VALUES (?, ?) "
"ON DUPLICATE KEY UPDATE Points=Points+?;",
GetPrefix());
PrepareStatement(aBuf);
BindString(1, pPlayer);
BindInt(2, Points);

View file

@ -1,8 +1,8 @@
#ifndef ENGINE_SERVER_DATABASES_MYSQL_H
#define ENGINE_SERVER_DATABASES_MYSQL_H
#include <engine/server/databases/connection.h>
#include <atomic>
#include <engine/server/databases/connection.h>
#include <memory>
class lock;
@ -17,13 +17,13 @@ class CMysqlConnection : public IDbConnection
{
public:
CMysqlConnection(
const char *pDatabase,
const char *pPrefix,
const char *pUser,
const char *pPass,
const char *pIp,
int Port,
bool Setup);
const char *pDatabase,
const char *pPrefix,
const char *pUser,
const char *pPass,
const char *pIp,
int Port,
bool Setup);
virtual ~CMysqlConnection();
virtual void Print(IConsole *pConsole, const char *Mode);

View file

@ -3,8 +3,8 @@
#include <base/math.h>
#include <engine/console.h>
#include <stdexcept>
#include <sqlite3.h>
#include <stdexcept>
CSqliteConnection::CSqliteConnection(const char *pFilename, bool Setup) :
IDbConnection("record"),
@ -30,8 +30,8 @@ void CSqliteConnection::Print(IConsole *pConsole, const char *Mode)
{
char aBuf[512];
str_format(aBuf, sizeof(aBuf),
"SQLite-%s: DB: '%s'",
Mode, m_aFilename);
"SQLite-%s: DB: '%s'",
Mode, m_aFilename);
pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
}
@ -117,11 +117,11 @@ void CSqliteConnection::PrepareStatement(const char *pStmt)
sqlite3_finalize(m_pStmt);
m_pStmt = nullptr;
int Result = sqlite3_prepare_v2(
m_pDb,
pStmt,
-1, // pStmt can be any length
&m_pStmt,
NULL);
m_pDb,
pStmt,
-1, // pStmt can be any length
&m_pStmt,
NULL);
ExceptionOnError(Result);
m_Done = false;
}
@ -238,10 +238,10 @@ void CSqliteConnection::AddPoints(const char *pPlayer, int Points)
{
char aBuf[512];
str_format(aBuf, sizeof(aBuf),
"INSERT INTO %s_points(Name, Points) "
"VALUES (?, ?) "
"ON CONFLICT(Name) UPDATE SET Points=Points+?;",
GetPrefix());
"INSERT INTO %s_points(Name, Points) "
"VALUES (?, ?) "
"ON CONFLICT(Name) UPDATE SET Points=Points+?;",
GetPrefix());
PrepareStatement(aBuf);
BindString(1, pPlayer);
BindInt(2, Points);

View file

@ -6,8 +6,8 @@
enum
{
MAX_NAME_SKELETON_LENGTH=MAX_NAME_LENGTH*4,
MAX_NAMEBAN_REASON_LENGTH=64
MAX_NAME_SKELETON_LENGTH = MAX_NAME_LENGTH * 4,
MAX_NAMEBAN_REASON_LENGTH = 64
};
class CNameBan

View file

@ -1,10 +1,10 @@
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <base/system.h>
#include <engine/shared/network.h>
#include <engine/shared/config.h>
#include <engine/console.h>
#include <engine/masterserver.h>
#include <engine/shared/config.h>
#include <engine/shared/network.h>
#include <mastersrv/mastersrv.h>
@ -82,7 +82,7 @@ void CRegister::RegisterSendHeartbeat(NETADDR Addr, SECURITY_TOKEN ResponseToken
if(g_Config.m_SvExternalPort)
Port = g_Config.m_SvExternalPort;
aData[sizeof(SERVERBROWSE_HEARTBEAT)] = Port >> 8;
aData[sizeof(SERVERBROWSE_HEARTBEAT)+1] = Port&0xff;
aData[sizeof(SERVERBROWSE_HEARTBEAT) + 1] = Port & 0xff;
if(m_Sixup)
m_pNetServer->SendConnlessSixup(&Packet, ResponseToken);
else
@ -106,7 +106,7 @@ void CRegister::RegisterSendCountRequest(NETADDR Addr, SECURITY_TOKEN ResponseTo
void CRegister::RegisterGotCount(CNetChunk *pChunk)
{
unsigned char *pData = (unsigned char *)pChunk->m_pData;
int Count = (pData[sizeof(SERVERBROWSE_COUNT)]<<8) | pData[sizeof(SERVERBROWSE_COUNT)+1];
int Count = (pData[sizeof(SERVERBROWSE_COUNT)] << 8) | pData[sizeof(SERVERBROWSE_COUNT) + 1];
for(int i = 0; i < IMasterServer::MAX_MASTERSERVERS; i++)
{
@ -135,7 +135,7 @@ void CRegister::RegisterUpdate(int Nettype)
m_pMasterServer->Update();
if(m_Sixup && (m_RegisterState == REGISTERSTATE_HEARTBEAT || m_RegisterState == REGISTERSTATE_REGISTERED) && Now > m_LastTokenRequest+Freq*5)
if(m_Sixup && (m_RegisterState == REGISTERSTATE_HEARTBEAT || m_RegisterState == REGISTERSTATE_REGISTERED) && Now > m_LastTokenRequest + Freq * 5)
{
m_pNetServer->SendTokenSixup(m_aMasterserverInfo[m_RegisterRegisteredServer].m_Addr, NET_SECURITY_TOKEN_UNKNOWN);
m_LastTokenRequest = Now;
@ -191,7 +191,7 @@ void CRegister::RegisterUpdate(int Nettype)
if(m_aMasterserverInfo[i].m_Count == -1)
{
Left++;
if(m_aMasterserverInfo[i].m_LastSend+Freq < Now)
if(m_aMasterserverInfo[i].m_LastSend + Freq < Now)
{
m_aMasterserverInfo[i].m_LastSend = Now;
if(m_Sixup && m_aMasterserverInfo[i].m_Token == NET_SECURITY_TOKEN_UNKNOWN)
@ -203,7 +203,7 @@ void CRegister::RegisterUpdate(int Nettype)
}
// check if we are done or timed out
if(Left == 0 || Now > m_RegisterStateStart+Freq*5)
if(Left == 0 || Now > m_RegisterStateStart + Freq * 5)
{
// choose server
int Best = -1;
@ -237,13 +237,13 @@ void CRegister::RegisterUpdate(int Nettype)
else if(m_RegisterState == REGISTERSTATE_HEARTBEAT)
{
// check if we should send heartbeat
if(Now > m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend+Freq*15)
if(Now > m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend + Freq * 15)
{
m_aMasterserverInfo[m_RegisterRegisteredServer].m_LastSend = Now;
RegisterSendHeartbeat(m_aMasterserverInfo[m_RegisterRegisteredServer].m_Addr, m_aMasterserverInfo[m_RegisterRegisteredServer].m_Token);
}
if(Now > m_RegisterStateStart+Freq*60)
if(Now > m_RegisterStateStart + Freq * 60)
{
m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, m_pName, "WARNING: Master server is not responding, switching master");
RegisterNewState(REGISTERSTATE_START);
@ -257,7 +257,7 @@ void CRegister::RegisterUpdate(int Nettype)
m_RegisterFirst = 0;
// check if we should send new heartbeat again
if(Now > m_RegisterStateStart+Freq)
if(Now > m_RegisterStateStart + Freq)
{
if(m_RegisterCount == 120) // redo the whole process after 60 minutes to balance out the master servers
RegisterNewState(REGISTERSTATE_START);
@ -271,7 +271,7 @@ void CRegister::RegisterUpdate(int Nettype)
else if(m_RegisterState == REGISTERSTATE_ERROR)
{
// check for restart
if(Now > m_RegisterStateStart+Freq*60)
if(Now > m_RegisterStateStart + Freq * 60)
RegisterNewState(REGISTERSTATE_START);
}
}
@ -317,7 +317,7 @@ int CRegister::RegisterProcessPacket(CNetChunk *pPacket, SECURITY_TOKEN Response
//RegisterNewState(REGISTERSTATE_ERROR);
return 1;
}
else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_COUNT)+2 &&
else if(pPacket->m_DataSize == sizeof(SERVERBROWSE_COUNT) + 2 &&
mem_comp(pPacket->m_pData, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT)) == 0)
{
RegisterGotCount(pPacket);

View file

@ -4,12 +4,13 @@
#define ENGINE_SERVER_REGISTER_H
#include <engine/masterserver.h>
#include <engine/shared/network.h>
class CRegister
{
enum
{
REGISTERSTATE_START=0,
REGISTERSTATE_START = 0,
REGISTERSTATE_UPDATE_ADDRS,
REGISTERSTATE_QUERY_COUNT,
REGISTERSTATE_HEARTBEAT,

File diff suppressed because it is too large Load diff

View file

@ -10,15 +10,15 @@
#include <engine/server.h>
#include <engine/map.h>
#include <engine/shared/demo.h>
#include <engine/shared/protocol.h>
#include <engine/shared/snapshot.h>
#include <engine/shared/network.h>
#include <engine/server/register.h>
#include <engine/shared/console.h>
#include <engine/shared/demo.h>
#include <engine/shared/econ.h>
#include <engine/shared/fifo.h>
#include <engine/shared/netban.h>
#include <engine/shared/network.h>
#include <engine/shared/protocol.h>
#include <engine/shared/snapshot.h>
#include <engine/shared/uuid_manager.h>
#include <base/tl/array.h>
@ -29,15 +29,15 @@
#include "authmanager.h"
#include "name_ban.h"
#if defined (CONF_UPNP)
#include "upnp.h"
#if defined(CONF_UPNP)
#include "upnp.h"
#endif
class CSnapIDPool
{
enum
{
MAX_IDS = 16*1024,
MAX_IDS = 16 * 1024,
};
class CID
@ -57,7 +57,6 @@ class CSnapIDPool
int m_InUsage;
public:
CSnapIDPool();
void Reset();
@ -67,12 +66,12 @@ public:
void FreeID(int ID);
};
class CServerBan : public CNetBan
{
class CServer *m_pServer;
template<class T> int BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason);
template<class T>
int BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason);
public:
class CServer *Server() const { return m_pServer; }
@ -87,7 +86,6 @@ public:
static void ConBanRegionRange(class IConsole::IResult *pResult, void *pUser);
};
class CServer : public IServer
{
class IGameServer *m_pGameServer;
@ -116,13 +114,12 @@ public:
enum
{
MAX_RCONCMD_SEND=16,
MAX_RCONCMD_SEND = 16,
};
class CClient
{
public:
enum
{
STATE_EMPTY = 0,
@ -132,11 +129,11 @@ public:
STATE_READY,
STATE_INGAME,
SNAPRATE_INIT=0,
SNAPRATE_INIT = 0,
SNAPRATE_FULL,
SNAPRATE_RECOVER,
DNSBL_STATE_NONE=0,
DNSBL_STATE_NONE = 0,
DNSBL_STATE_PENDING,
DNSBL_STATE_BLACKLISTED,
DNSBL_STATE_WHITELISTED,
@ -217,9 +214,9 @@ public:
enum
{
UNINITIALIZED=0,
RUNNING=1,
STOPPING=2
UNINITIALIZED = 0,
RUNNING = 1,
STOPPING = 2
};
int m_RunServer;
@ -235,7 +232,7 @@ public:
enum
{
SIX=0,
SIX = 0,
SIXUP,
};
@ -245,7 +242,7 @@ public:
unsigned char *m_apCurrentMapData[2];
unsigned int m_aCurrentMapSize[2];
CDemoRecorder m_aDemoRecorder[MAX_CLIENTS+1];
CDemoRecorder m_aDemoRecorder[MAX_CLIENTS + 1];
CRegister m_Register;
CRegister m_RegSixup;
CAuthManager m_AuthManager;
@ -322,9 +319,11 @@ public:
void ProcessClientPacket(CNetChunk *pPacket);
class CCache {
class CCache
{
public:
class CCacheChunk {
class CCacheChunk
{
public:
CCacheChunk(const void *pData, int Size);
CCacheChunk(const CCacheChunk &) = delete;
@ -412,7 +411,6 @@ public:
void RegisterCommands();
virtual int SnapNewID();
virtual void SnapFreeID(int ID);
virtual void *SnapNewItem(int Type, int ID, int Size);
@ -426,13 +424,13 @@ public:
unsigned m_AnnouncementLastLine;
void RestrictRconOutput(int ClientID) { m_RconRestrict = ClientID; }
virtual int* GetIdMap(int ClientID);
virtual int *GetIdMap(int ClientID);
void InitDnsbl(int ClientID);
bool DnsblWhite(int ClientID)
{
return m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_NONE ||
m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_WHITELISTED;
m_aClients[ClientID].m_DnsblState == CClient::DNSBL_STATE_WHITELISTED;
}
bool DnsblPending(int ClientID)
{
@ -460,13 +458,12 @@ public:
#ifdef CONF_FAMILY_UNIX
enum CONN_LOGGING_CMD
{
OPEN_SESSION=1,
CLOSE_SESSION=2,
OPEN_SESSION = 1,
CLOSE_SESSION = 2,
};
void SendConnLoggingCommand(CONN_LOGGING_CMD cmd, const NETADDR *pAddr);
#endif
};
#endif

View file

@ -6,7 +6,7 @@
void sqlstr::FuzzyString(char *pString, int size)
{
char * newString = new char [size * 4 - 1];
char *newString = new char[size * 4 - 1];
int pos = 0;
for(int i = 0; i < size; i++)
@ -15,13 +15,13 @@ void sqlstr::FuzzyString(char *pString, int size)
break;
newString[pos++] = pString[i];
if (pString[i] != '\\' && str_utf8_isstart(pString[i+1]))
if(pString[i] != '\\' && str_utf8_isstart(pString[i + 1]))
newString[pos++] = '%';
}
newString[pos] = '\0';
str_copy(pString, newString, size);
delete [] newString;
delete[] newString;
}
int sqlstr::EscapeLike(char *pDst, const char *pSrc, int DstSize)
@ -35,7 +35,6 @@ int sqlstr::EscapeLike(char *pDst, const char *pSrc, int DstSize)
if(pSrc[Pos] == '\\' || pSrc[Pos] == '%' || pSrc[Pos] == '_' || pSrc[Pos] == '[')
pDst[DstPos++] = '\\';
pDst[DstPos++] = pSrc[Pos++];
}
pDst[DstPos++] = '\0';
return DstPos;
@ -45,25 +44,23 @@ void sqlstr::AgoTimeToString(int AgoTime, char *pAgoString)
{
char aBuf[20];
int aTimes[7] =
{
60 * 60 * 24 * 365 ,
60 * 60 * 24 * 30 ,
{
60 * 60 * 24 * 365,
60 * 60 * 24 * 30,
60 * 60 * 24 * 7,
60 * 60 * 24 ,
60 * 60 ,
60 ,
1
};
60 * 60 * 24,
60 * 60,
60,
1};
char aaNames[7][6] =
{
{
"year",
"month",
"week",
"day",
"hour",
"min",
"sec"
};
"sec"};
int Seconds = 0;
char aName[6];
@ -76,7 +73,7 @@ void sqlstr::AgoTimeToString(int AgoTime, char *pAgoString)
Seconds = aTimes[i];
strcpy(aName, aaNames[i]);
Count = floor((float)AgoTime/(float)Seconds);
Count = floor((float)AgoTime / (float)Seconds);
if(Count != 0)
{
break;
@ -85,33 +82,33 @@ void sqlstr::AgoTimeToString(int AgoTime, char *pAgoString)
if(Count == 1)
{
str_format(aBuf, sizeof(aBuf), "%d %s", 1 , aName);
str_format(aBuf, sizeof(aBuf), "%d %s", 1, aName);
}
else
{
str_format(aBuf, sizeof(aBuf), "%d %ss", Count , aName);
str_format(aBuf, sizeof(aBuf), "%d %ss", Count, aName);
}
strcat(pAgoString, aBuf);
if (i + 1 < 7)
if(i + 1 < 7)
{
// getting second piece now
int Seconds2 = aTimes[i+1];
int Seconds2 = aTimes[i + 1];
char aName2[6];
strcpy(aName2, aaNames[i+1]);
strcpy(aName2, aaNames[i + 1]);
// add second piece if it's greater than 0
int Count2 = floor((float)(AgoTime - (Seconds * Count)) / (float)Seconds2);
if (Count2 != 0)
if(Count2 != 0)
{
if(Count2 == 1)
{
str_format(aBuf, sizeof(aBuf), " and %d %s", 1 , aName2);
str_format(aBuf, sizeof(aBuf), " and %d %s", 1, aName2);
}
else
{
str_format(aBuf, sizeof(aBuf), " and %d %ss", Count2 , aName2);
str_format(aBuf, sizeof(aBuf), " and %d %ss", Count2, aName2);
}
strcat(pAgoString, aBuf);
}

View file

@ -1,8 +1,7 @@
#ifndef ENGINE_SERVER_SQL_STRING_HELPERS_H
#define ENGINE_SERVER_SQL_STRING_HELPERS_H
namespace sqlstr
{
namespace sqlstr {
void FuzzyString(char *pString, int size);
@ -11,6 +10,6 @@ int EscapeLike(char *pDst, const char *pSrc, int DstSize);
void AgoTimeToString(int agoTime, char *pAgoString);
}
} // namespace sqlstr
#endif

View file

@ -1,12 +1,12 @@
#ifdef CONF_UPNP
#include "upnp.h"
#include <base/system.h>
#include <engine/shared/config.h>
#include <game/version.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#include <engine/shared/config.h>
#include <base/system.h>
#include <game/version.h>
#include "upnp.h"
void CUPnP::Open(NETADDR Address)
{
@ -31,10 +31,10 @@ void CUPnP::Open(NETADDR Address)
m_Enabled = true;
dbg_msg("upnp", "found valid IGD: %s", m_UPnPUrls->controlURL);
str_format(aPort, sizeof(aPort), "%d", m_Addr.port);
Error = UPNP_AddPortMapping(m_UPnPUrls->controlURL, m_UPnPData->first.servicetype,
aPort, aPort, aLanAddr,
"DDNet Server " GAME_RELEASE_VERSION,
"UDP", NULL, "0");
Error = UPNP_AddPortMapping(m_UPnPUrls->controlURL, m_UPnPData->first.servicetype,
aPort, aPort, aLanAddr,
"DDNet Server " GAME_RELEASE_VERSION,
"UDP", NULL, "0");
if(Error)
dbg_msg("upnp", "failed to map port, error: %s", strupnperror(Error));
@ -68,7 +68,6 @@ void CUPnP::Shutdown()
m_UPnPUrls = NULL;
m_UPnPData = NULL;
}
}
#endif

View file

@ -12,7 +12,7 @@ class CUPnP
public:
void Open(NETADDR Address);
void Shutdown();
void Shutdown();
};
#endif

View file

@ -81,7 +81,6 @@ class IServerBrowser : public IInterface
{
MACRO_INTERFACE("serverbrowser", 0)
public:
/* Constants: Server Browser Sorting
SORT_NAME - Sort by name.
SORT_PING - Sort by ping.
@ -89,16 +88,17 @@ public:
SORT_GAMETYPE - Sort by game type. DM, TDM etc.
SORT_NUMPLAYERS - Sort after how many players there are on the server.
*/
enum{
enum
{
SORT_NAME = 0,
SORT_PING,
SORT_MAP,
SORT_GAMETYPE,
SORT_NUMPLAYERS,
QUICK_SERVERNAME=1,
QUICK_PLAYER=2,
QUICK_MAPNAME=4,
QUICK_SERVERNAME = 1,
QUICK_PLAYER = 2,
QUICK_MAPNAME = 4,
TYPE_NONE = 0,
TYPE_INTERNET = 1,
@ -107,14 +107,14 @@ public:
TYPE_DDNET = 4,
TYPE_KOG = 5,
SET_MASTER_ADD=1,
SET_MASTER_ADD = 1,
SET_FAV_ADD,
SET_DDNET_ADD,
SET_KOG_ADD,
SET_TOKEN,
NETWORK_DDNET=0,
NETWORK_KOG=1,
NETWORK_DDNET = 0,
NETWORK_KOG = 1,
NUM_NETWORKS,
};

View file

@ -7,10 +7,10 @@
// Format: ESDDDDDD EDDDDDDD EDD... Extended, Data, Sign
unsigned char *CVariableInt::Pack(unsigned char *pDst, int i)
{
*pDst = (i>>25)&0x40; // set sign bit if i<0
i = i^(i>>31); // if(i<0) i = ~i
*pDst = (i >> 25) & 0x40; // set sign bit if i<0
i = i ^ (i >> 31); // if(i<0) i = ~i
*pDst |= i&0x3F; // pack 6bit into dst
*pDst |= i & 0x3F; // pack 6bit into dst
i >>= 6; // discard 6 bits
if(i)
{
@ -18,9 +18,9 @@ unsigned char *CVariableInt::Pack(unsigned char *pDst, int i)
while(1)
{
pDst++;
*pDst = i&(0x7F); // pack 7bit
*pDst = i & (0x7F); // pack 7bit
i >>= 7; // discard 7 bits
*pDst |= (i!=0)<<7; // set extend bit (may branch)
*pDst |= (i != 0) << 7; // set extend bit (may branch)
if(!i)
break;
}
@ -32,26 +32,30 @@ unsigned char *CVariableInt::Pack(unsigned char *pDst, int i)
const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut)
{
int Sign = (*pSrc>>6)&1;
*pInOut = *pSrc&0x3F;
int Sign = (*pSrc >> 6) & 1;
*pInOut = *pSrc & 0x3F;
do
{
if(!(*pSrc&0x80)) break;
if(!(*pSrc & 0x80))
break;
pSrc++;
*pInOut |= (*pSrc&(0x7F))<<(6);
*pInOut |= (*pSrc & (0x7F)) << (6);
if(!(*pSrc&0x80)) break;
if(!(*pSrc & 0x80))
break;
pSrc++;
*pInOut |= (*pSrc&(0x7F))<<(6+7);
*pInOut |= (*pSrc & (0x7F)) << (6 + 7);
if(!(*pSrc&0x80)) break;
if(!(*pSrc & 0x80))
break;
pSrc++;
*pInOut |= (*pSrc&(0x7F))<<(6+7+7);
*pInOut |= (*pSrc & (0x7F)) << (6 + 7 + 7);
if(!(*pSrc&0x80)) break;
if(!(*pSrc & 0x80))
break;
pSrc++;
*pInOut |= (*pSrc&(0x7F))<<(6+7+7+7);
*pInOut |= (*pSrc & (0x7F)) << (6 + 7 + 7 + 7);
} while(0);
pSrc++;
@ -59,7 +63,6 @@ const unsigned char *CVariableInt::Unpack(const unsigned char *pSrc, int *pInOut
return pSrc;
}
long CVariableInt::Decompress(const void *pSrc_, int Size, void *pDst_, int DstSize)
{
const unsigned char *pSrc = (unsigned char *)pSrc_;
@ -73,7 +76,7 @@ long CVariableInt::Decompress(const void *pSrc_, int Size, void *pDst_, int DstS
pSrc = CVariableInt::Unpack(pSrc, pDst);
pDst++;
}
return (unsigned char *)pDst-(unsigned char *)pDst_;
return (unsigned char *)pDst - (unsigned char *)pDst_;
}
long CVariableInt::Compress(const void *pSrc_, int Size, void *pDst_, int DstSize)
@ -90,5 +93,5 @@ long CVariableInt::Compress(const void *pSrc_, int Size, void *pDst_, int DstSiz
Size--;
pSrc++;
}
return pDst-(unsigned char *)pDst_;
return pDst - (unsigned char *)pDst_;
}

View file

@ -1,9 +1,9 @@
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <engine/config.h>
#include <engine/storage.h>
#include <engine/shared/config.h>
#include <engine/shared/protocol.h>
#include <engine/storage.h>
CConfiguration g_Config;
@ -33,7 +33,6 @@ class CConfig : public IConfig
}
public:
CConfig()
{
m_ConfigFile = 0;
@ -49,15 +48,15 @@ public:
virtual void Reset()
{
#define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) g_Config.m_##Name = def;
#define MACRO_CONFIG_COL(Name,ScriptName,def,flags,desc) MACRO_CONFIG_INT(Name,ScriptName,def,0,0,flags,desc)
#define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) str_copy(g_Config.m_##Name, def, len);
#define MACRO_CONFIG_INT(Name, ScriptName, def, min, max, flags, desc) g_Config.m_##Name = def;
#define MACRO_CONFIG_COL(Name, ScriptName, def, flags, desc) MACRO_CONFIG_INT(Name, ScriptName, def, 0, 0, flags, desc)
#define MACRO_CONFIG_STR(Name, ScriptName, len, def, flags, desc) str_copy(g_Config.m_##Name, def, len);
#include "config_variables.h"
#include "config_variables.h"
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
}
virtual void Save()
@ -75,18 +74,34 @@ public:
m_Failed = false;
char aLineBuf[1024*2];
char aEscapeBuf[1024*2];
char aLineBuf[1024 * 2];
char aEscapeBuf[1024 * 2];
#define MACRO_CONFIG_INT(Name,ScriptName,def,min,max,flags,desc) if((flags)&CFGFLAG_SAVE && g_Config.m_##Name != def) { str_format(aLineBuf, sizeof(aLineBuf), "%s %i", #ScriptName, g_Config.m_##Name); WriteLine(aLineBuf); }
#define MACRO_CONFIG_COL(Name,ScriptName,def,flags,desc) if((flags)&CFGFLAG_SAVE && g_Config.m_##Name != def) { str_format(aLineBuf, sizeof(aLineBuf), "%s %u", #ScriptName, g_Config.m_##Name); WriteLine(aLineBuf); }
#define MACRO_CONFIG_STR(Name,ScriptName,len,def,flags,desc) if((flags)&CFGFLAG_SAVE && str_comp(g_Config.m_##Name, def) != 0) { EscapeParam(aEscapeBuf, g_Config.m_##Name, sizeof(aEscapeBuf)); str_format(aLineBuf, sizeof(aLineBuf), "%s \"%s\"", #ScriptName, aEscapeBuf); WriteLine(aLineBuf); }
#define MACRO_CONFIG_INT(Name, ScriptName, def, min, max, flags, desc) \
if((flags)&CFGFLAG_SAVE && g_Config.m_##Name != def) \
{ \
str_format(aLineBuf, sizeof(aLineBuf), "%s %i", #ScriptName, g_Config.m_##Name); \
WriteLine(aLineBuf); \
}
#define MACRO_CONFIG_COL(Name, ScriptName, def, flags, desc) \
if((flags)&CFGFLAG_SAVE && g_Config.m_##Name != def) \
{ \
str_format(aLineBuf, sizeof(aLineBuf), "%s %u", #ScriptName, g_Config.m_##Name); \
WriteLine(aLineBuf); \
}
#define MACRO_CONFIG_STR(Name, ScriptName, len, def, flags, desc) \
if((flags)&CFGFLAG_SAVE && str_comp(g_Config.m_##Name, def) != 0) \
{ \
EscapeParam(aEscapeBuf, g_Config.m_##Name, sizeof(aEscapeBuf)); \
str_format(aLineBuf, sizeof(aLineBuf), "%s \"%s\"", #ScriptName, aEscapeBuf); \
WriteLine(aLineBuf); \
}
#include "config_variables.h"
#include "config_variables.h"
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
for(int i = 0; i < m_NumCallbacks; i++)
m_aCallbacks[i].m_pfnFunc(this, m_aCallbacks[i].m_pUserData);

View file

@ -10,33 +10,33 @@
struct CConfiguration
{
#define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Save,Desc) int m_##Name;
#define MACRO_CONFIG_COL(Name,ScriptName,Def,Save,Desc) unsigned m_##Name;
#define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Save,Desc) char m_##Name[Len]; // Flawfinder: ignore
#include "config_variables.h"
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
#define MACRO_CONFIG_INT(Name, ScriptName, Def, Min, Max, Save, Desc) int m_##Name;
#define MACRO_CONFIG_COL(Name, ScriptName, Def, Save, Desc) unsigned m_##Name;
#define MACRO_CONFIG_STR(Name, ScriptName, Len, Def, Save, Desc) char m_##Name[Len]; // Flawfinder: ignore
#include "config_variables.h"
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
};
extern CConfiguration g_Config;
enum
{
CFGFLAG_SAVE=1<<0,
CFGFLAG_CLIENT=1<<1,
CFGFLAG_SERVER=1<<2,
CFGFLAG_STORE=1<<3,
CFGFLAG_MASTER=1<<4,
CFGFLAG_ECON=1<<5,
CFGFLAG_SAVE = 1 << 0,
CFGFLAG_CLIENT = 1 << 1,
CFGFLAG_SERVER = 1 << 2,
CFGFLAG_STORE = 1 << 3,
CFGFLAG_MASTER = 1 << 4,
CFGFLAG_ECON = 1 << 5,
// DDRace
CMDFLAG_TEST=1<<6,
CFGFLAG_CHAT=1<<7,
CFGFLAG_GAME=1<<8,
CFGFLAG_NONTEEHISTORIC=1<<9,
CFGFLAG_COLLIGHT=1<<10,
CFGFLAG_COLALPHA=1<<11,
CMDFLAG_TEST = 1 << 6,
CFGFLAG_CHAT = 1 << 7,
CFGFLAG_GAME = 1 << 8,
CFGFLAG_NONTEEHISTORIC = 1 << 9,
CFGFLAG_COLLIGHT = 1 << 10,
CFGFLAG_COLALPHA = 1 << 11,
};
#endif

View file

@ -2,13 +2,13 @@
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <new>
#include <base/math.h>
#include <base/vmath.h>
#include <base/color.h>
#include <base/math.h>
#include <base/system.h>
#include <base/vmath.h>
#include <engine/storage.h>
#include <engine/shared/protocol.h>
#include <engine/storage.h>
#include "config.h"
#include "console.h"
@ -18,21 +18,21 @@
const char *CConsole::CResult::GetString(unsigned Index)
{
if (Index >= m_NumArgs)
if(Index >= m_NumArgs)
return "";
return m_apArgs[Index];
}
int CConsole::CResult::GetInteger(unsigned Index)
{
if (Index >= m_NumArgs)
if(Index >= m_NumArgs)
return 0;
return str_toint(m_apArgs[Index]);
}
float CConsole::CResult::GetFloat(unsigned Index)
{
if (Index >= m_NumArgs)
if(Index >= m_NumArgs)
return 0.0f;
return str_tofloat(m_apArgs[Index]);
}
@ -44,7 +44,7 @@ ColorHSLA CConsole::CResult::GetColor(unsigned Index, bool Light)
return hsl;
const char *pStr = m_apArgs[Index];
if(str_isallnum(pStr) || ((pStr[0] == '-' || pStr[0] == '+') && str_isallnum(pStr+1))) // Teeworlds Color (Packed HSL)
if(str_isallnum(pStr) || ((pStr[0] == '-' || pStr[0] == '+') && str_isallnum(pStr + 1))) // Teeworlds Color (Packed HSL)
{
hsl = ColorHSLA(str_toulong_base(pStr, 10), true);
if(Light)
@ -76,17 +76,17 @@ ColorHSLA CConsole::CResult::GetColor(unsigned Index, bool Light)
hsl = color_cast<ColorHSLA>(rgb);
}
else if(!str_comp_nocase(pStr, "red"))
hsl = ColorHSLA(0.0f/6.0f, 1, .5f);
hsl = ColorHSLA(0.0f / 6.0f, 1, .5f);
else if(!str_comp_nocase(pStr, "yellow"))
hsl = ColorHSLA(1.0f/6.0f, 1, .5f);
hsl = ColorHSLA(1.0f / 6.0f, 1, .5f);
else if(!str_comp_nocase(pStr, "green"))
hsl = ColorHSLA(2.0f/6.0f, 1, .5f);
hsl = ColorHSLA(2.0f / 6.0f, 1, .5f);
else if(!str_comp_nocase(pStr, "cyan"))
hsl = ColorHSLA(3.0f/6.0f, 1, .5f);
hsl = ColorHSLA(3.0f / 6.0f, 1, .5f);
else if(!str_comp_nocase(pStr, "blue"))
hsl = ColorHSLA(4.0f/6.0f, 1, .5f);
hsl = ColorHSLA(4.0f / 6.0f, 1, .5f);
else if(!str_comp_nocase(pStr, "magenta"))
hsl = ColorHSLA(5.0f/6.0f, 1, .5f);
hsl = ColorHSLA(5.0f / 6.0f, 1, .5f);
else if(!str_comp_nocase(pStr, "white"))
hsl = ColorHSLA(0, 0, 1);
else if(!str_comp_nocase(pStr, "gray"))
@ -102,7 +102,7 @@ const IConsole::CCommandInfo *CConsole::CCommand::NextCommandInfo(int AccessLeve
const CCommand *pInfo = m_pNext;
while(pInfo)
{
if(pInfo->m_Flags&FlagMask && pInfo->m_AccessLevel >= AccessLevel)
if(pInfo->m_Flags & FlagMask && pInfo->m_AccessLevel >= AccessLevel)
break;
pInfo = pInfo->m_pNext;
}
@ -113,7 +113,7 @@ const IConsole::CCommandInfo *CConsole::FirstCommandInfo(int AccessLevel, int Fl
{
for(const CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)
{
if(pCommand->m_Flags&FlagMask && pCommand->GetAccessLevel() >= AccessLevel)
if(pCommand->m_Flags & FlagMask && pCommand->GetAccessLevel() >= AccessLevel)
return pCommand;
}
@ -122,7 +122,6 @@ const IConsole::CCommandInfo *CConsole::FirstCommandInfo(int AccessLevel, int Fl
// the maximum number of tokens occurs in a string of length CONSOLE_MAX_STR_LENGTH with tokens size 1 separated by single spaces
int CConsole::ParseStart(CResult *pResult, const char *pString, int Length)
{
char *pStr;
@ -220,7 +219,6 @@ int CConsole::ParseArgs(CResult *pResult, const char *pFormat)
// write null termination
*pDst = 0;
pStr++;
}
else
@ -265,16 +263,16 @@ int CConsole::ParseArgs(CResult *pResult, const char *pFormat)
char CConsole::NextParam(const char *&pFormat)
{
if (*pFormat)
if(*pFormat)
{
pFormat++;
if (*pFormat == '[')
if(*pFormat == '[')
{
// skip bracket contents
for (; *pFormat != ']'; pFormat++)
for(; *pFormat != ']'; pFormat++)
{
if (!*pFormat)
if(!*pFormat)
return *pFormat;
}
@ -282,7 +280,7 @@ char CConsole::NextParam(const char *&pFormat)
pFormat++;
// skip space if there is one
if (*pFormat == ' ')
if(*pFormat == ' ')
pFormat++;
}
}
@ -317,7 +315,7 @@ char *CConsole::Format(char *pBuf, int Size, const char *pFrom, const char *pStr
void CConsole::Print(int Level, const char *pFrom, const char *pStr, bool Highlighted)
{
dbg_msg(pFrom ,"%s", pStr);
dbg_msg(pFrom, "%s", pStr);
char aBuf[1024];
Format(aBuf, sizeof(aBuf), pFrom, pStr);
for(int i = 0; i < m_NumPrintCB; ++i)
@ -360,7 +358,7 @@ bool CConsole::LineIsValid(const char *pStr)
{
if(*pEnd == ';') // command separator
{
pNextPart = pEnd+1;
pNextPart = pEnd + 1;
break;
}
else if(*pEnd == '#') // comment, no need to do anything more
@ -370,7 +368,7 @@ bool CConsole::LineIsValid(const char *pStr)
pEnd++;
}
if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0)
if(ParseStart(&Result, pStr, (pEnd - pStr) + 1) != 0)
return false;
CCommand *pCommand = FindCommand(Result.m_pCommand, m_FlagMask);
@ -378,8 +376,7 @@ bool CConsole::LineIsValid(const char *pStr)
return false;
pStr = pNextPart;
}
while(pStr && *pStr);
} while(pStr && *pStr);
return true;
}
@ -413,7 +410,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo
{
if(*pEnd == ';') // command separator
{
pNextPart = pEnd+1;
pNextPart = pEnd + 1;
break;
}
else if(*pEnd == '#') // comment, no need to do anything more
@ -423,7 +420,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo
pEnd++;
}
if(ParseStart(&Result, pStr, (pEnd-pStr) + 1) != 0)
if(ParseStart(&Result, pStr, (pEnd - pStr) + 1) != 0)
return;
if(!*Result.m_pCommand)
@ -433,8 +430,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo
if(pCommand)
{
if(ClientID == IConsole::CLIENT_ID_GAME
&& !(pCommand->m_Flags & CFGFLAG_GAME))
if(ClientID == IConsole::CLIENT_ID_GAME && !(pCommand->m_Flags & CFGFLAG_GAME))
{
if(Stroke)
{
@ -443,8 +439,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo
Print(OUTPUT_LEVEL_STANDARD, "console", aBuf);
}
}
else if(ClientID == IConsole::CLIENT_ID_NO_GAME
&& pCommand->m_Flags & CFGFLAG_GAME)
else if(ClientID == IConsole::CLIENT_ID_NO_GAME && pCommand->m_Flags & CFGFLAG_GAME)
{
if(Stroke)
{
@ -473,7 +468,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo
str_format(aBuf, sizeof(aBuf), "Invalid arguments... Usage: %s %s", pCommand->m_pName, pCommand->m_pParams);
Print(OUTPUT_LEVEL_STANDARD, "console", aBuf);
}
else if(m_StoreCommands && pCommand->m_Flags&CFGFLAG_STORE)
else if(m_StoreCommands && pCommand->m_Flags & CFGFLAG_STORE)
{
m_ExecutionQueue.AddEntry();
m_ExecutionQueue.m_pLast->m_pfnCommandCallback = pCommand->m_pfnCallback;
@ -482,10 +477,10 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo
}
else
{
if(pCommand->m_Flags&CMDFLAG_TEST && !g_Config.m_SvTestingCommands)
if(pCommand->m_Flags & CMDFLAG_TEST && !g_Config.m_SvTestingCommands)
return;
if(m_pfnTeeHistorianCommandCallback && !(pCommand->m_Flags&CFGFLAG_NONTEEHISTORIC))
if(m_pfnTeeHistorianCommandCallback && !(pCommand->m_Flags & CFGFLAG_NONTEEHISTORIC))
{
m_pfnTeeHistorianCommandCallback(ClientID, m_FlagMask, pCommand->m_pName, &Result, m_pTeeHistorianCommandUserdata);
}
@ -495,7 +490,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo
if(Result.HasVictim() && Result.GetVictim() == CResult::VICTIM_ALL)
{
for (int i = 0; i < MAX_CLIENTS; i++)
for(int i = 0; i < MAX_CLIENTS; i++)
{
Result.SetVictim(i);
pCommand->m_pfnCallback(&Result, pCommand->m_pUserData);
@ -506,7 +501,7 @@ void CConsole::ExecuteLineStroked(int Stroke, const char *pStr, int ClientID, bo
pCommand->m_pfnCallback(&Result, pCommand->m_pUserData);
}
if (pCommand->m_Flags&CMDFLAG_TEST)
if(pCommand->m_Flags & CMDFLAG_TEST)
m_Cheated = true;
}
}
@ -533,7 +528,7 @@ void CConsole::PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPoss
{
for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)
{
if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp)
if(pCommand->m_Flags & FlagMask && pCommand->m_Temp == Temp)
{
if(str_find_nocase(pCommand->m_pName, pStr))
pfnCallback(pCommand->m_pName, pUser);
@ -545,7 +540,7 @@ CConsole::CCommand *CConsole::FindCommand(const char *pName, int FlagMask)
{
for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)
{
if(pCommand->m_Flags&FlagMask)
if(pCommand->m_Flags & FlagMask)
{
if(str_comp_nocase(pCommand->m_pName, pName) == 0)
return pCommand;
@ -569,7 +564,6 @@ void CConsole::ExecuteLineFlag(const char *pStr, int FlagMask, int ClientID, boo
m_FlagMask = Temp;
}
void CConsole::ExecuteFile(const char *pFilename, int ClientID, bool LogFailure, int StorageType)
{
// make sure that this isn't being executed already
@ -618,12 +612,12 @@ void CConsole::ExecuteFile(const char *pFilename, int ClientID, bool LogFailure,
void CConsole::Con_Echo(IResult *pResult, void *pUserData)
{
((CConsole*)pUserData)->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", pResult->GetString(0));
((CConsole *)pUserData)->Print(IConsole::OUTPUT_LEVEL_STANDARD, "console", pResult->GetString(0));
}
void CConsole::Con_Exec(IResult *pResult, void *pUserData)
{
((CConsole*)pUserData)->ExecuteFile(pResult->GetString(0), -1, true, IStorage::TYPE_ALL);
((CConsole *)pUserData)->ExecuteFile(pResult->GetString(0), -1, true, IStorage::TYPE_ALL);
}
void CConsole::ConCommandAccess(IResult *pResult, void *pUser)
@ -666,7 +660,7 @@ void CConsole::ConCommandStatus(IResult *pResult, void *pUser)
for(CCommand *pCommand = pConsole->m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)
{
if(pCommand->m_Flags&pConsole->m_FlagMask && pCommand->GetAccessLevel() >= clamp(pResult->GetInteger(0), (int)ACCESS_LEVEL_ADMIN, (int)ACCESS_LEVEL_USER))
if(pCommand->m_Flags & pConsole->m_FlagMask && pCommand->GetAccessLevel() >= clamp(pResult->GetInteger(0), (int)ACCESS_LEVEL_ADMIN, (int)ACCESS_LEVEL_USER))
{
int Length = str_length(pCommand->m_pName);
if(Used + Length + 2 < (int)(sizeof(aBuf)))
@ -741,9 +735,9 @@ static void IntVariableCommand(IConsole::IResult *pResult, void *pUserData)
// do clamping
if(pData->m_Min != pData->m_Max)
{
if (Val < pData->m_Min)
if(Val < pData->m_Min)
Val = pData->m_Min;
if (pData->m_Max != 0 && Val > pData->m_Max)
if(pData->m_Max != 0 && Val > pData->m_Max)
Val = pData->m_Max;
}
@ -796,8 +790,6 @@ static void ColVariableCommand(IConsole::IResult *pResult, void *pUserData)
}
}
static void StrVariableCommand(IConsole::IResult *pResult, void *pUserData)
{
CStrVariableData *pData = (CStrVariableData *)pUserData;
@ -812,9 +804,9 @@ static void StrVariableCommand(IConsole::IResult *pResult, void *pUserData)
while(*pString)
{
int Size = str_utf8_encode(aTemp, static_cast<unsigned char>(*pString++));
if(Length+Size < pData->m_MaxSize)
if(Length + Size < pData->m_MaxSize)
{
mem_copy(pData->m_pStr+Length, aTemp, Size);
mem_copy(pData->m_pStr + Length, aTemp, Size);
Length += Size;
}
else
@ -857,7 +849,7 @@ void CConsole::ConToggle(IConsole::IResult *pResult, void *pUser)
if(pfnCallback == IntVariableCommand)
{
CIntVariableData *pData = static_cast<CIntVariableData *>(pUserData);
int Val = *(pData->m_pVariable)==pResult->GetInteger(1) ? pResult->GetInteger(2) : pResult->GetInteger(1);
int Val = *(pData->m_pVariable) == pResult->GetInteger(1) ? pResult->GetInteger(2) : pResult->GetInteger(1);
str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(0), Val);
pConsole->ExecuteLine(aBuf);
aBuf[0] = 0;
@ -914,7 +906,7 @@ void CConsole::ConToggleStroke(IConsole::IResult *pResult, void *pUser)
if(pfnCallback == IntVariableCommand)
{
int Val = pResult->GetInteger(0)==0 ? pResult->GetInteger(3) : pResult->GetInteger(2);
int Val = pResult->GetInteger(0) == 0 ? pResult->GetInteger(3) : pResult->GetInteger(2);
str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(1), Val);
pConsole->ExecuteLine(aBuf);
aBuf[0] = 0;
@ -950,41 +942,41 @@ CConsole::CConsole(int FlagMask)
// register some basic commands
Register("echo", "r[text]", CFGFLAG_SERVER, Con_Echo, this, "Echo the text");
Register("exec", "r[file]", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file");
Register("exec", "r[file]", CFGFLAG_SERVER | CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file");
Register("toggle", "s[config-option] i[value 1] i[value 2]", CFGFLAG_SERVER|CFGFLAG_CLIENT, ConToggle, this, "Toggle config value");
Register("toggle", "s[config-option] i[value 1] i[value 2]", CFGFLAG_SERVER | CFGFLAG_CLIENT, ConToggle, this, "Toggle config value");
Register("+toggle", "s[config-option] i[value 1] i[value 2]", CFGFLAG_CLIENT, ConToggleStroke, this, "Toggle config value via keypress");
Register("access_level", "s[command] ?i[accesslevel]", CFGFLAG_SERVER, ConCommandAccess, this, "Specify command accessibility (admin = 0, moderator = 1, helper = 2, all = 3)");
Register("access_status", "i[accesslevel]", CFGFLAG_SERVER, ConCommandStatus, this, "List all commands which are accessible for admin = 0, moderator = 1, helper = 2, all = 3");
Register("cmdlist", "", CFGFLAG_SERVER|CFGFLAG_CHAT, ConUserCommandStatus, this, "List all commands which are accessible for users");
Register("cmdlist", "", CFGFLAG_SERVER | CFGFLAG_CHAT, ConUserCommandStatus, this, "List all commands which are accessible for users");
// TODO: this should disappear
#define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \
// TODO: this should disappear
#define MACRO_CONFIG_INT(Name, ScriptName, Def, Min, Max, Flags, Desc) \
{ \
static CIntVariableData Data = { this, &g_Config.m_##Name, Min, Max, Def }; \
static CIntVariableData Data = {this, &g_Config.m_##Name, Min, Max, Def}; \
Register(#ScriptName, "?i", Flags, IntVariableCommand, &Data, Desc); \
}
#define MACRO_CONFIG_COL(Name,ScriptName,Def,Flags,Desc) \
#define MACRO_CONFIG_COL(Name, ScriptName, Def, Flags, Desc) \
{ \
static CColVariableData Data = { this, &g_Config.m_##Name, static_cast<bool>((Flags) & CFGFLAG_COLLIGHT), \
static_cast<bool>((Flags) & CFGFLAG_COLALPHA), Def}; \
static CColVariableData Data = {this, &g_Config.m_##Name, static_cast<bool>((Flags)&CFGFLAG_COLLIGHT), \
static_cast<bool>((Flags)&CFGFLAG_COLALPHA), Def}; \
Register(#ScriptName, "?i", Flags, ColVariableCommand, &Data, Desc); \
}
#define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \
#define MACRO_CONFIG_STR(Name, ScriptName, Len, Def, Flags, Desc) \
{ \
static char OldValue[Len] = Def; \
static CStrVariableData Data = { this, g_Config.m_##Name, Len, OldValue }; \
static CStrVariableData Data = {this, g_Config.m_##Name, Len, OldValue}; \
Register(#ScriptName, "?r", Flags, StrVariableCommand, &Data, Desc); \
}
#include "config_variables.h"
#include "config_variables.h"
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
// DDRace
@ -1014,7 +1006,7 @@ void CConsole::ParseArguments(int NumArgs, const char **ppArguments)
if(ppArguments[i][0] == '-' && ppArguments[i][1] == 'f' && ppArguments[i][2] == 0)
{
if(NumArgs - i > 1)
ExecuteFile(ppArguments[i+1], -1, true, IStorage::TYPE_ABSOLUTE);
ExecuteFile(ppArguments[i + 1], -1, true, IStorage::TYPE_ABSOLUTE);
i++;
}
else if(!str_comp("-s", ppArguments[i]) || !str_comp("--silent", ppArguments[i]))
@ -1077,11 +1069,11 @@ void CConsole::Register(const char *pName, const char *pParams,
if(DoAdd)
AddCommandSorted(pCommand);
if(pCommand->m_Flags&CFGFLAG_CHAT)
if(pCommand->m_Flags & CFGFLAG_CHAT)
pCommand->SetAccessLevel(ACCESS_LEVEL_USER);
}
void CConsole::RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp)
void CConsole::RegisterTemp(const char *pName, const char *pParams, int Flags, const char *pHelp)
{
CCommand *pCommand;
if(m_pRecycleList)
@ -1150,7 +1142,8 @@ void CConsole::DeregisterTemp(const char *pName)
void CConsole::DeregisterTempAll()
{
// set non temp as first one
for(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->m_pNext);
for(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->m_pNext)
;
// remove temp entries from command list
for(CCommand *pCommand = m_pFirstCommand; pCommand && pCommand->m_pNext; pCommand = pCommand->m_pNext)
@ -1158,7 +1151,8 @@ void CConsole::DeregisterTempAll()
CCommand *pNext = pCommand->m_pNext;
if(pNext->m_Temp)
{
for(; pNext && pNext->m_Temp; pNext = pNext->m_pNext);
for(; pNext && pNext->m_Temp; pNext = pNext->m_pNext)
;
pCommand->m_pNext = pNext;
}
}
@ -1209,12 +1203,11 @@ void CConsole::StoreCommands(bool Store)
m_StoreCommands = Store;
}
const IConsole::CCommandInfo *CConsole::GetCommandInfo(const char *pName, int FlagMask, bool Temp)
{
for(CCommand *pCommand = m_pFirstCommand; pCommand; pCommand = pCommand->m_pNext)
{
if(pCommand->m_Flags&FlagMask && pCommand->m_Temp == Temp)
if(pCommand->m_Flags & FlagMask && pCommand->m_Temp == Temp)
{
if(str_comp_nocase(pCommand->m_pName, pName) == 0)
return pCommand;
@ -1224,14 +1217,13 @@ const IConsole::CCommandInfo *CConsole::GetCommandInfo(const char *pName, int Fl
return 0;
}
extern IConsole *CreateConsole(int FlagMask) { return new CConsole(FlagMask); }
void CConsole::ResetServerGameSettings()
{
#define MACRO_CONFIG_INT(Name,ScriptName,Def,Min,Max,Flags,Desc) \
#define MACRO_CONFIG_INT(Name, ScriptName, Def, Min, Max, Flags, Desc) \
{ \
if(((Flags) & (CFGFLAG_SERVER|CFGFLAG_GAME)) == (CFGFLAG_SERVER|CFGFLAG_GAME)) \
if(((Flags) & (CFGFLAG_SERVER | CFGFLAG_GAME)) == (CFGFLAG_SERVER | CFGFLAG_GAME)) \
{ \
CCommand *pCommand = FindCommand(#ScriptName, CFGFLAG_SERVER); \
void *pUserData = pCommand->m_pUserData; \
@ -1247,11 +1239,11 @@ void CConsole::ResetServerGameSettings()
} \
}
#define MACRO_CONFIG_COL(Name,ScriptName,Def,Save,Desc) MACRO_CONFIG_INT(Name,ScriptName,Def,0,0,Save,Desc)
#define MACRO_CONFIG_COL(Name, ScriptName, Def, Save, Desc) MACRO_CONFIG_INT(Name, ScriptName, Def, 0, 0, Save, Desc)
#define MACRO_CONFIG_STR(Name,ScriptName,Len,Def,Flags,Desc) \
#define MACRO_CONFIG_STR(Name, ScriptName, Len, Def, Flags, Desc) \
{ \
if(((Flags) & (CFGFLAG_SERVER|CFGFLAG_GAME)) == (CFGFLAG_SERVER|CFGFLAG_GAME)) \
if(((Flags) & (CFGFLAG_SERVER | CFGFLAG_GAME)) == (CFGFLAG_SERVER | CFGFLAG_GAME)) \
{ \
CCommand *pCommand = FindCommand(#ScriptName, CFGFLAG_SERVER); \
void *pUserData = pCommand->m_pUserData; \
@ -1267,11 +1259,11 @@ void CConsole::ResetServerGameSettings()
} \
}
#include "config_variables.h"
#include "config_variables.h"
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
#undef MACRO_CONFIG_INT
#undef MACRO_CONFIG_COL
#undef MACRO_CONFIG_STR
}
int CConsole::CResult::GetVictim()

View file

@ -3,10 +3,10 @@
#ifndef ENGINE_SHARED_CONSOLE_H
#define ENGINE_SHARED_CONSOLE_H
#include "memheap.h"
#include <base/math.h>
#include <engine/console.h>
#include <engine/storage.h>
#include <base/math.h>
#include "memheap.h"
class CConsole : public IConsole
{
@ -24,7 +24,6 @@ class CConsole : public IConsole
void SetAccessLevel(int AccessLevel) { m_AccessLevel = clamp(AccessLevel, (int)(ACCESS_LEVEL_ADMIN), (int)(ACCESS_LEVEL_USER)); }
};
class CChain
{
public:
@ -77,19 +76,20 @@ class CConsole : public IConsole
enum
{
CONSOLE_MAX_STR_LENGTH = 8192,
MAX_PARTS = (CONSOLE_MAX_STR_LENGTH+1)/2
MAX_PARTS = (CONSOLE_MAX_STR_LENGTH + 1) / 2
};
class CResult : public IResult
{
public:
char m_aStringStorage[CONSOLE_MAX_STR_LENGTH+1];
char m_aStringStorage[CONSOLE_MAX_STR_LENGTH + 1];
char *m_pArgsStart;
const char *m_pCommand;
const char *m_apArgs[MAX_PARTS];
CResult() : IResult()
CResult() :
IResult()
{
mem_zero(m_aStringStorage, sizeof(m_aStringStorage));
m_pArgsStart = 0;
@ -97,16 +97,16 @@ class CConsole : public IConsole
mem_zero(m_apArgs, sizeof(m_apArgs));
}
CResult &operator =(const CResult &Other)
CResult &operator=(const CResult &Other)
{
if(this != &Other)
{
IResult::operator=(Other);
mem_copy(m_aStringStorage, Other.m_aStringStorage, sizeof(m_aStringStorage));
m_pArgsStart = m_aStringStorage+(Other.m_pArgsStart-Other.m_aStringStorage);
m_pCommand = m_aStringStorage+(Other.m_pCommand-Other.m_aStringStorage);
m_pArgsStart = m_aStringStorage + (Other.m_pArgsStart - Other.m_aStringStorage);
m_pCommand = m_aStringStorage + (Other.m_pCommand - Other.m_aStringStorage);
for(unsigned i = 0; i < Other.m_NumArgs; ++i)
m_apArgs[i] = m_aStringStorage+(Other.m_apArgs[i]-Other.m_aStringStorage);
m_apArgs[i] = m_aStringStorage + (Other.m_apArgs[i] - Other.m_aStringStorage);
}
return *this;
}
@ -134,9 +134,9 @@ class CConsole : public IConsole
enum
{
VICTIM_NONE=-3,
VICTIM_ME=-2,
VICTIM_ALL=-1,
VICTIM_NONE = -3,
VICTIM_ME = -2,
VICTIM_ALL = -1,
};
int m_Victim;
@ -169,7 +169,7 @@ class CConsole : public IConsole
FCommandCallback m_pfnCommandCallback;
void *m_pCommandUserData;
CResult m_Result;
} *m_pFirst, *m_pLast;
} * m_pFirst, *m_pLast;
void AddEntry()
{

View file

@ -3,8 +3,8 @@
#include "datafile.h"
#include <base/math.h>
#include <base/hash_ctxt.h>
#include <base/math.h>
#include <base/system.h>
#include <engine/storage.h>
@ -12,12 +12,12 @@
#include <zlib.h>
static const int DEBUG=0;
static const int DEBUG = 0;
enum
{
OFFSET_UUID_TYPE=0x8000,
ITEMTYPE_EX=0xffff,
OFFSET_UUID_TYPE = 0x8000,
ITEMTYPE_EX = 0xffff,
};
struct CItemEx
@ -57,13 +57,12 @@ static int GetTypeFromIndex(int Index)
return ITEMTYPE_EX - Index - 1;
}
struct CDatafileItemType
{
int m_Type;
int m_Start;
int m_Num;
} ;
};
struct CDatafileItem
{
@ -128,14 +127,13 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int
return false;
}
// take the CRC of the file and store it
unsigned Crc = 0;
SHA256_DIGEST Sha256;
{
enum
{
BUFFER_SIZE = 64*1024
BUFFER_SIZE = 64 * 1024
};
SHA256_CTX Sha256Ctxt;
@ -155,10 +153,9 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int
io_seek(File, 0, IOSEEK_START);
}
// TODO: change this header
CDatafileHeader Header;
if (sizeof(Header) != io_read(File, &Header, sizeof(Header)))
if(sizeof(Header) != io_read(File, &Header, sizeof(Header)))
{
dbg_msg("datafile", "couldn't load header");
return 0;
@ -173,7 +170,7 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int
}
#if defined(CONF_ARCH_ENDIAN_BIG)
swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int));
swap_endian(&Header, sizeof(int), sizeof(Header) / sizeof(int));
#endif
if(Header.m_Version != 3 && Header.m_Version != 4)
{
@ -183,27 +180,27 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int
// read in the rest except the data
unsigned Size = 0;
Size += Header.m_NumItemTypes*sizeof(CDatafileItemType);
Size += (Header.m_NumItems+Header.m_NumRawData)*sizeof(int);
Size += Header.m_NumItemTypes * sizeof(CDatafileItemType);
Size += (Header.m_NumItems + Header.m_NumRawData) * sizeof(int);
if(Header.m_Version == 4)
Size += Header.m_NumRawData*sizeof(int); // v4 has uncompressed data sizes as well
Size += Header.m_NumRawData * sizeof(int); // v4 has uncompressed data sizes as well
Size += Header.m_ItemSize;
unsigned AllocSize = Size;
AllocSize += sizeof(CDatafile); // add space for info structure
AllocSize += Header.m_NumRawData*sizeof(void*); // add space for data pointers
AllocSize += Header.m_NumRawData * sizeof(void *); // add space for data pointers
CDatafile *pTmpDataFile = (CDatafile *)malloc(AllocSize);
pTmpDataFile->m_Header = Header;
pTmpDataFile->m_DataStartOffset = sizeof(CDatafileHeader) + Size;
pTmpDataFile->m_ppDataPtrs = (char **)(pTmpDataFile+1);
pTmpDataFile->m_pData = (char *)(pTmpDataFile+1)+Header.m_NumRawData*sizeof(char *);
pTmpDataFile->m_ppDataPtrs = (char **)(pTmpDataFile + 1);
pTmpDataFile->m_pData = (char *)(pTmpDataFile + 1) + Header.m_NumRawData * sizeof(char *);
pTmpDataFile->m_File = File;
pTmpDataFile->m_Sha256 = Sha256;
pTmpDataFile->m_Crc = Crc;
// clear the data pointers
mem_zero(pTmpDataFile->m_ppDataPtrs, Header.m_NumRawData*sizeof(void*));
mem_zero(pTmpDataFile->m_ppDataPtrs, Header.m_NumRawData * sizeof(void *));
// read types, offsets, sizes and item data
unsigned ReadSize = io_read(File, pTmpDataFile->m_pData, Size);
@ -285,24 +282,33 @@ bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename, int
int CDataFileReader::NumData()
{
if(!m_pDataFile) { return 0; }
if(!m_pDataFile)
{
return 0;
}
return m_pDataFile->m_Header.m_NumRawData;
}
// returns the size in the file
int CDataFileReader::GetFileDataSize(int Index)
{
if(!m_pDataFile) { return 0; }
if(!m_pDataFile)
{
return 0;
}
if(Index == m_pDataFile->m_Header.m_NumRawData-1)
return m_pDataFile->m_Header.m_DataSize-m_pDataFile->m_Info.m_pDataOffsets[Index];
return m_pDataFile->m_Info.m_pDataOffsets[Index+1]-m_pDataFile->m_Info.m_pDataOffsets[Index];
if(Index == m_pDataFile->m_Header.m_NumRawData - 1)
return m_pDataFile->m_Header.m_DataSize - m_pDataFile->m_Info.m_pDataOffsets[Index];
return m_pDataFile->m_Info.m_pDataOffsets[Index + 1] - m_pDataFile->m_Info.m_pDataOffsets[Index];
}
// returns the size of the resulting data
int CDataFileReader::GetDataSize(int Index)
{
if(!m_pDataFile) { return 0; }
if(!m_pDataFile)
{
return 0;
}
if(m_pDataFile->m_Header.m_Version == 4)
return m_pDataFile->m_Info.m_pDataSizes[Index];
@ -312,7 +318,10 @@ int CDataFileReader::GetDataSize(int Index)
void *CDataFileReader::GetDataImpl(int Index, int Swap)
{
if(!m_pDataFile) { return 0; }
if(!m_pDataFile)
{
return 0;
}
if(Index < 0 || Index >= m_pDataFile->m_Header.m_NumRawData)
return 0;
@ -337,12 +346,12 @@ void *CDataFileReader::GetDataImpl(int Index, int Swap)
m_pDataFile->m_ppDataPtrs[Index] = (char *)malloc(UncompressedSize);
// read the compressed data
io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START);
io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset + m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START);
io_read(m_pDataFile->m_File, pTemp, DataSize);
// decompress the data, TODO: check for errors
s = UncompressedSize;
uncompress((Bytef*)m_pDataFile->m_ppDataPtrs[Index], &s, (Bytef*)pTemp, DataSize); // ignore_convention
uncompress((Bytef *)m_pDataFile->m_ppDataPtrs[Index], &s, (Bytef *)pTemp, DataSize); // ignore_convention
#if defined(CONF_ARCH_ENDIAN_BIG)
SwapSize = s;
#endif
@ -355,13 +364,13 @@ void *CDataFileReader::GetDataImpl(int Index, int Swap)
// load the data
dbg_msg("datafile", "loading data index=%d size=%d", Index, DataSize);
m_pDataFile->m_ppDataPtrs[Index] = (char *)malloc(DataSize);
io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START);
io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset + m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START);
io_read(m_pDataFile->m_File, m_pDataFile->m_ppDataPtrs[Index], DataSize);
}
#if defined(CONF_ARCH_ENDIAN_BIG)
if(Swap && SwapSize)
swap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize/sizeof(int));
swap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize / sizeof(int));
#endif
}
@ -392,9 +401,9 @@ int CDataFileReader::GetItemSize(int Index)
{
if(!m_pDataFile)
return 0;
if(Index == m_pDataFile->m_Header.m_NumItems-1)
return m_pDataFile->m_Header.m_ItemSize-m_pDataFile->m_Info.m_pItemOffsets[Index] - sizeof(CDatafileItem);
return m_pDataFile->m_Info.m_pItemOffsets[Index+1]-m_pDataFile->m_Info.m_pItemOffsets[Index] - sizeof(CDatafileItem);
if(Index == m_pDataFile->m_Header.m_NumItems - 1)
return m_pDataFile->m_Header.m_ItemSize - m_pDataFile->m_Info.m_pItemOffsets[Index] - sizeof(CDatafileItem);
return m_pDataFile->m_Info.m_pItemOffsets[Index + 1] - m_pDataFile->m_Info.m_pItemOffsets[Index] - sizeof(CDatafileItem);
}
int CDataFileReader::GetExternalItemType(int InternalType)
@ -439,19 +448,26 @@ int CDataFileReader::GetInternalItemType(int ExternalType)
void *CDataFileReader::GetItem(int Index, int *pType, int *pID)
{
if(!m_pDataFile) { if(pType) *pType = 0; if(pID) *pID = 0; return 0; }
if(!m_pDataFile)
{
if(pType)
*pType = 0;
if(pID)
*pID = 0;
return 0;
}
CDatafileItem *i = (CDatafileItem *)(m_pDataFile->m_Info.m_pItemStart+m_pDataFile->m_Info.m_pItemOffsets[Index]);
CDatafileItem *i = (CDatafileItem *)(m_pDataFile->m_Info.m_pItemStart + m_pDataFile->m_Info.m_pItemOffsets[Index]);
if(pType)
{
// remove sign extension
*pType = GetExternalItemType((i->m_TypeAndID>>16)&0xffff);
*pType = GetExternalItemType((i->m_TypeAndID >> 16) & 0xffff);
}
if(pID)
{
*pID = i->m_TypeAndID&0xffff;
*pID = i->m_TypeAndID & 0xffff;
}
return (void *)(i+1);
return (void *)(i + 1);
}
void CDataFileReader::GetType(int Type, int *pStart, int *pNum)
@ -507,7 +523,8 @@ void *CDataFileReader::FindItem(int Type, int ID)
int CDataFileReader::NumItems()
{
if(!m_pDataFile) return 0;
if(!m_pDataFile)
return 0;
return m_pDataFile->m_Header.m_NumItems;
}
@ -543,23 +560,25 @@ SHA256_DIGEST CDataFileReader::Sha256()
unsigned CDataFileReader::Crc()
{
if(!m_pDataFile) return 0xFFFFFFFF;
if(!m_pDataFile)
return 0xFFFFFFFF;
return m_pDataFile->m_Crc;
}
int CDataFileReader::MapSize()
{
if(!m_pDataFile) return 0;
if(!m_pDataFile)
return 0;
return m_pDataFile->m_Header.m_Size + 16;
}
IOHANDLE CDataFileReader::File()
{
if(!m_pDataFile) return 0;
if(!m_pDataFile)
return 0;
return m_pDataFile->m_File;
}
CDataFileWriter::CDataFileWriter()
{
m_File = 0;
@ -632,7 +651,7 @@ int CDataFileWriter::AddItem(int Type, int ID, int Size, void *pData)
{
dbg_assert((Type >= 0 && Type < MAX_ITEM_TYPES) || Type >= OFFSET_UUID, "incorrect type");
dbg_assert(m_NumItems < 1024, "too many items");
dbg_assert(Size%sizeof(int) == 0, "incorrect boundary");
dbg_assert(Size % sizeof(int) == 0, "incorrect boundary");
if(Type >= OFFSET_UUID)
{
@ -664,7 +683,7 @@ int CDataFileWriter::AddItem(int Type, int ID, int Size, void *pData)
m_pItemTypes[Type].m_Num++;
m_NumItems++;
return m_NumItems-1;
return m_NumItems - 1;
}
int CDataFileWriter::AddData(int Size, void *pData)
@ -675,7 +694,7 @@ int CDataFileWriter::AddData(int Size, void *pData)
unsigned long s = compressBound(Size);
void *pCompData = malloc(s); // temporary buffer that we use during compression
int Result = compress((Bytef*)pCompData, &s, (Bytef*)pData, Size); // ignore_convention
int Result = compress((Bytef *)pCompData, &s, (Bytef *)pData, Size); // ignore_convention
if(Result != Z_OK)
{
dbg_msg("datafile", "compression error %d", Result);
@ -689,17 +708,17 @@ int CDataFileWriter::AddData(int Size, void *pData)
free(pCompData);
m_NumDatas++;
return m_NumDatas-1;
return m_NumDatas - 1;
}
int CDataFileWriter::AddDataSwapped(int Size, void *pData)
{
dbg_assert(Size%sizeof(int) == 0, "incorrect boundary");
dbg_assert(Size % sizeof(int) == 0, "incorrect boundary");
#if defined(CONF_ARCH_ENDIAN_BIG)
void *pSwapped = malloc(Size); // temporary buffer that we use during compression
mem_copy(pSwapped, pData, Size);
swap_endian(pSwapped, sizeof(int), Size/sizeof(int));
swap_endian(pSwapped, sizeof(int), Size / sizeof(int));
int Index = AddData(Size, pSwapped);
free(pSwapped);
return Index;
@ -708,10 +727,10 @@ int CDataFileWriter::AddDataSwapped(int Size, void *pData)
#endif
}
int CDataFileWriter::Finish()
{
if(!m_File) return 1;
if(!m_File)
return 1;
int ItemSize = 0;
int TypesSize, HeaderSize, OffsetSize, FileSize, SwapSize;
@ -730,12 +749,11 @@ int CDataFileWriter::Finish()
ItemSize += m_pItems[i].m_Size + sizeof(CDatafileItem);
}
for(int i = 0; i < m_NumDatas; i++)
DataSize += m_pDatas[i].m_CompressedSize;
// calculate the complete size
TypesSize = m_NumItemTypes*sizeof(CDatafileItemType);
TypesSize = m_NumItemTypes * sizeof(CDatafileItemType);
HeaderSize = sizeof(CDatafileHeader);
OffsetSize = (m_NumItems + m_NumDatas + m_NumDatas) * sizeof(int); // ItemOffsets, DataOffsets, DataUncompressedSizes
FileSize = HeaderSize + TypesSize + OffsetSize + ItemSize + DataSize;
@ -765,7 +783,7 @@ int CDataFileWriter::Finish()
if(DEBUG)
dbg_msg("datafile", "HeaderSize=%d", (int)sizeof(Header));
#if defined(CONF_ARCH_ENDIAN_BIG)
swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int));
swap_endian(&Header, sizeof(int), sizeof(Header) / sizeof(int));
#endif
io_write(m_File, &Header, sizeof(Header));
}
@ -783,7 +801,7 @@ int CDataFileWriter::Finish()
if(DEBUG)
dbg_msg("datafile", "writing type=%x start=%d num=%d", Info.m_Type, Info.m_Start, Info.m_Num);
#if defined(CONF_ARCH_ENDIAN_BIG)
swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType)/sizeof(int));
swap_endian(&Info, sizeof(int), sizeof(CDatafileItemType) / sizeof(int));
#endif
io_write(m_File, &Info, sizeof(Info));
Count += m_pItemTypes[i].m_Num;
@ -803,7 +821,7 @@ int CDataFileWriter::Finish()
dbg_msg("datafile", "writing item offset num=%d offset=%d", k, Offset);
int Temp = Offset;
#if defined(CONF_ARCH_ENDIAN_BIG)
swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int));
swap_endian(&Temp, sizeof(int), sizeof(Temp) / sizeof(int));
#endif
io_write(m_File, &Temp, sizeof(Temp));
Offset += m_pItems[k].m_Size + sizeof(CDatafileItem);
@ -821,7 +839,7 @@ int CDataFileWriter::Finish()
dbg_msg("datafile", "writing data offset num=%d offset=%d", i, Offset);
int Temp = Offset;
#if defined(CONF_ARCH_ENDIAN_BIG)
swap_endian(&Temp, sizeof(int), sizeof(Temp)/sizeof(int));
swap_endian(&Temp, sizeof(int), sizeof(Temp) / sizeof(int));
#endif
io_write(m_File, &Temp, sizeof(Temp));
Offset += m_pDatas[i].m_CompressedSize;
@ -834,7 +852,7 @@ int CDataFileWriter::Finish()
dbg_msg("datafile", "writing data uncompressed size num=%d size=%d", i, m_pDatas[i].m_UncompressedSize);
int UncompressedSize = m_pDatas[i].m_UncompressedSize;
#if defined(CONF_ARCH_ENDIAN_BIG)
swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize)/sizeof(int));
swap_endian(&UncompressedSize, sizeof(int), sizeof(UncompressedSize) / sizeof(int));
#endif
io_write(m_File, &UncompressedSize, sizeof(UncompressedSize));
}
@ -849,14 +867,14 @@ int CDataFileWriter::Finish()
while(k != -1)
{
CDatafileItem Item;
Item.m_TypeAndID = (i<<16)|m_pItems[k].m_ID;
Item.m_TypeAndID = (i << 16) | m_pItems[k].m_ID;
Item.m_Size = m_pItems[k].m_Size;
if(DEBUG)
dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, m_pItems[k].m_ID, m_pItems[k].m_Size);
#if defined(CONF_ARCH_ENDIAN_BIG)
swap_endian(&Item, sizeof(int), sizeof(Item)/sizeof(int));
swap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size/sizeof(int));
swap_endian(&Item, sizeof(int), sizeof(Item) / sizeof(int));
swap_endian(m_pItems[k].m_pData, sizeof(int), m_pItems[k].m_Size / sizeof(int));
#endif
io_write(m_File, &Item, sizeof(Item));
io_write(m_File, m_pItems[k].m_pData, m_pItems[k].m_Size);

View file

@ -5,8 +5,8 @@
#include <engine/storage.h>
#include <base/system.h>
#include <base/hash.h>
#include <base/system.h>
// raw datafile access
class CDataFileReader
@ -19,7 +19,8 @@ class CDataFileReader
int GetInternalItemType(int ExternalType);
public:
CDataFileReader() : m_pDataFile(0) {}
CDataFileReader() :
m_pDataFile(0) {}
~CDataFileReader() { Close(); }
bool IsOpen() const { return m_pDataFile != 0; }
@ -75,10 +76,10 @@ class CDataFileWriter
enum
{
MAX_ITEM_TYPES=0x10000,
MAX_ITEMS=1024,
MAX_DATAS=1024,
MAX_EXTENDED_ITEM_TYPES=64,
MAX_ITEM_TYPES = 0x10000,
MAX_ITEMS = 1024,
MAX_DATAS = 1024,
MAX_EXTENDED_ITEM_TYPES = 64,
};
IOHANDLE m_File;
@ -105,5 +106,4 @@ public:
int Finish();
};
#endif

View file

@ -9,7 +9,7 @@
#include <engine/shared/config.h>
#if defined(CONF_VIDEORECORDER)
#include <engine/shared/video.h>
#include <engine/shared/video.h>
#endif
#include <game/generated/protocol.h>
@ -28,7 +28,6 @@ static const unsigned char gs_VersionTickCompression = 5; // demo files with thi
static const int gs_LengthOffset = 152;
static const int gs_NumMarkersOffset = 176;
CDemoRecorder::CDemoRecorder(class CSnapshotDelta *pSnapshotDelta, bool NoMapData)
{
m_File = 0;
@ -63,7 +62,8 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con
CDemoHeader Header;
CTimelineMarkers TimelineMarkers;
if(m_File) {
if(m_File)
{
io_close(DemoFile);
return -1;
}
@ -130,13 +130,13 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con
Header.m_Version = gs_ActVersion;
str_copy(Header.m_aNetversion, pNetVersion, sizeof(Header.m_aNetversion));
str_copy(Header.m_aMapName, pMap, sizeof(Header.m_aMapName));
Header.m_aMapSize[0] = (MapSize>>24)&0xff;
Header.m_aMapSize[1] = (MapSize>>16)&0xff;
Header.m_aMapSize[2] = (MapSize>>8)&0xff;
Header.m_aMapSize[0] = (MapSize >> 24) & 0xff;
Header.m_aMapSize[1] = (MapSize >> 16) & 0xff;
Header.m_aMapSize[2] = (MapSize >> 8) & 0xff;
Header.m_aMapSize[3] = (MapSize)&0xff;
Header.m_aMapCrc[0] = (Crc>>24)&0xff;
Header.m_aMapCrc[1] = (Crc>>16)&0xff;
Header.m_aMapCrc[2] = (Crc>>8)&0xff;
Header.m_aMapCrc[0] = (Crc >> 24) & 0xff;
Header.m_aMapCrc[1] = (Crc >> 16) & 0xff;
Header.m_aMapCrc[2] = (Crc >> 8) & 0xff;
Header.m_aMapCrc[3] = (Crc)&0xff;
str_copy(Header.m_aType, pType, sizeof(Header.m_aType));
// Header.m_Length - add this on stop
@ -160,7 +160,7 @@ int CDemoRecorder::Start(class IStorage *pStorage, class IConsole *pConsole, con
// write map data
while(1)
{
unsigned char aChunk[1024*64];
unsigned char aChunk[1024 * 64];
int Bytes = io_read(MapFile, &aChunk, sizeof(aChunk));
if(Bytes <= 0)
break;
@ -221,13 +221,13 @@ enum
void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe)
{
if(m_LastTickMarker == -1 || Tick-m_LastTickMarker > CHUNKMASK_TICK || Keyframe)
if(m_LastTickMarker == -1 || Tick - m_LastTickMarker > CHUNKMASK_TICK || Keyframe)
{
unsigned char aChunk[5];
aChunk[0] = CHUNKTYPEFLAG_TICKMARKER;
aChunk[1] = (Tick>>24)&0xff;
aChunk[2] = (Tick>>16)&0xff;
aChunk[3] = (Tick>>8)&0xff;
aChunk[1] = (Tick >> 24) & 0xff;
aChunk[2] = (Tick >> 16) & 0xff;
aChunk[3] = (Tick >> 8) & 0xff;
aChunk[4] = (Tick)&0xff;
if(Keyframe)
@ -238,7 +238,7 @@ void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe)
else
{
unsigned char aChunk[1];
aChunk[0] = CHUNKTYPEFLAG_TICKMARKER | CHUNKTICKFLAG_TICK_COMPRESSED | (Tick-m_LastTickMarker);
aChunk[0] = CHUNKTYPEFLAG_TICKMARKER | CHUNKTICKFLAG_TICK_COMPRESSED | (Tick - m_LastTickMarker);
io_write(m_File, aChunk, sizeof(aChunk));
}
@ -249,20 +249,20 @@ void CDemoRecorder::WriteTickMarker(int Tick, int Keyframe)
void CDemoRecorder::Write(int Type, const void *pData, int Size)
{
char aBuffer[64*1024];
char aBuffer2[64*1024];
char aBuffer[64 * 1024];
char aBuffer2[64 * 1024];
unsigned char aChunk[3];
if(!m_File)
return;
if(Size > 64*1024)
if(Size > 64 * 1024)
return;
/* pad the data with 0 so we get an alignment of 4,
else the compression won't work and miss some bytes */
mem_copy(aBuffer2, pData, Size);
while(Size&3)
while(Size & 3)
aBuffer2[Size++] = 0;
Size = CVariableInt::Compress(aBuffer2, Size, aBuffer, sizeof(aBuffer)); // buffer2 -> buffer
if(Size < 0)
@ -272,8 +272,7 @@ void CDemoRecorder::Write(int Type, const void *pData, int Size)
if(Size < 0)
return;
aChunk[0] = ((Type&0x3)<<5);
aChunk[0] = ((Type & 0x3) << 5);
if(Size < 30)
{
aChunk[0] |= Size;
@ -284,14 +283,14 @@ void CDemoRecorder::Write(int Type, const void *pData, int Size)
if(Size < 256)
{
aChunk[0] |= 30;
aChunk[1] = Size&0xff;
aChunk[1] = Size & 0xff;
io_write(m_File, aChunk, 2);
}
else
{
aChunk[0] |= 31;
aChunk[1] = Size&0xff;
aChunk[2] = Size>>8;
aChunk[1] = Size & 0xff;
aChunk[2] = Size >> 8;
io_write(m_File, aChunk, 3);
}
}
@ -301,7 +300,7 @@ void CDemoRecorder::Write(int Type, const void *pData, int Size)
void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size)
{
if(m_LastKeyFrame == -1 || (Tick-m_LastKeyFrame) > SERVER_TICK_SPEED*5)
if(m_LastKeyFrame == -1 || (Tick - m_LastKeyFrame) > SERVER_TICK_SPEED * 5)
{
// write full tickmarker
WriteTickMarker(Tick, 1);
@ -315,13 +314,13 @@ void CDemoRecorder::RecordSnapshot(int Tick, const void *pData, int Size)
else
{
// create delta, prepend tick
char aDeltaData[CSnapshot::MAX_SIZE+sizeof(int)];
char aDeltaData[CSnapshot::MAX_SIZE + sizeof(int)];
int DeltaSize;
// write tickmarker
WriteTickMarker(Tick, 0);
DeltaSize = m_pSnapshotDelta->CreateDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)pData, &aDeltaData);
DeltaSize = m_pSnapshotDelta->CreateDelta((CSnapshot *)m_aLastSnapshotData, (CSnapshot *)pData, &aDeltaData);
if(DeltaSize)
{
// record delta
@ -352,27 +351,27 @@ int CDemoRecorder::Stop()
io_seek(m_File, gs_LengthOffset, IOSEEK_START);
int DemoLength = Length();
char aLength[4];
aLength[0] = (DemoLength>>24)&0xff;
aLength[1] = (DemoLength>>16)&0xff;
aLength[2] = (DemoLength>>8)&0xff;
aLength[0] = (DemoLength >> 24) & 0xff;
aLength[1] = (DemoLength >> 16) & 0xff;
aLength[2] = (DemoLength >> 8) & 0xff;
aLength[3] = (DemoLength)&0xff;
io_write(m_File, aLength, sizeof(aLength));
// add the timeline markers to the header
io_seek(m_File, gs_NumMarkersOffset, IOSEEK_START);
char aNumMarkers[4];
aNumMarkers[0] = (m_NumTimelineMarkers>>24)&0xff;
aNumMarkers[1] = (m_NumTimelineMarkers>>16)&0xff;
aNumMarkers[2] = (m_NumTimelineMarkers>>8)&0xff;
aNumMarkers[0] = (m_NumTimelineMarkers >> 24) & 0xff;
aNumMarkers[1] = (m_NumTimelineMarkers >> 16) & 0xff;
aNumMarkers[2] = (m_NumTimelineMarkers >> 8) & 0xff;
aNumMarkers[3] = (m_NumTimelineMarkers)&0xff;
io_write(m_File, aNumMarkers, sizeof(aNumMarkers));
for(int i = 0; i < m_NumTimelineMarkers; i++)
{
int Marker = m_aTimelineMarkers[i];
char aMarker[4];
aMarker[0] = (Marker>>24)&0xff;
aMarker[1] = (Marker>>16)&0xff;
aMarker[2] = (Marker>>8)&0xff;
aMarker[0] = (Marker >> 24) & 0xff;
aMarker[1] = (Marker >> 16) & 0xff;
aMarker[2] = (Marker >> 8) & 0xff;
aMarker[3] = (Marker)&0xff;
io_write(m_File, aMarker, sizeof(aMarker));
}
@ -393,8 +392,8 @@ void CDemoRecorder::AddDemoMarker()
// not more than 1 marker in a second
if(m_NumTimelineMarkers > 0)
{
int Diff = m_LastTickMarker - m_aTimelineMarkers[m_NumTimelineMarkers-1];
if(Diff < SERVER_TICK_SPEED*1.0f)
int Diff = m_LastTickMarker - m_aTimelineMarkers[m_NumTimelineMarkers - 1];
if(Diff < SERVER_TICK_SPEED * 1.0f)
return;
}
@ -404,8 +403,6 @@ void CDemoRecorder::AddDemoMarker()
m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Added timeline marker");
}
CDemoPlayer::CDemoPlayer(class CSnapshotDelta *pSnapshotDelta)
{
m_File = 0;
@ -424,7 +421,6 @@ void CDemoPlayer::SetListener(IListener *pListener)
m_pListener = pListener;
}
int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick)
{
unsigned char Chunk = 0;
@ -438,19 +434,19 @@ int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick)
if(io_read(m_File, &Chunk, sizeof(Chunk)) != sizeof(Chunk))
return -1;
if(Chunk&CHUNKTYPEFLAG_TICKMARKER)
if(Chunk & CHUNKTYPEFLAG_TICKMARKER)
{
// decode tick marker
int Tickdelta_legacy = Chunk&(CHUNKMASK_TICK_LEGACY); // compatibility
*pType = Chunk&(CHUNKTYPEFLAG_TICKMARKER|CHUNKTICKFLAG_KEYFRAME);
int Tickdelta_legacy = Chunk & (CHUNKMASK_TICK_LEGACY); // compatibility
*pType = Chunk & (CHUNKTYPEFLAG_TICKMARKER | CHUNKTICKFLAG_KEYFRAME);
if(m_Info.m_Header.m_Version < gs_VersionTickCompression && Tickdelta_legacy != 0)
{
*pTick += Tickdelta_legacy;
}
else if(Chunk&(CHUNKTICKFLAG_TICK_COMPRESSED))
else if(Chunk & (CHUNKTICKFLAG_TICK_COMPRESSED))
{
int Tickdelta = Chunk&(CHUNKMASK_TICK);
int Tickdelta = Chunk & (CHUNKMASK_TICK);
*pTick += Tickdelta;
}
else
@ -458,15 +454,14 @@ int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick)
unsigned char aTickdata[4];
if(io_read(m_File, aTickdata, sizeof(aTickdata)) != sizeof(aTickdata))
return -1;
*pTick = (aTickdata[0]<<24) | (aTickdata[1]<<16) | (aTickdata[2]<<8) | aTickdata[3];
*pTick = (aTickdata[0] << 24) | (aTickdata[1] << 16) | (aTickdata[2] << 8) | aTickdata[3];
}
}
else
{
// decode normal chunk
*pType = (Chunk&CHUNKMASK_TYPE)>>5;
*pSize = Chunk&CHUNKMASK_SIZE;
*pType = (Chunk & CHUNKMASK_TYPE) >> 5;
*pSize = Chunk & CHUNKMASK_SIZE;
if(*pSize == 30)
{
@ -474,14 +469,13 @@ int CDemoPlayer::ReadChunkHeader(int *pType, int *pSize, int *pTick)
if(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata))
return -1;
*pSize = aSizedata[0];
}
else if(*pSize == 31)
{
unsigned char aSizedata[2];
if(io_read(m_File, aSizedata, sizeof(aSizedata)) != sizeof(aSizedata))
return -1;
*pSize = (aSizedata[1]<<8) | aSizedata[0];
*pSize = (aSizedata[1] << 8) | aSizedata[0];
}
}
@ -509,9 +503,9 @@ void CDemoPlayer::ScanFile()
break;
// read the chunk
if(ChunkType&CHUNKTYPEFLAG_TICKMARKER)
if(ChunkType & CHUNKTYPEFLAG_TICKMARKER)
{
if(ChunkType&CHUNKTICKFLAG_KEYFRAME)
if(ChunkType & CHUNKTICKFLAG_KEYFRAME)
{
CKeyFrameSearch *pKey;
@ -534,7 +528,6 @@ void CDemoPlayer::ScanFile()
}
else if(ChunkSize)
io_skip(m_File, ChunkSize);
}
// copy all the frames to an array instead for fast access
@ -567,10 +560,10 @@ void CDemoPlayer::DoTick()
// stop on error or eof
if(m_pConsole)
m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "demo_player", "end of file");
#if defined(CONF_VIDEORECORDER)
if (IVideo::Current())
Stop();
#endif
#if defined(CONF_VIDEORECORDER)
if(IVideo::Current())
Stop();
#endif
if(m_Info.m_PreviousTick == -1)
{
if(m_pConsole)
@ -622,7 +615,7 @@ void CDemoPlayer::DoTick()
GotSnapshot = 1;
DataSize = m_pSnapshotDelta->UnpackDelta((CSnapshot*)m_aLastSnapshotData, (CSnapshot*)aNewsnap, aData, DataSize);
DataSize = m_pSnapshotDelta->UnpackDelta((CSnapshot *)m_aLastSnapshotData, (CSnapshot *)aNewsnap, aData, DataSize);
if(DataSize >= 0)
{
@ -662,7 +655,7 @@ void CDemoPlayer::DoTick()
}
// check the remaining types
if(ChunkType&CHUNKTYPEFLAG_TICKMARKER)
if(ChunkType & CHUNKTYPEFLAG_TICKMARKER)
{
m_Info.m_NextTick = ChunkTick;
break;
@ -786,11 +779,11 @@ int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const
m_DemoType = DEMOTYPE_INVALID;
// read map
unsigned MapSize = (m_Info.m_Header.m_aMapSize[0]<<24) | (m_Info.m_Header.m_aMapSize[1]<<16) | (m_Info.m_Header.m_aMapSize[2]<<8) | (m_Info.m_Header.m_aMapSize[3]);
unsigned MapSize = (m_Info.m_Header.m_aMapSize[0] << 24) | (m_Info.m_Header.m_aMapSize[1] << 16) | (m_Info.m_Header.m_aMapSize[2] << 8) | (m_Info.m_Header.m_aMapSize[3]);
// check if we already have the map
// TODO: improve map checking (maps folder, check crc)
unsigned Crc = (m_Info.m_Header.m_aMapCrc[0]<<24) | (m_Info.m_Header.m_aMapCrc[1]<<16) | (m_Info.m_Header.m_aMapCrc[2]<<8) | (m_Info.m_Header.m_aMapCrc[3]);
unsigned Crc = (m_Info.m_Header.m_aMapCrc[0] << 24) | (m_Info.m_Header.m_aMapCrc[1] << 16) | (m_Info.m_Header.m_aMapCrc[2] << 8) | (m_Info.m_Header.m_aMapCrc[3]);
// save byte offset of map for later use
m_MapOffset = io_tell(m_File);
@ -805,14 +798,14 @@ int CDemoPlayer::Load(class IStorage *pStorage, class IConsole *pConsole, const
if(m_Info.m_Header.m_Version > gs_OldVersion)
{
// get timeline markers
int Num = ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[0]<<24)&0xFF000000) | ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[1]<<16)&0xFF0000) |
((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[2]<<8)&0xFF00) | (m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[3]&0xFF);
int Num = ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[0] << 24) & 0xFF000000) | ((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[1] << 16) & 0xFF0000) |
((m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[2] << 8) & 0xFF00) | (m_Info.m_TimelineMarkers.m_aNumTimelineMarkers[3] & 0xFF);
m_Info.m_Info.m_NumTimelineMarkers = minimum(Num, (int)MAX_TIMELINE_MARKERS);
for(int i = 0; i < m_Info.m_Info.m_NumTimelineMarkers; i++)
{
char *pTimelineMarker = m_Info.m_TimelineMarkers.m_aTimelineMarkers[i];
m_Info.m_Info.m_aTimelineMarkers[i] = ((pTimelineMarker[0]<<24)&0xFF000000) | ((pTimelineMarker[1]<<16)&0xFF0000) |
((pTimelineMarker[2]<<8)&0xFF00) | (pTimelineMarker[3]&0xFF);
m_Info.m_Info.m_aTimelineMarkers[i] = ((pTimelineMarker[0] << 24) & 0xFF000000) | ((pTimelineMarker[1] << 16) & 0xFF0000) |
((pTimelineMarker[2] << 8) & 0xFF00) | (pTimelineMarker[3] & 0xFF);
}
}
@ -879,9 +872,9 @@ int64 CDemoPlayer::time()
{
#if defined(CONF_VIDEORECORDER)
static bool s_Recording = false;
if (IVideo::Current())
if(IVideo::Current())
{
if (!s_Recording)
if(!s_Recording)
{
s_Recording = true;
m_Info.m_LastUpdate = IVideo::Time();
@ -891,7 +884,7 @@ int64 CDemoPlayer::time()
else
{
int64 Now = time_get();
if (s_Recording)
if(s_Recording)
{
s_Recording = false;
m_Info.m_LastUpdate = Now;
@ -912,7 +905,7 @@ int CDemoPlayer::Play()
// set start info
/*m_Info.start_tick = m_Info.previous_tick;
m_Info.start_time = time_get();*/
m_Info.m_CurrentTime = m_Info.m_PreviousTick*time_freq()/SERVER_TICK_SPEED;
m_Info.m_CurrentTime = m_Info.m_PreviousTick * time_freq() / SERVER_TICK_SPEED;
m_Info.m_LastUpdate = time();
return 0;
}
@ -971,14 +964,14 @@ void CDemoPlayer::SetSpeed(float Speed)
void CDemoPlayer::SetSpeedIndex(int Offset)
{
m_SpeedIndex = clamp(m_SpeedIndex + Offset, 0, (int)(sizeof(g_aSpeeds)/sizeof(g_aSpeeds[0])-1));
m_SpeedIndex = clamp(m_SpeedIndex + Offset, 0, (int)(sizeof(g_aSpeeds) / sizeof(g_aSpeeds[0]) - 1));
SetSpeed(g_aSpeeds[m_SpeedIndex]);
}
int CDemoPlayer::Update(bool RealTime)
{
int64 Now = time();
int64 Deltatime = Now-m_Info.m_LastUpdate;
int64 Deltatime = Now - m_Info.m_LastUpdate;
m_Info.m_LastUpdate = Now;
if(!IsPlaying())
@ -986,16 +979,15 @@ int CDemoPlayer::Update(bool RealTime)
if(m_Info.m_Info.m_Paused)
{
}
else
{
int64 Freq = time_freq();
m_Info.m_CurrentTime += (int64)(Deltatime*(double)m_Info.m_Info.m_Speed);
m_Info.m_CurrentTime += (int64)(Deltatime * (double)m_Info.m_Info.m_Speed);
while(1)
{
int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED;
int64 CurtickStart = (m_Info.m_Info.m_CurrentTick) * Freq / SERVER_TICK_SPEED;
// break if we are ready
if(RealTime && CurtickStart > m_Info.m_CurrentTime)
@ -1010,9 +1002,9 @@ int CDemoPlayer::Update(bool RealTime)
// update intratick
{
int64 CurtickStart = (m_Info.m_Info.m_CurrentTick)*Freq/SERVER_TICK_SPEED;
int64 PrevtickStart = (m_Info.m_PreviousTick)*Freq/SERVER_TICK_SPEED;
m_Info.m_IntraTick = (m_Info.m_CurrentTime - PrevtickStart) / (float)(CurtickStart-PrevtickStart);
int64 CurtickStart = (m_Info.m_Info.m_CurrentTick) * Freq / SERVER_TICK_SPEED;
int64 PrevtickStart = (m_Info.m_PreviousTick) * Freq / SERVER_TICK_SPEED;
m_Info.m_IntraTick = (m_Info.m_CurrentTime - PrevtickStart) / (float)(CurtickStart - PrevtickStart);
m_Info.m_TickTime = (m_Info.m_CurrentTime - PrevtickStart) / (float)Freq;
}
@ -1037,8 +1029,8 @@ int CDemoPlayer::Update(bool RealTime)
int CDemoPlayer::Stop()
{
#if defined(CONF_VIDEORECORDER)
if (IVideo::Current())
IVideo::Current()->Stop();
if(IVideo::Current())
IVideo::Current()->Stop();
#endif
if(!m_File)
@ -1062,12 +1054,12 @@ void CDemoPlayer::GetDemoName(char *pBuffer, int BufferSize) const
for(; *pFileName; ++pFileName)
{
if(*pFileName == '/' || *pFileName == '\\')
pExtractedName = pFileName+1;
pExtractedName = pFileName + 1;
else if(*pFileName == '.')
pEnd = pFileName;
}
int Length = pEnd > pExtractedName ? minimum(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize;
int Length = pEnd > pExtractedName ? minimum(BufferSize, (int)(pEnd - pExtractedName + 1)) : BufferSize;
str_copy(pBuffer, pExtractedName, Length);
}
@ -1087,7 +1079,7 @@ bool CDemoPlayer::GetDemoInfo(class IStorage *pStorage, const char *pFilename, i
io_read(File, pTimelineMarkers, sizeof(CTimelineMarkers));
str_copy(pMapInfo->m_aName, pDemoHeader->m_aMapName, sizeof(pMapInfo->m_aName));
pMapInfo->m_Crc = (pDemoHeader->m_aMapCrc[0]<<24) | (pDemoHeader->m_aMapCrc[1]<<16) | (pDemoHeader->m_aMapCrc[2]<<8) | (pDemoHeader->m_aMapCrc[3]);
pMapInfo->m_Crc = (pDemoHeader->m_aMapCrc[0] << 24) | (pDemoHeader->m_aMapCrc[1] << 16) | (pDemoHeader->m_aMapCrc[2] << 8) | (pDemoHeader->m_aMapCrc[3]);
SHA256_DIGEST Sha256 = SHA256_ZEROED;
if(pDemoHeader->m_Version >= gs_Sha256Version)
@ -1108,7 +1100,7 @@ bool CDemoPlayer::GetDemoInfo(class IStorage *pStorage, const char *pFilename, i
}
pMapInfo->m_Sha256 = Sha256;
pMapInfo->m_Size = (pDemoHeader->m_aMapSize[0]<<24) | (pDemoHeader->m_aMapSize[1]<<16) | (pDemoHeader->m_aMapSize[2]<<8) | (pDemoHeader->m_aMapSize[3]);
pMapInfo->m_Size = (pDemoHeader->m_aMapSize[0] << 24) | (pDemoHeader->m_aMapSize[1] << 16) | (pDemoHeader->m_aMapSize[2] << 8) | (pDemoHeader->m_aMapSize[3]);
io_close(File);
return !(mem_comp(pDemoHeader->m_aMarker, gs_aHeaderMarker, sizeof(gs_aHeaderMarker)) || pDemoHeader->m_Version < gs_OldVersion);
@ -1143,7 +1135,7 @@ void CDemoEditor::Slice(const char *pDemo, const char *pDst, int StartTick, int
m_SliceTo = EndTick;
m_Stop = false;
if (m_pDemoPlayer->Load(m_pStorage, m_pConsole, pDemo, IStorage::TYPE_ALL) == -1)
if(m_pDemoPlayer->Load(m_pStorage, m_pConsole, pDemo, IStorage::TYPE_ALL) == -1)
return;
const CMapInfo *pMapInfo = m_pDemoPlayer->GetMapInfo();
@ -1156,16 +1148,16 @@ void CDemoEditor::Slice(const char *pDemo, const char *pDst, int StartTick, int
Sha256 = pMapInfo->m_Sha256;
}
if (m_pDemoRecorder->Start(m_pStorage, m_pConsole, pDst, m_pNetVersion, pMapInfo->m_aName, &Sha256, pMapInfo->m_Crc, "client", pMapInfo->m_Size, NULL, NULL, pfnFilter, pUser) == -1)
if(m_pDemoRecorder->Start(m_pStorage, m_pConsole, pDst, m_pNetVersion, pMapInfo->m_aName, &Sha256, pMapInfo->m_Crc, "client", pMapInfo->m_Size, NULL, NULL, pfnFilter, pUser) == -1)
return;
m_pDemoPlayer->Play();
while (m_pDemoPlayer->IsPlaying() && !m_Stop) {
while(m_pDemoPlayer->IsPlaying() && !m_Stop)
{
m_pDemoPlayer->Update(false);
if (pInfo->m_Info.m_Paused)
if(pInfo->m_Info.m_Paused)
break;
}
@ -1177,9 +1169,9 @@ void CDemoEditor::OnDemoPlayerSnapshot(void *pData, int Size)
{
const CDemoPlayer::CPlaybackInfo *pInfo = m_pDemoPlayer->Info();
if (m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo)
if(m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo)
m_Stop = true;
else if (m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom)
else if(m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom)
m_pDemoRecorder->RecordSnapshot(pInfo->m_Info.m_CurrentTick, pData, Size);
}
@ -1187,8 +1179,8 @@ void CDemoEditor::OnDemoPlayerMessage(void *pData, int Size)
{
const CDemoPlayer::CPlaybackInfo *pInfo = m_pDemoPlayer->Info();
if (m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo)
if(m_SliceTo != -1 && pInfo->m_Info.m_CurrentTick > m_SliceTo)
m_Stop = true;
else if (m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom)
else if(m_SliceFrom == -1 || pInfo->m_Info.m_CurrentTick >= m_SliceFrom)
m_pDemoRecorder->RecordMessage(pData, Size);
}

View file

@ -30,6 +30,7 @@ class CDemoRecorder : public IDemoRecorder
void WriteTickMarker(int Tick, int Keyframe);
void Write(int Type, const void *pData, int Size);
public:
CDemoRecorder(class CSnapshotDelta *pSnapshotDelta, bool NoMapData = false);
CDemoRecorder() {}
@ -44,7 +45,7 @@ public:
bool IsRecording() const { return m_File != 0; }
char *GetCurrentFilename() { return m_aCurrentFilename; }
int Length() const { return (m_LastTickMarker - m_FirstTick)/SERVER_TICK_SPEED; }
int Length() const { return (m_LastTickMarker - m_FirstTick) / SERVER_TICK_SPEED; }
};
class CDemoPlayer : public IDemoPlayer
@ -80,7 +81,6 @@ public:
private:
IListener *m_pListener;
// Playback
struct CKeyFrame
{
@ -119,7 +119,6 @@ private:
int64 m_Time;
public:
CDemoPlayer(class CSnapshotDelta *m_pSnapshotDelta);
void SetListener(IListener *pListener);
@ -141,7 +140,7 @@ public:
const char *GetDemoFileName() { return m_aFilename; };
int GetDemoType() const;
int Update(bool RealTime=true);
int Update(bool RealTime = true);
const CPlaybackInfo *Info() const { return &m_Info; }
virtual bool IsPlaying() const { return m_File != 0; }

View file

@ -4,7 +4,6 @@
#include "econ.h"
#include "netban.h"
int CEcon::NewClientCallback(int ClientID, void *pUser)
{
CEcon *pThis = (CEcon *)pUser;
@ -93,7 +92,7 @@ void CEcon::Init(IConsole *pConsole, CNetBan *pNetBan)
m_Ready = true;
char aBuf[128];
str_format(aBuf, sizeof(aBuf), "bound to %s:%d", g_Config.m_EcBindaddr, g_Config.m_EcPort);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", aBuf);
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "econ", aBuf);
Console()->Chain("ec_output_level", ConchainEconOutputLevelUpdate, this);
m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_EcOutputLevel, SendLineCB, this);
@ -101,7 +100,7 @@ void CEcon::Init(IConsole *pConsole, CNetBan *pNetBan)
Console()->Register("logout", "", CFGFLAG_ECON, ConLogout, this, "Logout of econ");
}
else
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", "couldn't open socket. port might already be in use");
Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "econ", "couldn't open socket. port might already be in use");
}
void CEcon::Update()
@ -114,7 +113,7 @@ void CEcon::Update()
char aBuf[NET_MAX_PACKETSIZE];
int ClientID;
while(m_NetConsole.Recv(aBuf, (int)(sizeof(aBuf))-1, &ClientID))
while(m_NetConsole.Recv(aBuf, (int)(sizeof(aBuf)) - 1, &ClientID))
{
dbg_assert(m_aClients[ClientID].m_State != CClient::STATE_EMPTY, "got message from empty slot");
if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTED)
@ -138,7 +137,7 @@ void CEcon::Update()
if(!g_Config.m_EcBantime)
m_NetConsole.Drop(ClientID, "Too many authentication tries");
else
m_NetConsole.NetBan()->BanAddr(m_NetConsole.ClientAddr(ClientID), g_Config.m_EcBantime*60, "Too many authentication tries");
m_NetConsole.NetBan()->BanAddr(m_NetConsole.ClientAddr(ClientID), g_Config.m_EcBantime * 60, "Too many authentication tries");
}
}
}

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