Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

test(cmake): add a test harness and nine suites over the ported libs

Olcay Seyganc13a474fbef8
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index 36881cd84..c14ec913e 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -96,7 +96,8 @@ add_library(wwlib STATIC
${WW}/WWLib/cpudetect.cpp ${WW}/WWLib/crc.cpp ${WW}/WWLib/cstraw.cpp
${WW}/WWLib/data.cpp ${WW}/WWLib/ddraw.cpp ${WW}/WWLib/dsurface.cpp
${WW}/WWLib/Except.cpp ${WW}/WWLib/FastAllocator.cpp
- ${WW}/WWLib/ffactory.cpp ${WW}/WWLib/gcd_lcm.cpp ${WW}/WWLib/hash.cpp
+ ${WW}/WWLib/ffactory.cpp ${WW}/WWLib/fixed.cpp ${WW}/WWLib/md5.cpp
+ ${WW}/WWLib/gcd_lcm.cpp ${WW}/WWLib/hash.cpp
${WW}/WWLib/hsv.cpp ${WW}/WWLib/ini.cpp ${WW}/WWLib/int.cpp
${WW}/WWLib/jshell.cpp ${WW}/WWLib/keyboard.cpp ${WW}/WWLib/LaunchWeb.cpp
${WW}/WWLib/lcw.cpp ${WW}/WWLib/load.cpp ${WW}/WWLib/mixfile.cpp
@@ -117,7 +118,9 @@ add_library(wwlib STATIC
${WW}/WWLib/wwfile.cpp ${WW}/WWLib/wwfont.cpp ${WW}/WWLib/wwstring.cpp
${WW}/WWLib/xpipe.cpp ${WW}/WWLib/xstraw.cpp ${WW}/WWLib/xsurface.cpp)
target_include_directories(wwlib PUBLIC ${WW}/WWLib PRIVATE ${WW}/WWMath ${WW}/Wwutil)
-target_link_libraries(wwlib PRIVATE wwdebug PUBLIC winmm) # timeGetTime/timeBeginPeriod
+# winmm: timeGetTime/timeBeginPeriod. version: verchk.cpp's GetFileVersionInfo,
+# which Wwutil drags in for Get_File_Id_String.
+target_link_libraries(wwlib PRIVATE wwdebug PUBLIC winmm version)
# ---- wwsaveload -----------------------------------------------------------
add_library(wwsaveload STATIC
@@ -180,7 +183,14 @@ target_include_directories(ww3d2
${WW}/wwshade ${WW}/WWAudio ${WW}/Miles6/include
${CMAKE_CURRENT_SOURCE_DIR}/Libraries/DirectX/Include)
target_link_directories(ww3d2 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/DirectX/Lib)
-target_link_libraries(ww3d2 PUBLIC d3d8 d3dx8 dxguid PRIVATE wwlib wwmath wwdebug wwsaveload)
+# vfw32: FramGrab.cpp writes AVIs. legacy_stdio_definitions: d3dx8.lib calls
+# _vsnprintf, which the modern CRT only provides as an inline.
+target_link_libraries(ww3d2
+ PUBLIC d3d8 d3dx8 dxguid vfw32 legacy_stdio_definitions
+ PRIVATE wwlib wwmath wwdebug wwsaveload)
+# The 2001 d3dx8.lib predates SAFESEH and was built against the long-gone
+# libci.lib CRT, so anything linking it has to opt out of both.
+target_link_options(ww3d2 INTERFACE /SAFESEH:NO /NODEFAULTLIB:libci.lib)
# ponytail: VC6 for-scope leaks at ~40 sites across ww3d2; scoped flag beats mass
# edits in render code. Burn the sites down later, then drop the flag.
target_compile_options(ww3d2 PRIVATE /Zc:forScope-)
@@ -211,6 +221,9 @@ add_library(debug STATIC
${LIBSRC}/debug/debug_stack.cpp)
target_include_directories(debug PUBLIC ${LIBSRC}/debug)
target_link_libraries(debug PUBLIC dbghelp comctl32 ws2_32)
+# "debug" is also a target_link_libraries config keyword, so it can never be
+# passed as a plain library name. Link this alias instead.
+add_library(debuglib ALIAS debug)
# ---- wwdownload -----------------------------------------------------------
# FTP patch downloader. Its wlib/resource.h includes are all commented out in
@@ -266,3 +279,57 @@ set(GS_SECURESECONNECT OFF CACHE BOOL "" FORCE)
set(GS_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GS_INCLUDE_VOICE OFF CACHE BOOL "" FORCE)
add_subdirectory(${LIBSRC}/GameSpy ${CMAKE_CURRENT_BINARY_DIR}/gamespy)
+
+# ===========================================================================
+# Tests. Run with: ctest --test-dir build -C Release --output-on-failure
+# ===========================================================================
+enable_testing()
+
+set(TESTS ${CMAKE_CURRENT_SOURCE_DIR}/Tests)
+
+# Shared runner for the micro-harness in Tests/test_harness.h; every test
+# binary links it instead of writing its own main().
+add_library(test_harness STATIC ${TESTS}/test_main.cpp)
+target_include_directories(test_harness PUBLIC ${TESTS})
+
+# add_lib_test(<name> <libs...>) -> Tests/<name>.cpp, built and registered.
+function(add_lib_test name)
+ add_executable(${name} ${TESTS}/${name}.cpp)
+ target_link_libraries(${name} PRIVATE test_harness ${ARGN})
+ add_test(NAME ${name} COMMAND ${name})
+endfunction()
+
+add_lib_test(test_wwmath wwmath wwlib wwsaveload wwdebug)
+target_include_directories(test_wwmath PRIVATE ${WW}/WWLib ${WW}/WWSaveLoad ${WW}/Wwutil)
+
+add_lib_test(test_wwlib wwlib wwmath wwsaveload wwdebug)
+target_include_directories(test_wwlib PRIVATE ${WW}/WWLib ${WW}/WWMath ${WW}/WWSaveLoad ${WW}/Wwutil)
+
+add_lib_test(test_wwsaveload wwsaveload wwlib wwmath wwdebug)
+target_include_directories(test_wwsaveload PRIVATE ${WW}/WWSaveLoad ${WW}/WWLib ${WW}/WWMath ${WW}/WWDebug ${WW}/Wwutil)
+
+add_lib_test(test_wwutil wwutil wwmath wwlib wwdebug)
+target_include_directories(test_wwutil PRIVATE ${WW}/Wwutil ${WW}/WWLib ${WW}/WWMath)
+
+add_lib_test(test_compression compression)
+
+# ww3d2 needs the same /Zc:forScope- as the library: its headers are included
+# here and dx8fvf.h et al were written for VC6 for-scope rules.
+add_lib_test(test_ww3d2 ww3d2 wwsaveload wwlib wwmath wwdebug)
+target_include_directories(test_ww3d2 PRIVATE
+ ${WW}/WW3D2 ${WW}/WWLib ${WW}/WWMath ${WW}/WWDebug ${WW}/WWSaveLoad ${WW}/Wwutil
+ ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/DirectX/Include)
+target_compile_options(test_ww3d2 PRIVATE /Zc:forScope-)
+
+add_lib_test(test_wwdownload wwdownload)
+target_include_directories(test_wwdownload PRIVATE ${WW}/WWDownload)
+
+add_lib_test(test_debug debuglib)
+
+add_lib_test(test_support benchmark eabrowserdispatch)
+
+# The three hand-written self-checks predate the harness; run them from ctest
+# too so one command covers everything.
+add_test(NAME wwmath_selfcheck COMMAND wwmath_selfcheck)
+add_test(NAME compression_selfcheck COMMAND compression_selfcheck)
+add_test(NAME dx8_smoke COMMAND dx8_smoke)
diff --git a/GeneralsMD/Code/Tests/test_compression.cpp b/GeneralsMD/Code/Tests/test_compression.cpp
new file mode 100644
index 000000000..0f0ddc443
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_compression.cpp
@@ -0,0 +1,408 @@
+/*
+ * CompressionManager coverage.
+ *
+ * The existing compression_selfcheck already proves one 64K payload survives
+ * every codec. This goes after the parts around that: header sniffing, the
+ * size estimators, the buffer-too-small paths, degenerate payload sizes, and
+ * the documented trap that the name tables stop at COMPRESSION_MAX while the
+ * enum keeps going.
+ */
+#include "test_harness.h"
+#include "Compression.h"
+
+#include <stdlib.h>
+
+//////////////////////////////////////////////////////////////////////////////
+// Helpers
+//////////////////////////////////////////////////////////////////////////////
+
+/* Every codec CompressionManager can actually produce. A MIN..MAX sweep is
+ useless here - COMPRESSION_MAX == COMPRESSION_REFPACK even though the enum
+ runs on for another twelve entries. */
+static const struct { CompressionType type; const char *name; } CODECS[] = {
+ { COMPRESSION_REFPACK, "RefPack" },
+ { COMPRESSION_NOXLZH, "NoxLZH" },
+ { COMPRESSION_ZLIB1, "ZLib1" },
+ { COMPRESSION_ZLIB2, "ZLib2" },
+ { COMPRESSION_ZLIB3, "ZLib3" },
+ { COMPRESSION_ZLIB4, "ZLib4" },
+ { COMPRESSION_ZLIB5, "ZLib5" },
+ { COMPRESSION_ZLIB6, "ZLib6" },
+ { COMPRESSION_ZLIB7, "ZLib7" },
+ { COMPRESSION_ZLIB8, "ZLib8" },
+ { COMPRESSION_ZLIB9, "ZLib9" },
+ { COMPRESSION_BTREE, "BTree" },
+ { COMPRESSION_HUFF, "Huff" },
+};
+static const int CODEC_COUNT = (int)(sizeof(CODECS) / sizeof(CODECS[0]));
+
+/* Compressible but not trivial - a pure run would let a broken match finder
+ pass by accident. */
+static void fill_text(char *buf, int len, int variant)
+{
+ static const char *seed = "Command & Conquer Generals Zero Hour ";
+ for (int i = 0; i < len; ++i)
+ buf[i] = (char)(seed[i % 37] + ((i / 1024 + variant) % 7));
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Header sniffing
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(compression_type_from_magic)
+{
+ struct { const char *magic; CompressionType type; } cases[] = {
+ { "NOX\0", COMPRESSION_NOXLZH },
+ { "ZL1\0", COMPRESSION_ZLIB1 },
+ { "ZL5\0", COMPRESSION_ZLIB5 },
+ { "ZL9\0", COMPRESSION_ZLIB9 },
+ { "EAB\0", COMPRESSION_BTREE },
+ { "EAH\0", COMPRESSION_HUFF },
+ { "EAR\0", COMPRESSION_REFPACK },
+ };
+
+ for (int i = 0; i < 7; ++i)
+ {
+ char header[16];
+ memset(header, 0, sizeof(header));
+ memcpy(header, cases[i].magic, 4);
+
+ CHECK_EQ((int)CompressionManager::getCompressionType(header, sizeof(header)),
+ (int)cases[i].type);
+ CHECK(CompressionManager::isDataCompressed(header, sizeof(header)) != 0);
+ }
+}
+
+TEST(compression_type_rejects_junk)
+{
+ char header[16];
+ memset(header, 0, sizeof(header));
+
+ memcpy(header, "ZLA\0", 4);
+ CHECK_EQ((int)CompressionManager::getCompressionType(header, sizeof(header)),
+ (int)COMPRESSION_NONE);
+
+ memcpy(header, "plain text, not a header", 16);
+ CHECK_EQ((int)CompressionManager::getCompressionType(header, sizeof(header)),
+ (int)COMPRESSION_NONE);
+ CHECK(!CompressionManager::isDataCompressed(header, sizeof(header)));
+
+ /* The magic is only checked when there is a full 8-byte header to check;
+ anything shorter is uncompressed by definition. */
+ memcpy(header, "EAR\0", 4);
+ for (int len = 0; len < 8; ++len)
+ {
+ CHECK_EQ((int)CompressionManager::getCompressionType(header, len),
+ (int)COMPRESSION_NONE);
+ CHECK(!CompressionManager::isDataCompressed(header, len));
+ }
+ CHECK_EQ((int)CompressionManager::getCompressionType(header, 8),
+ (int)COMPRESSION_REFPACK);
+}
+
+TEST(compression_preferred_is_refpack)
+{
+ /* Everything that writes a .sav leans on this; if it ever changes, the
+ corresponding decompress path has to have been verified first. */
+ CHECK_EQ((int)CompressionManager::getPreferredCompression(), (int)COMPRESSION_REFPACK);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Size estimators
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(max_compressed_size_leaves_room_for_the_header)
+{
+ for (int c = 0; c < CODEC_COUNT; ++c)
+ {
+ int est = CompressionManager::getMaxCompressedSize(1024, CODECS[c].type);
+ /* Every codec prefixes an 8-byte magic + length header. */
+ CHECK(est >= 1024 + 8);
+ }
+
+ /* COMPRESSION_NONE has no encoder, so it has no estimate either. */
+ CHECK_EQ(CompressionManager::getMaxCompressedSize(1024, COMPRESSION_NONE), 0);
+}
+
+TEST(uncompressed_size_reads_the_header_field)
+{
+ enum { SRC_LEN = 8192 };
+ static char src[SRC_LEN];
+ fill_text(src, SRC_LEN, 0);
+
+ for (int c = 0; c < CODEC_COUNT; ++c)
+ {
+ int max_out = CompressionManager::getMaxCompressedSize(SRC_LEN, CODECS[c].type);
+ char *packed = (char *)malloc(max_out);
+
+ int packed_len = CompressionManager::compressData(CODECS[c].type, src, SRC_LEN,
+ packed, max_out);
+ CHECK(packed_len > 0);
+ CHECK_EQ(CompressionManager::getUncompressedSize(packed, packed_len), (int)SRC_LEN);
+ free(packed);
+ }
+}
+
+TEST(uncompressed_size_passes_through_plain_data)
+{
+ char plain[64];
+ memset(plain, 'x', sizeof(plain));
+
+ /* No magic -> the buffer is its own uncompressed form. */
+ CHECK_EQ(CompressionManager::getUncompressedSize(plain, sizeof(plain)), (int)sizeof(plain));
+
+ /* Too short to even hold a header. */
+ CHECK_EQ(CompressionManager::getUncompressedSize(plain, 4), 4);
+ CHECK_EQ(CompressionManager::getUncompressedSize(plain, 0), 0);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Round trips
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(every_codec_round_trips_text)
+{
+ enum { SRC_LEN = 64 * 1024 };
+ static char src[SRC_LEN];
+ static char back[SRC_LEN];
+ fill_text(src, SRC_LEN, 0);
+
+ for (int c = 0; c < CODEC_COUNT; ++c)
+ {
+ int max_out = CompressionManager::getMaxCompressedSize(SRC_LEN, CODECS[c].type);
+ char *packed = (char *)malloc(max_out);
+
+ int packed_len = CompressionManager::compressData(CODECS[c].type, src, SRC_LEN,
+ packed, max_out);
+ CHECK(packed_len > 0);
+ CHECK(packed_len <= max_out);
+
+ /* The header the encoder stamped has to name the codec back. */
+ CHECK_EQ((int)CompressionManager::getCompressionType(packed, packed_len),
+ (int)CODECS[c].type);
+
+ memset(back, 0, SRC_LEN);
+ int back_len = CompressionManager::decompressData(packed, packed_len, back, SRC_LEN);
+ CHECK_EQ(back_len, (int)SRC_LEN);
+ CHECK_MEM(src, back, SRC_LEN);
+
+ free(packed);
+ }
+}
+
+TEST(every_codec_round_trips_awkward_sizes)
+{
+ /* 1 byte, either side of the 8-byte header, and a couple of odd sizes.
+ These are where getMaxCompressedSize used to under-estimate: RefPack,
+ BTree and Huff all emit more than uncompressedLen+8 for tiny inputs, so
+ the old estimate handed the encoders a buffer they wrote straight past. */
+ static const int SIZES[] = { 1, 2, 3, 4, 7, 8, 9, 63, 64, 65, 1000, 4097 };
+ static const int SIZE_COUNT = (int)(sizeof(SIZES) / sizeof(SIZES[0]));
+
+ char src[4097];
+ char back[4097];
+
+ for (int s = 0; s < SIZE_COUNT; ++s)
+ {
+ int len = SIZES[s];
+ fill_text(src, len, s);
+
+ for (int c = 0; c < CODEC_COUNT; ++c)
+ {
+ /* NoxLZH refuses anything under four bytes - see the dedicated
+ test below. */
+ if (CODECS[c].type == COMPRESSION_NOXLZH && len < 4)
+ continue;
+
+ int max_out = CompressionManager::getMaxCompressedSize(len, CODECS[c].type);
+ char *packed = (char *)malloc(max_out);
+
+ int packed_len = CompressionManager::compressData(CODECS[c].type, src, len,
+ packed, max_out);
+ CHECK(packed_len > 0);
+ CHECK(packed_len <= max_out);
+
+ memset(back, 0, sizeof(back));
+ int back_len = CompressionManager::decompressData(packed, packed_len, back, len);
+ CHECK_EQ(back_len, len);
+ CHECK_MEM(src, back, len);
+
+ free(packed);
+ }
+ }
+}
+
+TEST(noxlzh_refuses_inputs_under_four_bytes)
+{
+ /* LZHL's block header needs four bytes to describe; below that
+ CompressMemory just returns false and compressData reports 0. Callers
+ have to be ready to store the payload uncompressed. */
+ char src[8];
+ char packed[256];
+ fill_text(src, sizeof(src), 0);
+
+ for (int len = 1; len < 4; ++len)
+ CHECK_EQ(CompressionManager::compressData(COMPRESSION_NOXLZH, src, len,
+ packed, sizeof(packed)), 0);
+
+ CHECK(CompressionManager::compressData(COMPRESSION_NOXLZH, src, 4,
+ packed, sizeof(packed)) > 0);
+}
+
+TEST(max_compressed_size_covers_adversarial_payloads)
+{
+ /* The estimate is the only bound the EAC encoders get - they take no
+ destination length at all - so it has to hold for payloads that do not
+ compress. A canary past the estimate catches an encoder that writes
+ further than it promised. */
+ enum { SRC_LEN = 32 * 1024, CANARY = 256 };
+ static unsigned char src[SRC_LEN];
+
+ unsigned state = 0xdeadbeefu;
+ for (int i = 0; i < SRC_LEN; ++i)
+ {
+ state = state * 1664525u + 1013904223u;
+ /* Skewed distribution: the shape that makes Huffman codes longest. */
+ src[i] = (unsigned char)(((state >> 24) & 0x0f) ? 0 : (state >> 16));
+ }
+
+ for (int c = 0; c < CODEC_COUNT; ++c)
+ {
+ int max_out = CompressionManager::getMaxCompressedSize(SRC_LEN, CODECS[c].type);
+ unsigned char *packed = (unsigned char *)malloc(max_out + CANARY);
+ memset(packed + max_out, 0xcd, CANARY);
+
+ int packed_len = CompressionManager::compressData(CODECS[c].type, src, SRC_LEN,
+ packed, max_out);
+ CHECK(packed_len > 0);
+ CHECK(packed_len <= max_out);
+
+ for (int i = 0; i < CANARY; ++i)
+ CHECK_EQ((int)packed[max_out + i], 0xcd);
+
+ free(packed);
+ }
+}
+
+TEST(every_codec_round_trips_a_pure_run)
+{
+ enum { SRC_LEN = 16 * 1024 };
+ static char src[SRC_LEN];
+ static char back[SRC_LEN];
+ memset(src, 0, SRC_LEN);
+
+ for (int c = 0; c < CODEC_COUNT; ++c)
+ {
+ int max_out = CompressionManager::getMaxCompressedSize(SRC_LEN, CODECS[c].type);
+ char *packed = (char *)malloc(max_out);
+
+ int packed_len = CompressionManager::compressData(CODECS[c].type, src, SRC_LEN,
+ packed, max_out);
+ CHECK(packed_len > 0);
+ /* 16K of one byte must actually shrink under every one of these. */
+ CHECK(packed_len < SRC_LEN / 4);
+
+ memset(back, 1, SRC_LEN);
+ CHECK_EQ(CompressionManager::decompressData(packed, packed_len, back, SRC_LEN),
+ (int)SRC_LEN);
+ CHECK_MEM(src, back, SRC_LEN);
+
+ free(packed);
+ }
+}
+
+TEST(zlib_round_trips_incompressible_noise)
+{
+ /* Only the ZLib levels publish a real worst-case bound (n*1.1+12+8); the
+ others "guess" at n+8, so noise is not safe to hand them. */
+ enum { SRC_LEN = 8192 };
+ static unsigned char src[SRC_LEN];
+ static unsigned char back[SRC_LEN];
+
+ unsigned state = 0x12345678u;
+ for (int i = 0; i < SRC_LEN; ++i)
+ {
+ state = state * 1664525u + 1013904223u;
+ src[i] = (unsigned char)(state >> 24);
+ }
+
+ for (int level = COMPRESSION_ZLIB1; level <= COMPRESSION_ZLIB9; ++level)
+ {
+ CompressionType type = (CompressionType)level;
+ int max_out = CompressionManager::getMaxCompressedSize(SRC_LEN, type);
+ char *packed = (char *)malloc(max_out);
+
+ int packed_len = CompressionManager::compressData(type, src, SRC_LEN, packed, max_out);
+ CHECK(packed_len > 0);
+ CHECK(packed_len <= max_out);
+
+ memset(back, 0, SRC_LEN);
+ CHECK_EQ(CompressionManager::decompressData(packed, packed_len, back, SRC_LEN),
+ (int)SRC_LEN);
+ CHECK_MEM(src, back, SRC_LEN);
+
+ free(packed);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Failure paths
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(compress_refuses_a_destination_too_small_for_the_header)
+{
+ char src[64];
+ char dest[64];
+ fill_text(src, sizeof(src), 0);
+
+ for (int destLen = 0; destLen < 8; ++destLen)
+ {
+ for (int c = 0; c < CODEC_COUNT; ++c)
+ CHECK_EQ(CompressionManager::compressData(CODECS[c].type, src, sizeof(src),
+ dest, destLen), 0);
+ }
+}
+
+TEST(compress_refuses_an_unknown_codec)
+{
+ char src[64];
+ char dest[256];
+ fill_text(src, sizeof(src), 0);
+
+ /* COMPRESSION_NONE has no encoder branch, so it falls through to 0. */
+ CHECK_EQ(CompressionManager::compressData(COMPRESSION_NONE, src, sizeof(src),
+ dest, sizeof(dest)), 0);
+}
+
+TEST(decompress_refuses_short_or_unheadered_input)
+{
+ char packed[256];
+ char dest[256];
+
+ memset(packed, 0, sizeof(packed));
+ for (int srcLen = 0; srcLen < 8; ++srcLen)
+ CHECK_EQ(CompressionManager::decompressData(packed, srcLen, dest, sizeof(dest)), 0);
+
+ /* A full-length buffer with no magic is not compressed data. */
+ memcpy(packed, "just some plain bytes", 21);
+ CHECK_EQ(CompressionManager::decompressData(packed, 21, dest, sizeof(dest)), 0);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Name tables
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(name_tables_stop_at_compression_max)
+{
+ /* Both name tables are sized [COMPRESSION_MAX+1] with the rest of the
+ entries commented out, while the enum continues well past MAX. Indexing
+ them with anything above COMPRESSION_MAX reads off the end - pinned here
+ so the bound is documented rather than rediscovered. */
+ CHECK_EQ((int)COMPRESSION_MAX, (int)COMPRESSION_REFPACK);
+
+ CHECK_STR(CompressionManager::getCompressionNameByType(COMPRESSION_NONE), "No compression");
+ CHECK_STR(CompressionManager::getCompressionNameByType(COMPRESSION_REFPACK), "RefPack");
+
+ CHECK_STR(CompressionManager::getDecompressionNameByType(COMPRESSION_NONE), "d_None");
+ CHECK_STR(CompressionManager::getDecompressionNameByType(COMPRESSION_REFPACK), "d_RefPack");
+}
diff --git a/GeneralsMD/Code/Tests/test_debug.cpp b/GeneralsMD/Code/Tests/test_debug.cpp
new file mode 100644
index 000000000..5bb599cd3
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_debug.cpp
@@ -0,0 +1,848 @@
+/*
+ * Tests for the debug library.
+ *
+ * The module is a process-wide singleton wired up from the CRT static
+ * initialiser table, so there is nothing to construct: linking it is the setup.
+ * Two extension points make the whole thing observable from a test:
+ *
+ * - a DebugIOInterface registered with Debug::AddIOFactory captures every
+ * byte the module writes,
+ * - a DebugCmdInterface registered with Debug::AddCommands is handed the
+ * Debug& itself, which is the only way to reach the output stream in a
+ * Release build (DLOG/DASSERT compile to nothing without HAS_LOGS).
+ *
+ * DebugGetDefaultCommands lives in its own translation unit precisely so a host
+ * program can override it; this file does, which both wires the capture class
+ * up at startup and exercises the empty-line handling of the loop that consumes
+ * it. The stock implementation therefore cannot be tested here - it returns
+ * the literal "!debug.io flat add" and has no logic.
+ *
+ * Deliberately NOT covered: the con/net/ods/flat I/O classes (window, named
+ * pipe, OutputDebugString, log files), DebugStackwalk (needs dbghelp and real
+ * frames), the exception filter, and debug.exit (it calls exit(1)).
+ */
+#include "test_harness.h"
+
+#include <string>
+#include <vector>
+#include <stdlib.h>
+
+#include "debug.h"
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Capture I/O class
+///////////////////////////////////////////////////////////////////////////////
+
+static std::string captured;
+static std::string captured_source;
+static int captured_type = -1;
+static int flush_signals = 0;
+
+class CaptureIO : public DebugIOInterface
+{
+public:
+ static DebugIOInterface *Create(void) { return new CaptureIO; }
+
+ virtual int Read(char * /*buf*/, int /*maxchar*/) { return 0; }
+
+ virtual void Write(StringType type, const char *src, const char *str)
+ {
+ if (!str) {
+ /* NULL means "flush what you have", not "write nothing". */
+ ++flush_signals;
+ return;
+ }
+ captured += str;
+ captured_source = src ? src : "";
+ captured_type = int(type);
+ }
+
+ virtual void EmergencyFlush(void) {}
+ virtual void Execute(Debug & /*dbg*/, const char * /*cmd*/, bool /*structured*/,
+ unsigned /*argn*/, const char * const * /*argv*/) {}
+ virtual void Delete(void) { delete this; }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Test command group
+///////////////////////////////////////////////////////////////////////////////
+
+static std::string last_cmd;
+static int last_mode = -1;
+static std::vector<std::string> last_args;
+static int execute_calls = 0;
+static int startup_calls = 0;
+
+class TestCmds : public DebugCmdInterface
+{
+public:
+ virtual bool Execute(Debug &dbg, const char *cmd, CommandMode cmdmode,
+ unsigned argn, const char * const *argv);
+ virtual void Delete(void) { delete this; }
+};
+
+bool TestCmds::Execute(Debug &dbg, const char *cmd, CommandMode cmdmode,
+ unsigned argn, const char * const *argv)
+{
+ ++execute_calls;
+ last_cmd = cmd;
+ last_mode = int(cmdmode);
+ last_args.clear();
+ for (unsigned i = 0; i < argn; ++i) {
+ last_args.push_back(argv[i]);
+ }
+
+ if (!strcmp(cmd, "startup")) {
+ ++startup_calls;
+ return true;
+ }
+
+ if (!strcmp(cmd, "noop")) {
+ return true;
+ }
+
+ if (!strcmp(cmd, "echo")) {
+ for (unsigned i = 0; i < argn; ++i) {
+ if (i) dbg << "|";
+ dbg << argv[i];
+ }
+ return true;
+ }
+
+ if (!strcmp(cmd, "repeat")) {
+ Debug::RepeatChar rc('=', argn ? atoi(argv[0]) : 0);
+ dbg << rc;
+ return true;
+ }
+
+ if (!strcmp(cmd, "fmt")) {
+ Debug::Format f("[%s:%d]", argn ? argv[0] : "", argn > 1 ? atoi(argv[1]) : 0);
+ dbg << f;
+ return true;
+ }
+
+ if (!strcmp(cmd, "fmtlong")) {
+ /* 600 characters through a 512 byte buffer. */
+ std::string huge(600, 'F');
+ Debug::Format f("%s", huge.c_str());
+ dbg << f;
+ return true;
+ }
+
+ if (!strcmp(cmd, "nul")) {
+ dbg << (const char *)0;
+ return true;
+ }
+
+ if (!strcmp(cmd, "empty")) {
+ /* An empty string returns early, so it must not consume the width. */
+ Debug::Width w(4);
+ dbg << w << "" << "ab";
+ return true;
+ }
+
+ if (!strcmp(cmd, "ints")) {
+ dbg << int(-42) << " " << unsigned(4000000000u) << " " << long(-7L)
+ << " " << (unsigned long)(0xFFFFFFFFul) << " " << short(-3)
+ << " " << (unsigned short)(65535) << " " << (__int64)(-5000000000i64)
+ << " " << (unsigned __int64)(10000000000ui64) << " " << true << " " << false;
+ return true;
+ }
+
+ if (!strcmp(cmd, "radix")) {
+ Debug::Hex hex;
+ Debug::Dec dec;
+ Debug::Bin bin;
+ dbg << hex << 255 << " " << bin << 5 << " " << dec << 255;
+ return true;
+ }
+
+ if (!strcmp(cmd, "radix_sticky")) {
+ /* The radix is module state, so it survives across insertions. */
+ Debug::Hex hex;
+ dbg << hex << 255 << " " << 16;
+ return true;
+ }
+
+ if (!strcmp(cmd, "width")) {
+ Debug::Width w(6);
+ Debug::Width w2(6);
+ dbg << w << "ab" << "cd" << w2 << "ef";
+ return true;
+ }
+
+ if (!strcmp(cmd, "fill")) {
+ Debug::FillChar f('0');
+ Debug::FillChar back(' ');
+ Debug::Width w(5);
+ dbg << f << w << "42" << back;
+ return true;
+ }
+
+ if (!strcmp(cmd, "negwidth")) {
+ Debug::Width w(-5);
+ dbg << w << "ab";
+ return true;
+ }
+
+ if (!strcmp(cmd, "widthprefix")) {
+ /* The radix prefix is written straight to the buffer, so the padding
+ lands between the prefix and the digits. */
+ Debug::Hex hex;
+ Debug::Dec dec;
+ Debug::Width w(6);
+ dbg << hex << w << 255 << dec;
+ return true;
+ }
+
+ if (!strcmp(cmd, "floats")) {
+ dbg << 1.5f << " " << 2.25;
+ return true;
+ }
+
+ if (!strcmp(cmd, "ptr")) {
+ dbg << (const void *)0;
+ return true;
+ }
+
+ if (!strcmp(cmd, "hresult")) {
+ dbg << Debug::HResult(0x80004005L);
+ return true;
+ }
+
+ if (!strcmp(cmd, "mem")) {
+ static const char blob[] = "ABCDEFGHIJKLMNOP";
+ dbg << Debug::MemDump::CharRel(blob, 16);
+ return true;
+ }
+
+ if (!strcmp(cmd, "memraw")) {
+ static const char blob[] = "ABCD";
+ dbg << Debug::MemDump::RawRel(blob, 4);
+ return true;
+ }
+
+ /* Everything else, "help" included, is unknown - which is what makes the
+ module's own error messages reachable. */
+ return false;
+}
+
+/* Both run as ordinary static initialisers, i.e. after Debug::PreStaticInit
+ (.CRT$XCB) and before Debug::PostStaticInit (.CRT$XCY). */
+static bool registered_io = Debug::AddIOFactory("capture", "test capture", CaptureIO::Create);
+static bool registered_cmds = Debug::AddCommands("test", new TestCmds);
+
+/* Overrides the library's own definition. The leading, doubled and trailing
+ newlines are the point: the loop that consumes this only advanced past
+ non-empty lines, so any one of them used to hang the process before main. */
+const char *DebugGetDefaultCommands(void)
+{
+ return "\n!debug.io capture add\n\ntest.startup\n\n";
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Helpers
+///////////////////////////////////////////////////////////////////////////////
+
+static std::string run(const char *cmd)
+{
+ captured.clear();
+ captured_source.clear();
+ captured_type = -1;
+ Debug::Command(cmd);
+ return captured;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Debug::SimpleMatch
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(simplematch_literals)
+{
+ CHECK(Debug::SimpleMatch("", ""));
+ CHECK(Debug::SimpleMatch("abc", "abc"));
+ CHECK(!Debug::SimpleMatch("abc", "abd"));
+ CHECK(!Debug::SimpleMatch("abc", "ab"));
+ CHECK(!Debug::SimpleMatch("ab", "abc"));
+ CHECK(!Debug::SimpleMatch("abc", ""));
+ CHECK(!Debug::SimpleMatch("", "abc"));
+
+ /* Case sensitive, and no metacharacter other than '*'. */
+ CHECK(!Debug::SimpleMatch("ABC", "abc"));
+ CHECK(!Debug::SimpleMatch("abc", "a?c"));
+ CHECK(Debug::SimpleMatch("a?c", "a?c"));
+ CHECK(Debug::SimpleMatch("a.c", "a.c"));
+}
+
+TEST(simplematch_star)
+{
+ CHECK(Debug::SimpleMatch("abc", "*"));
+ CHECK(Debug::SimpleMatch("abc", "*c"));
+ CHECK(Debug::SimpleMatch("abc", "*bc"));
+ CHECK(Debug::SimpleMatch("abc", "*abc"));
+ CHECK(Debug::SimpleMatch("abc", "a*c"));
+ CHECK(Debug::SimpleMatch("abc", "*b*"));
+ CHECK(Debug::SimpleMatch("abcdef", "a*f"));
+ CHECK(Debug::SimpleMatch("abcdef", "*c*e*"));
+ CHECK(Debug::SimpleMatch("abcdef", "**f"));
+
+ CHECK(!Debug::SimpleMatch("abc", "*d"));
+ CHECK(!Debug::SimpleMatch("abc", "b*"));
+ CHECK(!Debug::SimpleMatch("abcdef", "*f*g"));
+}
+
+TEST(simplematch_DEFECT_star_never_matches_zero_chars_at_the_end)
+{
+ /* The loop only enters the '*' branch while there is input left, so a
+ trailing '*' with nothing to consume falls through to a plain
+ *str=='*' comparison. Every caller passes patterns from debug
+ commands, so this is pinned rather than changed. */
+ CHECK(!Debug::SimpleMatch("", "*"));
+ CHECK(!Debug::SimpleMatch("a", "a*"));
+ CHECK(!Debug::SimpleMatch("abc", "abc*"));
+
+ /* ...but a '*' with at least one character to eat works as expected. */
+ CHECK(Debug::SimpleMatch("ab", "a*"));
+ CHECK(Debug::SimpleMatch("abcd", "abc*"));
+}
+
+TEST(simplematch_realistic_log_group_patterns)
+{
+ CHECK(Debug::SimpleMatch("debug_debug", "debug_*g"));
+ CHECK(Debug::SimpleMatch("gameengine", "*engine"));
+ CHECK(Debug::SimpleMatch("w3dview.cpp", "*.cpp"));
+ CHECK(!Debug::SimpleMatch("w3dview.h", "*.cpp"));
+ CHECK(Debug::SimpleMatch("net/socket", "net/*t"));
+}
+
+TEST(simplematch_backtracking)
+{
+ /* The recursion has to retry every start position, not just the first. */
+ CHECK(Debug::SimpleMatch("aaab", "*ab"));
+ CHECK(Debug::SimpleMatch("xaxbxc", "*a*b*c"));
+ CHECK(!Debug::SimpleMatch("xaxbxc", "*c*b*a"));
+ CHECK(Debug::SimpleMatch("aaaaaaaaab", "*a*a*a*b"));
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Startup path
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(startup_ran_the_default_commands)
+{
+ /* Reaching this point at all proves the empty lines in the override did not
+ spin forever, and both non-empty lines must have executed. */
+ CHECK_EQ(startup_calls, 1);
+ CHECK(registered_io);
+ CHECK(registered_cmds);
+
+ /* If the capture class had not been added, nothing below could see output. */
+ CHECK(run("test.noop").length() > 0);
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Command dispatch and reply framing
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(command_normal_reply_framing)
+{
+ std::string out = run("test.echo a b");
+
+ CHECK_STR(out.c_str(), "> test.echo a b\na|b\n");
+ CHECK_STR(captured_source.c_str(), "test.echo");
+ CHECK_EQ(captured_type, int(DebugIOInterface::CmdReply));
+ CHECK_EQ(last_mode, int(DebugCmdInterface::Normal));
+}
+
+TEST(command_structured_reply_drops_the_prompt)
+{
+ std::string out = run("!test.echo a");
+
+ CHECK_STR(out.c_str(), "!test.echo a\na\n");
+ CHECK_STR(captured_source.c_str(), "test.echo");
+ CHECK_EQ(captured_type, int(DebugIOInterface::StructuredCmdReply));
+ CHECK_EQ(last_mode, int(DebugCmdInterface::Structured));
+}
+
+TEST(command_bang_is_only_special_at_offset_zero)
+{
+ std::string out = run("test.echo !x");
+
+ CHECK_STR(out.c_str(), "> test.echo !x\n!x\n");
+ CHECK_EQ(last_mode, int(DebugCmdInterface::Normal));
+}
+
+TEST(command_empty_produces_nothing)
+{
+ int before = execute_calls;
+
+ CHECK_STR(run("").c_str(), "");
+ CHECK_STR(run(" ").c_str(), "");
+ CHECK_EQ(execute_calls, before);
+}
+
+TEST(command_group_selection_alone_is_a_no_op)
+{
+ int before = execute_calls;
+ std::string out = run("test.");
+
+ CHECK_STR(out.c_str(), "> test.\n");
+ CHECK_EQ(execute_calls, before);
+
+ /* ...but the group sticks, so the next bare command lands in it. */
+ CHECK_STR(run("noop").c_str(), "> noop\n");
+ CHECK_EQ(execute_calls, before + 1);
+ CHECK_STR(last_cmd.c_str(), "noop");
+}
+
+TEST(command_unknown_group_is_reported)
+{
+ std::string out = run("nosuchgroup.whatever");
+
+ /* Reachable only since the two searches stopped shadowing each other. */
+ CHECK_STR(out.c_str(), "> nosuchgroup.whatever\nUnknown command group nosuchgroup\n");
+}
+
+TEST(command_unknown_command_is_reported)
+{
+ std::string out = run("test.nosuchcommand");
+
+ CHECK_STR(out.c_str(), "> test.nosuchcommand\nUnknown command\n");
+ CHECK_STR(last_cmd.c_str(), "nosuchcommand");
+}
+
+TEST(command_help_without_args_stays_silent)
+{
+ /* help is broadcast to every interface in the group and gets no error
+ message of its own when nobody answers. */
+ std::string out = run("test.help");
+
+ CHECK_STR(out.c_str(), "> test.help\n");
+}
+
+TEST(command_help_with_args_reports_the_miss)
+{
+ std::string out = run("test.help sometopic");
+
+ CHECK_STR(out.c_str(), "> test.help sometopic\nUnknown command, help not available\n");
+}
+
+TEST(command_structured_mode_suppresses_the_error_messages)
+{
+ std::string out = run("!test.nosuchcommand");
+
+ CHECK_STR(out.c_str(), "!test.nosuchcommand\n");
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Command tokenizer
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(tokenizer_splits_on_spaces_and_tabs)
+{
+ run("test.noop a b\tc \t d");
+
+ CHECK_EQ(last_args.size(), size_t(4));
+ CHECK_STR(last_args[0].c_str(), "a");
+ CHECK_STR(last_args[1].c_str(), "b");
+ CHECK_STR(last_args[2].c_str(), "c");
+ CHECK_STR(last_args[3].c_str(), "d");
+}
+
+TEST(tokenizer_does_not_treat_cr_as_whitespace)
+{
+ run("test.noop a\r");
+
+ CHECK_EQ(last_args.size(), size_t(1));
+ CHECK_STR(last_args[0].c_str(), "a\r");
+}
+
+TEST(tokenizer_quotes)
+{
+ run("test.noop \"a b\" 'c d' e");
+
+ CHECK_EQ(last_args.size(), size_t(3));
+ CHECK_STR(last_args[0].c_str(), "a b");
+ CHECK_STR(last_args[1].c_str(), "c d");
+ CHECK_STR(last_args[2].c_str(), "e");
+}
+
+TEST(tokenizer_empty_quotes_are_a_real_argument)
+{
+ run("test.noop \"\" x");
+
+ CHECK_EQ(last_args.size(), size_t(2));
+ CHECK_STR(last_args[0].c_str(), "");
+ CHECK_STR(last_args[1].c_str(), "x");
+}
+
+TEST(tokenizer_quote_inside_a_word_is_literal)
+{
+ run("test.noop a\"b c");
+
+ CHECK_EQ(last_args.size(), size_t(2));
+ CHECK_STR(last_args[0].c_str(), "a\"b");
+ CHECK_STR(last_args[1].c_str(), "c");
+}
+
+TEST(tokenizer_unterminated_quote_swallows_the_rest_of_the_line)
+{
+ run("test.noop \"a b c");
+
+ CHECK_EQ(last_args.size(), size_t(1));
+ CHECK_STR(last_args[0].c_str(), "a b c");
+}
+
+TEST(tokenizer_semicolon_ends_the_command)
+{
+ run("test.noop a ; b");
+ CHECK_EQ(last_args.size(), size_t(1));
+ CHECK_STR(last_args[0].c_str(), "a");
+
+ /* No separator needed - the semicolon terminates the token too. */
+ run("test.noop a;b");
+ CHECK_EQ(last_args.size(), size_t(1));
+ CHECK_STR(last_args[0].c_str(), "a");
+
+ /* And there is no second command: only one Execute happens. */
+ int before = execute_calls;
+ run("test.noop x ; test.noop y");
+ CHECK_EQ(execute_calls, before + 1);
+ CHECK_STR(last_args[0].c_str(), "x");
+}
+
+TEST(tokenizer_drops_arguments_past_the_fixed_array)
+{
+ /* parts[100] holds the command plus 99 arguments; the rest are dropped
+ silently, which is documented in the source as intentional. */
+ std::string cmd = "test.noop";
+ for (int i = 0; i < 150; ++i) {
+ cmd += " a";
+ }
+
+ run(cmd.c_str());
+ CHECK_EQ(last_args.size(), size_t(99));
+}
+
+TEST(tokenizer_only_the_first_dot_splits_the_group)
+{
+ run("test.noop.extra");
+
+ CHECK_STR(last_cmd.c_str(), "noop.extra");
+ /* Unknown to the handler, so it reports a miss rather than running noop. */
+ CHECK_STR(captured.c_str(), "> test.noop.extra\nUnknown command\n");
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Output stream
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(stream_null_string)
+{
+ CHECK_STR(run("test.nul").c_str(), "> test.nul\n[NULL]\n");
+}
+
+TEST(stream_empty_string_does_not_consume_the_width)
+{
+ CHECK_STR(run("test.empty").c_str(), "> test.empty\n ab\n");
+}
+
+TEST(stream_integers)
+{
+ CHECK_STR(run("test.ints").c_str(),
+ "> test.ints\n-42 4000000000 -7 4294967295 -3 65535 -5000000000 10000000000 true false\n");
+}
+
+TEST(stream_radix_prefixes)
+{
+ CHECK_STR(run("test.radix").c_str(), "> test.radix\n0xff %101 255\n");
+}
+
+TEST(stream_radix_is_sticky_until_changed)
+{
+ CHECK_STR(run("test.radix_sticky").c_str(), "> test.radix_sticky\n0xff 0x10\n");
+}
+
+TEST(stream_width_applies_to_one_insertion)
+{
+ CHECK_STR(run("test.width").c_str(), "> test.width\n abcd ef\n");
+}
+
+TEST(stream_fill_character)
+{
+ CHECK_STR(run("test.fill").c_str(), "> test.fill\n00042\n");
+}
+
+TEST(stream_negative_width_pads_nothing)
+{
+ /* The padding loop compares against an unsigned, so a negative width used
+ to wrap round into four billion fill characters. */
+ CHECK_STR(run("test.negwidth").c_str(), "> test.negwidth\nab\n");
+}
+
+TEST(stream_DEFECT_width_pads_after_the_radix_prefix)
+{
+ /* The prefix goes straight into the buffer while the digits go through the
+ width-aware path, so padding lands in the middle of the number. */
+ CHECK_STR(run("test.widthprefix").c_str(), "> test.widthprefix\n0x ff\n");
+}
+
+TEST(stream_floats)
+{
+ CHECK_STR(run("test.floats").c_str(), "> test.floats\n1.500000 2.250000\n");
+}
+
+TEST(stream_null_pointer)
+{
+ CHECK_STR(run("test.ptr").c_str(), "> test.ptr\nptr:NULL\n");
+}
+
+TEST(stream_hresult_without_translators)
+{
+ CHECK_STR(run("test.hresult").c_str(), "> test.hresult\nHResult:0x80004005\n");
+}
+
+TEST(stream_repeatchar_keeps_the_remainder)
+{
+ /* The old loop decremented before testing, so 79 came out as 70 and every
+ count below 10 after a >=10 count was lost. */
+ CHECK_STR(run("test.repeat 0").c_str(), "> test.repeat 0\n");
+ CHECK_STR(run("test.repeat 1").c_str(), "> test.repeat 1\n=\n");
+ CHECK_STR(run("test.repeat 9").c_str(), "> test.repeat 9\n=========\n");
+ CHECK_STR(run("test.repeat 10").c_str(), "> test.repeat 10\n==========\n");
+
+ std::string out = run("test.repeat 79");
+ CHECK_EQ(out.length(), strlen("> test.repeat 79\n") + 79 + 1);
+ CHECK_EQ(out.find_first_not_of('=', strlen("> test.repeat 79\n")),
+ strlen("> test.repeat 79\n") + 79);
+
+ out = run("test.repeat 25");
+ CHECK_EQ(out.length(), strlen("> test.repeat 25\n") + 25 + 1);
+
+ /* A negative count writes nothing rather than looping. */
+ CHECK_STR(run("test.repeat -3").c_str(), "> test.repeat -3\n");
+}
+
+TEST(stream_format)
+{
+ CHECK_STR(run("test.fmt abc 7").c_str(), "> test.fmt abc 7\n[abc:7]\n");
+}
+
+TEST(stream_format_truncates_and_stays_terminated)
+{
+ /* _vsnprintf writes no NUL when it fills the buffer, and m_buffer has no
+ initialiser - this used to run off the end of the object. */
+ std::string out = run("test.fmtlong");
+ std::string payload = out.substr(strlen("> test.fmtlong\n"));
+
+ CHECK_EQ(payload.length(), size_t(511 + 1));
+ CHECK_EQ(payload.find_first_not_of('F'), size_t(511));
+}
+
+TEST(stream_memdump_with_characters)
+{
+ CHECK_STR(run("test.mem").c_str(),
+ "> test.mem\n"
+ "00000000 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 ABCDEFGHIJKLMNOP\n");
+}
+
+TEST(stream_memdump_pads_a_short_line)
+{
+ /* Four bytes with 21 items per line: the rest of the row is blanks. */
+ std::string out = run("test.memraw");
+
+ CHECK_EQ(out.compare(0, strlen("> test.memraw\n00000000 41 42 43 44 "),
+ "> test.memraw\n00000000 41 42 43 44 "), 0);
+ CHECK_EQ(out.find_first_not_of(' ', strlen("> test.memraw\n00000000 41 42 43 44")),
+ out.length() - 1);
+ CHECK_EQ(out[out.length()-1], '\n');
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// HRESULT translators
+///////////////////////////////////////////////////////////////////////////////
+
+static std::string translator_log;
+
+static bool translator_low(Debug &dbg, long hresult, void *user)
+{
+ translator_log += "low";
+ if (hresult != 0x80004005L) return false;
+ dbg << "LOW" << (const char *)user;
+ return true;
+}
+
+static bool translator_high(Debug &dbg, long hresult, void *user)
+{
+ translator_log += "high";
+ if (hresult != 0x80004005L) return false;
+ dbg << "HIGH" << (const char *)user;
+ return true;
+}
+
+TEST(hresult_translators_run_in_priority_order)
+{
+ translator_log.clear();
+
+ Debug::AddHResultTranslator(1, translator_low, (void *)"1");
+ Debug::AddHResultTranslator(10, translator_high, (void *)"2");
+
+ CHECK_STR(run("test.hresult").c_str(), "> test.hresult\nHIGH2\n");
+ CHECK_STR(translator_log.c_str(), "high");
+
+ Debug::RemoveHResultTranslator(translator_high, (void *)"2");
+ translator_log.clear();
+ CHECK_STR(run("test.hresult").c_str(), "> test.hresult\nLOW1\n");
+ CHECK_STR(translator_log.c_str(), "low");
+
+ Debug::RemoveHResultTranslator(translator_low, (void *)"1");
+ CHECK_STR(run("test.hresult").c_str(), "> test.hresult\nHResult:0x80004005\n");
+}
+
+TEST(hresult_removing_an_unregistered_translator_is_harmless)
+{
+ Debug::RemoveHResultTranslator(translator_low, (void *)"nope");
+ CHECK_STR(run("test.hresult").c_str(), "> test.hresult\nHResult:0x80004005\n");
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// The built-in 'debug' command group
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(debug_group_help_lists_commands)
+{
+ std::string out = run("debug.help");
+
+ CHECK(out.find("alwaysflush") != std::string::npos);
+ CHECK(out.find("timestamp") != std::string::npos);
+ CHECK(out.find("io") != std::string::npos);
+ CHECK(out.find("list") != std::string::npos);
+}
+
+TEST(debug_group_io_lists_only_the_active_classes)
+{
+ std::string out = run("debug.io");
+
+ CHECK(out.find("Active:") != std::string::npos);
+ CHECK(out.find("capture (test capture)") != std::string::npos);
+ /* Registered by PostStaticInit, but none of them was ever added. */
+ CHECK(out.find("flat") == std::string::npos);
+ CHECK(out.find("ods") == std::string::npos);
+}
+
+TEST(debug_group_io_question_mark_lists_every_registered_class)
+{
+ std::string out = run("debug.io ?");
+
+ CHECK(out.find("Possible:") != std::string::npos);
+ CHECK(out.find("capture") != std::string::npos);
+ CHECK(out.find("flat") != std::string::npos);
+ CHECK(out.find("con") != std::string::npos);
+ CHECK(out.find("net") != std::string::npos);
+ CHECK(out.find("ods") != std::string::npos);
+}
+
+TEST(debug_group_unknown_io_class_is_reported)
+{
+ std::string out = run("debug.io nosuchclass add");
+
+ CHECK(out.find("Unknown I/O class") != std::string::npos);
+}
+
+TEST(debug_group_alwaysflush_toggles)
+{
+ int before = flush_signals;
+
+ CHECK(run("debug.alwaysflush +").find("alwaysflush") != std::string::npos);
+ run("test.noop");
+ CHECK(flush_signals > before);
+
+ before = flush_signals;
+ run("debug.alwaysflush -");
+ run("test.noop");
+ CHECK_EQ(flush_signals, before);
+}
+
+TEST(debug_group_flag_without_a_sign_only_reports)
+{
+ run("debug.alwaysflush -");
+ int before = flush_signals;
+
+ /* Only '+' and '-' change anything; anything else just prints the state. */
+ CHECK(run("debug.alwaysflush x").find("alwaysflush") != std::string::npos);
+ run("test.noop");
+ CHECK_EQ(flush_signals, before);
+
+ CHECK(run("debug.alwaysflush").find("alwaysflush") != std::string::npos);
+ run("test.noop");
+ CHECK_EQ(flush_signals, before);
+}
+
+/* Kept last: it changes the shape of every reply while it is on. */
+TEST(debug_group_timestamp_prefixes_every_line)
+{
+ run("debug.timestamp +");
+
+ std::string out = run("test.echo a");
+ run("debug.timestamp -");
+
+ CHECK_EQ(out[0], '[');
+ CHECK(out.find("] > test.echo a\n") != std::string::npos);
+ /* Each line gets its own stamp, so the payload carries a second one. */
+ CHECK_EQ(out.find('['), size_t(0));
+ CHECK(out.rfind('[') > size_t(0));
+
+ /* And the shape is back to normal afterwards. */
+ CHECK_STR(run("test.echo a").c_str(), "> test.echo a\na\n");
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Internal allocator
+///////////////////////////////////////////////////////////////////////////////
+
+void *DebugAllocMemory(unsigned numBytes);
+void *DebugReAllocMemory(void *oldPtr, unsigned newSize);
+void DebugFreeMemory(void *ptr);
+
+TEST(debug_memory_alloc_and_free)
+{
+ void *p = DebugAllocMemory(64);
+ CHECK(p != 0);
+ memset(p, 0xAB, 64);
+ CHECK_EQ(((unsigned char *)p)[63], (unsigned char)0xAB);
+ DebugFreeMemory(p);
+
+ /* Freeing NULL is a no-op rather than a crash. */
+ DebugFreeMemory(0);
+}
+
+TEST(debug_memory_realloc_truth_table)
+{
+ CHECK_EQ(DebugReAllocMemory(0, 0), (void *)0);
+
+ void *p = DebugReAllocMemory(0, 16);
+ CHECK(p != 0);
+
+ memcpy(p, "0123456789abcde", 16);
+ p = DebugReAllocMemory(p, 4096);
+ CHECK(p != 0);
+ /* Growing keeps the contents, whichever of the two paths it took. */
+ CHECK_STR((const char *)p, "0123456789abcde");
+
+ p = DebugReAllocMemory(p, 8);
+ CHECK(p != 0);
+ CHECK_MEM(p, "01234567", 8);
+
+ CHECK_EQ(DebugReAllocMemory(p, 0), (void *)0);
+}
diff --git a/GeneralsMD/Code/Tests/test_harness.h b/GeneralsMD/Code/Tests/test_harness.h
new file mode 100644
index 000000000..eb0f5e358
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_harness.h
@@ -0,0 +1,65 @@
+/*
+ * Minimal self-registering test harness.
+ *
+ * No framework on purpose (see CLAUDE.md): a test is one TEST(name) { ... }
+ * block, registration happens at static-init time, and test_main.cpp supplies
+ * main(). Every binary links this plus the lib under test and is registered
+ * with CTest, so `ctest -C Release` runs the lot.
+ *
+ * TEST(vector3_dot) {
+ * CHECK_NEAR(Vector3::Dot_Product(a, b), 32.0f, 1e-5f);
+ * }
+ */
+#ifndef TEST_HARNESS_H
+#define TEST_HARNESS_H
+
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+void test_check(bool ok, const char *expr, const char *file, int line);
+void test_register(const char *name, void (*fn)(void));
+
+struct TestRegistrar
+{
+ TestRegistrar(const char *name, void (*fn)(void)) { test_register(name, fn); }
+};
+
+#define TEST(name) \
+ static void name(void); \
+ static TestRegistrar test_reg_##name(#name, name); \
+ static void name(void)
+
+#define CHECK(expr) test_check(!!(expr), #expr, __FILE__, __LINE__)
+
+#define CHECK_EQ(a, b) \
+ test_check((a) == (b), #a " == " #b, __FILE__, __LINE__)
+
+#define CHECK_NE(a, b) \
+ test_check((a) != (b), #a " != " #b, __FILE__, __LINE__)
+
+/* Absolute tolerance. Fine for the value ranges this codebase deals in
+ (unit vectors, world coordinates in the hundreds). */
+#define CHECK_NEAR(a, b, eps) \
+ test_check(fabs(double(a) - double(b)) <= double(eps), \
+ #a " ~= " #b, __FILE__, __LINE__)
+
+/* The casts matter: StringClass converts to const char*, but it also has an
+ operator!=(const char*) that would take over the null check and call
+ _tcscmp(buffer, NULL). It goes through a function rather than a macro body
+ so each side is evaluated exactly once - the macro used to name (a) twice,
+ which ran any side effect in the argument twice. */
+inline void test_check_str(const char *a, const char *b, const char *expr,
+ const char *file, int line)
+{
+ test_check(a != 0 && b != 0 && !strcmp(a, b), expr, file, line);
+}
+
+#define CHECK_STR(a, b) \
+ test_check_str((const char *)(a), (const char *)(b), \
+ #a " streq " #b, __FILE__, __LINE__)
+
+#define CHECK_MEM(a, b, n) \
+ test_check(!memcmp((a), (b), (n)), #a " memeq " #b, __FILE__, __LINE__)
+
+#endif /* TEST_HARNESS_H */
diff --git a/GeneralsMD/Code/Tests/test_main.cpp b/GeneralsMD/Code/Tests/test_main.cpp
new file mode 100644
index 000000000..fd38d593a
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_main.cpp
@@ -0,0 +1,97 @@
+/*
+ * Runner for the micro-harness in test_harness.h. One of these is linked into
+ * every test binary; the tests themselves register from static initialisers.
+ *
+ * Exit code is the number of failed checks (capped at 125 so it stays a valid
+ * process exit status), which is what CTest keys off.
+ */
+#include "test_harness.h"
+
+#include <stdlib.h>
+
+namespace
+{
+ /* Fixed-capacity registry: static-init order is unspecified, so a
+ std::vector here would risk being constructed after the first
+ registrar runs. A POD array is zero-initialised before any of it. */
+ const int MAX_TESTS = 512;
+
+ struct Entry
+ {
+ const char *name;
+ void (*fn)(void);
+ };
+
+ Entry g_tests[MAX_TESTS];
+ int g_numTests;
+
+ const char *g_currentTest;
+ int g_currentFails;
+ int g_totalChecks;
+ int g_totalFails;
+ int g_failedTests;
+}
+
+void test_register(const char *name, void (*fn)(void))
+{
+ if (g_numTests >= MAX_TESTS)
+ {
+ fprintf(stderr, "test registry full, raise MAX_TESTS\n");
+ exit(1);
+ }
+ g_tests[g_numTests].name = name;
+ g_tests[g_numTests].fn = fn;
+ ++g_numTests;
+}
+
+void test_check(bool ok, const char *expr, const char *file, int line)
+{
+ ++g_totalChecks;
+ if (ok)
+ return;
+
+ ++g_currentFails;
+ ++g_totalFails;
+
+ /* Strip the directory so failures stay readable in a narrow console. */
+ const char *base = strrchr(file, '\\');
+ if (!base)
+ base = strrchr(file, '/');
+ printf(" FAIL %s:%d %s\n", base ? base + 1 : file, line, expr);
+}
+
+int main(int argc, char *argv[])
+{
+ /* Optional substring filter, so a single failing test can be re-run alone:
+ test_wwlib.exe crc */
+ const char *filter = (argc > 1) ? argv[1] : 0;
+ int ran = 0;
+
+ for (int i = 0; i < g_numTests; ++i)
+ {
+ if (filter && !strstr(g_tests[i].name, filter))
+ continue;
+
+ g_currentTest = g_tests[i].name;
+ g_currentFails = 0;
+ ++ran;
+
+ g_tests[i].fn();
+
+ if (g_currentFails)
+ {
+ ++g_failedTests;
+ printf("FAIL %s (%d)\n", g_currentTest, g_currentFails);
+ }
+ }
+
+ printf("%d tests, %d checks, %d failed\n", ran, g_totalChecks, g_totalFails);
+
+ if (!ran)
+ {
+ printf("no tests matched\n");
+ return 1;
+ }
+
+ return g_failedTests > 125 ? 125 : g_failedTests;
+}
diff --git a/GeneralsMD/Code/Tests/test_support.cpp b/GeneralsMD/Code/Tests/test_support.cpp
new file mode 100644
index 000000000..fce82d972
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_support.cpp
@@ -0,0 +1,184 @@
+/*
+ * Tests for the two remaining leaf support libraries, benchmark and
+ * eabrowserdispatch. Neither has enough surface to deserve a binary of its
+ * own: one is a stub with a single entry point, the other is MIDL output.
+ *
+ * What is actually worth pinning here:
+ *
+ * - RunBenchmark's contract with its one caller (W3DShaderManager ->
+ * GameLODManager): all three indices written, NULLs tolerated, 0 returned.
+ * The values themselves are the calibration knob documented in
+ * benchmark_stub.c, so they are checked as "positive and equal", not as
+ * magic numbers a future tuning pass would have to come and edit here.
+ * - that the MIDL step really produced the GUIDs from BrowserDispatch.idl and
+ * that the generated interface is callable through its vtable, which is how
+ * GameEngine's WebBrowser.h uses it. A silently misgenerated header would
+ * otherwise only show up in Phase 4.
+ *
+ * Not covered: gamespy. It is vendored third party (TheSuperHackers/GamespySDK)
+ * and ships its own test suite, which the port turns off with GS_BUILD_TESTS=OFF
+ * because those tests want a live GameSpy backend that has been dead since 2014.
+ */
+#include "test_harness.h"
+
+#include <windows.h>
+
+#include "benchmark.h"
+#include "EABrowserDispatch/BrowserDispatch.h"
+
+
+///////////////////////////////////////////////////////////////////////////////
+// benchmark
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(benchmark_fills_in_every_result)
+{
+ float f = -1.0f, i = -1.0f, m = -1.0f;
+
+ CHECK_EQ(RunBenchmark(0, 0, &f, &i, &m), 0);
+
+ /* GameLOD only ever takes ratios of these, so what matters is that they are
+ usable numbers - not which ones. */
+ CHECK(f > 0.0f);
+ CHECK(i > 0.0f);
+ CHECK(m > 0.0f);
+ CHECK_EQ(f, i);
+ CHECK_EQ(i, m);
+}
+
+TEST(benchmark_is_deterministic)
+{
+ float f1 = 0.0f, i1 = 0.0f, m1 = 0.0f;
+ float f2 = 0.0f, i2 = 0.0f, m2 = 0.0f;
+
+ RunBenchmark(0, 0, &f1, &i1, &m1);
+ RunBenchmark(0, 0, &f2, &i2, &m2);
+
+ /* The stub stands in for a measurement, so this pins the substitution: two
+ calls must agree, which the real BYTEmark would not have guaranteed. */
+ CHECK_EQ(f1, f2);
+ CHECK_EQ(i1, i2);
+ CHECK_EQ(m1, m2);
+}
+
+TEST(benchmark_tolerates_null_results)
+{
+ float f = 0.0f;
+
+ CHECK_EQ(RunBenchmark(0, 0, 0, 0, 0), 0);
+ CHECK_EQ(RunBenchmark(0, 0, &f, 0, 0), 0);
+ CHECK(f > 0.0f);
+}
+
+TEST(benchmark_ignores_its_argv)
+{
+ char arg0[] = "whatever";
+ char *argv[] = { arg0, 0 };
+ float f = 0.0f, i = 0.0f, m = 0.0f;
+ float f2 = 0.0f, i2 = 0.0f, m2 = 0.0f;
+
+ RunBenchmark(0, 0, &f, &i, &m);
+ RunBenchmark(1, argv, &f2, &i2, &m2);
+
+ CHECK_EQ(f, f2);
+ CHECK_EQ(i, i2);
+ CHECK_EQ(m, m2);
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// eabrowserdispatch
+///////////////////////////////////////////////////////////////////////////////
+
+/* The two UUIDs written out in BrowserDispatch.idl, spelled independently of
+ the generated _i.c so that a regenerated-from-a-different-idl mismatch shows
+ up as a failure rather than as agreement with itself. */
+static const GUID idl_libid =
+ { 0xC92D8250, 0xA628, 0x4CE5, { 0x82, 0x3F, 0x1A, 0x1F, 0x11, 0x6E, 0xFC, 0xC9 } };
+static const GUID idl_iid =
+ { 0xBC834510, 0xC5BC, 0x4B90, { 0x8C, 0x9A, 0x0E, 0x4B, 0x19, 0x98, 0x79, 0x6F } };
+
+TEST(browserdispatch_guids_match_the_idl)
+{
+ CHECK(IsEqualGUID(LIBID_BROWSERDISPATCHLib, idl_libid));
+ CHECK(IsEqualGUID(IID_IBrowserDispatch, idl_iid));
+
+ /* Different objects, so a copy-paste in the .idl would be caught too. */
+ CHECK(!IsEqualGUID(LIBID_BROWSERDISPATCHLib, IID_IBrowserDispatch));
+}
+
+TEST(browserdispatch_guids_come_from_the_library)
+{
+ /* MIDL emits the GUIDs as selectany data in BrowserDispatch_i.c, i.e. in the
+ eabrowserdispatch archive - the header only declares them. Taking their
+ address is what makes this a link-time check that the archive is really on
+ the line and not quietly empty. */
+ CHECK(&IID_IBrowserDispatch != 0);
+ CHECK(&LIBID_BROWSERDISPATCHLib != 0);
+}
+
+/* Minimal implementation of the generated interface. WebBrowser.h talks to
+ IBrowserDispatch through exactly this shape. */
+class TestBrowserDispatch : public IBrowserDispatch
+{
+public:
+ TestBrowserDispatch(void) : m_refs(1), m_lastNum(0), m_calls(0) {}
+
+ STDMETHOD(QueryInterface)(REFIID riid, void **ppv)
+ {
+ if (IsEqualGUID(riid, IID_IUnknown) || IsEqualGUID(riid, IID_IBrowserDispatch)) {
+ *ppv = this;
+ AddRef();
+ return S_OK;
+ }
+ *ppv = 0;
+ return E_NOINTERFACE;
+ }
+ STDMETHOD_(ULONG, AddRef)(void) { return ++m_refs; }
+ STDMETHOD_(ULONG, Release)(void) { return --m_refs; }
+
+ STDMETHOD(TestMethod)(int num1)
+ {
+ ++m_calls;
+ m_lastNum = num1;
+ return S_OK;
+ }
+
+ ULONG m_refs;
+ int m_lastNum;
+ int m_calls;
+};
+
+TEST(browserdispatch_interface_is_callable)
+{
+ TestBrowserDispatch obj;
+ IBrowserDispatch *p = &obj;
+
+ CHECK_EQ(p->TestMethod(42), S_OK);
+ CHECK_EQ(obj.m_calls, 1);
+ CHECK_EQ(obj.m_lastNum, 42);
+
+ /* IUnknown first, TestMethod at slot 3: the vtable layout the game relies on. */
+ void **vtbl = *(void ***)p;
+ CHECK(vtbl[0] != 0);
+ CHECK(vtbl[1] != 0);
+ CHECK(vtbl[2] != 0);
+ CHECK(vtbl[3] != 0);
+}
+
+TEST(browserdispatch_queryinterface_follows_the_iid)
+{
+ TestBrowserDispatch obj;
+ IUnknown *unk = &obj;
+ void *out = 0;
+
+ CHECK_EQ(unk->QueryInterface(IID_IBrowserDispatch, &out), S_OK);
+ CHECK(out == (void *)&obj);
+ CHECK_EQ(obj.m_refs, 2u);
+ ((IBrowserDispatch *)out)->Release();
+
+ out = (void *)1;
+ CHECK_EQ(unk->QueryInterface(LIBID_BROWSERDISPATCHLib, &out), E_NOINTERFACE);
+ CHECK(out == 0);
+ CHECK_EQ(obj.m_refs, 1u);
+}
diff --git a/GeneralsMD/Code/Tests/test_ww3d2.cpp b/GeneralsMD/Code/Tests/test_ww3d2.cpp
new file mode 100644
index 000000000..ef5c5324f
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_ww3d2.cpp
@@ -0,0 +1,1559 @@
+/*
+ * Device-free coverage for ww3d2.
+ *
+ * ww3d2 is the DX8 renderer, so most of it needs a live IDirect3DDevice8.
+ * The pieces below are pure computation - format tables, the shader bitfield,
+ * the FVF offset arithmetic and the w3d-file <-> runtime converters - and
+ * every one of them is reachable without a device. Anything that routes
+ * through DX8Wrapper::Get_Current_Caps() (Get_Valid_Texture_Format,
+ * ShaderClass::Apply) is deliberately not called here.
+ *
+ * Several tests pin behaviour that is plainly wrong in EA's source. Those are
+ * marked DEFECT and assert what the code actually does, not what it should do:
+ * the functions in question have no callers left in this tree, so "fixing"
+ * them would be inventing new behaviour with nothing to validate it against.
+ */
+
+#include "test_harness.h"
+
+#include "ww3dformat.h"
+#include "formconv.h"
+#include "shader.h"
+#include "dx8fvf.h"
+#include "w3d_util.h"
+#include "w3d_file.h"
+#include "w3d_obsolete.h"
+#include "targa.h"
+#include "wwstring.h"
+#include "vector3.h"
+#include "vector4.h"
+#include "quat.h"
+
+/*
+ * W3DMPO_GLUE gives every pooled class an operator new that routes through
+ * GameEngine's memory pools. GameEngine is not ported yet, so back the pools
+ * with plain new/delete - the classes under test here are value types and none
+ * of them care where their storage came from.
+ * ponytail: move to a shared Tests/*.cpp once a second test links ww3d2.
+ */
+void *createW3DMemPool(const char * /*poolName*/, int /*allocationSize*/)
+{
+ return (void *)1; /* opaque handle; the stub never dereferences it */
+}
+
+void *allocateFromW3DMemPool(void * /*pool*/, int allocationSize)
+{
+ return ::operator new(size_t(allocationSize));
+}
+
+void *allocateFromW3DMemPool(void *pool, int allocationSize, const char * /*msg*/, int /*unused*/)
+{
+ return allocateFromW3DMemPool(pool, allocationSize);
+}
+
+void freeFromW3DMemPool(void * /*pool*/, void *p)
+{
+ ::operator delete(p);
+}
+
+/*=========================================================================
+ ww3dformat - format property tables
+ =========================================================================*/
+
+TEST(has_alpha_flags_exactly_the_alpha_formats)
+{
+ /* Everything the switch lists, and nothing else. */
+ static const WW3DFormat with_alpha[] = {
+ WW3D_FORMAT_A8R8G8B8, WW3D_FORMAT_A1R5G5B5, WW3D_FORMAT_A4R4G4B4,
+ WW3D_FORMAT_A8, WW3D_FORMAT_A8R3G3B2, WW3D_FORMAT_A8P8,
+ WW3D_FORMAT_A8L8, WW3D_FORMAT_A4L4,
+ WW3D_FORMAT_DXT2, WW3D_FORMAT_DXT3, WW3D_FORMAT_DXT4, WW3D_FORMAT_DXT5
+ };
+
+ for (int f = 0; f < WW3D_FORMAT_COUNT; ++f) {
+ bool expected = false;
+ for (int i = 0; i < int(sizeof(with_alpha)/sizeof(with_alpha[0])); ++i) {
+ if (with_alpha[i] == WW3DFormat(f)) expected = true;
+ }
+ CHECK_EQ(Has_Alpha(WW3DFormat(f)), expected);
+ }
+
+ /* X1R5G5B5 / X4R4G4B4 have an unused bit where the alpha would be. */
+ CHECK(!Has_Alpha(WW3D_FORMAT_X1R5G5B5));
+ CHECK(!Has_Alpha(WW3D_FORMAT_X4R4G4B4));
+ CHECK(!Has_Alpha(WW3D_FORMAT_DXT1));
+ CHECK(!Has_Alpha(WW3D_FORMAT_UNKNOWN));
+}
+
+TEST(alpha_bits_agrees_with_has_alpha)
+{
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_A8R8G8B8), 8);
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_A8), 8);
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_A8R3G3B2), 8);
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_A8P8), 8);
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_A8L8), 8);
+
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_A4R4G4B4), 4);
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_A4L4), 4);
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_DXT3), 4);
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_DXT4), 4);
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_DXT5), 4);
+
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_A1R5G5B5), 1);
+ CHECK_EQ(Alpha_Bits(WW3D_FORMAT_DXT2), 1);
+
+ /* The two tables are independent switches; they must not disagree. */
+ for (int f = 0; f < WW3D_FORMAT_COUNT; ++f) {
+ CHECK_EQ(Alpha_Bits(WW3DFormat(f)) > 0, Has_Alpha(WW3DFormat(f)));
+ }
+}
+
+TEST(bytes_per_pixel_of_the_supported_formats)
+{
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_A8R8G8B8), 4u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_X8R8G8B8), 4u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_X8L8V8U8), 4u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_R8G8B8), 3u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_R5G6B5), 2u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_A1R5G5B5), 2u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_A4R4G4B4), 2u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_U8V8), 2u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_L6V5U5), 2u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_R3G3B2), 1u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_L8), 1u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_A8), 1u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_P8), 1u);
+}
+
+TEST(bytes_per_pixel_returns_zero_for_formats_it_does_not_list)
+{
+ /* The switch only covers the formats the texture loader actually hands it;
+ everything else trips a WWASSERT (inert in this build) and falls through
+ to 0. Callers must never size a surface from these. */
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_UNKNOWN), 0u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_X1R5G5B5), 0u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_X4R4G4B4), 0u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_A8R3G3B2), 0u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_A8P8), 0u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_A8L8), 0u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_A4L4), 0u);
+
+ /* DXT is block-compressed - "bytes per pixel" is meaningless for it. */
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_DXT1), 0u);
+ CHECK_EQ(Get_Bytes_Per_Pixel(WW3D_FORMAT_DXT5), 0u);
+}
+
+TEST(format_names_cover_every_format_and_are_unique)
+{
+ StringClass names[WW3D_FORMAT_COUNT];
+
+ for (int f = 0; f < WW3D_FORMAT_COUNT; ++f) {
+ Get_WW3D_Format_Name(WW3DFormat(f), names[f]);
+ CHECK(names[f].Get_Length() > 0);
+ }
+
+ CHECK_STR(names[WW3D_FORMAT_UNKNOWN], "Unknown");
+ CHECK_STR(names[WW3D_FORMAT_A8R8G8B8], "A8R8G8B8");
+ CHECK_STR(names[WW3D_FORMAT_R5G6B5], "R5G6B5");
+ CHECK_STR(names[WW3D_FORMAT_L6V5U5], "L6V5U5");
+ CHECK_STR(names[WW3D_FORMAT_DXT5], "DXT5");
+
+ for (int i = 0; i < WW3D_FORMAT_COUNT; ++i) {
+ for (int j = i + 1; j < WW3D_FORMAT_COUNT; ++j) {
+ CHECK_NE(strcmp(names[i], names[j]), 0);
+ }
+ }
+
+ /* Out of range falls into the default arm, which shares the UNKNOWN case. */
+ StringClass junk;
+ Get_WW3D_Format_Name(WW3DFormat(WW3D_FORMAT_COUNT + 17), junk);
+ CHECK_STR(junk, "Unknown");
+}
+
+TEST(zformat_names_cover_every_zformat_and_are_unique)
+{
+ StringClass names[WW3D_ZFORMAT_COUNT];
+
+ for (int f = 0; f < WW3D_ZFORMAT_COUNT; ++f) {
+ Get_WW3D_ZFormat_Name(WW3DZFormat(f), names[f]);
+ CHECK(names[f].Get_Length() > 0);
+ }
+
+ CHECK_STR(names[WW3D_ZFORMAT_UNKNOWN], "Unknown");
+ CHECK_STR(names[WW3D_ZFORMAT_D16_LOCKABLE], "D16Lockable");
+ CHECK_STR(names[WW3D_ZFORMAT_D24S8], "D24S8");
+ CHECK_STR(names[WW3D_ZFORMAT_D24X4S4], "D24X4S4");
+
+ for (int i = 0; i < WW3D_ZFORMAT_COUNT; ++i) {
+ for (int j = i + 1; j < WW3D_ZFORMAT_COUNT; ++j) {
+ CHECK_NE(strcmp(names[i], names[j]), 0);
+ }
+ }
+}
+
+TEST(depth_and_stencil_bit_counts)
+{
+ CHECK_EQ(Get_Num_Depth_Bits(WW3D_ZFORMAT_D16_LOCKABLE), 16u);
+ CHECK_EQ(Get_Num_Depth_Bits(WW3D_ZFORMAT_D32), 32u);
+ CHECK_EQ(Get_Num_Depth_Bits(WW3D_ZFORMAT_D15S1), 15u);
+ CHECK_EQ(Get_Num_Depth_Bits(WW3D_ZFORMAT_D24S8), 24u);
+ CHECK_EQ(Get_Num_Depth_Bits(WW3D_ZFORMAT_D16), 16u);
+ CHECK_EQ(Get_Num_Depth_Bits(WW3D_ZFORMAT_D24X8), 24u);
+ CHECK_EQ(Get_Num_Depth_Bits(WW3D_ZFORMAT_D24X4S4), 24u);
+ CHECK_EQ(Get_Num_Depth_Bits(WW3D_ZFORMAT_UNKNOWN), 0u);
+
+ CHECK_EQ(Get_Num_Stencil_Bits(WW3D_ZFORMAT_D16_LOCKABLE), 0u);
+ CHECK_EQ(Get_Num_Stencil_Bits(WW3D_ZFORMAT_D32), 0u);
+ CHECK_EQ(Get_Num_Stencil_Bits(WW3D_ZFORMAT_D15S1), 1u);
+ CHECK_EQ(Get_Num_Stencil_Bits(WW3D_ZFORMAT_D24S8), 8u);
+ CHECK_EQ(Get_Num_Stencil_Bits(WW3D_ZFORMAT_D16), 0u);
+ CHECK_EQ(Get_Num_Stencil_Bits(WW3D_ZFORMAT_D24X8), 0u);
+ CHECK_EQ(Get_Num_Stencil_Bits(WW3D_ZFORMAT_D24X4S4), 4u);
+ CHECK_EQ(Get_Num_Stencil_Bits(WW3D_ZFORMAT_UNKNOWN), 0u);
+
+ /* Depth + stencil always fits the 16 or 32 bit surface the format names.
+ D24X8 and D24X4S4 leave the spare bits unaccounted for, so this is an
+ upper bound, not an equality. */
+ for (int f = 1; f < WW3D_ZFORMAT_COUNT; ++f) {
+ unsigned total = Get_Num_Depth_Bits(WW3DZFormat(f)) +
+ Get_Num_Stencil_Bits(WW3DZFormat(f));
+ CHECK(total == 16 || (total > 16 && total <= 32));
+ }
+}
+
+/*=========================================================================
+ ww3dformat - Targa header -> source format
+ =========================================================================*/
+
+static void set_tga(Targa &tga, int depth, int colormap_type, int image_type)
+{
+ memset(&tga.Header, 0, sizeof(tga.Header));
+ tga.Header.PixelDepth = (unsigned char)depth;
+ tga.Header.ColorMapType = (unsigned char)colormap_type;
+ tga.Header.ImageType = (unsigned char)image_type;
+}
+
+TEST(targa_header_selects_the_source_format)
+{
+ Targa tga;
+ WW3DFormat format;
+ unsigned bpp;
+
+ set_tga(tga, 32, 0, TGA_TRUECOLOR);
+ Get_WW3D_Format(format, bpp, tga);
+ CHECK_EQ(format, WW3D_FORMAT_A8R8G8B8);
+ CHECK_EQ(bpp, 4u);
+
+ set_tga(tga, 24, 0, TGA_TRUECOLOR);
+ Get_WW3D_Format(format, bpp, tga);
+ CHECK_EQ(format, WW3D_FORMAT_R8G8B8);
+ CHECK_EQ(bpp, 3u);
+
+ /* 16 bit targa is really X1R5G5B5, but the loader treats the top bit as
+ alpha - matching what the art tools of the era wrote. */
+ set_tga(tga, 16, 0, TGA_TRUECOLOR);
+ Get_WW3D_Format(format, bpp, tga);
+ CHECK_EQ(format, WW3D_FORMAT_A1R5G5B5);
+ CHECK_EQ(bpp, 2u);
+}
+
+TEST(targa_8bit_depth_splits_three_ways)
+{
+ Targa tga;
+ WW3DFormat format;
+ unsigned bpp;
+
+ /* Palettised: the colour map flag wins over the image type. */
+ set_tga(tga, 8, 1, TGA_MONO);
+ Get_WW3D_Format(format, bpp, tga);
+ CHECK_EQ(format, WW3D_FORMAT_P8);
+ CHECK_EQ(bpp, 1u);
+
+ /* Greyscale, no palette. */
+ set_tga(tga, 8, 0, TGA_MONO);
+ Get_WW3D_Format(format, bpp, tga);
+ CHECK_EQ(format, WW3D_FORMAT_L8);
+ CHECK_EQ(bpp, 1u);
+
+ /* Neither -> treated as an alpha-only surface. */
+ set_tga(tga, 8, 0, TGA_TRUECOLOR);
+ Get_WW3D_Format(format, bpp, tga);
+ CHECK_EQ(format, WW3D_FORMAT_A8);
+ CHECK_EQ(bpp, 1u);
+}
+
+TEST(targa_unsupported_depth_yields_unknown_and_zero_bpp)
+{
+ Targa tga;
+ WW3DFormat format;
+ unsigned bpp;
+
+ set_tga(tga, 15, 0, TGA_TRUECOLOR);
+ Get_WW3D_Format(format, bpp, tga);
+ CHECK_EQ(format, WW3D_FORMAT_UNKNOWN);
+ CHECK_EQ(bpp, 0u);
+
+ /* Both outputs are seeded before the switch, so a garbage header cannot
+ leave the caller's locals untouched. */
+ format = WW3D_FORMAT_DXT5;
+ bpp = 99;
+ set_tga(tga, 0, 0, 0);
+ Get_WW3D_Format(format, bpp, tga);
+ CHECK_EQ(format, WW3D_FORMAT_UNKNOWN);
+ CHECK_EQ(bpp, 0u);
+}
+
+/*=========================================================================
+ ww3dformat - colour packing
+ =========================================================================*/
+
+TEST(vector4_to_color_passes_32bit_formats_through_unchanged)
+{
+ /* The 8888 cases do no byte shuffling at all - they hand back exactly what
+ DX8Wrapper::Convert_Color produced (0xAARRGGBB). */
+ Vector4 red(1.0f, 0.0f, 0.0f, 1.0f);
+ unsigned int out = 0;
+
+ Vector4_to_Color(&out, red, WW3D_FORMAT_A8R8G8B8);
+ CHECK_EQ(out, 0xffff0000u);
+
+ Vector4_to_Color(&out, red, WW3D_FORMAT_X8R8G8B8);
+ CHECK_EQ(out, 0xffff0000u);
+
+ Vector4_to_Color(&out, red, WW3D_FORMAT_R8G8B8);
+ CHECK_EQ(out, 0xffff0000u);
+
+ Vector4 black(0.0f, 0.0f, 0.0f, 0.0f);
+ Vector4_to_Color(&out, black, WW3D_FORMAT_A8R8G8B8);
+ CHECK_EQ(out, 0x00000000u);
+
+ Vector4 white(1.0f, 1.0f, 1.0f, 1.0f);
+ Vector4_to_Color(&out, white, WW3D_FORMAT_A8R8G8B8);
+ CHECK_EQ(out, 0xffffffffu);
+}
+
+TEST(vector4_to_color_saturated_white_packs_correctly)
+{
+ /* All-ones is the one input the byte-order defect below cannot corrupt, so
+ the packed layouts can still be checked against their bit widths. */
+ Vector4 white(1.0f, 1.0f, 1.0f, 1.0f);
+ unsigned int out = 0;
+
+ Vector4_to_Color(&out, white, WW3D_FORMAT_R5G6B5);
+ CHECK_EQ(out, 0xffffu); /* 5+6+5 all set */
+
+ Vector4_to_Color(&out, white, WW3D_FORMAT_A1R5G5B5);
+ CHECK_EQ(out, 0xffffu); /* 1+5+5+5 all set */
+
+ Vector4_to_Color(&out, white, WW3D_FORMAT_A4R4G4B4);
+ CHECK_EQ(out, 0xffffu);
+
+ Vector4_to_Color(&out, white, WW3D_FORMAT_A8R3G3B2);
+ CHECK_EQ(out, 0xffffu); /* alpha byte + 3+3+2 */
+
+ Vector4_to_Color(&out, white, WW3D_FORMAT_A8);
+ CHECK_EQ(out, 0xffu);
+}
+
+TEST(vector4_to_color_packed_formats_read_the_bytes_backwards)
+{
+ /* DEFECT (dead code): the packed arms index the 32 bit ARGB value as
+ argb[0]=A, argb[1]=R, argb[2]=G, argb[3]=B. That is big-endian byte
+ order; on x86 byte 0 is B and byte 3 is A, so every channel lands in the
+ wrong slot. Nothing in this tree calls Vector4_to_Color, which is why
+ the bug survived - the assertions below pin what it really does so the
+ damage is visible the moment somebody wires it up. */
+ unsigned int out = 0;
+
+ /* Pure red in -> pure green out. */
+ Vector4 red(1.0f, 0.0f, 0.0f, 0.0f);
+ Vector4_to_Color(&out, red, WW3D_FORMAT_R5G6B5);
+ CHECK_EQ(out, 0x07e0u); /* green field, should have been 0xf800 */
+
+ /* Pure blue in -> read as the alpha channel. */
+ Vector4 blue(0.0f, 0.0f, 1.0f, 0.0f);
+ Vector4_to_Color(&out, blue, WW3D_FORMAT_A8);
+ CHECK_EQ(out, 0xffu); /* should have been 0 - alpha was 0 */
+
+ /* Pure alpha in -> dropped entirely. */
+ Vector4 alpha(0.0f, 0.0f, 0.0f, 1.0f);
+ Vector4_to_Color(&out, alpha, WW3D_FORMAT_A8);
+ CHECK_EQ(out, 0x00u); /* should have been 0xff */
+}
+
+TEST(vector4_to_color_luminance_formats_use_ciey)
+{
+ /* The L8/A8L8/A4L4 arms compute luminance from the float vector directly,
+ so they dodge the byte-order defect. 0.2126 R + 0.7152 G + 0.0722 B. */
+ unsigned int out = 0;
+
+ Vector4 green(0.0f, 1.0f, 0.0f, 0.0f);
+ Vector4_to_Color(&out, green, WW3D_FORMAT_L8);
+ CHECK_EQ(out, (unsigned int)(255.0f * 0.7152f));
+
+ Vector4 black(0.0f, 0.0f, 0.0f, 0.0f);
+ Vector4_to_Color(&out, black, WW3D_FORMAT_L8);
+ CHECK_EQ(out, 0u);
+
+ Vector4 white(1.0f, 1.0f, 1.0f, 1.0f);
+ Vector4_to_Color(&out, white, WW3D_FORMAT_L8);
+ CHECK_EQ(out, 255u); /* the three weights sum to exactly 1 */
+
+ /* A4L4 packs alpha high, luminance low, both nibbles. */
+ Vector4_to_Color(&out, white, WW3D_FORMAT_A4L4);
+ CHECK_EQ(out, 0xffu);
+}
+
+TEST(color_to_vector4_reverses_the_channel_order)
+{
+ /* DEFECT (dead code): same big-endian byte indexing as Vector4_to_Color,
+ so unpacking an 0xAARRGGBB value hands back the channels reversed.
+ Round-tripping A8R8G8B8 through the pair does NOT recover the input. */
+ Vector4 out(9.0f, 9.0f, 9.0f, 9.0f);
+
+ Color_to_Vector4(&out, 0x11223344u, WW3D_FORMAT_A8R8G8B8);
+ CHECK_NEAR(out.X, 0x33 / 255.0f, 1e-6f); /* red slot got green */
+ CHECK_NEAR(out.Y, 0x22 / 255.0f, 1e-6f); /* green slot got red */
+ CHECK_NEAR(out.Z, 0x11 / 255.0f, 1e-6f); /* blue slot got alpha */
+ CHECK_NEAR(out.W, 0x44 / 255.0f, 1e-6f); /* alpha slot got blue */
+
+ /* Grey survives because every byte is equal. */
+ Color_to_Vector4(&out, 0x80808080u, WW3D_FORMAT_A8R8G8B8);
+ CHECK_NEAR(out.X, 0x80 / 255.0f, 1e-6f);
+ CHECK_NEAR(out.W, 0x80 / 255.0f, 1e-6f);
+}
+
+TEST(color_to_vector4_zeroes_the_channels_a_format_lacks)
+{
+ /* a=r=g=b=0 is seeded before the switch, so channels the format has no
+ room for come back as 0 rather than garbage. */
+ Vector4 out(9.0f, 9.0f, 9.0f, 9.0f);
+
+ Color_to_Vector4(&out, 0xffffffffu, WW3D_FORMAT_R5G6B5);
+ CHECK_NEAR(out.W, 0.0f, 1e-6f); /* R5G6B5 has no alpha */
+
+ Color_to_Vector4(&out, 0xffffffffu, WW3D_FORMAT_X4R4G4B4);
+ CHECK_NEAR(out.W, 0.0f, 1e-6f); /* the X nibble is not alpha */
+
+ Color_to_Vector4(&out, 0xffffffffu, WW3D_FORMAT_A8);
+ CHECK_NEAR(out.X, 0.0f, 1e-6f);
+ CHECK_NEAR(out.Y, 0.0f, 1e-6f);
+ CHECK_NEAR(out.Z, 0.0f, 1e-6f);
+ CHECK_NEAR(out.W, 1.0f, 1e-6f);
+
+ /* Unhandled formats trip the WWASSERT (inert here) and fall through with
+ every channel still zero. */
+ Color_to_Vector4(&out, 0xffffffffu, WW3D_FORMAT_A8L8);
+ CHECK_NEAR(out.X, 0.0f, 1e-6f);
+ CHECK_NEAR(out.W, 0.0f, 1e-6f);
+}
+
+/*=========================================================================
+ formconv - WW3DFormat <-> D3DFORMAT
+ =========================================================================*/
+
+TEST(ww3d_format_to_d3d_format_round_trips)
+{
+ Init_D3D_To_WW3_Conversion();
+
+ static const WW3DFormat formats[] = {
+ WW3D_FORMAT_R8G8B8, WW3D_FORMAT_A8R8G8B8, WW3D_FORMAT_X8R8G8B8,
+ WW3D_FORMAT_R5G6B5, WW3D_FORMAT_X1R5G5B5, WW3D_FORMAT_A1R5G5B5,
+ WW3D_FORMAT_A4R4G4B4, WW3D_FORMAT_R3G3B2, WW3D_FORMAT_A8,
+ WW3D_FORMAT_A8R3G3B2, WW3D_FORMAT_X4R4G4B4, WW3D_FORMAT_A8P8,
+ WW3D_FORMAT_P8, WW3D_FORMAT_L8, WW3D_FORMAT_A8L8, WW3D_FORMAT_A4L4,
+ WW3D_FORMAT_U8V8, WW3D_FORMAT_L6V5U5, WW3D_FORMAT_X8L8V8U8,
+ WW3D_FORMAT_DXT1, WW3D_FORMAT_DXT2, WW3D_FORMAT_DXT3,
+ WW3D_FORMAT_DXT4, WW3D_FORMAT_DXT5
+ };
+
+ for (int i = 0; i < int(sizeof(formats)/sizeof(formats[0])); ++i) {
+ D3DFORMAT d3d = WW3DFormat_To_D3DFormat(formats[i]);
+ CHECK_NE(d3d, D3DFMT_UNKNOWN);
+ CHECK_EQ(D3DFormat_To_WW3DFormat(d3d), formats[i]);
+ }
+
+ CHECK_EQ(WW3DFormat_To_D3DFormat(WW3D_FORMAT_UNKNOWN), D3DFMT_UNKNOWN);
+ CHECK_EQ(D3DFormat_To_WW3DFormat(D3DFMT_UNKNOWN), WW3D_FORMAT_UNKNOWN);
+}
+
+TEST(ww3d_format_maps_to_the_expected_d3d_enumerators)
+{
+ CHECK_EQ(WW3DFormat_To_D3DFormat(WW3D_FORMAT_A8R8G8B8), D3DFMT_A8R8G8B8);
+ CHECK_EQ(WW3DFormat_To_D3DFormat(WW3D_FORMAT_R5G6B5), D3DFMT_R5G6B5);
+ CHECK_EQ(WW3DFormat_To_D3DFormat(WW3D_FORMAT_P8), D3DFMT_P8);
+ CHECK_EQ(WW3DFormat_To_D3DFormat(WW3D_FORMAT_DXT3), D3DFMT_DXT3);
+
+ /* WW3D spells the bumpmap format U8V8; D3D spells the same layout V8U8. */
+ CHECK_EQ(WW3DFormat_To_D3DFormat(WW3D_FORMAT_U8V8), D3DFMT_V8U8);
+ CHECK_EQ(D3DFormat_To_WW3DFormat(D3DFMT_V8U8), WW3D_FORMAT_U8V8);
+}
+
+TEST(d3d_formats_outside_the_table_map_to_unknown)
+{
+ Init_D3D_To_WW3_Conversion();
+
+ /* Anything past the highest entry the table was sized for is rejected
+ before the array is touched - this is the bounds check that keeps a
+ FOURCC format from indexing off the end. */
+ CHECK_EQ(D3DFormat_To_WW3DFormat(D3DFMT_VERTEXDATA), WW3D_FORMAT_UNKNOWN);
+ CHECK_EQ(D3DFormat_To_WW3DFormat(D3DFMT_INDEX16), WW3D_FORMAT_UNKNOWN);
+
+ /* In range but never assigned. */
+ CHECK_EQ(D3DFormat_To_WW3DFormat(D3DFMT_A2B10G10R10), WW3D_FORMAT_UNKNOWN);
+ CHECK_EQ(D3DFormat_To_WW3DFormat(D3DFMT_G16R16), WW3D_FORMAT_UNKNOWN);
+}
+
+TEST(zformat_to_d3d_format_round_trips)
+{
+ Init_D3D_To_WW3_Conversion();
+
+ for (int f = 1; f < WW3D_ZFORMAT_COUNT; ++f) {
+ D3DFORMAT d3d = WW3DZFormat_To_D3DFormat(WW3DZFormat(f));
+ CHECK_NE(d3d, D3DFMT_UNKNOWN);
+ CHECK_EQ(D3DFormat_To_WW3DZFormat(d3d), WW3DZFormat(f));
+ }
+
+ CHECK_EQ(WW3DZFormat_To_D3DFormat(WW3D_ZFORMAT_UNKNOWN), D3DFMT_UNKNOWN);
+ CHECK_EQ(WW3DZFormat_To_D3DFormat(WW3D_ZFORMAT_D24S8), D3DFMT_D24S8);
+ CHECK_EQ(D3DFormat_To_WW3DZFormat(D3DFMT_D16), WW3D_ZFORMAT_D16);
+
+ /* A colour format is not a depth format. */
+ CHECK_EQ(D3DFormat_To_WW3DZFormat(D3DFMT_A8R8G8B8), WW3D_ZFORMAT_UNKNOWN);
+}
+
+/*=========================================================================
+ shader - the packed state word
+ =========================================================================*/
+
+TEST(shader_reset_sets_the_documented_defaults)
+{
+ ShaderClass s; /* the default ctor calls Reset() */
+
+ CHECK_EQ(s.Get_Depth_Compare(), ShaderClass::PASS_LEQUAL);
+ CHECK_EQ(s.Get_Depth_Mask(), ShaderClass::DEPTH_WRITE_ENABLE);
+ CHECK_EQ(s.Get_Color_Mask(), ShaderClass::COLOR_WRITE_ENABLE);
+ CHECK_EQ(s.Get_Dst_Blend_Func(), ShaderClass::DSTBLEND_ZERO);
+ CHECK_EQ(s.Get_Fog_Func(), ShaderClass::FOG_DISABLE);
+ CHECK_EQ(s.Get_Primary_Gradient(), ShaderClass::GRADIENT_MODULATE);
+ CHECK_EQ(s.Get_Secondary_Gradient(), ShaderClass::SECONDARY_GRADIENT_DISABLE);
+ CHECK_EQ(s.Get_Src_Blend_Func(), ShaderClass::SRCBLEND_ONE);
+ CHECK_EQ(s.Get_Texturing(), ShaderClass::TEXTURING_DISABLE);
+ CHECK_EQ(s.Get_Alpha_Test(), ShaderClass::ALPHATEST_DISABLE);
+ CHECK_EQ(s.Get_Cull_Mode(), ShaderClass::CULL_MODE_ENABLE);
+ CHECK_EQ(s.Get_Post_Detail_Color_Func(), ShaderClass::DETAILCOLOR_DISABLE);
+ CHECK_EQ(s.Get_Post_Detail_Alpha_Func(), ShaderClass::DETAILALPHA_DISABLE);
+ CHECK_EQ(s.Get_NPatch_Enable(), ShaderClass::NPATCH_DISABLE);
+
+ /* Reset() on a dirtied shader must land on the same word. */
+ ShaderClass dirty(0xffffffff);
+ dirty.Reset();
+ CHECK_EQ(dirty.Get_Bits(), s.Get_Bits());
+}
+
+/* Set every value of one field, check it reads back and no other field moved. */
+#define CHECK_FIELD(setter, getter, type, max) \
+ do { \
+ for (int v = 0; v < ShaderClass::max; ++v) { \
+ ShaderClass s; \
+ unsigned int before = s.Get_Bits(); \
+ s.setter(ShaderClass::type(v)); \
+ CHECK_EQ(int(s.getter()), v); \
+ /* only this field's bits may differ */ \
+ unsigned int changed = before ^ s.Get_Bits(); \
+ s.setter(ShaderClass::type(v)); \
+ CHECK_EQ(changed & ~(changed), 0u); \
+ ShaderClass back(s); \
+ back.setter(ShaderClass::type(0)); \
+ CHECK_EQ(int(back.getter()), 0); \
+ } \
+ } while (0)
+
+TEST(shader_every_field_round_trips_over_its_whole_range)
+{
+ CHECK_FIELD(Set_Depth_Compare, Get_Depth_Compare, DepthCompareType, PASS_MAX);
+ CHECK_FIELD(Set_Depth_Mask, Get_Depth_Mask, DepthMaskType, DEPTH_WRITE_MAX);
+ CHECK_FIELD(Set_Color_Mask, Get_Color_Mask, ColorMaskType, COLOR_WRITE_MAX);
+ CHECK_FIELD(Set_Dst_Blend_Func, Get_Dst_Blend_Func, DstBlendFuncType, DSTBLEND_MAX);
+ CHECK_FIELD(Set_Fog_Func, Get_Fog_Func, FogFuncType, FOG_MAX);
+ CHECK_FIELD(Set_Primary_Gradient, Get_Primary_Gradient, PriGradientType, GRADIENT_MAX);
+ CHECK_FIELD(Set_Secondary_Gradient, Get_Secondary_Gradient, SecGradientType, SECONDARY_GRADIENT_MAX);
+ CHECK_FIELD(Set_Src_Blend_Func, Get_Src_Blend_Func, SrcBlendFuncType, SRCBLEND_MAX);
+ CHECK_FIELD(Set_Texturing, Get_Texturing, TexturingType, TEXTURING_MAX);
+ CHECK_FIELD(Set_NPatch_Enable, Get_NPatch_Enable, NPatchEnableType, NPATCH_TYPE_MAX);
+ CHECK_FIELD(Set_Alpha_Test, Get_Alpha_Test, AlphaTestType, ALPHATEST_MAX);
+ CHECK_FIELD(Set_Cull_Mode, Get_Cull_Mode, CullModeType, CULL_MODE_MAX);
+ CHECK_FIELD(Set_Post_Detail_Color_Func, Get_Post_Detail_Color_Func, DetailColorFuncType, DETAILCOLOR_MAX);
+ CHECK_FIELD(Set_Post_Detail_Alpha_Func, Get_Post_Detail_Alpha_Func, DetailAlphaFuncType, DETAILALPHA_MAX);
+}
+
+#undef CHECK_FIELD
+
+TEST(shader_fields_do_not_overlap)
+{
+ /* Write the maximum legal value into every field at once; each one must
+ still read back. This is the real test that the MASK_/SHIFT_ pairs
+ partition the word - a single overlapping bit shows up here. */
+ ShaderClass s;
+ s.Set_Depth_Compare(ShaderClass::PASS_ALWAYS);
+ s.Set_Depth_Mask(ShaderClass::DEPTH_WRITE_ENABLE);
+ s.Set_Color_Mask(ShaderClass::COLOR_WRITE_ENABLE);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
+ s.Set_Fog_Func(ShaderClass::FOG_WHITE);
+ s.Set_Primary_Gradient(ShaderClass::GRADIENT_MODULATE2X);
+ s.Set_Secondary_Gradient(ShaderClass::SECONDARY_GRADIENT_ENABLE);
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE_MINUS_SRC_ALPHA);
+ s.Set_Texturing(ShaderClass::TEXTURING_ENABLE);
+ s.Set_NPatch_Enable(ShaderClass::NPATCH_ENABLE);
+ s.Set_Alpha_Test(ShaderClass::ALPHATEST_ENABLE);
+ s.Set_Cull_Mode(ShaderClass::CULL_MODE_ENABLE);
+ s.Set_Post_Detail_Color_Func(ShaderClass::DETAILCOLOR_MODALPHAADDCOLOR);
+ s.Set_Post_Detail_Alpha_Func(ShaderClass::DETAILALPHA_INVSCALE);
+
+ CHECK_EQ(s.Get_Depth_Compare(), ShaderClass::PASS_ALWAYS);
+ CHECK_EQ(s.Get_Depth_Mask(), ShaderClass::DEPTH_WRITE_ENABLE);
+ CHECK_EQ(s.Get_Color_Mask(), ShaderClass::COLOR_WRITE_ENABLE);
+ CHECK_EQ(s.Get_Dst_Blend_Func(), ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
+ CHECK_EQ(s.Get_Fog_Func(), ShaderClass::FOG_WHITE);
+ CHECK_EQ(s.Get_Primary_Gradient(), ShaderClass::GRADIENT_MODULATE2X);
+ CHECK_EQ(s.Get_Secondary_Gradient(), ShaderClass::SECONDARY_GRADIENT_ENABLE);
+ CHECK_EQ(s.Get_Src_Blend_Func(), ShaderClass::SRCBLEND_ONE_MINUS_SRC_ALPHA);
+ CHECK_EQ(s.Get_Texturing(), ShaderClass::TEXTURING_ENABLE);
+ CHECK_EQ(s.Get_NPatch_Enable(), ShaderClass::NPATCH_ENABLE);
+ CHECK_EQ(s.Get_Alpha_Test(), ShaderClass::ALPHATEST_ENABLE);
+ CHECK_EQ(s.Get_Cull_Mode(), ShaderClass::CULL_MODE_ENABLE);
+ CHECK_EQ(s.Get_Post_Detail_Color_Func(), ShaderClass::DETAILCOLOR_MODALPHAADDCOLOR);
+ CHECK_EQ(s.Get_Post_Detail_Alpha_Func(), ShaderClass::DETAILALPHA_INVSCALE);
+}
+
+TEST(shader_masks_partition_the_word_without_overlap)
+{
+ static const unsigned int masks[] = {
+ ShaderClass::MASK_DEPTHCOMPARE, ShaderClass::MASK_DEPTHMASK,
+ ShaderClass::MASK_COLORMASK, ShaderClass::MASK_DSTBLEND,
+ ShaderClass::MASK_FOG, ShaderClass::MASK_PRIGRADIENT,
+ ShaderClass::MASK_SECGRADIENT, ShaderClass::MASK_SRCBLEND,
+ ShaderClass::MASK_TEXTURING, ShaderClass::MASK_NPATCHENABLE,
+ ShaderClass::MASK_ALPHATEST, ShaderClass::MASK_CULLMODE,
+ ShaderClass::MASK_POSTDETAILCOLORFUNC, ShaderClass::MASK_POSTDETAILALPHAFUNC
+ };
+
+ unsigned int seen = 0;
+ for (int i = 0; i < int(sizeof(masks)/sizeof(masks[0])); ++i) {
+ CHECK_EQ(seen & masks[i], 0u);
+ seen |= masks[i];
+ }
+
+ /* Bits 27..31 are unallocated; the shader word never sets them. */
+ CHECK_EQ(seen & 0xf8000000u, 0u);
+}
+
+TEST(get_depth_compare_survives_its_missing_parentheses)
+{
+ /* shader.h writes (ShaderBits & MASK_DEPTHCOMPARE >> SHIFT_DEPTHCOMPARE)
+ - >> binds tighter than &, so the mask is shifted, not the result. It
+ is correct only because SHIFT_DEPTHCOMPARE happens to be 0. Pinned so
+ that moving the field breaks a test instead of the renderer. */
+ CHECK_EQ(int(SHIFT_DEPTHCOMPARE), 0);
+
+ for (int v = 0; v < ShaderClass::PASS_MAX; ++v) {
+ ShaderClass s;
+ s.Set_Depth_Compare(ShaderClass::DepthCompareType(v));
+ CHECK_EQ(int(s.Get_Depth_Compare()), v);
+ }
+}
+
+TEST(shade_cnst_macro_matches_the_setters)
+{
+ /* Every preset is built with SHADE_CNST; if the macro's argument order
+ ever drifts from the Set_* calls the whole preset table is silently
+ wrong. Build the same state both ways and compare the words. */
+ ShaderClass from_macro(SHADE_CNST(
+ ShaderClass::PASS_GEQUAL,
+ ShaderClass::DEPTH_WRITE_DISABLE,
+ ShaderClass::COLOR_WRITE_ENABLE,
+ ShaderClass::SRCBLEND_SRC_ALPHA,
+ ShaderClass::DSTBLEND_ONE_MINUS_SRC_COLOR,
+ ShaderClass::FOG_SCALE_FRAGMENT,
+ ShaderClass::GRADIENT_ADD,
+ ShaderClass::SECONDARY_GRADIENT_ENABLE,
+ ShaderClass::TEXTURING_ENABLE,
+ ShaderClass::ALPHATEST_ENABLE,
+ ShaderClass::CULL_MODE_DISABLE,
+ ShaderClass::DETAILCOLOR_SUBR,
+ ShaderClass::DETAILALPHA_SCALE));
+
+ ShaderClass from_setters;
+ from_setters.Set_Depth_Compare(ShaderClass::PASS_GEQUAL);
+ from_setters.Set_Depth_Mask(ShaderClass::DEPTH_WRITE_DISABLE);
+ from_setters.Set_Color_Mask(ShaderClass::COLOR_WRITE_ENABLE);
+ from_setters.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);
+ from_setters.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_COLOR);
+ from_setters.Set_Fog_Func(ShaderClass::FOG_SCALE_FRAGMENT);
+ from_setters.Set_Primary_Gradient(ShaderClass::GRADIENT_ADD);
+ from_setters.Set_Secondary_Gradient(ShaderClass::SECONDARY_GRADIENT_ENABLE);
+ from_setters.Set_Texturing(ShaderClass::TEXTURING_ENABLE);
+ from_setters.Set_Alpha_Test(ShaderClass::ALPHATEST_ENABLE);
+ from_setters.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE);
+ from_setters.Set_Post_Detail_Color_Func(ShaderClass::DETAILCOLOR_SUBR);
+ from_setters.Set_Post_Detail_Alpha_Func(ShaderClass::DETAILALPHA_SCALE);
+
+ CHECK_EQ(from_macro.Get_Bits(), from_setters.Get_Bits());
+
+ /* SHADE_CNST has no npatch argument, so that field stays clear. */
+ CHECK_EQ(from_macro.Get_NPatch_Enable(), ShaderClass::NPATCH_DISABLE);
+}
+
+TEST(shader_copy_and_comparison)
+{
+ ShaderClass a;
+ a.Set_Fog_Func(ShaderClass::FOG_ENABLE);
+
+ ShaderClass b(a);
+ CHECK(a == b);
+ CHECK(!(a != b));
+ CHECK_EQ(b.Get_Fog_Func(), ShaderClass::FOG_ENABLE);
+
+ b.Set_Fog_Func(ShaderClass::FOG_WHITE);
+ CHECK(a != b);
+ CHECK(!(a == b));
+
+ ShaderClass c(a.Get_Bits());
+ CHECK(a == c);
+}
+
+TEST(shader_uses_alpha_covers_every_trigger)
+{
+ ShaderClass s;
+ CHECK(!s.Uses_Alpha()); /* reset default blends nothing */
+
+ s.Reset();
+ s.Set_Alpha_Test(ShaderClass::ALPHATEST_ENABLE);
+ CHECK(s.Uses_Alpha());
+
+ s.Reset();
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_SRC_ALPHA);
+ CHECK(s.Uses_Alpha());
+
+ s.Reset();
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
+ CHECK(s.Uses_Alpha());
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);
+ CHECK(s.Uses_Alpha());
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE_MINUS_SRC_ALPHA);
+ CHECK(s.Uses_Alpha());
+
+ /* Colour-only blends do not. */
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ZERO);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_SRC_COLOR);
+ CHECK(!s.Uses_Alpha());
+}
+
+TEST(shader_uses_predicates_track_their_fields)
+{
+ ShaderClass s;
+
+ CHECK(!s.Uses_Fog());
+ s.Set_Fog_Func(ShaderClass::FOG_SCALE_FRAGMENT);
+ CHECK(s.Uses_Fog());
+
+ s.Reset();
+ CHECK(s.Uses_Primary_Gradient()); /* MODULATE is the default */
+ s.Set_Primary_Gradient(ShaderClass::GRADIENT_DISABLE);
+ CHECK(!s.Uses_Primary_Gradient());
+
+ s.Reset();
+ CHECK(!s.Uses_Secondary_Gradient());
+ s.Set_Secondary_Gradient(ShaderClass::SECONDARY_GRADIENT_ENABLE);
+ CHECK(s.Uses_Secondary_Gradient());
+
+ s.Reset();
+ CHECK(!s.Uses_Texture());
+ s.Set_Texturing(ShaderClass::TEXTURING_ENABLE);
+ CHECK(s.Uses_Texture());
+}
+
+TEST(uses_post_detail_texture_requires_texturing)
+{
+ ShaderClass s;
+
+ /* Detail funcs set but texturing off -> no detail pass. */
+ s.Set_Post_Detail_Color_Func(ShaderClass::DETAILCOLOR_ADD);
+ CHECK(!s.Uses_Post_Detail_Texture());
+
+ s.Set_Texturing(ShaderClass::TEXTURING_ENABLE);
+ CHECK(s.Uses_Post_Detail_Texture());
+
+ s.Set_Post_Detail_Color_Func(ShaderClass::DETAILCOLOR_DISABLE);
+ CHECK(!s.Uses_Post_Detail_Texture());
+
+ /* The alpha func alone is enough. */
+ s.Set_Post_Detail_Alpha_Func(ShaderClass::DETAILALPHA_SCALE);
+ CHECK(s.Uses_Post_Detail_Texture());
+}
+
+TEST(static_sort_category_classification)
+{
+ ShaderClass s;
+
+ /* Opaque: no alpha test and nothing read back from the frame buffer. */
+ s.Reset();
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ZERO);
+ CHECK_EQ(s.Get_SS_Category(), ShaderClass::SSCAT_OPAQUE);
+
+ /* Alpha test wins over opaque only once the alpha test is on. */
+ s.Set_Alpha_Test(ShaderClass::ALPHATEST_ENABLE);
+ CHECK_EQ(s.Get_SS_Category(), ShaderClass::SSCAT_ALPHA_TEST);
+
+ /* Alpha test plus the standard alpha blend is still the alpha-test bin. */
+ s.Reset();
+ s.Set_Alpha_Test(ShaderClass::ALPHATEST_ENABLE);
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
+ CHECK_EQ(s.Get_SS_Category(), ShaderClass::SSCAT_ALPHA_TEST);
+
+ /* Additive. */
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE);
+ CHECK_EQ(s.Get_SS_Category(), ShaderClass::SSCAT_ADDITIVE);
+
+ /* Screen. */
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_COLOR);
+ CHECK_EQ(s.Get_SS_Category(), ShaderClass::SSCAT_SCREEN);
+
+ /* Plain alpha blend without alpha test falls in the catch-all bin. */
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
+ CHECK_EQ(s.Get_SS_Category(), ShaderClass::SSCAT_OTHER);
+
+ /* Multiplicative too. */
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ZERO);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_SRC_COLOR);
+ CHECK_EQ(s.Get_SS_Category(), ShaderClass::SSCAT_OTHER);
+
+ /* Alpha test on top of an additive blend drops through to additive - the
+ alpha-test arm only claims the two blend combinations above. */
+ s.Reset();
+ s.Set_Alpha_Test(ShaderClass::ALPHATEST_ENABLE);
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE);
+ CHECK_EQ(s.Get_SS_Category(), ShaderClass::SSCAT_ADDITIVE);
+}
+
+TEST(guess_sort_level_follows_the_category)
+{
+ ShaderClass s;
+
+ s.Reset(); /* opaque */
+ CHECK_EQ(s.Guess_Sort_Level(), SORT_LEVEL_NONE);
+
+ s.Set_Alpha_Test(ShaderClass::ALPHATEST_ENABLE);
+ CHECK_EQ(s.Guess_Sort_Level(), SORT_LEVEL_NONE);
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_COLOR);
+ CHECK_EQ(s.Guess_Sort_Level(), SORT_LEVEL_BIN2);
+
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE);
+ CHECK_EQ(s.Guess_Sort_Level(), SORT_LEVEL_BIN3);
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
+ CHECK_EQ(s.Guess_Sort_Level(), SORT_LEVEL_BIN1);
+
+ /* Sorted bins draw back-to-front after the unsorted ones, so alpha must
+ land on a higher level than additive, which beats screen. */
+ CHECK(SORT_LEVEL_BIN1 > SORT_LEVEL_BIN2);
+ CHECK(SORT_LEVEL_BIN2 > SORT_LEVEL_BIN3);
+ CHECK(SORT_LEVEL_BIN3 > SORT_LEVEL_NONE);
+}
+
+TEST(enable_fog_picks_a_mode_per_blend_pair)
+{
+ ShaderClass s;
+
+ /* Multiplicative -> the fragment must be replaced by the fog colour. */
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ZERO);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_SRC_COLOR);
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Fog_Func(), ShaderClass::FOG_WHITE);
+
+ /* Opaque -> ordinary fog blend. */
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ZERO);
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Fog_Func(), ShaderClass::FOG_ENABLE);
+
+ /* Additive and screen -> scale the fragment towards black instead. */
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE);
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Fog_Func(), ShaderClass::FOG_SCALE_FRAGMENT);
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_COLOR);
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Fog_Func(), ShaderClass::FOG_SCALE_FRAGMENT);
+
+ /* Both alpha blends. */
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Fog_Func(), ShaderClass::FOG_ENABLE);
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE_MINUS_SRC_ALPHA);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_SRC_ALPHA);
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Fog_Func(), ShaderClass::FOG_ENABLE);
+}
+
+TEST(enable_fog_leaves_unfoggable_blends_alone)
+{
+ /* The unhandled combinations only warn (a no-op without WWDEBUG) - the
+ shader must come back unmodified rather than half-set. */
+ ShaderClass s;
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ZERO);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE);
+ unsigned int before = s.Get_Bits();
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Bits(), before);
+ CHECK_EQ(s.Get_Fog_Func(), ShaderClass::FOG_DISABLE);
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_SRC_ALPHA);
+ before = s.Get_Bits();
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Bits(), before);
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ONE);
+ before = s.Get_Bits();
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Bits(), before);
+
+ s.Reset();
+ s.Set_Src_Blend_Func(ShaderClass::SRCBLEND_ONE_MINUS_SRC_ALPHA);
+ s.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_ZERO);
+ before = s.Get_Bits();
+ s.Enable_Fog("test");
+ CHECK_EQ(s.Get_Bits(), before);
+}
+
+TEST(init_from_material3_only_reacts_to_the_alpha_attribute)
+{
+ W3dMaterial3Struct mat;
+ memset(&mat, 0, sizeof(mat));
+
+ ShaderClass s;
+ unsigned int before = s.Get_Bits();
+ s.Init_From_Material3(mat);
+ CHECK_EQ(s.Get_Bits(), before);
+
+ mat.Attributes = W3DMATERIAL_USE_ALPHA;
+ s.Init_From_Material3(mat);
+ CHECK_EQ(s.Get_Depth_Mask(), ShaderClass::DEPTH_WRITE_DISABLE);
+ CHECK_EQ(s.Get_Src_Blend_Func(), ShaderClass::SRCBLEND_SRC_ALPHA);
+ CHECK_EQ(s.Get_Dst_Blend_Func(), ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
+
+ /* Nothing else in the material is looked at. */
+ ShaderClass t;
+ W3dMaterial3Struct loud;
+ memset(&loud, 0xff, sizeof(loud));
+ loud.Attributes = 0;
+ before = t.Get_Bits();
+ t.Init_From_Material3(loud);
+ CHECK_EQ(t.Get_Bits(), before);
+}
+
+TEST(shader_description_reports_the_state)
+{
+ ShaderClass s;
+ StringClass str;
+
+ s.Get_Description(str);
+ CHECK(strstr(str, "DEPTH_COMPARE:PASS_LEQUAL") != 0);
+ CHECK(strstr(str, "DEPTH_WRITE_ENABLE") != 0);
+ CHECK(strstr(str, "COLOR_WRITE_ENABLE") != 0);
+ CHECK(strstr(str, "DSTBLEND_ZERO") != 0);
+ CHECK(strstr(str, "FOG_DISABLE") != 0);
+ CHECK(strstr(str, "GRADIENT_MODULATE |") != 0);
+ CHECK(strstr(str, "SECONDARY_GRADIENT_DISABLE") != 0);
+ CHECK(strstr(str, "SRCBLEND_ONE |") != 0);
+ CHECK(strstr(str, "TEXTURING_DISABLE") != 0);
+ CHECK(strstr(str, "NPATCH_DISABLE") != 0);
+ CHECK(strstr(str, "ALPHATEST_DISABLE") != 0);
+ CHECK(strstr(str, "CULL_MODE_ENABLE") != 0);
+ CHECK(strstr(str, "DETAILCOLOR_DISABLE") != 0);
+
+ /* The string is rebuilt from scratch, not appended to. */
+ StringClass again;
+ s.Set_Fog_Func(ShaderClass::FOG_WHITE);
+ s.Get_Description(again);
+ CHECK(strstr(again, "FOG_WHITE") != 0);
+ CHECK(strstr(again, "FOG_DISABLE") == 0);
+ s.Get_Description(again);
+ CHECK_EQ(strstr(again, "FOG_WHITE"), strstr(again, "FOG_WHITE"));
+ CHECK(again.Get_Length() < 400); /* no runaway concatenation */
+
+ /* Get_Description returns the same string it filled in. */
+ CHECK_STR(s.Get_Description(again), again);
+}
+
+TEST(shader_description_never_lists_the_post_detail_alpha_func)
+{
+ /* Every other field is printed; the post-detail alpha func is the one
+ Get_Description forgets. Pinned so the omission is a known gap rather
+ than a surprise when reading a shader dump. */
+ ShaderClass s;
+ s.Set_Post_Detail_Alpha_Func(ShaderClass::DETAILALPHA_INVSCALE);
+
+ StringClass str;
+ s.Get_Description(str);
+ CHECK(strstr(str, "DETAILALPHA") == 0);
+}
+
+TEST(preset_shaders_are_configured_as_documented)
+{
+ /* Opaque: writes depth, no blend, textured. */
+ CHECK_EQ(ShaderClass::_PresetOpaqueShader.Get_Depth_Mask(), ShaderClass::DEPTH_WRITE_ENABLE);
+ CHECK_EQ(ShaderClass::_PresetOpaqueShader.Get_Src_Blend_Func(), ShaderClass::SRCBLEND_ONE);
+ CHECK_EQ(ShaderClass::_PresetOpaqueShader.Get_Dst_Blend_Func(), ShaderClass::DSTBLEND_ZERO);
+ CHECK(ShaderClass::_PresetOpaqueShader.Uses_Texture());
+ CHECK_EQ(ShaderClass::_PresetOpaqueShader.Get_SS_Category(), ShaderClass::SSCAT_OPAQUE);
+
+ /* Additive: one/one, depth read but no write. */
+ CHECK_EQ(ShaderClass::_PresetAdditiveShader.Get_Depth_Mask(), ShaderClass::DEPTH_WRITE_DISABLE);
+ CHECK_EQ(ShaderClass::_PresetAdditiveShader.Get_Src_Blend_Func(), ShaderClass::SRCBLEND_ONE);
+ CHECK_EQ(ShaderClass::_PresetAdditiveShader.Get_Dst_Blend_Func(), ShaderClass::DSTBLEND_ONE);
+ CHECK_EQ(ShaderClass::_PresetAdditiveShader.Get_SS_Category(), ShaderClass::SSCAT_ADDITIVE);
+
+ /* Alpha. */
+ CHECK_EQ(ShaderClass::_PresetAlphaShader.Get_Src_Blend_Func(), ShaderClass::SRCBLEND_SRC_ALPHA);
+ CHECK_EQ(ShaderClass::_PresetAlphaShader.Get_Dst_Blend_Func(), ShaderClass::DSTBLEND_ONE_MINUS_SRC_ALPHA);
+ CHECK(ShaderClass::_PresetAlphaShader.Uses_Alpha());
+
+ /* Multiplicative. */
+ CHECK_EQ(ShaderClass::_PresetMultiplicativeShader.Get_Src_Blend_Func(), ShaderClass::SRCBLEND_ZERO);
+ CHECK_EQ(ShaderClass::_PresetMultiplicativeShader.Get_Dst_Blend_Func(), ShaderClass::DSTBLEND_SRC_COLOR);
+
+ /* Bumpenvmap is the only preset using the bump gradient. */
+ CHECK_EQ(ShaderClass::_PresetBumpenvmapShader.Get_Primary_Gradient(), ShaderClass::GRADIENT_BUMPENVMAP);
+ CHECK_EQ(ShaderClass::_PresetBumpenvmapShader.Get_Post_Detail_Color_Func(), ShaderClass::DETAILCOLOR_ADD);
+}
+
+TEST(preset_2d_shaders_ignore_the_depth_buffer)
+{
+ static ShaderClass *const two_d[] = {
+ &ShaderClass::_PresetOpaque2DShader,
+ &ShaderClass::_PresetAdditive2DShader,
+ &ShaderClass::_PresetAlpha2DShader,
+ &ShaderClass::_PresetATest2DShader,
+ &ShaderClass::_PresetATestBlend2DShader,
+ &ShaderClass::_PresetScreen2DShader,
+ &ShaderClass::_PresetMultiplicative2DShader
+ };
+
+ for (int i = 0; i < int(sizeof(two_d)/sizeof(two_d[0])); ++i) {
+ CHECK_EQ(two_d[i]->Get_Depth_Compare(), ShaderClass::PASS_ALWAYS);
+ CHECK_EQ(two_d[i]->Get_Depth_Mask(), ShaderClass::DEPTH_WRITE_DISABLE);
+ CHECK_EQ(two_d[i]->Get_Primary_Gradient(), ShaderClass::GRADIENT_DISABLE);
+ CHECK(two_d[i]->Uses_Texture());
+ CHECK(!two_d[i]->Uses_Fog());
+ }
+}
+
+TEST(preset_sprite_shaders_read_depth_but_never_write_it)
+{
+ static ShaderClass *const sprites[] = {
+ &ShaderClass::_PresetOpaqueSpriteShader,
+ &ShaderClass::_PresetAdditiveSpriteShader,
+ &ShaderClass::_PresetAlphaSpriteShader,
+ &ShaderClass::_PresetScreenSpriteShader,
+ &ShaderClass::_PresetMultiplicativeSpriteShader
+ };
+
+ for (int i = 0; i < int(sizeof(sprites)/sizeof(sprites[0])); ++i) {
+ CHECK_EQ(sprites[i]->Get_Depth_Compare(), ShaderClass::PASS_LEQUAL);
+ CHECK_EQ(sprites[i]->Get_Depth_Mask(), ShaderClass::DEPTH_WRITE_DISABLE);
+ }
+
+ /* The solid presets are the untextured ones. */
+ CHECK(!ShaderClass::_PresetOpaqueSolidShader.Uses_Texture());
+ CHECK(!ShaderClass::_PresetAdditiveSolidShader.Uses_Texture());
+ CHECK(!ShaderClass::_PresetAlphaSolidShader.Uses_Texture());
+ CHECK(ShaderClass::_PresetOpaqueSolidShader.Uses_Primary_Gradient());
+
+ /* The alpha-test presets are the ones that actually enable it. */
+ CHECK_EQ(ShaderClass::_PresetATest2DShader.Get_Alpha_Test(), ShaderClass::ALPHATEST_ENABLE);
+ CHECK_EQ(ShaderClass::_PresetATestSpriteShader.Get_Alpha_Test(), ShaderClass::ALPHATEST_ENABLE);
+ CHECK_EQ(ShaderClass::_PresetATestBlend2DShader.Get_Alpha_Test(), ShaderClass::ALPHATEST_ENABLE);
+ CHECK_EQ(ShaderClass::_PresetATestBlendSpriteShader.Get_Alpha_Test(), ShaderClass::ALPHATEST_ENABLE);
+ CHECK_EQ(ShaderClass::_PresetOpaqueShader.Get_Alpha_Test(), ShaderClass::ALPHATEST_DISABLE);
+}
+
+TEST(no_preset_enables_fog_or_npatches)
+{
+ /* The header promises "none of them have fogging"; the npatch field was
+ added later and SHADE_CNST cannot set it, so it must be clear too. */
+ static ShaderClass *const presets[] = {
+ &ShaderClass::_PresetOpaqueShader, &ShaderClass::_PresetAdditiveShader,
+ &ShaderClass::_PresetBumpenvmapShader, &ShaderClass::_PresetAlphaShader,
+ &ShaderClass::_PresetMultiplicativeShader, &ShaderClass::_PresetOpaque2DShader,
+ &ShaderClass::_PresetOpaqueSpriteShader, &ShaderClass::_PresetAdditive2DShader,
+ &ShaderClass::_PresetAlpha2DShader, &ShaderClass::_PresetAdditiveSpriteShader,
+ &ShaderClass::_PresetAlphaSpriteShader, &ShaderClass::_PresetOpaqueSolidShader,
+ &ShaderClass::_PresetAdditiveSolidShader, &ShaderClass::_PresetAlphaSolidShader,
+ &ShaderClass::_PresetATest2DShader, &ShaderClass::_PresetATestSpriteShader,
+ &ShaderClass::_PresetATestBlend2DShader, &ShaderClass::_PresetATestBlendSpriteShader,
+ &ShaderClass::_PresetScreen2DShader, &ShaderClass::_PresetScreenSpriteShader,
+ &ShaderClass::_PresetMultiplicative2DShader, &ShaderClass::_PresetMultiplicativeSpriteShader
+ };
+
+ for (int i = 0; i < int(sizeof(presets)/sizeof(presets[0])); ++i) {
+ CHECK_EQ(presets[i]->Get_Fog_Func(), ShaderClass::FOG_DISABLE);
+ CHECK_EQ(presets[i]->Get_NPatch_Enable(), ShaderClass::NPATCH_DISABLE);
+ CHECK_EQ(presets[i]->Get_Color_Mask(), ShaderClass::COLOR_WRITE_ENABLE);
+ CHECK_EQ(presets[i]->Get_Cull_Mode(), ShaderClass::CULL_MODE_ENABLE);
+ CHECK_EQ(presets[i]->Get_Secondary_Gradient(), ShaderClass::SECONDARY_GRADIENT_DISABLE);
+ /* Unallocated high bits stay clear. */
+ CHECK_EQ(presets[i]->Get_Bits() & 0xf8000000u, 0u);
+ }
+}
+
+TEST(every_preset_can_be_fogged_or_is_deliberately_unfoggable)
+{
+ /* Enable_Fog on a preset must either set a fog mode or leave it alone -
+ never leave the shader in a state that renders differently without
+ fogging being on. */
+ static ShaderClass *const presets[] = {
+ &ShaderClass::_PresetOpaqueShader, &ShaderClass::_PresetAdditiveShader,
+ &ShaderClass::_PresetAlphaShader, &ShaderClass::_PresetMultiplicativeShader,
+ &ShaderClass::_PresetOpaque2DShader, &ShaderClass::_PresetScreen2DShader
+ };
+
+ for (int i = 0; i < int(sizeof(presets)/sizeof(presets[0])); ++i) {
+ ShaderClass copy(*presets[i]);
+ copy.Enable_Fog("preset");
+ CHECK_EQ(copy.Get_Bits() & ~unsigned(ShaderClass::MASK_FOG),
+ presets[i]->Get_Bits() & ~unsigned(ShaderClass::MASK_FOG));
+ CHECK_NE(copy.Get_Fog_Func(), ShaderClass::FOG_DISABLE);
+ }
+}
+
+TEST(backface_culling_inversion_is_a_global_toggle)
+{
+ bool original = ShaderClass::Is_Backface_Culling_Inverted();
+
+ ShaderClass::Invert_Backface_Culling(true);
+ CHECK(ShaderClass::Is_Backface_Culling_Inverted());
+
+ ShaderClass::Invert_Backface_Culling(false);
+ CHECK(!ShaderClass::Is_Backface_Culling_Inverted());
+
+ /* Default is un-inverted; restore whatever we found. */
+ CHECK(!original);
+ ShaderClass::Invert_Backface_Culling(original);
+}
+
+/*=========================================================================
+ dx8fvf - vertex layout arithmetic
+ =========================================================================*/
+
+TEST(fvf_sizes_match_the_matching_vertex_structs)
+{
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZ).Get_FVF_Size(), sizeof(VertexFormatXYZ));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZN).Get_FVF_Size(), sizeof(VertexFormatXYZN));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZNUV1).Get_FVF_Size(), sizeof(VertexFormatXYZNUV1));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZNUV2).Get_FVF_Size(), sizeof(VertexFormatXYZNUV2));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZNDUV1).Get_FVF_Size(), sizeof(VertexFormatXYZNDUV1));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZNDUV2).Get_FVF_Size(), sizeof(VertexFormatXYZNDUV2));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZDUV1).Get_FVF_Size(), sizeof(VertexFormatXYZDUV1));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZDUV2).Get_FVF_Size(), sizeof(VertexFormatXYZDUV2));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZUV1).Get_FVF_Size(), sizeof(VertexFormatXYZUV1));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZUV2).Get_FVF_Size(), sizeof(VertexFormatXYZUV2));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZNDUV1TG3).Get_FVF_Size(), sizeof(VertexFormatXYZNDUV1TG3));
+ CHECK_EQ(FVFInfoClass(DX8_FVF_XYZNDCUBEMAP).Get_FVF_Size(), sizeof(VertexFormatXYZNDCUBEMAP));
+}
+
+TEST(fvf_offsets_match_the_struct_member_layout)
+{
+ /* The offsets are what the renderer uses to poke a locked vertex buffer;
+ they have to line up with the structs the same header declares. */
+ FVFInfoClass nduv2(DX8_FVF_XYZNDUV2);
+ CHECK_EQ(nduv2.Get_Location_Offset(), 0u);
+ CHECK_EQ(nduv2.Get_Normal_Offset(), unsigned(offsetof(VertexFormatXYZNDUV2, nx)));
+ CHECK_EQ(nduv2.Get_Diffuse_Offset(), unsigned(offsetof(VertexFormatXYZNDUV2, diffuse)));
+ CHECK_EQ(nduv2.Get_Tex_Offset(0), unsigned(offsetof(VertexFormatXYZNDUV2, u1)));
+ CHECK_EQ(nduv2.Get_Tex_Offset(1), unsigned(offsetof(VertexFormatXYZNDUV2, u2)));
+ CHECK_EQ(nduv2.Get_FVF(), unsigned(DX8_FVF_XYZNDUV2));
+
+ FVFInfoClass duv2(DX8_FVF_XYZDUV2);
+ CHECK_EQ(duv2.Get_Diffuse_Offset(), unsigned(offsetof(VertexFormatXYZDUV2, diffuse)));
+ CHECK_EQ(duv2.Get_Tex_Offset(0), unsigned(offsetof(VertexFormatXYZDUV2, u1)));
+ CHECK_EQ(duv2.Get_Tex_Offset(1), unsigned(offsetof(VertexFormatXYZDUV2, u2)));
+
+ FVFInfoClass uv2(DX8_FVF_XYZUV2);
+ CHECK_EQ(uv2.Get_Tex_Offset(0), unsigned(offsetof(VertexFormatXYZUV2, u1)));
+ CHECK_EQ(uv2.Get_Tex_Offset(1), unsigned(offsetof(VertexFormatXYZUV2, u2)));
+
+ FVFInfoClass nuv1(DX8_FVF_XYZNUV1);
+ CHECK_EQ(nuv1.Get_Normal_Offset(), unsigned(offsetof(VertexFormatXYZNUV1, nx)));
+ CHECK_EQ(nuv1.Get_Tex_Offset(0), unsigned(offsetof(VertexFormatXYZNUV1, u1)));
+}
+
+TEST(fvf_offsets_of_absent_elements_alias_the_next_one)
+{
+ /* A missing element does not get its own slot - the offset simply equals
+ whatever comes next, so reading it without checking the FVF hands back
+ somebody else's data. */
+ FVFInfoClass xyz(DX8_FVF_XYZ);
+ CHECK_EQ(xyz.Get_Location_Offset(), 0u);
+ CHECK_EQ(xyz.Get_Normal_Offset(), 12u);
+ CHECK_EQ(xyz.Get_Diffuse_Offset(), 12u);
+ CHECK_EQ(xyz.Get_Specular_Offset(), 12u);
+ CHECK_EQ(xyz.Get_Tex_Offset(0), 12u);
+ CHECK_EQ(xyz.Get_FVF_Size(), 12u);
+
+ /* No preset FVF uses specular, so its offset always equals texcoord 0. */
+ static const unsigned fvfs[] = {
+ DX8_FVF_XYZ, DX8_FVF_XYZN, DX8_FVF_XYZNUV1, DX8_FVF_XYZNUV2,
+ DX8_FVF_XYZNDUV1, DX8_FVF_XYZNDUV2, DX8_FVF_XYZDUV1, DX8_FVF_XYZDUV2,
+ DX8_FVF_XYZUV1, DX8_FVF_XYZUV2, DX8_FVF_XYZNDCUBEMAP
+ };
+ for (int i = 0; i < int(sizeof(fvfs)/sizeof(fvfs[0])); ++i) {
+ FVFInfoClass info(fvfs[i]);
+ CHECK_EQ(info.Get_Specular_Offset(), info.Get_Tex_Offset(0));
+ CHECK(info.Get_Tex_Offset(0) <= info.Get_FVF_Size());
+ }
+}
+
+TEST(fvf_texcoord_offsets_assume_two_floats_per_set)
+{
+ /* DEFECT: the loop tests (FVF & D3DFVF_TEXCOORDSIZE2(i)) == ... , and
+ D3DFVF_TEXTUREFORMAT2 is 0, so that comparison is true for every FVF.
+ The size-3 and size-4 arms below it are unreachable, and any coordinate
+ set wider than two floats gets the wrong offset from there on.
+ XYZNDUV1TG3 declares three size-3 sets, so it is affected. */
+ CHECK_EQ(unsigned(D3DFVF_TEXTUREFORMAT2), 0u);
+
+ FVFInfoClass tg3(DX8_FVF_XYZNDUV1TG3);
+ CHECK_EQ(tg3.Get_Tex_Offset(0), unsigned(offsetof(VertexFormatXYZNDUV1TG3, u1)));
+ CHECK_EQ(tg3.Get_Tex_Offset(1), unsigned(offsetof(VertexFormatXYZNDUV1TG3, Sx)));
+
+ /* From here the walk is 8 bytes per set instead of 12. */
+ CHECK_EQ(tg3.Get_Tex_Offset(2), 44u);
+ CHECK_EQ(unsigned(offsetof(VertexFormatXYZNDUV1TG3, Tx)), 48u);
+ CHECK_EQ(tg3.Get_Tex_Offset(3), 52u);
+ CHECK_EQ(unsigned(offsetof(VertexFormatXYZNDUV1TG3, SxTx)), 60u);
+
+ /* D3DXGetFVFVertexSize does the arithmetic properly, so the size is right
+ even though the offsets are not. */
+ CHECK_EQ(tg3.Get_FVF_Size(), 72u);
+}
+
+TEST(fvf_size_can_be_supplied_for_a_zero_fvf)
+{
+ /* FVF 0 means "vertex shader declaration", where D3D cannot compute the
+ stride - the caller passes it in instead. */
+ FVFInfoClass shader_decl(0, 96);
+ CHECK_EQ(shader_decl.Get_FVF(), 0u);
+ CHECK_EQ(shader_decl.Get_FVF_Size(), 96u);
+
+ /* Every offset collapses to zero without any FVF bits. */
+ CHECK_EQ(shader_decl.Get_Location_Offset(), 0u);
+ CHECK_EQ(shader_decl.Get_Normal_Offset(), 0u);
+ CHECK_EQ(shader_decl.Get_Diffuse_Offset(), 0u);
+ CHECK_EQ(shader_decl.Get_Tex_Offset(0), 0u);
+
+ /* The two mutable setters exist so a vertex shader can be swapped in
+ after construction. */
+ shader_decl.Set_FVF(DX8_FVF_XYZ);
+ shader_decl.Set_FVF_Size(12);
+ CHECK_EQ(shader_decl.Get_FVF(), unsigned(DX8_FVF_XYZ));
+ CHECK_EQ(shader_decl.Get_FVF_Size(), 12u);
+}
+
+TEST(fvf_names_are_unique_per_preset)
+{
+ static const unsigned fvfs[] = {
+ DX8_FVF_XYZ, DX8_FVF_XYZN, DX8_FVF_XYZNUV1, DX8_FVF_XYZNUV2,
+ DX8_FVF_XYZNDUV1, DX8_FVF_XYZNDUV2, DX8_FVF_XYZDUV1, DX8_FVF_XYZDUV2,
+ DX8_FVF_XYZUV1, DX8_FVF_XYZUV2, DX8_FVF_XYZNDUV1TG3,
+ DX8_FVF_XYZNUV2DMAP, DX8_FVF_XYZNDCUBEMAP
+ };
+ const int count = int(sizeof(fvfs)/sizeof(fvfs[0]));
+
+ StringClass names[13];
+ for (int i = 0; i < count; ++i) {
+ FVFInfoClass(fvfs[i]).Get_FVF_Name(names[i]);
+ CHECK(names[i].Get_Length() > 0);
+ CHECK_NE(strcmp(names[i], "Unknown!"), 0);
+ }
+
+ for (int i = 0; i < count; ++i) {
+ for (int j = i + 1; j < count; ++j) {
+ CHECK_NE(strcmp(names[i], names[j]), 0);
+ }
+ }
+
+ CHECK_STR(names[0], "D3DFVF_XYZ");
+ CHECK_STR(names[1], "D3DFVF_XYZ|D3DFVF_NORMAL");
+
+ StringClass junk;
+ FVFInfoClass(D3DFVF_XYZ | D3DFVF_SPECULAR).Get_FVF_Name(junk);
+ CHECK_STR(junk, "Unknown!");
+}
+
+TEST(fvf_specular_offset_moves_texcoords_along)
+{
+ /* No preset FVF has specular, so exercise the branch directly. */
+ FVFInfoClass info(D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
+ D3DFVF_SPECULAR | D3DFVF_TEX1);
+
+ CHECK_EQ(info.Get_Location_Offset(), 0u);
+ CHECK_EQ(info.Get_Normal_Offset(), 12u);
+ CHECK_EQ(info.Get_Diffuse_Offset(), 24u);
+ CHECK_EQ(info.Get_Specular_Offset(), 28u);
+ CHECK_EQ(info.Get_Tex_Offset(0), 32u);
+ CHECK_EQ(info.Get_FVF_Size(), 40u);
+}
+
+/*=========================================================================
+ w3d_util - file struct <-> runtime class
+ =========================================================================*/
+
+TEST(convert_vector_both_ways)
+{
+ W3dVectorStruct file;
+ file.X = 1.5f; file.Y = -2.25f; file.Z = 1024.0f;
+
+ Vector3 v;
+ W3dUtilityClass::Convert_Vector(file, &v);
+ CHECK_NEAR(v.X, 1.5f, 1e-6f);
+ CHECK_NEAR(v.Y, -2.25f, 1e-6f);
+ CHECK_NEAR(v.Z, 1024.0f, 1e-6f);
+
+ W3dVectorStruct back;
+ W3dUtilityClass::Convert_Vector(v, &back);
+ CHECK_NEAR(back.X, file.X, 0.0f);
+ CHECK_NEAR(back.Y, file.Y, 0.0f);
+ CHECK_NEAR(back.Z, file.Z, 0.0f);
+}
+
+TEST(convert_quaternion_maps_q_array_to_xyzw)
+{
+ /* The file format stores the quaternion as Q[0..3]; the mapping to
+ X,Y,Z,W is positional and easy to get backwards. */
+ W3dQuaternionStruct file;
+ file.Q[0] = 0.1f; file.Q[1] = 0.2f; file.Q[2] = 0.3f; file.Q[3] = 0.4f;
+
+ Quaternion q;
+ W3dUtilityClass::Convert_Quaternion(file, &q);
+ CHECK_NEAR(q.X, 0.1f, 1e-6f);
+ CHECK_NEAR(q.Y, 0.2f, 1e-6f);
+ CHECK_NEAR(q.Z, 0.3f, 1e-6f);
+ CHECK_NEAR(q.W, 0.4f, 1e-6f);
+
+ W3dQuaternionStruct back;
+ W3dUtilityClass::Convert_Quaternion(q, &back);
+ CHECK_NEAR(back.Q[0], 0.1f, 0.0f);
+ CHECK_NEAR(back.Q[1], 0.2f, 0.0f);
+ CHECK_NEAR(back.Q[2], 0.3f, 0.0f);
+ CHECK_NEAR(back.Q[3], 0.4f, 0.0f);
+}
+
+TEST(convert_color_rgb_both_ways)
+{
+ W3dRGBStruct rgb(255, 128, 0);
+ rgb.pad = 0xcd;
+
+ Vector3 v;
+ W3dUtilityClass::Convert_Color(rgb, &v);
+ CHECK_NEAR(v.X, 1.0f, 1e-6f);
+ CHECK_NEAR(v.Y, 128.0f / 255.0f, 1e-6f);
+ CHECK_NEAR(v.Z, 0.0f, 1e-6f);
+
+ W3dRGBStruct back;
+ back.pad = 0xcd;
+ W3dUtilityClass::Convert_Color(v, &back);
+ CHECK_EQ(int(back.R), 255);
+ CHECK_EQ(int(back.G), 128);
+ CHECK_EQ(int(back.B), 0);
+ /* The writer clears pad so the struct hashes and compares consistently. */
+ CHECK_EQ(int(back.pad), 0);
+}
+
+TEST(convert_color_rgba_both_ways)
+{
+ W3dRGBAStruct rgba;
+ rgba.R = 10; rgba.G = 20; rgba.B = 30; rgba.A = 40;
+
+ Vector4 v;
+ W3dUtilityClass::Convert_Color(rgba, &v);
+ CHECK_NEAR(v.X, 10.0f / 255.0f, 1e-6f);
+ CHECK_NEAR(v.Y, 20.0f / 255.0f, 1e-6f);
+ CHECK_NEAR(v.Z, 30.0f / 255.0f, 1e-6f);
+ CHECK_NEAR(v.W, 40.0f / 255.0f, 1e-6f);
+
+ W3dRGBAStruct back;
+ W3dUtilityClass::Convert_Color(v, &back);
+ CHECK_EQ(int(back.R), 10);
+ CHECK_EQ(int(back.G), 20);
+ CHECK_EQ(int(back.B), 30);
+ CHECK_EQ(int(back.A), 40);
+}
+
+TEST(convert_color_round_trips_every_byte_value)
+{
+ /* x/255 * 255 must land back on x for all 256 values, otherwise repeated
+ load/save cycles would drift a mesh's vertex colours. */
+ for (int i = 0; i < 256; ++i) {
+ W3dRGBStruct rgb(uint8(i), uint8(255 - i), uint8((i * 7) & 0xff));
+ Vector3 v;
+ W3dUtilityClass::Convert_Color(rgb, &v);
+
+ W3dRGBStruct back;
+ W3dUtilityClass::Convert_Color(v, &back);
+ CHECK_EQ(int(back.R), i);
+ CHECK_EQ(int(back.G), 255 - i);
+ CHECK_EQ(int(back.B), (i * 7) & 0xff);
+ }
+}
+
+TEST(convert_color_truncates_rather_than_rounds)
+{
+ /* (uint8)(255.0f * v) - a value one bit below a step still floors down.
+ Worth pinning: it is why the round trip above is exact. */
+ Vector3 just_under(0.999f, 0.5f, 0.00001f);
+ W3dRGBStruct rgb;
+ W3dUtilityClass::Convert_Color(just_under, &rgb);
+ CHECK_EQ(int(rgb.R), 254); /* 254.745 -> 254 */
+ CHECK_EQ(int(rgb.G), 127); /* 127.5 -> 127 */
+ CHECK_EQ(int(rgb.B), 0);
+}
+
+TEST(convert_shader_round_trips_the_carried_fields)
+{
+ ShaderClass original;
+ original.Set_Depth_Compare(ShaderClass::PASS_GREATER);
+ original.Set_Depth_Mask(ShaderClass::DEPTH_WRITE_DISABLE);
+ original.Set_Dst_Blend_Func(ShaderClass::DSTBLEND_SRC_ALPHA);
+ original.Set_Primary_Gradient(ShaderClass::GRADIENT_ADD);
+ original.Set_Secondary_Gradient(ShaderClass::SECONDARY_GRADIENT_ENABLE);
+ original.Set_Src_Blend_Func(ShaderClass::SRCBLEND_SRC_ALPHA);
+ original.Set_Texturing(ShaderClass::TEXTURING_ENABLE);
+ original.Set_Alpha_Test(ShaderClass::ALPHATEST_ENABLE);
+
+ W3dShaderStruct file;
+ W3dUtilityClass::Convert_Shader(original, &file);
+
+ ShaderClass loaded;
+ W3dUtilityClass::Convert_Shader(file, &loaded);
+
+ CHECK_EQ(loaded.Get_Depth_Compare(), ShaderClass::PASS_GREATER);
+ CHECK_EQ(loaded.Get_Depth_Mask(), ShaderClass::DEPTH_WRITE_DISABLE);
+ CHECK_EQ(loaded.Get_Dst_Blend_Func(), ShaderClass::DSTBLEND_SRC_ALPHA);
+ CHECK_EQ(loaded.Get_Primary_Gradient(), ShaderClass::GRADIENT_ADD);
+ CHECK_EQ(loaded.Get_Secondary_Gradient(), ShaderClass::SECONDARY_GRADIENT_ENABLE);
+ CHECK_EQ(loaded.Get_Src_Blend_Func(), ShaderClass::SRCBLEND_SRC_ALPHA);
+ CHECK_EQ(loaded.Get_Texturing(), ShaderClass::TEXTURING_ENABLE);
+ CHECK_EQ(loaded.Get_Alpha_Test(), ShaderClass::ALPHATEST_ENABLE);
+}
+
+TEST(convert_shader_drops_the_fields_the_file_format_has_no_room_for)
+{
+ ShaderClass original;
+ original.Set_Fog_Func(ShaderClass::FOG_WHITE);
+ original.Set_Color_Mask(ShaderClass::COLOR_WRITE_DISABLE);
+ original.Set_Cull_Mode(ShaderClass::CULL_MODE_DISABLE);
+ original.Set_NPatch_Enable(ShaderClass::NPATCH_ENABLE);
+ original.Set_Post_Detail_Color_Func(ShaderClass::DETAILCOLOR_ADD);
+ original.Set_Post_Detail_Alpha_Func(ShaderClass::DETAILALPHA_SCALE);
+
+ W3dShaderStruct file;
+ W3dUtilityClass::Convert_Shader(original, &file);
+
+ ShaderClass loaded;
+ loaded.Set_NPatch_Enable(ShaderClass::NPATCH_ENABLE);
+ W3dUtilityClass::Convert_Shader(file, &loaded);
+
+ /* ColorMask and FogFunc are marked obsolete in the file struct, so the
+ loader hardcodes them. */
+ CHECK_EQ(loaded.Get_Fog_Func(), ShaderClass::FOG_DISABLE);
+ CHECK_EQ(loaded.Get_Color_Mask(), ShaderClass::COLOR_WRITE_ENABLE);
+
+ /* Cull mode and npatch are not in the file format at all, so the loader
+ leaves whatever the destination shader already had. */
+ CHECK_EQ(loaded.Get_NPatch_Enable(), ShaderClass::NPATCH_ENABLE);
+
+ /* Asymmetry by design: the writer stores the post-detail funcs in the
+ PostDetail* fields but the loader reads them back out of the Detail*
+ fields, which the writer never touched. Post-detail settings do not
+ survive a save/load cycle. */
+ CHECK_EQ(int(file.PostDetailColorFunc), int(ShaderClass::DETAILCOLOR_ADD));
+ CHECK_EQ(int(file.DetailColorFunc), int(ShaderClass::DETAILCOLOR_DISABLE));
+ CHECK_EQ(loaded.Get_Post_Detail_Color_Func(), ShaderClass::DETAILCOLOR_DISABLE);
+ CHECK_EQ(loaded.Get_Post_Detail_Alpha_Func(), ShaderClass::DETAILALPHA_DISABLE);
+}
+
+TEST(w3d_shader_reset_seeds_every_byte)
+{
+ /* W3d_Shader_Reset has to overwrite the whole struct - a stale byte would
+ be written straight into a .w3d file. */
+ W3dShaderStruct s;
+ memset(&s, 0xab, sizeof(s));
+ W3d_Shader_Reset(&s);
+
+ CHECK_EQ(int(s.DepthCompare), int(W3DSHADER_DEPTHCOMPARE_PASS_LEQUAL));
+ CHECK_EQ(int(s.DepthMask), int(W3DSHADER_DEPTHMASK_WRITE_ENABLE));
+ CHECK_EQ(int(s.ColorMask), 0);
+ CHECK_EQ(int(s.DestBlend), int(W3DSHADER_DESTBLENDFUNC_ZERO));
+ CHECK_EQ(int(s.FogFunc), 0);
+ CHECK_EQ(int(s.PriGradient), int(W3DSHADER_PRIGRADIENT_MODULATE));
+ CHECK_EQ(int(s.SecGradient), int(W3DSHADER_SECGRADIENT_DISABLE));
+ CHECK_EQ(int(s.SrcBlend), int(W3DSHADER_SRCBLENDFUNC_ONE));
+ CHECK_EQ(int(s.Texturing), int(W3DSHADER_TEXTURING_DISABLE));
+ CHECK_EQ(int(s.DetailColorFunc), int(W3DSHADER_DETAILCOLORFUNC_DISABLE));
+ CHECK_EQ(int(s.DetailAlphaFunc), int(W3DSHADER_DETAILALPHAFUNC_DISABLE));
+ CHECK_EQ(int(s.ShaderPreset), 0);
+ CHECK_EQ(int(s.AlphaTest), int(W3DSHADER_ALPHATEST_DISABLE));
+ CHECK_EQ(int(s.PostDetailColorFunc), int(W3DSHADER_DETAILCOLORFUNC_DISABLE));
+ CHECK_EQ(int(s.PostDetailAlphaFunc), int(W3DSHADER_DETAILALPHAFUNC_DISABLE));
+ CHECK_EQ(int(s.pad[0]), 0);
+
+ /* Two resets must produce identical bytes. */
+ W3dShaderStruct t;
+ memset(&t, 0x00, sizeof(t));
+ W3d_Shader_Reset(&t);
+ CHECK_MEM(&s, &t, sizeof(s));
+}
+
+TEST(w3d_shader_struct_is_the_size_the_file_format_expects)
+{
+ /* 16 bytes on disk; the pad byte exists to keep it even. */
+ CHECK_EQ(sizeof(W3dShaderStruct), 16u);
+ CHECK_EQ(sizeof(W3dRGBStruct), 4u);
+ CHECK_EQ(sizeof(W3dRGBAStruct), 4u);
+ CHECK_EQ(sizeof(W3dVectorStruct), 12u);
+ CHECK_EQ(sizeof(W3dQuaternionStruct), 16u);
+}
diff --git a/GeneralsMD/Code/Tests/test_wwdownload.cpp b/GeneralsMD/Code/Tests/test_wwdownload.cpp
new file mode 100644
index 000000000..12ce6b2c8
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_wwdownload.cpp
@@ -0,0 +1,534 @@
+/*
+ * Tests for the wwdownload support library.
+ *
+ * Scope: the parts that run without a network. Registry.cpp is fully covered
+ * (it only needs a scratch key), urlBuilder.cpp is covered structurally, and
+ * Prepare_Directories out of FTP.CPP is covered against a scratch directory.
+ *
+ * Deliberately NOT covered: CDownload and Cftp. Both are pure FTP state
+ * machines - DownloadFile/Abort/PumpMessages/ConnectToServer/... all either
+ * touch a socket or only mutate members that no accessor exposes. Cftp's one
+ * pure helper, GetDownloadFilename, is private with no friend hook.
+ *
+ * The registry tests never touch the real
+ * SOFTWARE\Electronic Arts\EA Games\Command and Conquer Generals Zero Hour
+ * key. Everything is written under HKCU\Software\CnCGeneralsZH_CMakeTests and
+ * deleted again; only the four capitalised wrappers see the real path, and
+ * those are exercised read-only against a subkey that cannot exist.
+ *
+ * Tests named *_DEFECT_* pin behaviour that is wrong but left alone, so a
+ * future fix trips the test instead of going unnoticed.
+ */
+#include "test_harness.h"
+
+#include <string>
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+
+#include "Registry.h"
+#include "urlBuilder.h"
+
+/* registry.cpp defines these with external linkage but Registry.h only declares
+ the four capitalised wrappers built on top of them. */
+bool getStringFromRegistry(HKEY root, std::string path, std::string key, std::string& val);
+bool getUnsignedIntFromRegistry(HKEY root, std::string path, std::string key, unsigned int& val);
+bool setStringInRegistry(HKEY root, std::string path, std::string key, std::string val);
+bool setUnsignedIntInRegistry(HKEY root, std::string path, std::string key, unsigned int val);
+
+/* FTP.CPP declares this at file scope only. */
+bool Prepare_Directories(const char *rootdir, const char *filename);
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Scratch registry key
+///////////////////////////////////////////////////////////////////////////////
+
+static const char *SCRATCH = "Software\\CnCGeneralsZH_CMakeTests";
+
+static void scrub(void)
+{
+ RegDeleteKeyA(HKEY_CURRENT_USER, SCRATCH);
+}
+
+/* Writes a value of an arbitrary type and length, so the tests can hand the
+ getters the kind of data a real registry can hold but setStringInRegistry
+ would never produce. */
+static bool raw_set(const char *key, unsigned long type, const void *data, unsigned long len)
+{
+ HKEY handle;
+ if (RegCreateKeyExA(HKEY_CURRENT_USER, SCRATCH, 0, NULL, REG_OPTION_NON_VOLATILE,
+ KEY_WRITE, NULL, &handle, NULL) != ERROR_SUCCESS) {
+ return false;
+ }
+
+ LONG result = RegSetValueExA(handle, key, 0, type, (const BYTE *)data, len);
+ RegCloseKey(handle);
+ return result == ERROR_SUCCESS;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// registry.cpp - round trips
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(registry_string_round_trip)
+{
+ scrub();
+
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "Greeting", "hello world"));
+
+ std::string val = "untouched";
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Greeting", val));
+ CHECK_STR(val.c_str(), "hello world");
+
+ /* A second set overwrites rather than appending a second value. */
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "Greeting", "goodbye"));
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Greeting", val));
+ CHECK_STR(val.c_str(), "goodbye");
+
+ scrub();
+}
+
+TEST(registry_uint_round_trip)
+{
+ scrub();
+
+ static const unsigned int values[] = { 0u, 1u, 42u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu };
+
+ for (int i = 0; i < int(sizeof(values)/sizeof(values[0])); ++i) {
+ CHECK(setUnsignedIntInRegistry(HKEY_CURRENT_USER, SCRATCH, "Version", values[i]));
+
+ unsigned int val = 0xDEADBEEFu;
+ CHECK(getUnsignedIntFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Version", val));
+ CHECK_EQ(val, values[i]);
+ }
+
+ scrub();
+}
+
+TEST(registry_set_creates_the_key)
+{
+ scrub();
+
+ /* Nothing exists yet, so this proves setStringInRegistry creates the key and
+ not just the value. */
+ std::string val;
+ CHECK(!getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Fresh", val));
+
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "Fresh", "made"));
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Fresh", val));
+ CHECK_STR(val.c_str(), "made");
+
+ scrub();
+}
+
+TEST(registry_multiple_values_are_independent)
+{
+ scrub();
+
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "Language", "german"));
+ CHECK(setUnsignedIntInRegistry(HKEY_CURRENT_USER, SCRATCH, "Version", 7));
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "BaseURL", "http://x/"));
+
+ std::string s;
+ unsigned int u = 0;
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Language", s));
+ CHECK_STR(s.c_str(), "german");
+ CHECK(getUnsignedIntFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Version", u));
+ CHECK_EQ(u, 7u);
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "BaseURL", s));
+ CHECK_STR(s.c_str(), "http://x/");
+
+ scrub();
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// registry.cpp - failure paths
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(registry_missing_key_fails_and_leaves_val_alone)
+{
+ scrub();
+
+ std::string s = "sentinel";
+ CHECK(!getStringFromRegistry(HKEY_CURRENT_USER, "Software\\CnCGeneralsZH_NoSuchKeyEver", "x", s));
+ CHECK_STR(s.c_str(), "sentinel");
+
+ unsigned int u = 12345u;
+ CHECK(!getUnsignedIntFromRegistry(HKEY_CURRENT_USER, "Software\\CnCGeneralsZH_NoSuchKeyEver", "x", u));
+ CHECK_EQ(u, 12345u);
+}
+
+TEST(registry_missing_value_fails_and_leaves_val_alone)
+{
+ scrub();
+
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "Present", "yes"));
+
+ std::string s = "sentinel";
+ CHECK(!getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Absent", s));
+ CHECK_STR(s.c_str(), "sentinel");
+
+ unsigned int u = 12345u;
+ CHECK(!getUnsignedIntFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Absent", u));
+ CHECK_EQ(u, 12345u);
+
+ scrub();
+}
+
+TEST(registry_string_write_to_hklm_is_denied_for_a_normal_user)
+{
+ /* Not an assertion about the machine's ACLs - just that the low-level setter
+ reports the failure instead of claiming success. HKLM\SOFTWARE requires
+ elevation; if this process happens to be elevated the write succeeds and
+ the key is cleaned up either way. */
+ bool ok = setStringInRegistry(HKEY_LOCAL_MACHINE, "Software\\CnCGeneralsZH_CMakeTests", "x", "y");
+
+ std::string s;
+ bool readable = getStringFromRegistry(HKEY_LOCAL_MACHINE, "Software\\CnCGeneralsZH_CMakeTests", "x", s);
+ CHECK_EQ(ok, readable);
+
+ if (ok) {
+ CHECK_STR(s.c_str(), "y");
+ RegDeleteKeyA(HKEY_LOCAL_MACHINE, "Software\\CnCGeneralsZH_CMakeTests");
+ }
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// registry.cpp - buffer edges
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(registry_255_char_string_is_the_longest_that_fits)
+{
+ scrub();
+
+ /* getStringFromRegistry hands RegQueryValueEx a 256 byte buffer, so 255
+ characters plus the terminator is exactly the limit. */
+ std::string longest(255, 'L');
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "Long", longest));
+
+ std::string val;
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Long", val));
+ CHECK_EQ(val.length(), size_t(255));
+ CHECK_STR(val.c_str(), longest.c_str());
+
+ /* One more character needs 257 bytes -> ERROR_MORE_DATA -> false, and the
+ caller's string is left alone rather than half filled. */
+ std::string toolong(256, 'L');
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "TooLong", toolong));
+
+ std::string untouched = "sentinel";
+ CHECK(!getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "TooLong", untouched));
+ CHECK_STR(untouched.c_str(), "sentinel");
+
+ scrub();
+}
+
+TEST(registry_empty_value_reads_as_empty_string)
+{
+ scrub();
+
+ /* Zero length REG_SZ: RegQueryValueEx succeeds without writing a single byte.
+ Before the buffer was zero initialised this handed back uninitialised
+ stack. */
+ CHECK(raw_set("Empty", REG_SZ, "", 0));
+
+ std::string val = "sentinel";
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Empty", val));
+ CHECK_EQ(val.length(), size_t(0));
+
+ scrub();
+}
+
+TEST(registry_unterminated_data_is_truncated_not_overread)
+{
+ scrub();
+
+ /* 256 bytes of 'A' with no NUL anywhere: the value fills the buffer exactly
+ and the terminator has to be forced in, or the std::string runs off the
+ end of the stack array. */
+ unsigned char blob[256];
+ memset(blob, 'A', sizeof(blob));
+ CHECK(raw_set("Blob", REG_BINARY, blob, sizeof(blob)));
+
+ std::string val;
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Blob", val));
+ CHECK_EQ(val.length(), size_t(255));
+ CHECK_EQ(val.find_first_not_of('A'), std::string::npos);
+
+ scrub();
+}
+
+TEST(registry_short_unterminated_data_stops_at_its_own_length)
+{
+ scrub();
+
+ /* Same idea below the buffer size: only the bytes the registry supplied may
+ show up, the rest of the buffer must read as zero. */
+ CHECK(raw_set("Short", REG_BINARY, "AB", 2));
+
+ std::string val;
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Short", val));
+ CHECK_STR(val.c_str(), "AB");
+
+ scrub();
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// registry.cpp - the getters ignore the value type
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(registry_DEFECT_getters_ignore_the_value_type)
+{
+ scrub();
+
+ /* Both getters pass &type to RegQueryValueEx and then never look at it, so a
+ value of the wrong type is happily reinterpreted. Nothing in the game
+ depends on the confusion, so this is pinned rather than fixed. */
+
+ /* REG_DWORD read as a string: four bytes, no terminator of its own. */
+ CHECK(setUnsignedIntInRegistry(HKEY_CURRENT_USER, SCRATCH, "Number", 0x41414141u));
+ std::string as_string;
+ CHECK(getStringFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Number", as_string));
+ CHECK_STR(as_string.c_str(), "AAAA");
+
+ /* REG_SZ read as a DWORD: "abc" is exactly four bytes with its terminator,
+ so the whole word is defined and comes back little endian. */
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "Text", "abc"));
+ unsigned int as_uint = 0;
+ CHECK(getUnsignedIntFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Text", as_uint));
+ CHECK_EQ(as_uint, 0x00636261u);
+
+ scrub();
+}
+
+TEST(registry_uint_read_of_a_long_string_fails)
+{
+ scrub();
+
+ /* More than four bytes does not fit the DWORD buffer -> ERROR_MORE_DATA. */
+ CHECK(setStringInRegistry(HKEY_CURRENT_USER, SCRATCH, "Text", "abcdefgh"));
+
+ unsigned int val = 999u;
+ CHECK(!getUnsignedIntFromRegistry(HKEY_CURRENT_USER, SCRATCH, "Text", val));
+ CHECK_EQ(val, 999u);
+
+ scrub();
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// registry.cpp - the capitalised wrappers
+///////////////////////////////////////////////////////////////////////////////
+
+TEST(registry_wrappers_append_the_path_and_report_misses)
+{
+ /* Read only on purpose: the wrappers hard code the real game key and this
+ test must not write there. A subkey that cannot exist proves the path is
+ appended (an unappended lookup would hit the real key and could succeed). */
+ std::string s = "sentinel";
+ CHECK(!GetStringFromRegistry("\\NoSuchSubkeyForCMakeTests", "BaseURL", s));
+ CHECK_STR(s.c_str(), "sentinel");
+
+ unsigned int u = 4242u;
+ CHECK(!GetUnsignedIntFromRegistry("\\NoSuchSubkeyForCMakeTests", "Version", u));
+ CHECK_EQ(u, 4242u);
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// urlBuilder.cpp
+///////////////////////////////////////////////////////////////////////////////
+
+/* The four URLs are built from whatever the machine's real EA registry key
+ holds, so only the structure is assertable, not the contents. */
+TEST(urlbuilder_shapes)
+{
+ std::string game, maps, config, motd;
+ FormatURLFromRegistry(game, maps, config, motd);
+
+ /* Every URL is <baseURL><something>.txt, and configURL is the one with a
+ fixed tail - so it pins the base the other three must share. */
+ CHECK(config.length() > strlen("config.txt"));
+ std::string base = config.substr(0, config.length() - strlen("config.txt"));
+ CHECK_EQ(config.compare(base.length(), std::string::npos, "config.txt"), 0);
+
+ CHECK_EQ(game.compare(0, base.length(), base), 0);
+ CHECK_EQ(maps.compare(0, base.length(), base), 0);
+ CHECK_EQ(motd.compare(0, base.length(), base), 0);
+
+ CHECK_EQ(game.compare(game.length()-4, 4, ".txt"), 0);
+ CHECK_EQ(maps.compare(maps.length()-4, 4, ".txt"), 0);
+ CHECK_EQ(motd.compare(motd.length()-4, 4, ".txt"), 0);
+
+ /* maps-<version>.txt and MOTD-<language>.txt are literal prefixes. */
+ CHECK_EQ(maps.compare(base.length(), 5, "maps-"), 0);
+ CHECK_EQ(motd.compare(base.length(), 5, "MOTD-"), 0);
+
+ /* The game patch URL is <language>-<version>.txt, and the language is the
+ same one the MOTD URL carries. */
+ std::string language = motd.substr(base.length() + 5);
+ language.erase(language.length() - 4); /* drop ".txt" */
+ CHECK(language.length() > 0);
+ CHECK_EQ(game.compare(base.length(), language.length(), language), 0);
+ CHECK_EQ(game[base.length() + language.length()], '-');
+
+ /* The version tails are decimal. */
+ std::string version = game.substr(base.length() + language.length() + 1);
+ version.erase(version.length() - 4);
+ CHECK(version.length() > 0);
+ CHECK_EQ(version.find_first_not_of("0123456789"), std::string::npos);
+
+ std::string mapversion = maps.substr(base.length() + 5);
+ mapversion.erase(mapversion.length() - 4);
+ CHECK(mapversion.length() > 0);
+ CHECK_EQ(mapversion.find_first_not_of("0123456789"), std::string::npos);
+
+ /* _snprintf(buf, 256, ...) is the ceiling on every one of them. */
+ CHECK(game.length() < 256);
+ CHECK(maps.length() < 256);
+ CHECK(config.length() < 256);
+ CHECK(motd.length() < 256);
+}
+
+TEST(urlbuilder_is_deterministic)
+{
+ std::string a1, a2, a3, a4;
+ std::string b1, b2, b3, b4;
+
+ FormatURLFromRegistry(a1, a2, a3, a4);
+ FormatURLFromRegistry(b1, b2, b3, b4);
+
+ CHECK_STR(a1.c_str(), b1.c_str());
+ CHECK_STR(a2.c_str(), b2.c_str());
+ CHECK_STR(a3.c_str(), b3.c_str());
+ CHECK_STR(a4.c_str(), b4.c_str());
+}
+
+TEST(urlbuilder_overwrites_whatever_it_was_handed)
+{
+ std::string game = "stale", maps = "stale", config = "stale", motd = "stale";
+ FormatURLFromRegistry(game, maps, config, motd);
+
+ CHECK(game != "stale");
+ CHECK(maps != "stale");
+ CHECK(config != "stale");
+ CHECK(motd != "stale");
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// FTP.CPP - Prepare_Directories
+///////////////////////////////////////////////////////////////////////////////
+
+static std::string scratch_dir(void)
+{
+ char temp[MAX_PATH];
+ GetTempPathA(sizeof(temp), temp);
+
+ std::string root = temp;
+ root += "wwdl_prepdirs_test";
+ return root;
+}
+
+static void remove_scratch_dirs(const std::string &root)
+{
+ RemoveDirectoryA((root + "\\a\\b").c_str());
+ RemoveDirectoryA((root + "\\a").c_str());
+ RemoveDirectoryA((root + "\\solo").c_str());
+ RemoveDirectoryA(root.c_str());
+}
+
+static bool is_dir(const std::string &path)
+{
+ DWORD attr = GetFileAttributesA(path.c_str());
+ return attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
+}
+
+TEST(prepare_directories_creates_every_level)
+{
+ std::string root = scratch_dir();
+ remove_scratch_dirs(root);
+ CHECK(CreateDirectoryA(root.c_str(), NULL) != 0);
+
+ CHECK(Prepare_Directories(root.c_str(), "a\\b\\patch.bin"));
+ CHECK(is_dir(root + "\\a"));
+ CHECK(is_dir(root + "\\a\\b"));
+
+ /* The file itself is never created - only the directories leading to it. */
+ CHECK(!is_dir(root + "\\a\\b\\patch.bin"));
+ CHECK_EQ(GetFileAttributesA((root + "\\a\\b\\patch.bin").c_str()), DWORD(INVALID_FILE_ATTRIBUTES));
+
+ remove_scratch_dirs(root);
+}
+
+TEST(prepare_directories_is_idempotent)
+{
+ std::string root = scratch_dir();
+ remove_scratch_dirs(root);
+ CHECK(CreateDirectoryA(root.c_str(), NULL) != 0);
+
+ CHECK(Prepare_Directories(root.c_str(), "a\\b\\one.bin"));
+ /* Second file into the same tree: every CreateDirectory now fails with
+ ERROR_ALREADY_EXISTS, which used to be reported as an error. */
+ CHECK(Prepare_Directories(root.c_str(), "a\\b\\two.bin"));
+ CHECK(Prepare_Directories(root.c_str(), "a\\b\\one.bin"));
+ CHECK(is_dir(root + "\\a\\b"));
+
+ remove_scratch_dirs(root);
+}
+
+TEST(prepare_directories_flat_name_creates_nothing)
+{
+ std::string root = scratch_dir();
+ remove_scratch_dirs(root);
+ CHECK(CreateDirectoryA(root.c_str(), NULL) != 0);
+
+ /* No backslash means no loop iterations at all. */
+ CHECK(Prepare_Directories(root.c_str(), "patch.bin"));
+ CHECK(!is_dir(root + "\\patch.bin"));
+
+ CHECK(Prepare_Directories(root.c_str(), ""));
+
+ remove_scratch_dirs(root);
+}
+
+TEST(prepare_directories_single_level)
+{
+ std::string root = scratch_dir();
+ remove_scratch_dirs(root);
+ CHECK(CreateDirectoryA(root.c_str(), NULL) != 0);
+
+ CHECK(Prepare_Directories(root.c_str(), "solo\\patch.bin"));
+ CHECK(is_dir(root + "\\solo"));
+
+ remove_scratch_dirs(root);
+}
+
+TEST(prepare_directories_trailing_separator_creates_the_whole_path)
+{
+ std::string root = scratch_dir();
+ remove_scratch_dirs(root);
+ CHECK(CreateDirectoryA(root.c_str(), NULL) != 0);
+
+ /* A name ending in a separator has no file part, so the last component is
+ treated as a directory too. */
+ CHECK(Prepare_Directories(root.c_str(), "a\\b\\"));
+ CHECK(is_dir(root + "\\a\\b"));
+
+ remove_scratch_dirs(root);
+}
+
+TEST(prepare_directories_unreachable_root_fails)
+{
+ /* A drive that cannot exist: CreateDirectory fails with something other than
+ ERROR_ALREADY_EXISTS, so the failure has to propagate. */
+ CHECK(!Prepare_Directories("\\\\?\\Q:\\no_such_volume_for_tests", "a\\patch.bin"));
+
+ /* ...but only when there is a directory to create at all. */
+ CHECK(Prepare_Directories("\\\\?\\Q:\\no_such_volume_for_tests", "patch.bin"));
+}
diff --git a/GeneralsMD/Code/Tests/test_wwlib.cpp b/GeneralsMD/Code/Tests/test_wwlib.cpp
new file mode 100644
index 000000000..5dd512891
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_wwlib.cpp
@@ -0,0 +1,1301 @@
+/*
+ * wwlib coverage.
+ *
+ * wwlib is the widest of the ported libraries - codecs, hashes, containers,
+ * strings, file abstractions and the CPU probe all live here. The tests
+ * concentrate on:
+ * 1. Anything with a published answer (SHA-1, MD5, RC4, base64) - those are
+ * checked against the standard vectors, not against what the code does.
+ * 2. Round trips, for the codecs that have no published vectors (LCW, RLE,
+ * Blowfish, chunk IO). A codec that round trips wrong is a corrupted
+ * save game, and nothing else in the build would notice.
+ * 3. cpudetect, which already produced one runtime-only port bug
+ * (os_info was left uninitialised on Windows >= Vista).
+ */
+#include "test_harness.h"
+
+#include "global.h" /* UINT4 / PROTO_LIST, which md5.h assumes */
+#include "realcrc.h"
+#include "crc.h"
+#include "base64.h"
+#include "blowfish.h"
+#include "rc4.h"
+#include "sha.h"
+#include "md5.h"
+#include "lcw.h"
+#include "rle.h"
+#include "random.h"
+#include "fixed.h"
+#include "wwstring.h"
+#include "widestring.h"
+#include "trim.h"
+#include "nstrdup.h"
+#include "strtok_r.h"
+#include "gcd_lcm.h"
+#include "vector.h"
+#include "simplevec.h"
+#include "hash.h"
+#include "multilist.h"
+#include "cpudetect.h"
+#include "ramfile.h"
+#include "chunkio.h"
+#include "wwfile.h"
+
+#include <stdlib.h>
+
+//////////////////////////////////////////////////////////////////////////////
+// Helpers
+//////////////////////////////////////////////////////////////////////////////
+
+/* Render a digest as lowercase hex so failures print something you can paste
+ into a reference table instead of a row of byte values. */
+static void to_hex(const unsigned char *bytes, int count, char *out)
+{
+ static const char *digits = "0123456789abcdef";
+ for (int i = 0; i < count; ++i)
+ {
+ out[i * 2 + 0] = digits[(bytes[i] >> 4) & 0xf];
+ out[i * 2 + 1] = digits[bytes[i] & 0xf];
+ }
+ out[count * 2] = 0;
+}
+
+/* Deterministic filler with enough structure to be compressible but enough
+ noise that a codec cannot pass by accident. */
+static void fill_pattern(unsigned char *buf, int len, unsigned seed)
+{
+ RandomClass rng(seed);
+ for (int i = 0; i < len; ++i)
+ {
+ if ((i / 17) % 3 == 0)
+ buf[i] = 0; /* runs, for RLE */
+ else if ((i / 29) % 4 == 0)
+ buf[i] = (unsigned char)(i & 0xff); /* ramps, for LCW */
+ else
+ buf[i] = (unsigned char)rng(0, 255);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// CRC
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(realcrc_string_and_memory_agree)
+{
+ const char *text = "Command & Conquer";
+ CHECK_EQ(CRC_String(text), CRC_Memory((const unsigned char *)text, (unsigned long)strlen(text)));
+
+ /* Different input must not collide on anything this short. */
+ CHECK_NE(CRC_String("abc"), CRC_String("abd"));
+ CHECK_NE(CRC_String("abc"), CRC_String("cba"));
+ CHECK_EQ(CRC_String(""), 0ul);
+}
+
+TEST(realcrc_seed_chains_across_calls)
+{
+ /* The crc argument is a continuation seed: hashing a buffer in two pieces
+ has to equal hashing it whole, or every streaming caller is wrong. */
+ const unsigned char data[] = "the quick brown fox jumps over the lazy dog";
+ const unsigned long len = (unsigned long)(sizeof(data) - 1);
+
+ unsigned long whole = CRC_Memory(data, len);
+ for (unsigned long split = 0; split <= len; ++split)
+ {
+ unsigned long part = CRC_Memory(data, split);
+ part = CRC_Memory(data + split, len - split, part);
+ CHECK_EQ(part, whole);
+ }
+}
+
+TEST(realcrc_case_insensitive_variant)
+{
+ CHECK_EQ(CRC_Stringi("MiXeD CaSe"), CRC_Stringi("mixed case"));
+ CHECK_EQ(CRC_Stringi("MiXeD CaSe"), CRC_Stringi("MIXED CASE"));
+ CHECK_NE(CRC_String("MiXeD CaSe"), CRC_String("mixed case"));
+}
+
+TEST(crc_class_table_variant)
+{
+ const char *text = "Zero Hour";
+ unsigned char buf[16];
+ memcpy(buf, text, strlen(text));
+
+ CHECK_EQ(CRC::String(text), CRC::Memory(buf, (unsigned long)strlen(text)));
+ CHECK_NE(CRC::String("Zero Hour"), CRC::String("Zero Hou"));
+
+ /* Same chaining contract as realcrc. */
+ unsigned long a = CRC::Memory(buf, 4);
+ CHECK_EQ(CRC::Memory(buf + 4, (unsigned long)strlen(text) - 4, a),
+ CRC::Memory(buf, (unsigned long)strlen(text)));
+}
+
+TEST(crcengine_byte_at_a_time_matches_block)
+{
+ const char *text = "Westwood Studios";
+ int len = (int)strlen(text);
+
+ CRCEngine block;
+ long whole = block(text, len);
+
+ CRCEngine drip;
+ for (int i = 0; i < len; ++i)
+ drip(text[i]);
+
+ /* Feeding one byte at a time has to land on the same accumulator - the
+ staging buffer exists precisely to make partial blocks equivalent. */
+ CHECK_EQ((long)drip, whole);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Base64
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(base64_known_vectors)
+{
+ /* RFC 4648 section 10. */
+ static const char *plain[] = { "", "f", "fo", "foo", "foob", "fooba", "foobar" };
+ static const char *coded[] = { "", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy" };
+
+ for (int i = 0; i < 7; ++i)
+ {
+ char out[32];
+ memset(out, 0, sizeof(out));
+ int n = Base64_Encode(plain[i], (int)strlen(plain[i]), out, sizeof(out));
+ CHECK_EQ(n, (int)strlen(coded[i]));
+ out[n] = 0;
+ CHECK_STR(out, coded[i]);
+ }
+}
+
+TEST(base64_round_trip_every_length)
+{
+ unsigned char src[300];
+ char enc[512];
+ unsigned char dec[300];
+ fill_pattern(src, sizeof(src), 7);
+
+ /* Every length mod 3 matters - that is what decides the padding. */
+ for (int len = 0; len <= 64; ++len)
+ {
+ int e = Base64_Encode(src, len, enc, sizeof(enc));
+ CHECK(e >= 0);
+ int d = Base64_Decode(enc, e, dec, sizeof(dec));
+ CHECK_EQ(d, len);
+ if (len > 0)
+ CHECK_MEM(src, dec, len);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Hashes
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(sha1_known_vectors)
+{
+ struct { const char *in; const char *out; } cases[] = {
+ { "", "da39a3ee5e6b4b0d3255bfef95601890afd80709" },
+ { "abc", "a9993e364706816aba3e25717850c26c9cd0d89d" },
+ { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
+ "84983e441c3bd26ebaae4aa1f95129e5e54670f1" },
+ };
+
+ for (int i = 0; i < 3; ++i)
+ {
+ SHAEngine sha;
+ sha.Hash(cases[i].in, (long)strlen(cases[i].in));
+
+ unsigned char digest[20];
+ CHECK_EQ(sha.Result(digest), 20);
+
+ char hex[41];
+ to_hex(digest, 20, hex);
+ CHECK_STR(hex, cases[i].out);
+ }
+}
+
+TEST(sha1_incremental_matches_single_shot)
+{
+ unsigned char data[257];
+ fill_pattern(data, sizeof(data), 11);
+
+ SHAEngine whole;
+ whole.Hash(data, sizeof(data));
+ unsigned char a[20];
+ whole.Result(a);
+
+ /* Split across the 64-byte block boundary in every position that matters. */
+ static const int splits[] = { 1, 63, 64, 65, 127, 128, 200 };
+ for (int i = 0; i < 7; ++i)
+ {
+ SHAEngine part;
+ part.Hash(data, splits[i]);
+ part.Hash(data + splits[i], (long)sizeof(data) - splits[i]);
+ unsigned char b[20];
+ part.Result(b);
+ CHECK_MEM(a, b, 20);
+ }
+}
+
+TEST(sha1_result_is_non_destructive)
+{
+ /* Result() is documented as "as if the source data were to stop now", so
+ asking twice, or continuing to hash afterwards, has to keep working. */
+ SHAEngine sha;
+ sha.Hash("abc", 3);
+
+ unsigned char first[20], second[20];
+ sha.Result(first);
+ sha.Result(second);
+ CHECK_MEM(first, second, 20);
+
+ sha.Hash("def", 3);
+ unsigned char after[20];
+ sha.Result(after);
+
+ SHAEngine reference;
+ reference.Hash("abcdef", 6);
+ unsigned char expect[20];
+ reference.Result(expect);
+ CHECK_MEM(after, expect, 20);
+}
+
+TEST(md5_known_vectors)
+{
+ struct { const char *in; const char *out; } cases[] = {
+ { "", "d41d8cd98f00b204e9800998ecf8427e" },
+ { "a", "0cc175b9c0f1b6a831c399e269772661" },
+ { "abc", "900150983cd24fb0d6963f7d28e17f72" },
+ { "message digest", "f96b697d7cb7938d525a2f31aaf161d0" },
+ { "abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b" },
+ };
+
+ for (int i = 0; i < 5; ++i)
+ {
+ MD5_CTX ctx;
+ MD5Init(&ctx);
+ MD5Update(&ctx, (unsigned char *)cases[i].in, (unsigned int)strlen(cases[i].in));
+
+ unsigned char digest[16];
+ MD5Final(digest, &ctx);
+
+ char hex[33];
+ to_hex(digest, 16, hex);
+ CHECK_STR(hex, cases[i].out);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Ciphers
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(rc4_known_vector)
+{
+ /* The classic "Key"/"Plaintext" vector. */
+ unsigned char buffer[9];
+ memcpy(buffer, "Plaintext", 9);
+
+ RC4Class rc4;
+ rc4.Prepare_Key((const unsigned char *)"Key", 3);
+ rc4.RC4(buffer, 9);
+
+ char hex[19];
+ to_hex(buffer, 9, hex);
+ CHECK_STR(hex, "bbf316e8d940af0ad3");
+}
+
+TEST(rc4_is_its_own_inverse)
+{
+ unsigned char data[128], copy[128];
+ fill_pattern(data, sizeof(data), 3);
+ memcpy(copy, data, sizeof(data));
+
+ RC4Class enc;
+ enc.Prepare_Key((const unsigned char *)"0123456789abcdef", 16);
+ enc.RC4(data, sizeof(data));
+ CHECK(memcmp(data, copy, sizeof(data)) != 0);
+
+ RC4Class dec;
+ dec.Prepare_Key((const unsigned char *)"0123456789abcdef", 16);
+ dec.RC4(data, sizeof(data));
+ CHECK_MEM(data, copy, sizeof(data));
+}
+
+TEST(rc4_key_length_shortcuts_agree)
+{
+ /* Prepare_Key has hand-rolled 8- and 16-byte fast paths; they must produce
+ the same key stream as the general loop would. */
+ static const unsigned char key8[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
+ unsigned char a[64], b[64];
+ memset(a, 0, sizeof(a));
+ memset(b, 0, sizeof(b));
+
+ RC4Class fast;
+ fast.Prepare_Key(key8, 8);
+ fast.RC4(a, sizeof(a));
+
+ /* Copying the prepared state must give an identical stream. */
+ RC4Class other;
+ other.Prepare_Key(key8, 8);
+ RC4Class copy;
+ copy = other;
+ copy.RC4(b, sizeof(b));
+
+ CHECK_MEM(a, b, sizeof(a));
+}
+
+TEST(blowfish_round_trip)
+{
+ unsigned char plain[64], cypher[64], back[64];
+ fill_pattern(plain, sizeof(plain), 5);
+
+ BlowfishEngine bf;
+ bf.Submit_Key("a moderately long key", 21);
+
+ int n = bf.Encrypt(plain, sizeof(plain), cypher);
+ CHECK_EQ(n, (int)sizeof(plain));
+ CHECK(memcmp(plain, cypher, sizeof(plain)) != 0);
+
+ int m = bf.Decrypt(cypher, n, back);
+ CHECK_EQ(m, (int)sizeof(plain));
+ CHECK_MEM(plain, back, sizeof(plain));
+}
+
+TEST(blowfish_key_matters)
+{
+ unsigned char plain[16], c1[16], c2[16];
+ memset(plain, 0x5a, sizeof(plain));
+
+ BlowfishEngine a;
+ a.Submit_Key("key one", 7);
+ a.Encrypt(plain, sizeof(plain), c1);
+
+ BlowfishEngine b;
+ b.Submit_Key("key two", 7);
+ b.Encrypt(plain, sizeof(plain), c2);
+
+ CHECK(memcmp(c1, c2, sizeof(c1)) != 0);
+
+ /* Decrypting with the wrong key must not accidentally work. */
+ unsigned char wrong[16];
+ b.Decrypt(c1, sizeof(c1), wrong);
+ CHECK(memcmp(wrong, plain, sizeof(plain)) != 0);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// LCW / RLE
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(lcw_round_trip)
+{
+ /* Worst case LCW expands slightly, so the destination is oversized. */
+ unsigned char src[4096], packed[8192], back[4096];
+
+ static const unsigned seeds[] = { 1, 2, 3 };
+ for (int s = 0; s < 3; ++s)
+ {
+ fill_pattern(src, sizeof(src), seeds[s]);
+
+ int packed_len = LCW_Comp(src, packed, sizeof(src));
+ CHECK(packed_len > 0);
+
+ int out_len = LCW_Uncomp(packed, back, sizeof(back));
+ CHECK_EQ(out_len, (int)sizeof(src));
+ CHECK_MEM(src, back, sizeof(src));
+ }
+}
+
+TEST(lcw_compresses_repetitive_data)
+{
+ unsigned char src[4096], packed[8192], back[4096];
+ memset(src, 0xab, sizeof(src));
+
+ int packed_len = LCW_Comp(src, packed, sizeof(src));
+ /* A 4K run of one byte has to come out dramatically smaller, otherwise
+ the run encoder is not running at all. */
+ CHECK(packed_len < (int)sizeof(src) / 8);
+
+ CHECK_EQ(LCW_Uncomp(packed, back, sizeof(back)), (int)sizeof(src));
+ CHECK_MEM(src, back, sizeof(src));
+}
+
+TEST(lcw_short_and_empty_input)
+{
+ unsigned char packed[256], back[256];
+
+ /* len 0 and 1 never reach the assembler - it assumes at least two bytes
+ of input and used to run off the end of a one-byte buffer. */
+ for (int len = 0; len <= 32; ++len)
+ {
+ unsigned char src[32];
+ fill_pattern(src, len, 13);
+
+ int packed_len = LCW_Comp(src, packed, len);
+ CHECK(packed_len > 0);
+ CHECK_EQ(LCW_Uncomp(packed, back, sizeof(back)), len);
+ if (len > 0)
+ CHECK_MEM(src, back, len);
+ }
+}
+
+TEST(rle_round_trip)
+{
+ RLEEngine rle;
+ unsigned char src[2048], packed[4096], back[2048];
+ fill_pattern(src, sizeof(src), 17);
+
+ int packed_len = rle.Compress(src, packed, sizeof(src));
+ CHECK(packed_len > 0);
+
+ int out_len = rle.Decompress(packed, back, packed_len);
+ CHECK_EQ(out_len, (int)sizeof(src));
+ CHECK_MEM(src, back, sizeof(src));
+}
+
+TEST(rle_zero_runs_shrink)
+{
+ /* RLEEngine only encodes runs of zero - that is its documented scope. */
+ RLEEngine rle;
+ unsigned char src[2048], packed[4096], back[2048];
+ memset(src, 0, sizeof(src));
+
+ int packed_len = rle.Compress(src, packed, sizeof(src));
+ CHECK(packed_len < (int)sizeof(src) / 4);
+ CHECK_EQ(rle.Decompress(packed, back, packed_len), (int)sizeof(src));
+ CHECK_MEM(src, back, sizeof(src));
+
+ /* Data with no zeros at all must survive unharmed even though it cannot
+ be compressed. */
+ memset(src, 0xff, sizeof(src));
+ packed_len = rle.Compress(src, packed, sizeof(src));
+ CHECK_EQ(rle.Decompress(packed, back, packed_len), (int)sizeof(src));
+ CHECK_MEM(src, back, sizeof(src));
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Random number generators
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(random_is_deterministic_per_seed)
+{
+ RandomClass a(12345), b(12345), c(54321);
+
+ bool differed = false;
+ for (int i = 0; i < 64; ++i)
+ {
+ int va = a();
+ CHECK_EQ(va, b());
+ if (va != c())
+ differed = true;
+ }
+ /* A different seed must actually produce a different sequence. */
+ CHECK(differed);
+}
+
+TEST(random_range_is_inclusive_and_covers)
+{
+ RandomClass rng(999);
+
+ bool seen[7];
+ memset(seen, 0, sizeof(seen));
+
+ for (int i = 0; i < 4000; ++i)
+ {
+ int v = rng(-3, 3);
+ CHECK(v >= -3 && v <= 3);
+ seen[v + 3] = true;
+ }
+ for (int i = 0; i < 7; ++i)
+ CHECK(seen[i]);
+
+ /* Degenerate range must not spin or overflow. */
+ for (int i = 0; i < 16; ++i)
+ CHECK_EQ(rng(5, 5), 5);
+
+ /* Reversed bounds are swapped internally rather than rejected. */
+ for (int i = 0; i < 64; ++i)
+ {
+ int v = rng(9, 2);
+ CHECK(v >= 2 && v <= 9);
+ }
+}
+
+TEST(random2_3_4_are_deterministic_and_ranged)
+{
+ Random2Class r2a(7), r2b(7);
+ Random3Class r3a(7, 11), r3b(7, 11);
+ Random4Class r4a(7), r4b(7);
+
+ for (int i = 0; i < 64; ++i)
+ {
+ CHECK_EQ(r2a(), r2b());
+ CHECK_EQ(r3a(), r3b());
+ CHECK_EQ(r4a(), r4b());
+
+ int v2 = r2a(0, 10); CHECK(v2 >= 0 && v2 <= 10);
+ int v3 = r3a(0, 10); CHECK(v3 >= 0 && v3 <= 10);
+ int v4 = r4a(0, 10); CHECK(v4 >= 0 && v4 <= 10);
+ r2b(0, 10); r3b(0, 10); r4b(0, 10);
+ }
+}
+
+TEST(pick_random_number_helper)
+{
+ RandomClass rng(4242);
+ for (int i = 0; i < 256; ++i)
+ {
+ int v = Pick_Random_Number(rng, 100, 200);
+ CHECK(v >= 100 && v <= 200);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// fixed point
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(fixed_construction_and_conversion)
+{
+ fixed half(1, 2);
+ fixed one(1);
+ fixed three_quarters(3, 4);
+
+ CHECK(half == fixed::_1_2);
+ CHECK(three_quarters == fixed::_3_4);
+ CHECK(one > half);
+ CHECK(half < one);
+
+ /* operator unsigned rounds to nearest, it does not truncate. */
+ CHECK_EQ((unsigned)half, 1u);
+ CHECK_EQ((unsigned)fixed(1, 4), 0u);
+ CHECK_EQ((unsigned)fixed(3, 4), 1u);
+ CHECK_EQ((unsigned)fixed(200), 200u);
+}
+
+TEST(fixed_arithmetic)
+{
+ fixed a(1, 2);
+ fixed b(1, 4);
+
+ CHECK(a + b == fixed(3, 4));
+ CHECK(a - b == fixed(1, 4));
+ CHECK(a * b == fixed(1, 8));
+ CHECK(a / b == fixed(2));
+
+ /* Mixed integer operators return integers, rounded. */
+ CHECK_EQ(fixed(1, 2) * 10, 5);
+ CHECK_EQ(10 * fixed(1, 2), 5);
+ CHECK_EQ(fixed(3, 4) * 10, 8); /* 7.5 rounds up */
+}
+
+TEST(fixed_rounding_and_saturation)
+{
+ fixed v(7, 4); /* 1.75 */
+
+ CHECK(Round_Down(v) == fixed(1));
+ CHECK(Round_Up(v) == fixed(2));
+ CHECK(Round(v) == fixed(2));
+ CHECK(Round(fixed(5, 4)) == fixed(1));
+
+ CHECK(Saturate(fixed(10), 3u) == fixed(3));
+ CHECK(Saturate(fixed(2), 3u) == fixed(2));
+ CHECK(Sub_Saturate(fixed(10), 3u) < fixed(3));
+}
+
+TEST(fixed_ascii_round_trip)
+{
+ fixed from_text("0.5");
+ CHECK(from_text == fixed::_1_2);
+
+ fixed whole("3");
+ CHECK(whole == fixed(3));
+
+ char buffer[32];
+ fixed(1, 2).To_ASCII(buffer, sizeof(buffer));
+ /* Whatever formatting it picks, it has to parse back to the same value. */
+ CHECK(fixed(buffer) == fixed(1, 2));
+
+ CHECK(fixed(fixed(3, 4).As_ASCII()) == fixed(3, 4));
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Strings
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(stringclass_basics)
+{
+ StringClass s("hello");
+ CHECK_EQ(s.Get_Length(), 5);
+ CHECK(s == "hello");
+ CHECK(s != "Hello");
+ CHECK(!s.Is_Empty());
+
+ StringClass empty;
+ CHECK(empty.Is_Empty());
+ CHECK_EQ(empty.Get_Length(), 0);
+
+ s += " world";
+ CHECK(s == "hello world");
+ CHECK_EQ(s.Get_Length(), 11);
+
+ CHECK_EQ(s[0], 'h');
+ s[0] = 'H';
+ CHECK(s == "Hello world");
+}
+
+TEST(stringclass_compare_and_concat)
+{
+ StringClass a("abc");
+ StringClass b("abd");
+
+ CHECK(a.Compare("abc") == 0);
+ CHECK(a.Compare_No_Case("ABC") == 0);
+ CHECK(a < "abd");
+ CHECK(b > "abc");
+ CHECK(a <= "abc");
+ CHECK(a >= "abc");
+
+ StringClass joined = a + b;
+ CHECK(joined == "abcabd");
+ CHECK(("x" + a) == "xabc");
+ CHECK((a + "y") == "abcy");
+}
+
+TEST(stringclass_format_and_erase)
+{
+ StringClass s;
+ s.Format("%s has %d %s", "player", 3, "units");
+ CHECK(s == "player has 3 units");
+
+ s.Erase(0, 7);
+ CHECK(s == "has 3 units");
+
+ /* Growing well past the small-buffer threshold has to keep working. */
+ StringClass big;
+ big.Format("%0512d", 1);
+ CHECK_EQ(big.Get_Length(), 512);
+}
+
+TEST(stringclass_trim)
+{
+ StringClass s(" padded ");
+ s.Trim();
+ CHECK(s == "padded");
+
+ StringClass onlyspace(" ");
+ onlyspace.Trim();
+ CHECK(onlyspace.Is_Empty());
+}
+
+TEST(stringclass_long_strings_survive_reassignment)
+{
+ /* Free_String decides between the temp-string pool and the heap by
+ comparing addresses; getting that wrong corrupts the pool. Churn
+ through both size regimes to make sure it holds up. */
+ StringClass s;
+ for (int i = 0; i < 200; ++i)
+ {
+ StringClass tmp;
+ tmp.Format("%d", i);
+ s = tmp;
+ CHECK_EQ(atoi(s), i);
+
+ StringClass longer;
+ longer.Format("%0300d", i);
+ s = longer;
+ CHECK_EQ(s.Get_Length(), 300);
+ }
+}
+
+TEST(widestring_basics)
+{
+ WideStringClass w(L"wide");
+ CHECK_EQ(w.Get_Length(), 4);
+ CHECK(w == L"wide");
+ CHECK(w != L"WIDE");
+
+ w += L" text";
+ CHECK(w == L"wide text");
+ CHECK_EQ(w.Get_Length(), 9);
+
+ /* Round trip through the narrow representation. */
+ WideStringClass from_narrow("ascii");
+ CHECK(from_narrow == L"ascii");
+
+ StringClass narrow;
+ narrow = from_narrow;
+ CHECK(narrow == "ascii");
+}
+
+TEST(widestring_compare_and_format)
+{
+ WideStringClass a(L"abc");
+ CHECK(a.Compare(L"abc") == 0);
+ CHECK(a.Compare_No_Case(L"ABC") == 0);
+ CHECK(a < L"abd");
+
+ WideStringClass f;
+ f.Format(L"%d-%d", 4, 5);
+ CHECK(f == L"4-5");
+}
+
+TEST(strtrim_in_place)
+{
+ char buffer[64];
+
+ strcpy(buffer, " leading and trailing ");
+ CHECK_STR(strtrim(buffer), "leading and trailing");
+
+ strcpy(buffer, "notrim");
+ CHECK_STR(strtrim(buffer), "notrim");
+
+ strcpy(buffer, " ");
+ CHECK_STR(strtrim(buffer), "");
+
+ strcpy(buffer, "");
+ CHECK_STR(strtrim(buffer), "");
+
+ strcpy(buffer, "\t\ntabs\r\n");
+ CHECK_STR(strtrim(buffer), "tabs");
+}
+
+TEST(nstrdup_copies)
+{
+ char *copy = nstrdup("duplicated");
+ CHECK_STR(copy, "duplicated");
+ delete[] copy;
+
+ CHECK(nstrdup(0) == 0);
+}
+
+TEST(strtok_r_is_reentrant)
+{
+ char outer[] = "a,b,c";
+ char inner[] = "1-2-3";
+ char *outer_state = 0;
+ char *inner_state = 0;
+
+ const char *expect_outer[] = { "a", "b", "c" };
+ const char *expect_inner[] = { "1", "2", "3" };
+
+ char *o = strtok_r(outer, ",", &outer_state);
+ for (int i = 0; i < 3; ++i)
+ {
+ CHECK_STR(o, expect_outer[i]);
+
+ /* Interleave a second tokenisation - the whole point of the _r form. */
+ char scratch[16];
+ strcpy(scratch, inner);
+ char *n = strtok_r(scratch, "-", &inner_state);
+ for (int j = 0; j < 3; ++j)
+ {
+ CHECK_STR(n, expect_inner[j]);
+ n = strtok_r(0, "-", &inner_state);
+ }
+ CHECK(n == 0);
+
+ o = strtok_r(0, ",", &outer_state);
+ }
+ CHECK(o == 0);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Small numeric helpers
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(gcd_and_lcm)
+{
+ CHECK_EQ(Greatest_Common_Divisor(12, 18), 6u);
+ CHECK_EQ(Greatest_Common_Divisor(18, 12), 6u);
+ CHECK_EQ(Greatest_Common_Divisor(17, 5), 1u);
+ CHECK_EQ(Greatest_Common_Divisor(9, 9), 9u);
+
+ CHECK_EQ(Least_Common_Multiple(4, 6), 12u);
+ CHECK_EQ(Least_Common_Multiple(21, 6), 42u);
+ CHECK_EQ(Least_Common_Multiple(7, 7), 7u);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Containers
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(vectorclass_resize_and_id)
+{
+ VectorClass<int> v(4);
+ CHECK_EQ(v.Length(), 4);
+
+ for (int i = 0; i < 4; ++i)
+ v[i] = i * 10;
+
+ CHECK_EQ(v.ID(20), 2);
+ CHECK_EQ(v.ID(99), -1);
+ CHECK_EQ(v.ID(&v[3]), 3);
+
+ /* Resize must preserve the surviving prefix. */
+ CHECK(v.Resize(8));
+ CHECK_EQ(v.Length(), 8);
+ for (int i = 0; i < 4; ++i)
+ CHECK_EQ(v[i], i * 10);
+
+ v.Clear();
+ CHECK_EQ(v.Length(), 0);
+}
+
+TEST(dynamicvector_add_insert_delete)
+{
+ DynamicVectorClass<int> v;
+ CHECK_EQ(v.Count(), 0);
+
+ for (int i = 0; i < 10; ++i)
+ CHECK(v.Add(i));
+ CHECK_EQ(v.Count(), 10);
+ for (int i = 0; i < 10; ++i)
+ CHECK_EQ(v[i], i);
+
+ CHECK(v.Add_Head(-1));
+ CHECK_EQ(v[0], -1);
+ CHECK_EQ(v.Count(), 11);
+
+ CHECK(v.Insert(5, 555));
+ CHECK_EQ(v[5], 555);
+ CHECK_EQ(v.Count(), 12);
+
+ CHECK(v.Delete_Index(5));
+ CHECK_EQ(v.Count(), 11);
+ CHECK_EQ(v.ID(555), -1);
+
+ CHECK(v.Delete_Index(0)); /* drops the -1 added at the head */
+ CHECK_EQ(v[0], 0);
+ CHECK_EQ(v.Count(), 10);
+
+ v.Delete_All();
+ CHECK_EQ(v.Count(), 0);
+}
+
+TEST(dynamicvector_delete_by_value)
+{
+ /* Delete(T const &) and Delete(int) are ambiguous for an int vector, so
+ the by-value overload gets exercised on a type that disambiguates. */
+ DynamicVectorClass<float> v;
+ for (int i = 0; i < 5; ++i)
+ v.Add(float(i) * 1.5f);
+
+ CHECK(v.Delete(3.0f));
+ CHECK_EQ(v.Count(), 4);
+ CHECK_EQ(v.ID(3.0f), -1);
+
+ CHECK(!v.Delete(99.0f));
+ CHECK_EQ(v.Count(), 4);
+}
+
+TEST(dynamicvector_grows_past_initial_capacity)
+{
+ DynamicVectorClass<int> v(2);
+ v.Set_Growth_Step(3);
+
+ for (int i = 0; i < 100; ++i)
+ CHECK(v.Add(i * 3));
+
+ CHECK_EQ(v.Count(), 100);
+ for (int i = 0; i < 100; ++i)
+ CHECK_EQ(v[i], i * 3);
+}
+
+TEST(simplevec_basics)
+{
+ SimpleVecClass<float> v(4);
+ CHECK_EQ(v.Length(), 4);
+
+ for (int i = 0; i < 4; ++i)
+ v[i] = float(i);
+
+ v.Resize(8);
+ CHECK_EQ(v.Length(), 8);
+ for (int i = 0; i < 4; ++i)
+ CHECK_NEAR(v[i], float(i), 1e-6f);
+
+ v.Zero_Memory();
+ for (int i = 0; i < 8; ++i)
+ CHECK_NEAR(v[i], 0.0f, 1e-6f);
+}
+
+namespace
+{
+ /* Minimal concrete HashableClass - the table stores the key by pointer,
+ so the string has to outlive the entry. */
+ class TestEntry : public HashableClass
+ {
+ public:
+ TestEntry(const char *key) : Key(key) {}
+ virtual const char *Get_Key(void) { return Key; }
+ const char *Key;
+ };
+
+ class ListItem : public MultiListObjectClass
+ {
+ public:
+ ListItem(int v) : Value(v) {}
+ int Value;
+ };
+}
+
+TEST(hashtable_add_find_remove)
+{
+ HashTableClass table(32);
+
+ TestEntry a("alpha"), b("beta"), c("gamma");
+ table.Add(&a);
+ table.Add(&b);
+ table.Add(&c);
+
+ CHECK(table.Find("alpha") == &a);
+ CHECK(table.Find("beta") == &b);
+ CHECK(table.Find("gamma") == &c);
+ CHECK(table.Find("delta") == 0);
+
+ CHECK(table.Remove(&b));
+ CHECK(table.Find("beta") == 0);
+ CHECK(table.Find("alpha") == &a);
+
+ table.Reset();
+ CHECK(table.Find("alpha") == 0);
+}
+
+TEST(hashtable_survives_collisions)
+{
+ /* A tiny table forces every key into a shared bucket chain. */
+ HashTableClass table(2);
+
+ const int COUNT = 64;
+ char keys[COUNT][16];
+ TestEntry *entries[COUNT];
+
+ for (int i = 0; i < COUNT; ++i)
+ {
+ sprintf(keys[i], "key%d", i);
+ entries[i] = new TestEntry(keys[i]);
+ table.Add(entries[i]);
+ }
+
+ for (int i = 0; i < COUNT; ++i)
+ CHECK(table.Find(keys[i]) == entries[i]);
+
+ /* Removing from the middle of a chain must not lose the rest of it. */
+ for (int i = 0; i < COUNT; i += 2)
+ CHECK(table.Remove(entries[i]));
+ for (int i = 1; i < COUNT; i += 2)
+ CHECK(table.Find(keys[i]) == entries[i]);
+
+ table.Reset();
+ for (int i = 0; i < COUNT; ++i)
+ delete entries[i];
+}
+
+TEST(hashtable_iterator_visits_everything)
+{
+ HashTableClass table(8);
+
+ const int COUNT = 20;
+ char keys[COUNT][16];
+ TestEntry *entries[COUNT];
+ for (int i = 0; i < COUNT; ++i)
+ {
+ sprintf(keys[i], "k%d", i);
+ entries[i] = new TestEntry(keys[i]);
+ table.Add(entries[i]);
+ }
+
+ bool seen[COUNT];
+ memset(seen, 0, sizeof(seen));
+
+ HashTableIteratorClass it(table);
+ int visited = 0;
+ for (it.First(); !it.Is_Done(); it.Next())
+ {
+ HashableClass *entry = it.Get_Current();
+ for (int i = 0; i < COUNT; ++i)
+ {
+ if (entry == entries[i])
+ {
+ CHECK(!seen[i]);
+ seen[i] = true;
+ }
+ }
+ ++visited;
+ }
+ CHECK_EQ(visited, COUNT);
+
+ table.Reset();
+ for (int i = 0; i < COUNT; ++i)
+ delete entries[i];
+}
+
+TEST(multilist_add_remove_and_membership)
+{
+ MultiListClass<ListItem> list;
+ CHECK(list.Is_Empty());
+
+ ListItem a(1), b(2), c(3);
+ CHECK(list.Add(&a));
+ CHECK(list.Add(&b));
+ CHECK(list.Add(&c));
+ CHECK(!list.Is_Empty());
+
+ CHECK(list.Contains(&a));
+ CHECK(list.Contains(&c));
+
+ /* onlyonce defaults to true, so a repeat add is refused. */
+ CHECK(!list.Add(&a));
+
+ CHECK(list.Remove(&b));
+ CHECK(!list.Contains(&b));
+ CHECK(!list.Remove(&b));
+
+ int count = 0;
+ MultiListIterator<ListItem> it(&list);
+ for (it.First(); !it.Is_Done(); it.Next())
+ ++count;
+ CHECK_EQ(count, 2);
+
+ /* Destroying a member has to unlink it - that is what the object base
+ class exists for. Empty the list before it goes out of scope, since
+ GenericMultiListClass asserts on a non-empty destructor. */
+ list.Remove(&a);
+ list.Remove(&c);
+ CHECK(list.Is_Empty());
+}
+
+TEST(multilist_object_unlinks_itself_on_destruction)
+{
+ MultiListClass<ListItem> list;
+ {
+ ListItem transient(9);
+ CHECK(list.Add(&transient));
+ CHECK(!list.Is_Empty());
+ }
+ /* transient is gone; MultiListObjectClass::~ must have pulled it out. */
+ CHECK(list.Is_Empty());
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// RAM files and chunk IO
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(ramfile_read_write_seek)
+{
+ char storage[256];
+ memset(storage, 0, sizeof(storage));
+
+ RAMFileClass file(storage, sizeof(storage));
+ CHECK(file.Open(FileClass::WRITE) != 0);
+
+ const char *payload = "chunk of bytes";
+ int len = (int)strlen(payload);
+ CHECK_EQ(file.Write(payload, len), len);
+ CHECK_EQ(file.Size(), len);
+ file.Close();
+
+ CHECK(file.Open(FileClass::READ) != 0);
+ char back[64];
+ memset(back, 0, sizeof(back));
+ CHECK_EQ(file.Read(back, len), len);
+ CHECK_STR(back, payload);
+
+ /* Seek back to the start and re-read. */
+ CHECK_EQ(file.Seek(0, SEEK_SET), 0);
+ memset(back, 0, sizeof(back));
+ CHECK_EQ(file.Read(back, 5), 5);
+ CHECK(!memcmp(back, "chunk", 5));
+
+ /* Reading past the end returns a short count rather than running off. */
+ CHECK_EQ(file.Seek(0, SEEK_END), len);
+ CHECK_EQ(file.Read(back, 32), 0);
+ file.Close();
+}
+
+TEST(chunkio_nested_chunks_round_trip)
+{
+ char storage[1024];
+ memset(storage, 0, sizeof(storage));
+
+ const uint32 OUTER = 0x100;
+ const uint32 INNER = 0x101;
+ const uint32 SIBLING = 0x102;
+ int written = 0;
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+
+ CHECK(csave.Begin_Chunk(OUTER));
+ CHECK_EQ(csave.Cur_Chunk_Depth(), 1);
+
+ CHECK(csave.Begin_Chunk(INNER));
+ CHECK_EQ(csave.Cur_Chunk_Depth(), 2);
+ int payload = 0x1234;
+ CHECK_EQ(csave.Write(&payload, sizeof(payload)), (uint32)sizeof(payload));
+ CHECK(csave.End_Chunk());
+
+ CHECK(csave.Begin_Chunk(SIBLING));
+ float f = 2.5f;
+ CHECK_EQ(csave.Write(&f, sizeof(f)), (uint32)sizeof(f));
+ CHECK(csave.End_Chunk());
+
+ CHECK(csave.End_Chunk());
+ CHECK_EQ(csave.Cur_Chunk_Depth(), 0);
+ written = file.Size();
+ file.Close();
+ }
+
+ /* Size the reader to what was actually written - a RAMFileClass spanning
+ the whole scratch buffer would hand ChunkLoadClass the trailing zeros as
+ a perfectly valid empty chunk header. */
+ {
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+
+ CHECK(cload.Open_Chunk());
+ CHECK_EQ(cload.Cur_Chunk_ID(), OUTER);
+ CHECK(cload.Contains_Chunks() != 0);
+
+ CHECK(cload.Open_Chunk());
+ CHECK_EQ(cload.Cur_Chunk_ID(), INNER);
+ int payload = 0;
+ CHECK_EQ(cload.Read(&payload, sizeof(payload)), (uint32)sizeof(payload));
+ CHECK_EQ(payload, 0x1234);
+ CHECK(cload.Close_Chunk());
+
+ CHECK(cload.Open_Chunk());
+ CHECK_EQ(cload.Cur_Chunk_ID(), SIBLING);
+ float f = 0.0f;
+ CHECK_EQ(cload.Read(&f, sizeof(f)), (uint32)sizeof(f));
+ CHECK_NEAR(f, 2.5f, 1e-6f);
+ CHECK(cload.Close_Chunk());
+
+ CHECK(!cload.Open_Chunk()); /* no more children */
+ CHECK(cload.Close_Chunk());
+ CHECK(!cload.Open_Chunk()); /* end of file */
+ }
+}
+
+TEST(chunkio_micro_chunks_round_trip)
+{
+ char storage[1024];
+ int written = 0;
+ memset(storage, 0, sizeof(storage));
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+
+ csave.Begin_Chunk(0x200);
+ for (int i = 0; i < 8; ++i)
+ {
+ CHECK(csave.Begin_Micro_Chunk(i));
+ int value = i * 100;
+ csave.Write(&value, sizeof(value));
+ CHECK(csave.End_Micro_Chunk());
+ }
+ csave.End_Chunk();
+ written = file.Size();
+ file.Close();
+ }
+
+ {
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+
+ CHECK(cload.Open_Chunk());
+ CHECK_EQ(cload.Cur_Chunk_ID(), (uint32)0x200);
+
+ int seen = 0;
+ while (cload.Open_Micro_Chunk())
+ {
+ int value = 0;
+ CHECK_EQ(cload.Cur_Micro_Chunk_ID(), (uint32)seen);
+ CHECK_EQ(cload.Cur_Micro_Chunk_Length(), (uint32)sizeof(value));
+ cload.Read(&value, sizeof(value));
+ CHECK_EQ(value, seen * 100);
+ CHECK(cload.Close_Micro_Chunk());
+ ++seen;
+ }
+ CHECK_EQ(seen, 8);
+ CHECK(cload.Close_Chunk());
+ }
+}
+
+TEST(chunkio_seek_skips_payload)
+{
+ char storage[512];
+ int written = 0;
+ memset(storage, 0, sizeof(storage));
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+ csave.Begin_Chunk(0x300);
+ unsigned char blob[64];
+ fill_pattern(blob, sizeof(blob), 21);
+ csave.Write(blob, sizeof(blob));
+ csave.End_Chunk();
+ written = file.Size();
+ file.Close();
+ }
+
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+
+ CHECK(cload.Open_Chunk());
+ CHECK_EQ(cload.Cur_Chunk_Length(), (uint32)64);
+ CHECK_EQ(cload.Seek(64), (uint32)64);
+ CHECK(cload.Close_Chunk());
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// CPU detection
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(cpudetect_reports_something_sane)
+{
+ /* Anything this port can run on has CPUID and RDTSC. */
+ CHECK(CPUDetectClass::Has_CPUID_Instruction());
+ CHECK(CPUDetectClass::Has_RDTSC_Instruction());
+ CHECK(CPUDetectClass::Has_MMX_Instruction_Set());
+ CHECK(CPUDetectClass::Has_SSE_Instruction_Set());
+
+ CHECK(CPUDetectClass::Get_Processor_Speed() > 0);
+ CHECK(CPUDetectClass::Get_Processor_Ticks_Per_Second() > 0);
+ CHECK(CPUDetectClass::Get_Total_Physical_Memory() > 0);
+
+ const char *name = CPUDetectClass::Get_Processor_Manufacturer_Name();
+ CHECK(name != 0 && name[0] != 0);
+ CHECK(CPUDetectClass::Get_Processor_String()[0] != 0);
+}
+
+TEST(cpudetect_logs_are_printable)
+{
+ /* Regression for the os_info bug: Get_OS_Info used to leave the struct
+ uninitialised on every Windows >= Vista, so the log strings were built
+ from dangling pointers. A printable, non-empty log is the cheap way to
+ assert the defaults are seeded. */
+ const StringClass &log = CPUDetectClass::Get_Processor_Log();
+ const StringClass &compact = CPUDetectClass::Get_Compact_Log();
+
+ CHECK(!log.Is_Empty());
+ CHECK(!compact.Is_Empty());
+
+ const char *p = compact;
+ for (int i = 0; p[i]; ++i)
+ {
+ unsigned char ch = (unsigned char)p[i];
+ CHECK(ch == '\t' || ch == '\n' || ch == '\r' || (ch >= 0x20 && ch < 0x7f));
+ }
+
+ /* The compact log is tab separated; the OS code is the first field and
+ must never be blank. */
+ CHECK(p[0] != '\t');
+}
diff --git a/GeneralsMD/Code/Tests/test_wwmath.cpp b/GeneralsMD/Code/Tests/test_wwmath.cpp
new file mode 100644
index 000000000..7dda6689a
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_wwmath.cpp
@@ -0,0 +1,1193 @@
+/*
+ * wwmath coverage.
+ *
+ * Priorities, in order:
+ * 1. Anything reimplemented during the port (Matrix3D::Get_Inverse, which
+ * replaced D3DXMatrixInverse) - these can silently produce wrong numbers.
+ * 2. Anything with 32-bit inline __asm (WWMath::Inv_Sqrt, Float_To_Long,
+ * the whole VectorProcessorClass) - the asm is the reason this port is
+ * Win32-only, and it is exactly what a compiler upgrade can miscompile.
+ * 3. The geometry predicates the renderer and collision system stand on.
+ *
+ * Where an answer is analytically known it is asserted against the closed
+ * form, not against whatever the code happens to return today.
+ */
+#include "test_harness.h"
+
+#include "wwmath.h"
+#include "vector2.h"
+#include "vector3.h"
+#include "vector4.h"
+#include "matrix3.h"
+#include "matrix3d.h"
+#include "matrix4.h"
+#include "quat.h"
+#include "euler.h"
+#include "aabox.h"
+#include "obbox.h"
+#include "sphere.h"
+#include "plane.h"
+#include "aaplane.h"
+#include "tri.h"
+#include "lineseg.h"
+#include "colmath.h"
+/* Several Overlap_Test overloads (box/point, box/box, plane/point) are WWINLINE
+ in these two headers rather than compiled into the lib, so anything calling
+ AABoxClass::Contains needs them or it fails at link time. */
+#include "colmathaabox.h"
+#include "colmathplane.h"
+#include "colmathinlines.h"
+#include "pot.h"
+#include "vp.h"
+#include "castres.h"
+
+static const float EPS = 1e-4f;
+
+/* Matrix3D has no operator*(Vector3) - transforming a point goes through the
+ static Transform_Vector. Wrap it so the tests read like the maths. */
+static Vector3 xform(const Matrix3D &m, const Vector3 &v)
+{
+ Vector3 out;
+ Matrix3D::Transform_Vector(m, v, &out);
+ return out;
+}
+
+/* WWMath::Init builds the Fast_Sin/Fast_Acos lookup tables; without it the
+ Fast_* family returns garbage. Run it once, lazily, from every test that
+ needs it rather than relying on static-init order. */
+static void ensure_math_init(void)
+{
+ static bool done = false;
+ if (!done)
+ {
+ WWMath::Init();
+ /* Init parks a default table in LookupTableMgrClass's static list;
+ leaving it there faults while the CRT tears the statics down, so
+ pair every Init with a Shutdown before that happens. */
+ atexit(WWMath::Shutdown);
+ done = true;
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Scalar helpers
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(wwmath_sqrt_and_inv_sqrt)
+{
+ /* Inv_Sqrt is __fastcall inline asm on x86 - the single most
+ port-sensitive function in the library. */
+ static const float vals[] = { 1.0f, 2.0f, 4.0f, 0.25f, 100.0f, 1e6f, 1e-6f };
+
+ for (int i = 0; i < int(sizeof(vals) / sizeof(vals[0])); ++i)
+ {
+ float v = vals[i];
+ CHECK_NEAR(WWMath::Sqrt(v), sqrt(double(v)), fabs(sqrt(double(v))) * 1e-5 + 1e-6);
+
+ /* Intel's rsqrt approximation - documented as ~30% faster, so it is
+ allowed to be loose, but not more than a few ulp of relative error. */
+ double expect = 1.0 / sqrt(double(v));
+ CHECK_NEAR(WWMath::Inv_Sqrt(v), expect, expect * 1e-4);
+ }
+}
+
+TEST(wwmath_float_to_long_rounds_like_asm)
+{
+ /* The asm version uses fistp, i.e. round-to-nearest-even, not C truncation.
+ Anything that relies on truncation here would be a porting bug. */
+ CHECK_EQ(WWMath::Float_To_Long(3.4f), 3L);
+ CHECK_EQ(WWMath::Float_To_Long(-3.4f), -3L);
+ CHECK_EQ(WWMath::Float_To_Long(0.0f), 0L);
+ CHECK_EQ(WWMath::Float_To_Long(2.5f), 2L); /* ties to even */
+ CHECK_EQ(WWMath::Float_To_Long(3.5f), 4L);
+ CHECK_EQ(WWMath::Float_To_Long(-2.5f), -2L);
+}
+
+TEST(wwmath_float_to_int_chop_and_floor)
+{
+ CHECK_EQ(WWMath::Float_To_Int_Chop(3.9f), 3);
+ CHECK_EQ(WWMath::Float_To_Int_Chop(-3.9f), -3);
+ CHECK_EQ(WWMath::Float_To_Int_Floor(3.9f), 3);
+ CHECK_EQ(WWMath::Float_To_Int_Floor(-3.9f), -4);
+ CHECK_EQ(WWMath::Float_To_Int_Floor(-4.0f), -4);
+}
+
+TEST(wwmath_clamp_wrap_lerp)
+{
+ CHECK_NEAR(WWMath::Clamp(0.5f, 0.0f, 1.0f), 0.5f, EPS);
+ CHECK_NEAR(WWMath::Clamp(-2.0f, 0.0f, 1.0f), 0.0f, EPS);
+ CHECK_NEAR(WWMath::Clamp(7.0f, 0.0f, 1.0f), 1.0f, EPS);
+ CHECK_EQ(WWMath::Clamp_Int(15, -3, 9), 9);
+ CHECK_EQ(WWMath::Clamp_Int(-15, -3, 9), -3);
+ CHECK_EQ(WWMath::Clamp_Int(4, -3, 9), 4);
+
+ /* Wrap is exclusive of max: wrapping exactly max lands on min. */
+ CHECK_NEAR(WWMath::Wrap(0.25f, 0.0f, 1.0f), 0.25f, EPS);
+ CHECK_NEAR(WWMath::Wrap(1.25f, 0.0f, 1.0f), 0.25f, EPS);
+ CHECK_NEAR(WWMath::Wrap(-0.75f, 0.0f, 1.0f), 0.25f, EPS);
+ CHECK_NEAR(WWMath::Wrap(5.5f, 2.0f, 4.0f), 3.5f, EPS);
+
+ CHECK_NEAR(WWMath::Lerp(10.0f, 20.0f, 0.0f), 10.0f, EPS);
+ CHECK_NEAR(WWMath::Lerp(10.0f, 20.0f, 1.0f), 20.0f, EPS);
+ CHECK_NEAR(WWMath::Lerp(10.0f, 20.0f, 0.25f), 12.5f, EPS);
+}
+
+TEST(wwmath_sign_min_max_fabs)
+{
+ CHECK_NEAR(WWMath::Sign(-9.0f), -1.0f, EPS);
+ CHECK_NEAR(WWMath::Sign(9.0f), 1.0f, EPS);
+ CHECK_NEAR(WWMath::Fabs(-3.5f), 3.5f, EPS);
+ CHECK_NEAR(WWMath::Min(3.0f, -1.0f), -1.0f, EPS);
+ CHECK_NEAR(WWMath::Max(3.0f, -1.0f), 3.0f, EPS);
+ CHECK(WWMath::Fast_Is_Float_Positive(1.0f));
+ CHECK(!WWMath::Fast_Is_Float_Positive(-1.0f));
+}
+
+TEST(wwmath_is_power_of_2)
+{
+ CHECK(WWMath::Is_Power_Of_2(1));
+ CHECK(WWMath::Is_Power_Of_2(2));
+ CHECK(WWMath::Is_Power_Of_2(256));
+ CHECK(WWMath::Is_Power_Of_2(1u << 31));
+ CHECK(!WWMath::Is_Power_Of_2(3));
+ CHECK(!WWMath::Is_Power_Of_2(255));
+}
+
+TEST(wwmath_unit_float_byte_roundtrip)
+{
+ for (int b = 0; b < 256; ++b)
+ {
+ float f = WWMath::Byte_To_Unit_Float((unsigned char)b);
+ CHECK_EQ(int(WWMath::Unit_Float_To_Byte(f)), b);
+ }
+}
+
+TEST(wwmath_fast_trig_matches_libm)
+{
+ ensure_math_init();
+
+ /* Table-driven approximations: tolerance is set by the table size
+ (SIN_TABLE_SIZE / ARC_TABLE_SIZE), not by float precision. */
+ for (int i = 0; i <= 64; ++i)
+ {
+ float t = float(i) / 64.0f;
+ float ang = -WWMATH_PI + t * 2.0f * WWMATH_PI;
+ CHECK_NEAR(WWMath::Fast_Sin(ang), sin(double(ang)), 0.005);
+ CHECK_NEAR(WWMath::Fast_Cos(ang), cos(double(ang)), 0.005);
+
+ float x = -1.0f + t * 2.0f;
+ CHECK_NEAR(WWMath::Fast_Acos(x), acos(double(x)), 0.02);
+ CHECK_NEAR(WWMath::Fast_Asin(x), asin(double(x)), 0.02);
+ }
+}
+
+TEST(wwmath_acos_asin_clamp_out_of_range)
+{
+ ensure_math_init();
+
+ /* WWMath::Acos/Asin are bare wrappers over libm - they do NOT clamp, so a
+ dot product that lands a hair outside [-1,1] (which normalised vectors
+ do all the time) yields NaN. Pinned here so nobody assumes otherwise:
+ callers have to clamp themselves. Fast_* inherits it, because outside
+ +/-0.975 it defers to the exact form. */
+ CHECK(WWMath::Acos(1.0000001f) != WWMath::Acos(1.0000001f));
+ CHECK(WWMath::Asin(-1.0000001f) != WWMath::Asin(-1.0000001f));
+ CHECK(WWMath::Fast_Acos(1.5f) != WWMath::Fast_Acos(1.5f));
+ CHECK(WWMath::Fast_Asin(-1.5f) != WWMath::Fast_Asin(-1.5f));
+
+ /* Exactly on the boundary is still finite. */
+ CHECK_NEAR(WWMath::Acos(1.0f), 0.0f, EPS);
+ CHECK_NEAR(WWMath::Acos(-1.0f), WWMATH_PI, EPS);
+ CHECK_NEAR(WWMath::Asin(1.0f), WWMATH_PI * 0.5f, EPS);
+ CHECK_NEAR(WWMath::Fast_Acos(1.0f), 0.0f, EPS);
+ CHECK_NEAR(WWMath::Fast_Asin(-1.0f), -WWMATH_PI * 0.5f, EPS);
+}
+
+TEST(pot_find_power_of_two)
+{
+ CHECK_EQ(Find_POT(1), 1);
+ CHECK_EQ(Find_POT(2), 2);
+ CHECK_EQ(Find_POT(3), 4);
+ CHECK_EQ(Find_POT(5), 8);
+ CHECK_EQ(Find_POT(256), 256);
+ CHECK_EQ(Find_POT(257), 512);
+
+ CHECK_EQ(int(Find_POT_Log2(1)), 0);
+ CHECK_EQ(int(Find_POT_Log2(2)), 1);
+ CHECK_EQ(int(Find_POT_Log2(4)), 2);
+ CHECK_EQ(int(Find_POT_Log2(256)), 8);
+ /* Every POT that a texture dimension can take must round-trip. */
+ for (int shift = 0; shift <= 12; ++shift)
+ CHECK_EQ(Find_POT(1 << shift), 1 << shift);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Vector2 / Vector3 / Vector4
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(vector3_arithmetic)
+{
+ Vector3 a(1.0f, 2.0f, 3.0f);
+ Vector3 b(4.0f, 5.0f, 6.0f);
+
+ Vector3 sum = a + b;
+ CHECK_NEAR(sum.X, 5.0f, EPS);
+ CHECK_NEAR(sum.Y, 7.0f, EPS);
+ CHECK_NEAR(sum.Z, 9.0f, EPS);
+
+ Vector3 diff = b - a;
+ CHECK_NEAR(diff.X, 3.0f, EPS);
+
+ Vector3 scaled = a * 2.0f;
+ CHECK_NEAR(scaled.Z, 6.0f, EPS);
+
+ Vector3 neg = -a;
+ CHECK_NEAR(neg.X, -1.0f, EPS);
+
+ a += b;
+ CHECK_NEAR(a.X, 5.0f, EPS);
+ a -= b;
+ CHECK_NEAR(a.X, 1.0f, EPS);
+
+ CHECK(Vector3(1.0f, 2.0f, 3.0f) == Vector3(1.0f, 2.0f, 3.0f));
+ CHECK(Vector3(1.0f, 2.0f, 3.0f) != Vector3(1.0f, 2.0f, 3.5f));
+}
+
+TEST(vector3_length_and_normalize)
+{
+ Vector3 v(3.0f, 4.0f, 12.0f);
+ CHECK_NEAR(v.Length2(), 169.0f, EPS);
+ CHECK_NEAR(v.Length(), 13.0f, EPS);
+ /* Quick_Length is the Graphics Gems approximation, worst case ~8.7% high
+ (which (3,4,12) hits almost exactly). That only holds once the three
+ components are actually sorted - the third swap used to assign min=mid
+ and lose the old mid, pushing this case to 14.375, i.e. 10.6% high. */
+ CHECK_NEAR(v.Quick_Length(), 13.0f, 13.0f * 0.09f);
+ CHECK_NEAR(Vector3(12.0f, 4.0f, 3.0f).Quick_Length(), 13.0f, 13.0f * 0.09f);
+ CHECK_NEAR(Vector3(-3.0f, -12.0f, -4.0f).Quick_Length(), 13.0f, 13.0f * 0.09f);
+ CHECK_NEAR(Vector3(0.0f, 0.0f, 0.0f).Quick_Length(), 0.0f, EPS);
+
+ v.Normalize();
+ CHECK_NEAR(v.Length(), 1.0f, EPS);
+ CHECK_NEAR(v.X, 3.0f / 13.0f, EPS);
+
+ Vector3 n(0.0f, 5.0f, 0.0f);
+ n.Normalize();
+ CHECK_NEAR(n.Y, 1.0f, EPS);
+}
+
+TEST(vector3_dot_and_cross)
+{
+ Vector3 a(1.0f, 2.0f, 3.0f);
+ Vector3 b(4.0f, -5.0f, 6.0f);
+
+ CHECK_NEAR(Vector3::Dot_Product(a, b), 4.0f - 10.0f + 18.0f, EPS);
+
+ Vector3 c;
+ Vector3::Cross_Product(a, b, &c);
+ /* a x b = (2*6-3*-5, 3*4-1*6, 1*-5-2*4) = (27, 6, -13) */
+ CHECK_NEAR(c.X, 27.0f, EPS);
+ CHECK_NEAR(c.Y, 6.0f, EPS);
+ CHECK_NEAR(c.Z, -13.0f, EPS);
+
+ /* The cross product is orthogonal to both inputs. */
+ CHECK_NEAR(Vector3::Dot_Product(c, a), 0.0f, EPS);
+ CHECK_NEAR(Vector3::Dot_Product(c, b), 0.0f, EPS);
+
+ /* ...and anti-commutative. */
+ Vector3 d;
+ Vector3::Cross_Product(b, a, &d);
+ CHECK_NEAR(d.X, -c.X, EPS);
+}
+
+TEST(vector3_lerp_minmax_cap)
+{
+ Vector3 a(0.0f, 0.0f, 0.0f);
+ Vector3 b(10.0f, 20.0f, -40.0f);
+
+ Vector3 mid;
+ Vector3::Lerp(a, b, 0.25f, &mid);
+ CHECK_NEAR(mid.X, 2.5f, EPS);
+ CHECK_NEAR(mid.Z, -10.0f, EPS);
+
+ Vector3 lo(1.0f, 9.0f, 5.0f);
+ lo.Update_Min(Vector3(4.0f, 2.0f, 5.0f));
+ CHECK_NEAR(lo.X, 1.0f, EPS);
+ CHECK_NEAR(lo.Y, 2.0f, EPS);
+
+ Vector3 hi(1.0f, 9.0f, 5.0f);
+ hi.Update_Max(Vector3(4.0f, 2.0f, 5.0f));
+ CHECK_NEAR(hi.X, 4.0f, EPS);
+ CHECK_NEAR(hi.Y, 9.0f, EPS);
+
+ Vector3 cap(-8.0f, 3.0f, 0.5f);
+ cap.Cap_Absolute_To(Vector3(5.0f, 5.0f, 5.0f));
+ CHECK_NEAR(cap.X, -5.0f, EPS);
+ CHECK_NEAR(cap.Y, 3.0f, EPS);
+}
+
+TEST(vector3_is_valid_rejects_nan_and_inf)
+{
+ CHECK(Vector3(1.0f, 2.0f, 3.0f).Is_Valid());
+
+ /* Built through a union so the compiler cannot fold the comparison away. */
+ union { unsigned u; float f; } nan_bits, inf_bits;
+ nan_bits.u = 0x7fc00000u;
+ inf_bits.u = 0x7f800000u;
+ CHECK(!Vector3(nan_bits.f, 0.0f, 0.0f).Is_Valid());
+ CHECK(!Vector3(0.0f, inf_bits.f, 0.0f).Is_Valid());
+}
+
+TEST(vector3_equal_within_epsilon)
+{
+ Vector3 a(1.0f, 1.0f, 1.0f);
+ Vector3 b(1.0f + 1e-6f, 1.0f, 1.0f);
+ CHECK(Equal_Within_Epsilon(a, b, 1e-4f));
+ CHECK(!Equal_Within_Epsilon(a, Vector3(1.1f, 1.0f, 1.0f), 1e-4f));
+}
+
+TEST(vector2_basics)
+{
+ Vector2 a(3.0f, 4.0f);
+ CHECK_NEAR(a.Length(), 5.0f, EPS);
+ CHECK_NEAR(a.Length2(), 25.0f, EPS);
+ CHECK_NEAR(Vector2::Dot_Product(a, Vector2(1.0f, 0.0f)), 3.0f, EPS);
+
+ a.Normalize();
+ CHECK_NEAR(a.Length(), 1.0f, EPS);
+
+ Vector2 lerp;
+ Vector2::Lerp(Vector2(0.0f, 0.0f), Vector2(4.0f, 8.0f), 0.5f, &lerp);
+ CHECK_NEAR(lerp.X, 2.0f, EPS);
+ CHECK_NEAR(lerp.Y, 4.0f, EPS);
+}
+
+TEST(vector4_basics)
+{
+ Vector4 a(1.0f, 2.0f, 3.0f, 4.0f);
+ Vector4 b(4.0f, 3.0f, 2.0f, 1.0f);
+ CHECK_NEAR(Vector4::Dot_Product(a, b), 4.0f + 6.0f + 6.0f + 4.0f, EPS);
+ CHECK_NEAR(a.Length2(), 30.0f, EPS);
+
+ Vector4 sum = a + b;
+ CHECK_NEAR(sum.X, 5.0f, EPS);
+ CHECK_NEAR(sum.W, 5.0f, EPS);
+
+ Vector4 lerp;
+ Vector4::Lerp(a, b, 0.5f, &lerp);
+ CHECK_NEAR(lerp.X, 2.5f, EPS);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Matrices
+//////////////////////////////////////////////////////////////////////////////
+
+static void check_is_identity(const Matrix3D &m)
+{
+ for (int r = 0; r < 3; ++r)
+ for (int c = 0; c < 4; ++c)
+ CHECK_NEAR(m[r][c], (r == c) ? 1.0f : 0.0f, 1e-3f);
+}
+
+TEST(matrix3d_identity_and_translation)
+{
+ Matrix3D m(1);
+ check_is_identity(m);
+
+ m.Set_Translation(Vector3(4.0f, -2.0f, 8.0f));
+ CHECK_NEAR(m.Get_X_Translation(), 4.0f, EPS);
+ CHECK_NEAR(m.Get_Y_Translation(), -2.0f, EPS);
+ CHECK_NEAR(m.Get_Z_Translation(), 8.0f, EPS);
+
+ Vector3 t = m.Get_Translation();
+ CHECK_NEAR(t.Z, 8.0f, EPS);
+
+ /* Translation moves a point, and the rotation part is untouched. */
+ Vector3 p = xform(m, Vector3(1.0f, 1.0f, 1.0f));
+ CHECK_NEAR(p.X, 5.0f, EPS);
+ CHECK_NEAR(p.Y, -1.0f, EPS);
+ CHECK_NEAR(p.Z, 9.0f, EPS);
+}
+
+TEST(matrix3d_axis_rotation)
+{
+ /* 90 degrees about Z sends +X to +Y. */
+ Matrix3D rz(Vector3(0.0f, 0.0f, 1.0f), WWMATH_PI * 0.5f);
+ Vector3 v = xform(rz, Vector3(1.0f, 0.0f, 0.0f));
+ CHECK_NEAR(v.X, 0.0f, 1e-3f);
+ CHECK_NEAR(v.Y, 1.0f, 1e-3f);
+ CHECK_NEAR(v.Z, 0.0f, 1e-3f);
+
+ /* 90 degrees about X sends +Y to +Z. */
+ Matrix3D rx(Vector3(1.0f, 0.0f, 0.0f), WWMATH_PI * 0.5f);
+ v = xform(rx, Vector3(0.0f, 1.0f, 0.0f));
+ CHECK_NEAR(v.Z, 1.0f, 1e-3f);
+
+ /* Four quarter turns is the identity. */
+ Matrix3D acc(1), tmp;
+ for (int i = 0; i < 4; ++i)
+ {
+ Matrix3D::Multiply(acc, rz, &tmp);
+ acc = tmp;
+ }
+ check_is_identity(acc);
+}
+
+TEST(matrix3d_get_inverse_general_affine)
+{
+ /* This is the function that was rewritten to drop D3DXMatrixInverse, so it
+ gets the hardest cases: rotation+translation, and non-uniform scale where
+ the transpose shortcut is wrong. */
+ Matrix3D rot(Vector3(0.3f, -0.7f, 0.65f), 1.1f);
+ rot.Set_Translation(Vector3(12.0f, -4.5f, 3.25f));
+
+ Matrix3D inv, prod;
+ rot.Get_Inverse(inv);
+ Matrix3D::Multiply(rot, inv, &prod);
+ check_is_identity(prod);
+ Matrix3D::Multiply(inv, rot, &prod);
+ check_is_identity(prod);
+
+ Matrix3D scale(Vector3(2.0f, 0.0f, 0.0f),
+ Vector3(0.0f, 0.5f, 0.0f),
+ Vector3(0.0f, 0.0f, 4.0f),
+ Vector3(1.0f, 2.0f, 3.0f));
+ scale.Get_Inverse(inv);
+ Matrix3D::Multiply(scale, inv, &prod);
+ check_is_identity(prod);
+ Matrix3D::Multiply(inv, scale, &prod);
+ check_is_identity(prod);
+
+ /* Shear, which has no orthogonal structure at all to fall back on. */
+ Matrix3D shear(Vector3(1.0f, 0.4f, -0.2f),
+ Vector3(0.0f, 1.0f, 0.7f),
+ Vector3(0.3f, 0.0f, 1.0f),
+ Vector3(-5.0f, 6.0f, 7.0f));
+ shear.Get_Inverse(inv);
+ Matrix3D::Multiply(shear, inv, &prod);
+ check_is_identity(prod);
+}
+
+TEST(matrix3d_inverse_transform_point_roundtrip)
+{
+ Matrix3D m(Vector3(0.1f, 0.9f, -0.4f), 0.77f);
+ m.Set_Translation(Vector3(-3.0f, 11.0f, 0.5f));
+
+ Matrix3D inv;
+ m.Get_Inverse(inv);
+
+ Vector3 p(2.5f, -7.0f, 4.25f);
+ Vector3 back = xform(inv, xform(m, p));
+ CHECK_NEAR(back.X, p.X, 1e-3f);
+ CHECK_NEAR(back.Y, p.Y, 1e-3f);
+ CHECK_NEAR(back.Z, p.Z, 1e-3f);
+}
+
+TEST(matrix3d_rotate_helpers_match_axis_form)
+{
+ Matrix3D a(1), b(1);
+ a.Rotate_X(0.6f);
+ b.Set(Vector3(1.0f, 0.0f, 0.0f), 0.6f);
+ for (int r = 0; r < 3; ++r)
+ for (int c = 0; c < 3; ++c)
+ CHECK_NEAR(a[r][c], b[r][c], 1e-4f);
+
+ Matrix3D cz(1), dz(1);
+ cz.Rotate_Z(-1.3f);
+ dz.Set(Vector3(0.0f, 0.0f, 1.0f), -1.3f);
+ for (int r = 0; r < 3; ++r)
+ for (int c = 0; c < 3; ++c)
+ CHECK_NEAR(cz[r][c], dz[r][c], 1e-4f);
+}
+
+TEST(matrix3d_get_axis_rotation)
+{
+ Matrix3D m(1);
+ m.Rotate_Z(0.42f);
+ CHECK_NEAR(m.Get_Z_Rotation(), 0.42f, 1e-3f);
+
+ Matrix3D n(1);
+ n.Rotate_X(-0.9f);
+ CHECK_NEAR(n.Get_X_Rotation(), -0.9f, 1e-3f);
+}
+
+TEST(matrix3x3_multiply_and_inverse)
+{
+ /* The axis-angle constructor assumes a unit axis - feed it anything else
+ and you get a matrix that is not a rotation at all. */
+ Vector3 axis(0.2f, 0.5f, -0.84f);
+ axis.Normalize();
+ Matrix3x3 r(axis, 0.9f);
+ Matrix3x3 inv = r.Inverse();
+ Matrix3x3 prod = r * inv;
+
+ for (int i = 0; i < 3; ++i)
+ for (int j = 0; j < 3; ++j)
+ CHECK_NEAR(prod[i][j], (i == j) ? 1.0f : 0.0f, 1e-3f);
+
+ /* A pure rotation has determinant 1 and its inverse is its transpose. */
+ CHECK_NEAR(r.Determinant(), 1.0f, 1e-3f);
+ Matrix3x3 t = r.Transpose();
+ for (int i = 0; i < 3; ++i)
+ for (int j = 0; j < 3; ++j)
+ CHECK_NEAR(t[i][j], inv[i][j], 1e-3f);
+}
+
+TEST(matrix4x4_identity_and_multiply)
+{
+ Matrix4x4 id(true);
+ Matrix4x4 m(true);
+ m[0][3] = 5.0f;
+ m[1][3] = -2.0f;
+
+ Matrix4x4 prod = id * m;
+ for (int r = 0; r < 4; ++r)
+ for (int c = 0; c < 4; ++c)
+ CHECK_NEAR(prod[r][c], m[r][c], EPS);
+
+ /* Homogeneous transform of a point picks up the translation column. */
+ Vector4 v = m * Vector4(1.0f, 1.0f, 1.0f, 1.0f);
+ CHECK_NEAR(v.X, 6.0f, EPS);
+ CHECK_NEAR(v.Y, -1.0f, EPS);
+ CHECK_NEAR(v.W, 1.0f, EPS);
+}
+
+TEST(matrix4x4_from_matrix3d_agrees_on_points)
+{
+ Matrix3D m3(Vector3(0.3f, 0.2f, 0.93f), 0.5f);
+ m3.Set_Translation(Vector3(2.0f, 3.0f, 4.0f));
+
+ Matrix4x4 m4(m3);
+
+ Vector3 p(1.5f, -2.5f, 0.75f);
+ Vector3 a = xform(m3, p);
+ Vector4 b = m4 * Vector4(p.X, p.Y, p.Z, 1.0f);
+
+ CHECK_NEAR(a.X, b.X, 1e-3f);
+ CHECK_NEAR(a.Y, b.Y, 1e-3f);
+ CHECK_NEAR(a.Z, b.Z, 1e-3f);
+ CHECK_NEAR(b.W, 1.0f, 1e-3f);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Quaternions
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(quaternion_axis_angle_roundtrip)
+{
+ Vector3 axis(0.0f, 0.0f, 1.0f);
+ Quaternion q = Axis_To_Quat(axis, WWMATH_PI * 0.5f);
+ CHECK_NEAR(q.Length(), 1.0f, EPS);
+
+ /* Same rotation as the matrix form. */
+ Matrix3D fromq(1);
+ fromq.Set(q, Vector3(0.0f, 0.0f, 0.0f));
+ Matrix3D fromaxis(axis, WWMATH_PI * 0.5f);
+
+ for (int r = 0; r < 3; ++r)
+ for (int c = 0; c < 3; ++c)
+ CHECK_NEAR(fromq[r][c], fromaxis[r][c], 1e-3f);
+}
+
+TEST(quaternion_build_from_matrix_roundtrip)
+{
+ Matrix3D m(Vector3(0.26726f, 0.53452f, 0.80178f), 1.234f);
+ Quaternion q = Build_Quaternion(m);
+ CHECK_NEAR(q.Length(), 1.0f, 1e-3f);
+
+ Matrix3D back(1);
+ back.Set(q, Vector3(0.0f, 0.0f, 0.0f));
+ for (int r = 0; r < 3; ++r)
+ for (int c = 0; c < 3; ++c)
+ CHECK_NEAR(back[r][c], m[r][c], 1e-3f);
+}
+
+TEST(quaternion_multiply_and_inverse)
+{
+ Quaternion a = Axis_To_Quat(Vector3(1.0f, 0.0f, 0.0f), 0.7f);
+ Quaternion b = Axis_To_Quat(Vector3(0.0f, 1.0f, 0.0f), -1.1f);
+
+ Quaternion ident = a * Inverse(a);
+ CHECK_NEAR(ident.W, 1.0f, 1e-3f);
+ CHECK_NEAR(ident.X, 0.0f, 1e-3f);
+
+ /* (ab)^-1 == b^-1 a^-1 */
+ Quaternion lhs = Inverse(a * b);
+ Quaternion rhs = Inverse(b) * Inverse(a);
+ CHECK(Equal_Within_Epsilon(lhs, rhs, 1e-3f));
+}
+
+TEST(quaternion_slerp_endpoints_and_midpoint)
+{
+ Quaternion a = Axis_To_Quat(Vector3(0.0f, 0.0f, 1.0f), 0.0f);
+ Quaternion b = Axis_To_Quat(Vector3(0.0f, 0.0f, 1.0f), WWMATH_PI * 0.5f);
+
+ Quaternion r;
+ Slerp(r, a, b, 0.0f);
+ CHECK(Equal_Within_Epsilon(r, a, 1e-3f));
+
+ Slerp(r, a, b, 1.0f);
+ CHECK(Equal_Within_Epsilon(r, b, 1e-3f));
+
+ /* Halfway along a great circle is the 45-degree rotation. */
+ Slerp(r, a, b, 0.5f);
+ Quaternion mid = Axis_To_Quat(Vector3(0.0f, 0.0f, 1.0f), WWMATH_PI * 0.25f);
+ CHECK(Equal_Within_Epsilon(r, mid, 1e-3f));
+ CHECK_NEAR(r.Length(), 1.0f, 1e-3f);
+
+ /* Fast_Slerp is the approximate variant; still has to stay on the sphere. */
+ Quaternion fr;
+ Fast_Slerp(fr, a, b, 0.5f);
+ CHECK_NEAR(fr.Length(), 1.0f, 1e-2f);
+ CHECK(Equal_Within_Epsilon(fr, mid, 1e-2f));
+}
+
+TEST(quaternion_normalize_and_conjugate)
+{
+ Quaternion q(0.0f, 3.0f, 0.0f, 4.0f);
+ CHECK_NEAR(q.Length(), 5.0f, EPS);
+
+ Quaternion n = Normalize(q);
+ CHECK_NEAR(n.Length(), 1.0f, EPS);
+
+ Quaternion c = Conjugate(n);
+ CHECK_NEAR(c.W, n.W, EPS);
+ CHECK_NEAR(c.Y, -n.Y, EPS);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Bounding volumes
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(aabox_from_points_and_contains)
+{
+ Vector3 pts[4] = {
+ Vector3(-1.0f, -2.0f, -3.0f),
+ Vector3(5.0f, 0.0f, 1.0f),
+ Vector3(0.0f, 4.0f, 0.0f),
+ Vector3(1.0f, 1.0f, 7.0f)
+ };
+
+ AABoxClass box(pts, 4);
+ /* min = (-1,-2,-3), max = (5,4,7) -> center (2,1,2), extent (3,3,5) */
+ CHECK_NEAR(box.Center.X, 2.0f, EPS);
+ CHECK_NEAR(box.Center.Y, 1.0f, EPS);
+ CHECK_NEAR(box.Center.Z, 2.0f, EPS);
+ CHECK_NEAR(box.Extent.X, 3.0f, EPS);
+ CHECK_NEAR(box.Extent.Z, 5.0f, EPS);
+
+ for (int i = 0; i < 4; ++i)
+ CHECK(box.Contains(pts[i]));
+
+ CHECK(!box.Contains(Vector3(100.0f, 0.0f, 0.0f)));
+ CHECK(box.Contains(AABoxClass(Vector3(2.0f, 1.0f, 2.0f), Vector3(0.5f, 0.5f, 0.5f))));
+ CHECK(!box.Contains(AABoxClass(Vector3(2.0f, 1.0f, 2.0f), Vector3(50.0f, 0.5f, 0.5f))));
+}
+
+TEST(aabox_add_point_grows_only_as_needed)
+{
+ AABoxClass box(Vector3(0.0f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f));
+ float vol_before = box.Volume();
+
+ box.Add_Point(Vector3(0.5f, 0.5f, 0.5f)); /* already inside */
+ CHECK_NEAR(box.Volume(), vol_before, EPS);
+
+ box.Add_Point(Vector3(3.0f, 0.0f, 0.0f));
+ CHECK(box.Contains(Vector3(3.0f, 0.0f, 0.0f)));
+ CHECK(box.Volume() > vol_before);
+ /* min stays -1, max becomes 3 -> center 1, extent 2 on X only. */
+ CHECK_NEAR(box.Center.X, 1.0f, EPS);
+ CHECK_NEAR(box.Extent.X, 2.0f, EPS);
+ CHECK_NEAR(box.Extent.Y, 1.0f, EPS);
+}
+
+TEST(aabox_project_to_axis_and_volume)
+{
+ AABoxClass box(Vector3(0.0f, 0.0f, 0.0f), Vector3(1.0f, 2.0f, 3.0f));
+ CHECK_NEAR(box.Volume(), 2.0f * 4.0f * 6.0f, 1e-3f);
+
+ /* Projection onto a cardinal axis is that axis' extent. */
+ CHECK_NEAR(box.Project_To_Axis(Vector3(1.0f, 0.0f, 0.0f)), 1.0f, EPS);
+ CHECK_NEAR(box.Project_To_Axis(Vector3(0.0f, 0.0f, 1.0f)), 3.0f, EPS);
+ /* Onto a diagonal it is the sum of |axis_i| * extent_i. */
+ CHECK_NEAR(box.Project_To_Axis(Vector3(1.0f, 1.0f, 0.0f)), 3.0f, EPS);
+}
+
+TEST(aabox_transform_by_rotation)
+{
+ AABoxClass box(Vector3(0.0f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f));
+ Matrix3D rot(Vector3(0.0f, 0.0f, 1.0f), WWMATH_PI * 0.25f);
+ box.Transform(rot);
+
+ /* A unit cube spun 45 degrees about Z needs a sqrt(2) box in X and Y,
+ and still contains its own centre. */
+ CHECK_NEAR(box.Extent.X, WWMATH_SQRT2, 1e-3f);
+ CHECK_NEAR(box.Extent.Y, WWMATH_SQRT2, 1e-3f);
+ CHECK_NEAR(box.Extent.Z, 1.0f, 1e-3f);
+ CHECK(box.Contains(box.Center));
+}
+
+TEST(aabox_translate)
+{
+ AABoxClass box(Vector3(1.0f, 2.0f, 3.0f), Vector3(1.0f, 1.0f, 1.0f));
+ box.Translate(Vector3(10.0f, 0.0f, -3.0f));
+ CHECK_NEAR(box.Center.X, 11.0f, EPS);
+ CHECK_NEAR(box.Center.Z, 0.0f, EPS);
+ /* Translation never changes size. */
+ CHECK_NEAR(box.Extent.X, 1.0f, EPS);
+}
+
+TEST(minmax_aabox_init_and_add)
+{
+ MinMaxAABoxClass mm(Vector3(0.0f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f));
+ mm.Add_Point(Vector3(-4.0f, 0.5f, 9.0f));
+ CHECK_NEAR(mm.MinCorner.X, -4.0f, EPS);
+ CHECK_NEAR(mm.MaxCorner.Z, 9.0f, EPS);
+
+ /* Converting to the centre/extent form must describe the same volume. */
+ AABoxClass box(mm);
+ CHECK_NEAR(box.Center.X, -1.5f, EPS);
+ CHECK_NEAR(box.Extent.X, 2.5f, EPS);
+ CHECK(box.Contains(Vector3(-4.0f, 0.5f, 9.0f)));
+}
+
+TEST(sphere_add_and_transform)
+{
+ SphereClass s(Vector3(0.0f, 0.0f, 0.0f), 1.0f);
+ CHECK_NEAR(s.Radius, 1.0f, EPS);
+
+ /* Absorbing a far sphere must cover both. */
+ s.Add_Sphere(SphereClass(Vector3(10.0f, 0.0f, 0.0f), 1.0f));
+ CHECK(s.Radius >= 6.0f - EPS);
+ CHECK_NEAR(s.Center.X, 5.0f, 1e-3f);
+
+ /* Rigid transforms move the centre and leave the radius alone. */
+ SphereClass t(Vector3(1.0f, 0.0f, 0.0f), 2.0f);
+ Matrix3D m(Vector3(0.0f, 0.0f, 1.0f), WWMATH_PI * 0.5f);
+ m.Set_Translation(Vector3(0.0f, 0.0f, 5.0f));
+ t.Transform(m);
+ CHECK_NEAR(t.Radius, 2.0f, 1e-3f);
+ CHECK_NEAR(t.Center.Y, 1.0f, 1e-3f);
+ CHECK_NEAR(t.Center.Z, 5.0f, 1e-3f);
+}
+
+TEST(obbox_axis_aligned_matches_aabox)
+{
+ /* An OBB with an identity basis must project exactly like the AABox. */
+ OBBoxClass obb(Vector3(0.0f, 0.0f, 0.0f), Vector3(1.0f, 2.0f, 3.0f));
+ CHECK_NEAR(obb.Project_To_Axis(Vector3(1.0f, 0.0f, 0.0f)), 1.0f, 1e-3f);
+ CHECK_NEAR(obb.Project_To_Axis(Vector3(0.0f, 1.0f, 0.0f)), 2.0f, 1e-3f);
+ CHECK_NEAR(obb.Volume(), 2.0f * 4.0f * 6.0f, 1e-2f);
+
+ /* OBBoxClass has no Contains of its own; point containment goes through
+ the collision layer. */
+ CHECK_EQ(CollisionMath::Overlap_Test(obb, Vector3(0.5f, 0.5f, 0.5f)),
+ CollisionMath::INSIDE);
+ CHECK_EQ(CollisionMath::Overlap_Test(obb, Vector3(0.5f, 0.5f, 9.0f)),
+ CollisionMath::OUTSIDE);
+
+ /* An identity-basis OBB's axis-aligned extent is just its extent. */
+ Vector3 aae;
+ obb.Compute_Axis_Aligned_Extent(&aae);
+ CHECK_NEAR(aae.X, 1.0f, 1e-3f);
+ CHECK_NEAR(aae.Z, 3.0f, 1e-3f);
+
+ /* Spun 90 degrees about Z, the X and Y extents swap. */
+ OBBoxClass spun(Vector3(0.0f, 0.0f, 0.0f), Vector3(1.0f, 2.0f, 3.0f),
+ Matrix3x3(Vector3(0.0f, 0.0f, 1.0f), WWMATH_PI * 0.5f));
+ spun.Compute_Axis_Aligned_Extent(&aae);
+ CHECK_NEAR(aae.X, 2.0f, 1e-3f);
+ CHECK_NEAR(aae.Y, 1.0f, 1e-3f);
+ CHECK_NEAR(aae.Z, 3.0f, 1e-3f);
+}
+
+TEST(obbox_transform_moves_center_and_basis)
+{
+ OBBoxClass in(Vector3(1.0f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f));
+
+ Matrix3D tm(Vector3(0.0f, 0.0f, 1.0f), WWMATH_PI * 0.5f);
+ tm.Set_Translation(Vector3(0.0f, 0.0f, 4.0f));
+
+ OBBoxClass out;
+ OBBoxClass::Transform(tm, in, &out);
+
+ /* Centre follows the transform; a rigid motion leaves the volume alone. */
+ CHECK_NEAR(out.Center.X, 0.0f, 1e-3f);
+ CHECK_NEAR(out.Center.Y, 1.0f, 1e-3f);
+ CHECK_NEAR(out.Center.Z, 4.0f, 1e-3f);
+ CHECK_NEAR(out.Volume(), in.Volume(), 1e-2f);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Planes, triangles, line segments
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(plane_from_three_points)
+{
+ PlaneClass p(Vector3(0.0f, 0.0f, 0.0f),
+ Vector3(1.0f, 0.0f, 0.0f),
+ Vector3(0.0f, 1.0f, 0.0f));
+
+ /* Normal is +/-Z and unit length, and the plane passes through origin. */
+ CHECK_NEAR(fabs(p.N.Z), 1.0f, 1e-3f);
+ CHECK_NEAR(p.N.Length(), 1.0f, 1e-3f);
+ CHECK_NEAR(p.D, 0.0f, 1e-3f);
+}
+
+TEST(plane_line_intersection)
+{
+ /* z = 5 plane, segment straight down the Z axis from 0 to 10. */
+ PlaneClass p(Vector3(0.0f, 0.0f, 1.0f), 5.0f);
+
+ float t = -1.0f;
+ bool hit = p.Compute_Intersection(Vector3(0.0f, 0.0f, 0.0f),
+ Vector3(0.0f, 0.0f, 10.0f), &t);
+ CHECK(hit);
+ CHECK_NEAR(t, 0.5f, 1e-3f);
+
+ /* Parallel segment never hits. */
+ CHECK(!p.Compute_Intersection(Vector3(0.0f, 0.0f, 0.0f),
+ Vector3(10.0f, 0.0f, 0.0f), &t));
+}
+
+TEST(plane_intersect_planes_gives_shared_line)
+{
+ PlaneClass a(Vector3(1.0f, 0.0f, 0.0f), 0.0f); /* x = 0 */
+ PlaneClass b(Vector3(0.0f, 1.0f, 0.0f), 0.0f); /* y = 0 */
+
+ Vector3 dir, point;
+ PlaneClass::Intersect_Planes(a, b, &dir, &point);
+
+ /* Their intersection is the Z axis. */
+ CHECK_NEAR(fabs(dir.Z), 1.0f, 1e-3f);
+ CHECK_NEAR(dir.X, 0.0f, 1e-3f);
+ CHECK_NEAR(dir.Y, 0.0f, 1e-3f);
+ /* The returned point lies on both planes. */
+ CHECK_NEAR(point.X, 0.0f, 1e-3f);
+ CHECK_NEAR(point.Y, 0.0f, 1e-3f);
+}
+
+TEST(tri_normal_and_contains_point)
+{
+ Vector3 v0(0.0f, 0.0f, 0.0f);
+ Vector3 v1(4.0f, 0.0f, 0.0f);
+ Vector3 v2(0.0f, 4.0f, 0.0f);
+ Vector3 n;
+
+ TriClass tri;
+ tri.V[0] = &v0;
+ tri.V[1] = &v1;
+ tri.V[2] = &v2;
+ tri.N = &n;
+ tri.Compute_Normal();
+
+ CHECK_NEAR(n.Length(), 1.0f, 1e-3f);
+ CHECK_NEAR(fabs(n.Z), 1.0f, 1e-3f);
+
+ CHECK(tri.Contains_Point(Vector3(1.0f, 1.0f, 0.0f)));
+ CHECK(!tri.Contains_Point(Vector3(3.0f, 3.0f, 0.0f))); /* past the hypotenuse */
+ CHECK(!tri.Contains_Point(Vector3(-1.0f, 1.0f, 0.0f)));
+
+ /* The dominant plane of a Z-facing triangle is the XY plane. */
+ int a1 = -1, a2 = -1;
+ tri.Find_Dominant_Plane(&a1, &a2);
+ CHECK_EQ(a1, 0);
+ CHECK_EQ(a2, 1);
+}
+
+TEST(lineseg_geometry)
+{
+ LineSegClass seg(Vector3(0.0f, 0.0f, 0.0f), Vector3(10.0f, 0.0f, 0.0f));
+ CHECK_NEAR(seg.Get_Length(), 10.0f, EPS);
+ CHECK_NEAR(seg.Get_Dir().X, 1.0f, EPS);
+ CHECK_NEAR(seg.Get_DP().X, 10.0f, EPS);
+
+ Vector3 p;
+ seg.Compute_Point(0.25f, &p);
+ CHECK_NEAR(p.X, 2.5f, EPS);
+
+ /* Closest point clamps to the segment, it does not run off the line. */
+ CHECK_NEAR(seg.Find_Point_Closest_To(Vector3(3.0f, 9.0f, 0.0f)).X, 3.0f, 1e-3f);
+ CHECK_NEAR(seg.Find_Point_Closest_To(Vector3(-8.0f, 1.0f, 0.0f)).X, 0.0f, 1e-3f);
+ CHECK_NEAR(seg.Find_Point_Closest_To(Vector3(50.0f, 1.0f, 0.0f)).X, 10.0f, 1e-3f);
+}
+
+TEST(lineseg_transform_preserves_length)
+{
+ LineSegClass seg(Vector3(1.0f, 2.0f, 3.0f), Vector3(4.0f, 6.0f, 3.0f));
+ float len = seg.Get_Length();
+
+ Matrix3D m(Vector3(0.0f, 1.0f, 0.0f), 0.8f);
+ m.Set_Translation(Vector3(-20.0f, 5.0f, 1.0f));
+
+ LineSegClass moved(seg, m);
+ CHECK_NEAR(moved.Get_Length(), len, 1e-3f);
+ CHECK_NEAR(moved.Get_P0().X, xform(m, seg.Get_P0()).X, 1e-3f);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// Collision predicates
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(colmath_overlap_plane_point)
+{
+ PlaneClass p(Vector3(0.0f, 0.0f, 1.0f), 0.0f); /* z = 0, normal +Z */
+
+ CHECK_EQ(CollisionMath::Overlap_Test(p, Vector3(0.0f, 0.0f, 5.0f)),
+ CollisionMath::POS);
+ CHECK_EQ(CollisionMath::Overlap_Test(p, Vector3(0.0f, 0.0f, -5.0f)),
+ CollisionMath::NEG);
+}
+
+TEST(colmath_overlap_aaplane_sphere)
+{
+ AAPlaneClass p(AAPlaneClass::ZNORMAL, 0.0f);
+
+ CHECK_EQ(CollisionMath::Overlap_Test(p, SphereClass(Vector3(0.0f, 0.0f, 10.0f), 1.0f)),
+ CollisionMath::POS);
+ CHECK_EQ(CollisionMath::Overlap_Test(p, SphereClass(Vector3(0.0f, 0.0f, -10.0f), 1.0f)),
+ CollisionMath::NEG);
+ /* Straddling the plane. The NEG test compared against +Radius instead of
+ -Radius, which made BOTH all but unreachable and reported every
+ straddling sphere as entirely behind the plane. */
+ CHECK_EQ(CollisionMath::Overlap_Test(p, SphereClass(Vector3(0.0f, 0.0f, 0.0f), 1.0f)),
+ CollisionMath::BOTH);
+ CHECK_EQ(CollisionMath::Overlap_Test(p, SphereClass(Vector3(0.0f, 0.0f, 0.5f), 1.0f)),
+ CollisionMath::BOTH);
+ CHECK_EQ(CollisionMath::Overlap_Test(p, SphereClass(Vector3(0.0f, 0.0f, -0.5f), 1.0f)),
+ CollisionMath::BOTH);
+}
+
+TEST(colmath_sphere_sphere_and_sphere_point)
+{
+ SphereClass s(Vector3(0.0f, 0.0f, 0.0f), 2.0f);
+
+ CHECK_EQ(CollisionMath::Overlap_Test(s, Vector3(1.0f, 0.0f, 0.0f)),
+ CollisionMath::INSIDE);
+ CHECK_EQ(CollisionMath::Overlap_Test(s, Vector3(9.0f, 0.0f, 0.0f)),
+ CollisionMath::OUTSIDE);
+
+ /* Sphere/sphere is coarser than the enum suggests: anything within the
+ summed radii reports INSIDE, and OVERLAPPED is reachable only for two
+ concentric spheres of equal radius. Pinned as-is - callers of this
+ overload cannot tell containment from a graze. */
+ CHECK_EQ(CollisionMath::Overlap_Test(s, SphereClass(Vector3(0.0f, 0.0f, 0.0f), 0.5f)),
+ CollisionMath::INSIDE);
+ CHECK_EQ(CollisionMath::Overlap_Test(s, SphereClass(Vector3(20.0f, 0.0f, 0.0f), 1.0f)),
+ CollisionMath::OUTSIDE);
+ CHECK_EQ(CollisionMath::Overlap_Test(s, SphereClass(Vector3(2.5f, 0.0f, 0.0f), 1.0f)),
+ CollisionMath::INSIDE);
+ CHECK_EQ(CollisionMath::Overlap_Test(s, SphereClass(Vector3(0.0f, 0.0f, 0.0f), 2.0f)),
+ CollisionMath::OVERLAPPED);
+}
+
+TEST(colmath_box_intersection_tests)
+{
+ AABoxClass a(Vector3(0.0f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f));
+ AABoxClass overlapping(Vector3(1.5f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f));
+ AABoxClass disjoint(Vector3(50.0f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f));
+
+ CHECK(CollisionMath::Intersection_Test(a, overlapping));
+ CHECK(!CollisionMath::Intersection_Test(a, disjoint));
+
+ /* Touching exactly at a face counts as intersecting. */
+ AABoxClass touching(Vector3(2.0f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f));
+ CHECK(CollisionMath::Intersection_Test(a, touching));
+
+ /* Same answers through the sphere/box pair. This one had its three axis
+ comparisons inverted, so it answered true only when the sphere was
+ clear of the box on every axis - the exact opposite of the question. */
+ CHECK(CollisionMath::Intersection_Test(SphereClass(Vector3(1.5f, 0.0f, 0.0f), 1.0f), a));
+ CHECK(CollisionMath::Intersection_Test(SphereClass(Vector3(0.0f, 0.0f, 0.0f), 0.1f), a));
+ CHECK(!CollisionMath::Intersection_Test(SphereClass(Vector3(50.0f, 0.0f, 0.0f), 1.0f), a));
+ CHECK(!CollisionMath::Intersection_Test(SphereClass(Vector3(0.0f, 0.0f, 9.0f), 1.0f), a));
+}
+
+TEST(colmath_obb_separating_axis)
+{
+ /* Two unit cubes, one spun 45 degrees about Z. Near enough to overlap,
+ far enough that only a proper separating-axis test gets it right. */
+ OBBoxClass a(Vector3(0.0f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f));
+
+ Matrix3x3 spin(Vector3(0.0f, 0.0f, 1.0f), WWMATH_PI * 0.25f);
+ OBBoxClass b(Vector3(2.2f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f), spin);
+ CHECK(CollisionMath::Intersection_Test(a, b));
+
+ OBBoxClass c(Vector3(3.0f, 0.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f), spin);
+ CHECK(!CollisionMath::Intersection_Test(a, c));
+}
+
+TEST(colmath_box_tri_intersection)
+{
+ Vector3 v0(0.0f, 0.0f, 0.0f);
+ Vector3 v1(4.0f, 0.0f, 0.0f);
+ Vector3 v2(0.0f, 4.0f, 0.0f);
+ Vector3 n;
+
+ TriClass tri;
+ tri.V[0] = &v0; tri.V[1] = &v1; tri.V[2] = &v2; tri.N = &n;
+ tri.Compute_Normal();
+
+ CHECK(CollisionMath::Intersection_Test(
+ AABoxClass(Vector3(1.0f, 1.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f)), tri));
+ CHECK(!CollisionMath::Intersection_Test(
+ AABoxClass(Vector3(1.0f, 1.0f, 50.0f), Vector3(1.0f, 1.0f, 1.0f)), tri));
+ /* Beyond the hypotenuse but still in the triangle's plane. */
+ CHECK(!CollisionMath::Intersection_Test(
+ AABoxClass(Vector3(9.0f, 9.0f, 0.0f), Vector3(1.0f, 1.0f, 1.0f)), tri));
+}
+
+//////////////////////////////////////////////////////////////////////////////
+// VectorProcessorClass - the SIMD/asm batch paths
+//////////////////////////////////////////////////////////////////////////////
+
+TEST(vp_transform_matches_scalar)
+{
+ Matrix3D m(Vector3(0.3f, 0.6f, 0.74f), 0.9f);
+ m.Set_Translation(Vector3(5.0f, -2.0f, 1.0f));
+
+ /* Deliberately not a multiple of 4: the asm paths process blocks and hand
+ the remainder to a scalar tail, which is where they get truncated. */
+ const int N = 13;
+ Vector3 src[N], dst[N];
+ for (int i = 0; i < N; ++i)
+ src[i] = Vector3(float(i), float(i) * -0.5f, float(N - i));
+
+ VectorProcessorClass::Transform(dst, src, m, N);
+
+ for (int i = 0; i < N; ++i)
+ {
+ Vector3 expect = xform(m, src[i]);
+ CHECK_NEAR(dst[i].X, expect.X, 1e-3f);
+ CHECK_NEAR(dst[i].Y, expect.Y, 1e-3f);
+ CHECK_NEAR(dst[i].Z, expect.Z, 1e-3f);
+ }
+}
+
+TEST(vp_transform_vector4_matches_scalar)
+{
+ Matrix4x4 m(true);
+ m[0][0] = 2.0f; m[1][1] = 3.0f; m[2][2] = -1.0f;
+ m[0][3] = 7.0f;
+
+ const int N = 7;
+ Vector3 src[N];
+ Vector4 dst[N];
+ for (int i = 0; i < N; ++i)
+ src[i] = Vector3(float(i), 1.0f, 2.0f);
+
+ VectorProcessorClass::Transform(dst, src, m, N);
+
+ for (int i = 0; i < N; ++i)
+ {
+ Vector4 expect = m * Vector4(src[i].X, src[i].Y, src[i].Z, 1.0f);
+ CHECK_NEAR(dst[i].X, expect.X, 1e-3f);
+ CHECK_NEAR(dst[i].W, expect.W, 1e-3f);
+ }
+}
+
+TEST(vp_copy_and_copy_indexed)
+{
+ const int N = 9;
+ Vector3 src[N], dst[N];
+ for (int i = 0; i < N; ++i)
+ src[i] = Vector3(float(i), float(i * 2), float(i * 3));
+
+ VectorProcessorClass::Copy(dst, src, N);
+ for (int i = 0; i < N; ++i)
+ CHECK_NEAR(dst[i].Y, float(i * 2), EPS);
+
+ /* Reverse the order through the index path. */
+ unsigned int index[N];
+ for (int i = 0; i < N; ++i)
+ index[i] = unsigned(N - 1 - i);
+
+ VectorProcessorClass::CopyIndexed(dst, src, index, N);
+ for (int i = 0; i < N; ++i)
+ CHECK_NEAR(dst[i].X, float(N - 1 - i), EPS);
+
+ /* The Vector4-from-Vector3-plus-alpha overload. */
+ Vector4 v4[N];
+ VectorProcessorClass::Copy(v4, src, 0.5f, N);
+ for (int i = 0; i < N; ++i)
+ {
+ CHECK_NEAR(v4[i].X, float(i), EPS);
+ CHECK_NEAR(v4[i].W, 0.5f, EPS);
+ }
+}
+
+TEST(vp_normalize_clear_minmax)
+{
+ const int N = 6;
+ Vector3 v[N];
+ for (int i = 0; i < N; ++i)
+ v[i] = Vector3(float(i + 1), float(i + 2), float(i + 3));
+
+ Vector3 min, max;
+ VectorProcessorClass::MinMax(v, min, max, N);
+ CHECK_NEAR(min.X, 1.0f, EPS);
+ CHECK_NEAR(max.X, float(N), EPS);
+ CHECK_NEAR(max.Z, float(N + 2), EPS);
+
+ VectorProcessorClass::Normalize(v, N);
+ for (int i = 0; i < N; ++i)
+ CHECK_NEAR(v[i].Length(), 1.0f, 1e-3f);
+
+ VectorProcessorClass::Clear(v, N);
+ for (int i = 0; i < N; ++i)
+ CHECK_NEAR(v[i].Length2(), 0.0f, EPS);
+}
+
+TEST(vp_scalar_batch_ops)
+{
+ const int N = 11;
+ float a[N], b[N];
+ for (int i = 0; i < N; ++i)
+ a[i] = float(i) - 5.0f;
+
+ VectorProcessorClass::ClampMin(b, a, 0.0f, N);
+ for (int i = 0; i < N; ++i)
+ CHECK_NEAR(b[i], a[i] < 0.0f ? 0.0f : a[i], EPS);
+
+ for (int i = 0; i < N; ++i)
+ a[i] = float(i);
+ VectorProcessorClass::MulAdd(a, 2.0f, 1.0f, N);
+ for (int i = 0; i < N; ++i)
+ CHECK_NEAR(a[i], float(i) * 2.0f + 1.0f, EPS);
+
+ for (int i = 0; i < N; ++i)
+ a[i] = float(i) + 1.0f;
+ VectorProcessorClass::Power(b, a, 2.0f, N);
+ for (int i = 0; i < N; ++i)
+ CHECK_NEAR(b[i], (float(i) + 1.0f) * (float(i) + 1.0f), 1e-2f);
+
+ Vector3 axis(1.0f, 0.0f, 0.0f);
+ Vector3 vecs[N];
+ float dots[N];
+ for (int i = 0; i < N; ++i)
+ vecs[i] = Vector3(float(i), 99.0f, -99.0f);
+ VectorProcessorClass::DotProduct(dots, axis, vecs, N);
+ for (int i = 0; i < N; ++i)
+ CHECK_NEAR(dots[i], float(i), 1e-3f);
+}
+
+TEST(vp_clamp_vector4)
+{
+ const int N = 5;
+ Vector4 src[N], dst[N];
+ for (int i = 0; i < N; ++i)
+ src[i] = Vector4(float(i) - 2.0f, 10.0f, -10.0f, 0.5f);
+
+ VectorProcessorClass::Clamp(dst, src, 0.0f, 1.0f, N);
+ for (int i = 0; i < N; ++i)
+ {
+ /* -2,-1,0,1,2 clamped into [0,1]. The low half is the interesting
+ part: the second assignment used to re-read src, throwing away the
+ min clamp and letting negatives through. */
+ float expect = WWMath::Clamp(float(i) - 2.0f, 0.0f, 1.0f);
+ CHECK_NEAR(dst[i].X, expect, EPS);
+ CHECK_NEAR(dst[i].Y, 1.0f, EPS);
+ CHECK_NEAR(dst[i].Z, 0.0f, EPS);
+ CHECK_NEAR(dst[i].W, 0.5f, EPS);
+ }
+}
diff --git a/GeneralsMD/Code/Tests/test_wwsaveload.cpp b/GeneralsMD/Code/Tests/test_wwsaveload.cpp
new file mode 100644
index 000000000..4adc863fa
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_wwsaveload.cpp
@@ -0,0 +1,1200 @@
+/*
+ * WWSaveLoad coverage: the pointer swizzler, the subsystem/persist-factory
+ * registries, the definition manager and the twiddler.
+ *
+ * The library is one big set of global registries wired up by static
+ * constructors, so the tests below plant their own subsystem, persist
+ * factories and definition factory at file scope and then drive the public
+ * entry points. Anything that mutates a global registry puts it back.
+ *
+ * Chunk ids come out of the PHYSTEST range in saveloadids.h - nothing in the
+ * ported libraries claims it, so the test types cannot collide with the real
+ * ones.
+ */
+#include "test_harness.h"
+
+#include "saveload.h"
+#include "saveloadids.h"
+#include "saveloadstatus.h"
+#include "saveloadsubsystem.h"
+#include "pointerremap.h"
+#include "persist.h"
+#include "persistfactory.h"
+#include "postloadable.h"
+#include "definition.h"
+#include "definitionclassids.h"
+#include "definitionfactory.h"
+#include "definitionfactorymgr.h"
+#include "definitionmgr.h"
+#include "simpledefinitionfactory.h"
+#include "twiddler.h"
+
+#include "chunkio.h"
+#include "ramfile.h"
+#include "refcount.h"
+#include "wwstring.h"
+#include "wwhack.h"
+
+#include <string.h>
+
+/* ------------------------------------------------------------------ */
+/* Test fixtures registered with the library's global registries */
+/* ------------------------------------------------------------------ */
+
+enum
+{
+ CHUNKID_TEST_SUBSYSTEM = CHUNKID_PHYSTEST_BEGIN + 1,
+ CHUNKID_TEST_PERSIST,
+ CHUNKID_TEST_DEFINITION,
+ CHUNKID_TEST_DEFINITION_B,
+};
+
+enum
+{
+ CLASSID_TEST_DEF = CLASSID_DUMMY_OBJECTS, /* is its own superclass */
+ CLASSID_TEST_DEF_B = CLASSID_DUMMY_OBJECTS + 1, /* same superclass, other class */
+};
+
+/*
+** A subsystem registers itself with SaveLoadSystemClass from its constructor,
+** so the single file-scope instance below is the registration.
+*/
+class TestSubSystemClass : public SaveLoadSubSystemClass
+{
+public:
+ TestSubSystemClass(void)
+ : Value(0), SaveCount(0), LoadCount(0), PostLoadCount(0), HasData(true) {}
+
+ virtual uint32 Chunk_ID(void) const { return CHUNKID_TEST_SUBSYSTEM; }
+ virtual void On_Post_Load(void) { PostLoadCount++; }
+
+ int Value;
+ int SaveCount;
+ int LoadCount;
+ int PostLoadCount;
+ bool HasData;
+
+protected:
+ enum { VARID_VALUE = 0x01 };
+
+ virtual bool Contains_Data(void) const { return HasData; }
+ virtual const char * Name(void) const { return "TestSubSystemClass"; }
+
+ virtual bool Save(ChunkSaveClass &csave)
+ {
+ SaveCount++;
+ WRITE_MICRO_CHUNK(csave, VARID_VALUE, Value);
+ return true;
+ }
+
+ virtual bool Load(ChunkLoadClass &cload)
+ {
+ LoadCount++;
+ while (cload.Open_Micro_Chunk()) {
+ switch (cload.Cur_Micro_Chunk_ID()) {
+ READ_MICRO_CHUNK(cload, VARID_VALUE, Value)
+ }
+ cload.Close_Micro_Chunk();
+ }
+ return true;
+ }
+};
+
+TestSubSystemClass TestSubSystem;
+
+/*
+** A persist object plus its factory. SimplePersistFactoryClass writes the
+** old address, then the object, and registers the old->new pair on load.
+*/
+class TestPersistClass : public PersistClass
+{
+public:
+ TestPersistClass(void) : Number(0), PostLoads(0), Text("") {}
+
+ virtual const PersistFactoryClass & Get_Factory(void) const;
+ virtual void On_Post_Load(void) { PostLoads++; }
+
+ enum { VARID_NUMBER = 0x01, VARID_TEXT };
+
+ virtual bool Save(ChunkSaveClass &csave)
+ {
+ WRITE_MICRO_CHUNK(csave, VARID_NUMBER, Number);
+ WRITE_MICRO_CHUNK_WWSTRING(csave, VARID_TEXT, Text);
+ return true;
+ }
+
+ virtual bool Load(ChunkLoadClass &cload)
+ {
+ while (cload.Open_Micro_Chunk()) {
+ switch (cload.Cur_Micro_Chunk_ID()) {
+ READ_MICRO_CHUNK(cload, VARID_NUMBER, Number)
+ READ_MICRO_CHUNK_WWSTRING(cload, VARID_TEXT, Text)
+ }
+ cload.Close_Micro_Chunk();
+ }
+ return true;
+ }
+
+ int Number;
+ int PostLoads;
+ StringClass Text;
+};
+
+SimplePersistFactoryClass<TestPersistClass, CHUNKID_TEST_PERSIST> _TestPersistFactory;
+
+const PersistFactoryClass & TestPersistClass::Get_Factory(void) const
+{
+ return _TestPersistFactory;
+}
+
+/*
+** Two definition types sharing a superclass, so ID_CLASS and ID_SUPERCLASS
+** enumeration can be told apart.
+*/
+class TestDefinitionClass : public DefinitionClass
+{
+public:
+ DECLARE_EDITABLE(TestDefinitionClass, DefinitionClass);
+
+ virtual uint32 Get_Class_ID(void) const { return CLASSID_TEST_DEF; }
+ virtual PersistClass * Create(void) const { return NULL; }
+ virtual const PersistFactoryClass & Get_Factory(void) const;
+};
+
+SimplePersistFactoryClass<TestDefinitionClass, CHUNKID_TEST_DEFINITION> _TestDefinitionPersistFactory;
+
+const PersistFactoryClass & TestDefinitionClass::Get_Factory(void) const
+{
+ return _TestDefinitionPersistFactory;
+}
+
+class TestDefinitionBClass : public DefinitionClass
+{
+public:
+ DECLARE_EDITABLE(TestDefinitionBClass, DefinitionClass);
+
+ virtual uint32 Get_Class_ID(void) const { return CLASSID_TEST_DEF_B; }
+ virtual PersistClass * Create(void) const { return NULL; }
+ virtual const PersistFactoryClass & Get_Factory(void) const;
+};
+
+SimplePersistFactoryClass<TestDefinitionBClass, CHUNKID_TEST_DEFINITION_B> _TestDefinitionBPersistFactory;
+
+const PersistFactoryClass & TestDefinitionBClass::Get_Factory(void) const
+{
+ return _TestDefinitionBPersistFactory;
+}
+
+/* Definition factories also self-register from their constructor. */
+DECLARE_DEFINITION_FACTORY(TestDefinitionClass, CLASSID_TEST_DEF, "TestDefinition") _TestDefinitionFactory;
+DECLARE_DEFINITION_FACTORY(TestDefinitionBClass, CLASSID_TEST_DEF_B, "TestDefinitionB") _TestDefinitionBFactory;
+
+class TestRefObjClass : public RefCountClass
+{
+public:
+ TestRefObjClass(int tag) : Tag(tag) {}
+ int Tag;
+};
+
+namespace
+{
+ /* The remap request signature grows file/line under WWDEBUG. */
+ void request_remap(PointerRemapClass &remapper, void **pointer)
+ {
+#ifdef WWDEBUG
+ remapper.Request_Pointer_Remap(pointer, __FILE__, __LINE__);
+#else
+ remapper.Request_Pointer_Remap(pointer);
+#endif
+ }
+
+ void request_ref_remap(PointerRemapClass &remapper, RefCountClass **pointer)
+ {
+#ifdef WWDEBUG
+ remapper.Request_Ref_Counted_Pointer_Remap(pointer, __FILE__, __LINE__);
+#else
+ remapper.Request_Ref_Counted_Pointer_Remap(pointer);
+#endif
+ }
+
+ /* Fabricated "old" addresses. They are never dereferenced - the remapper
+ only ever compares them. */
+ void *fake_old(int i)
+ {
+ return (void *)(0x10000 + i * 16);
+ }
+
+ /* Registers a definition and hands back the pointer so the test can
+ unregister and free it again. */
+ TestDefinitionClass *make_def(uint32 id, const char *name)
+ {
+ TestDefinitionClass *def = new TestDefinitionClass;
+ def->Set_Name(name);
+ def->Set_ID(id);
+ DefinitionMgrClass::Register_Definition(def);
+ return def;
+ }
+
+ void free_def(DefinitionClass *def)
+ {
+ DefinitionMgrClass::Unregister_Definition(def);
+ delete def;
+ }
+}
+
+/* ------------------------------------------------------------------ */
+/* PointerRemapClass */
+/* ------------------------------------------------------------------ */
+
+TEST(pointer_remap_swizzles_registered_pointers)
+{
+ PointerRemapClass remapper;
+
+ int targets[4] = { 10, 20, 30, 40 };
+
+ /* Registration order is deliberately scrambled - Process sorts first. */
+ remapper.Register_Pointer(fake_old(2), &targets[2]);
+ remapper.Register_Pointer(fake_old(0), &targets[0]);
+ remapper.Register_Pointer(fake_old(3), &targets[3]);
+ remapper.Register_Pointer(fake_old(1), &targets[1]);
+
+ void *slots[4];
+ for (int i = 0; i < 4; ++i) {
+ slots[i] = fake_old(i);
+ request_remap(remapper, &slots[i]);
+ }
+
+ remapper.Process();
+
+ for (int i = 0; i < 4; ++i) {
+ CHECK_EQ(slots[i], (void *)&targets[i]);
+ CHECK_EQ(*(int *)slots[i], (i + 1) * 10);
+ }
+}
+
+TEST(pointer_remap_handles_many_out_of_order_entries)
+{
+ /* Enough entries that the sorted merge in Process_Request_Table actually
+ has to walk, and requested in the opposite order to registration. */
+ enum { COUNT = 256 };
+ static int targets[COUNT];
+ static void *slots[COUNT];
+
+ PointerRemapClass remapper;
+
+ for (int i = COUNT - 1; i >= 0; --i) {
+ targets[i] = i * 3;
+ remapper.Register_Pointer(fake_old(i), &targets[i]);
+ }
+
+ for (int j = 0; j < COUNT; ++j) {
+ slots[j] = fake_old(COUNT - 1 - j);
+ request_remap(remapper, &slots[j]);
+ }
+
+ remapper.Process();
+
+ for (int k = 0; k < COUNT; ++k) {
+ int expected = COUNT - 1 - k;
+ CHECK_EQ(slots[k], (void *)&targets[expected]);
+ }
+}
+
+TEST(pointer_remap_repeated_requests_for_one_pointer)
+{
+ PointerRemapClass remapper;
+
+ int target = 77;
+ remapper.Register_Pointer(fake_old(5), &target);
+
+ void *a = fake_old(5);
+ void *b = fake_old(5);
+ void *c = fake_old(5);
+ request_remap(remapper, &a);
+ request_remap(remapper, &b);
+ request_remap(remapper, &c);
+
+ remapper.Process();
+
+ CHECK_EQ(a, (void *)&target);
+ CHECK_EQ(b, (void *)&target);
+ CHECK_EQ(c, (void *)&target);
+}
+
+#ifndef WWDEBUG
+TEST(pointer_remap_nulls_out_what_it_cannot_find)
+{
+ /* Release behaviour only: a WWDEBUG build asserts on the failed lookup
+ before it gets here. */
+ PointerRemapClass remapper;
+
+ int target = 1;
+ remapper.Register_Pointer(fake_old(0), &target);
+
+ void *known = fake_old(0);
+ void *bogus = fake_old(99);
+ request_remap(remapper, &known);
+ request_remap(remapper, &bogus);
+
+ remapper.Process();
+
+ CHECK_EQ(known, (void *)&target);
+ CHECK(bogus == NULL);
+}
+#endif
+
+TEST(pointer_remap_reset_clears_every_table)
+{
+ PointerRemapClass remapper;
+
+ int target = 5;
+ remapper.Register_Pointer(fake_old(0), &target);
+
+ void *slot = fake_old(0);
+ request_remap(remapper, &slot);
+
+ remapper.Reset();
+
+ /* With the tables empty Process is a no-op and leaves the slot alone. */
+ remapper.Process();
+ CHECK_EQ(slot, fake_old(0));
+
+ /* And the remapper is reusable afterwards. */
+ remapper.Register_Pointer(fake_old(0), &target);
+ request_remap(remapper, &slot);
+ remapper.Process();
+ CHECK_EQ(slot, (void *)&target);
+}
+
+TEST(pointer_remap_on_empty_tables_is_a_no_op)
+{
+ PointerRemapClass remapper;
+ remapper.Process();
+ remapper.Reset();
+ remapper.Process();
+ CHECK(true);
+}
+
+TEST(pointer_remap_adds_a_reference_to_ref_counted_pointers)
+{
+ PointerRemapClass remapper;
+
+ TestRefObjClass *obj_a = new TestRefObjClass(1);
+ TestRefObjClass *obj_b = new TestRefObjClass(2);
+ CHECK_EQ(obj_a->Num_Refs(), 1);
+
+ remapper.Register_Pointer(fake_old(0), obj_a);
+ remapper.Register_Pointer(fake_old(1), obj_b);
+
+ RefCountClass *slot_a = (RefCountClass *)fake_old(0);
+ RefCountClass *slot_b = (RefCountClass *)fake_old(1);
+ request_ref_remap(remapper, &slot_a);
+ request_ref_remap(remapper, &slot_b);
+
+ remapper.Process();
+
+ CHECK_EQ((void *)slot_a, (void *)obj_a);
+ CHECK_EQ((void *)slot_b, (void *)obj_b);
+
+ /* The remap took a reference on the caller's behalf. */
+ CHECK_EQ(obj_a->Num_Refs(), 2);
+ CHECK_EQ(obj_b->Num_Refs(), 2);
+
+ obj_a->Release_Ref();
+ obj_a->Release_Ref();
+ obj_b->Release_Ref();
+ obj_b->Release_Ref();
+}
+
+TEST(pointer_remap_keeps_plain_and_ref_counted_tables_apart)
+{
+ PointerRemapClass remapper;
+
+ TestRefObjClass *obj = new TestRefObjClass(7);
+ int plain = 3;
+
+ remapper.Register_Pointer(fake_old(0), &plain);
+ remapper.Register_Pointer(fake_old(1), obj);
+
+ void *plain_slot = fake_old(0);
+ RefCountClass *ref_slot = (RefCountClass *)fake_old(1);
+ request_remap(remapper, &plain_slot);
+ request_ref_remap(remapper, &ref_slot);
+
+ remapper.Process();
+
+ CHECK_EQ(plain_slot, (void *)&plain);
+ CHECK_EQ((void *)ref_slot, (void *)obj);
+
+ /* Only the ref-counted table adds a reference. */
+ CHECK_EQ(obj->Num_Refs(), 2);
+
+ obj->Release_Ref();
+ obj->Release_Ref();
+}
+
+/* ------------------------------------------------------------------ */
+/* saveloadstatus */
+/* ------------------------------------------------------------------ */
+
+TEST(status_count_is_a_plain_counter)
+{
+ SaveLoadStatus::Reset_Status_Count();
+ CHECK_EQ(SaveLoadStatus::Get_Status_Count(), 0);
+
+ for (int i = 1; i <= 5; ++i) {
+ SaveLoadStatus::Inc_Status_Count();
+ CHECK_EQ(SaveLoadStatus::Get_Status_Count(), i);
+ }
+
+ SaveLoadStatus::Reset_Status_Count();
+ CHECK_EQ(SaveLoadStatus::Get_Status_Count(), 0);
+}
+
+TEST(status_text_round_trips)
+{
+ StringClass text;
+
+ SaveLoadStatus::Set_Status_Text("loading", 0);
+ SaveLoadStatus::Get_Status_Text(text, 0);
+ CHECK_STR(text.Peek_Buffer(), "loading");
+
+ SaveLoadStatus::Set_Status_Text("terrain", 1);
+ SaveLoadStatus::Get_Status_Text(text, 1);
+ CHECK_STR(text.Peek_Buffer(), "terrain");
+
+ /* Setting the top-level text clears the sub-status - that is the whole
+ reason INIT_STATUS and INIT_SUB_STATUS are separate macros. */
+ INIT_STATUS("saving");
+ SaveLoadStatus::Get_Status_Text(text, 0);
+ CHECK_STR(text.Peek_Buffer(), "saving");
+ SaveLoadStatus::Get_Status_Text(text, 1);
+ CHECK_STR(text.Peek_Buffer(), "");
+
+ INIT_SUB_STATUS("objects");
+ SaveLoadStatus::Get_Status_Text(text, 1);
+ CHECK_STR(text.Peek_Buffer(), "objects");
+ SaveLoadStatus::Get_Status_Text(text, 0);
+ CHECK_STR(text.Peek_Buffer(), "saving");
+}
+
+/* ------------------------------------------------------------------ */
+/* SaveLoadSystemClass - subsystems */
+/* ------------------------------------------------------------------ */
+
+TEST(subsystem_save_load_round_trip)
+{
+ static char storage[4096];
+ int written = 0;
+
+ TestSubSystem.Value = 0x1234abcd;
+ TestSubSystem.HasData = true;
+ TestSubSystem.SaveCount = 0;
+ TestSubSystem.LoadCount = 0;
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+ CHECK(SaveLoadSystemClass::Save(csave, TestSubSystem));
+ written = file.Size();
+ file.Close();
+ }
+
+ CHECK_EQ(TestSubSystem.SaveCount, 1);
+ CHECK(written > 0);
+
+ TestSubSystem.Value = 0;
+
+ {
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+ CHECK(SaveLoadSystemClass::Load(cload));
+ file.Close();
+ }
+
+ CHECK_EQ(TestSubSystem.LoadCount, 1);
+ CHECK_EQ((unsigned)TestSubSystem.Value, 0x1234abcdu);
+}
+
+TEST(subsystem_that_contains_no_data_writes_nothing)
+{
+ static char storage[4096];
+ int written = 0;
+
+ TestSubSystem.HasData = false;
+ TestSubSystem.SaveCount = 0;
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+ CHECK(SaveLoadSystemClass::Save(csave, TestSubSystem));
+ written = file.Size();
+ file.Close();
+ }
+
+ CHECK_EQ(TestSubSystem.SaveCount, 0);
+ CHECK_EQ(written, 0);
+
+ TestSubSystem.HasData = true;
+}
+
+TEST(load_counts_every_chunk_it_walks)
+{
+ static char storage[4096];
+ int written = 0;
+
+ TestSubSystem.HasData = true;
+ TestSubSystem.LoadCount = 0;
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+ SaveLoadSystemClass::Save(csave, TestSubSystem);
+ SaveLoadSystemClass::Save(csave, TestSubSystem);
+ written = file.Size();
+ file.Close();
+ }
+
+ SaveLoadStatus::Reset_Status_Count();
+
+ {
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+ CHECK(SaveLoadSystemClass::Load(cload));
+ file.Close();
+ }
+
+ CHECK_EQ(SaveLoadStatus::Get_Status_Count(), 2);
+ CHECK_EQ(TestSubSystem.LoadCount, 2);
+}
+
+TEST(load_skips_chunks_no_subsystem_claims)
+{
+ static char storage[4096];
+ int written = 0;
+
+ TestSubSystem.LoadCount = 0;
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+
+ /* A chunk id nothing is registered for, then a real one. */
+ csave.Begin_Chunk(CHUNKID_PHYSTEST_BEGIN + 0x700);
+ int junk = 0xdeadbeef;
+ csave.Write(&junk, sizeof(junk));
+ csave.End_Chunk();
+
+ SaveLoadSystemClass::Save(csave, TestSubSystem);
+ written = file.Size();
+ file.Close();
+ }
+
+ {
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+ CHECK(SaveLoadSystemClass::Load(cload));
+ file.Close();
+ }
+
+ /* The unknown chunk is stepped over, the known one still loads. */
+ CHECK_EQ(TestSubSystem.LoadCount, 1);
+}
+
+TEST(load_of_an_empty_stream_succeeds)
+{
+ static char storage[64];
+ memset(storage, 0, sizeof(storage));
+
+ TestSubSystem.LoadCount = 0;
+
+ RAMFileClass file(storage, 0);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+ CHECK(SaveLoadSystemClass::Load(cload));
+ file.Close();
+
+ CHECK_EQ(TestSubSystem.LoadCount, 0);
+}
+
+/* ------------------------------------------------------------------ */
+/* SaveLoadSystemClass - post load callbacks */
+/* ------------------------------------------------------------------ */
+
+TEST(post_load_callbacks_fire_once_each)
+{
+ TestPersistClass a, b;
+
+ SaveLoadSystemClass::Register_Post_Load_Callback(&a);
+ SaveLoadSystemClass::Register_Post_Load_Callback(&b);
+ CHECK(a.Is_Post_Load_Registered());
+ CHECK(b.Is_Post_Load_Registered());
+
+ SaveLoadSystemClass::Post_Load_Processing(NULL);
+
+ CHECK_EQ(a.PostLoads, 1);
+ CHECK_EQ(b.PostLoads, 1);
+
+ /* The list is drained, so a second pass does nothing. */
+ CHECK(!a.Is_Post_Load_Registered());
+ CHECK(!b.Is_Post_Load_Registered());
+ SaveLoadSystemClass::Post_Load_Processing(NULL);
+ CHECK_EQ(a.PostLoads, 1);
+ CHECK_EQ(b.PostLoads, 1);
+}
+
+TEST(post_load_registration_is_idempotent)
+{
+ TestPersistClass obj;
+
+ SaveLoadSystemClass::Register_Post_Load_Callback(&obj);
+ SaveLoadSystemClass::Register_Post_Load_Callback(&obj);
+ SaveLoadSystemClass::Register_Post_Load_Callback(&obj);
+
+ SaveLoadSystemClass::Post_Load_Processing(NULL);
+ CHECK_EQ(obj.PostLoads, 1);
+}
+
+/* ------------------------------------------------------------------ */
+/* Persist factories */
+/* ------------------------------------------------------------------ */
+
+TEST(persist_factories_register_themselves)
+{
+ PersistFactoryClass *factory = SaveLoadSystemClass::Find_Persist_Factory(CHUNKID_TEST_PERSIST);
+ CHECK(factory != NULL);
+ CHECK_EQ(factory->Chunk_ID(), (uint32)CHUNKID_TEST_PERSIST);
+
+ CHECK(SaveLoadSystemClass::Find_Persist_Factory(CHUNKID_TEST_DEFINITION) != NULL);
+
+ /* Nothing claims this id. */
+ CHECK(SaveLoadSystemClass::Find_Persist_Factory(CHUNKID_PHYSTEST_BEGIN + 0x7ff) == NULL);
+}
+
+TEST(persist_object_round_trips_through_its_factory)
+{
+ static char storage[4096];
+ int written = 0;
+
+ TestPersistClass original;
+ original.Number = -12345;
+ original.Text = "persisted string";
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+ original.Get_Factory().Save(csave, &original);
+ written = file.Size();
+ file.Close();
+ }
+
+ CHECK(written > 0);
+
+ {
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+
+ PersistFactoryClass *factory = SaveLoadSystemClass::Find_Persist_Factory(CHUNKID_TEST_PERSIST);
+ CHECK(factory != NULL);
+ PersistClass *loaded = factory->Load(cload);
+ file.Close();
+
+ CHECK(loaded != NULL);
+ TestPersistClass *typed = (TestPersistClass *)loaded;
+ CHECK_EQ(typed->Number, -12345);
+ CHECK_STR(typed->Text.Peek_Buffer(), "persisted string");
+
+ /* The loaded object is a different instance, not the original. */
+ CHECK(typed != &original);
+ CHECK(&typed->Get_Factory() == &original.Get_Factory());
+
+ delete loaded;
+ }
+}
+
+TEST(persist_round_trip_of_default_state)
+{
+ static char storage[1024];
+ int written = 0;
+
+ TestPersistClass original;
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+ original.Get_Factory().Save(csave, &original);
+ written = file.Size();
+ file.Close();
+ }
+
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+ PersistClass *loaded = SaveLoadSystemClass::Find_Persist_Factory(CHUNKID_TEST_PERSIST)->Load(cload);
+ file.Close();
+
+ TestPersistClass *typed = (TestPersistClass *)loaded;
+ CHECK_EQ(typed->Number, 0);
+ CHECK_EQ((int)typed->Text.Get_Length(), 0);
+ delete loaded;
+}
+
+/* ------------------------------------------------------------------ */
+/* DefinitionFactoryMgrClass */
+/* ------------------------------------------------------------------ */
+
+TEST(definition_factories_are_findable_by_id_and_name)
+{
+ DefinitionFactoryClass *factory = DefinitionFactoryMgrClass::Find_Factory(CLASSID_TEST_DEF);
+ CHECK(factory != NULL);
+ CHECK_EQ(factory->Get_Class_ID(), (uint32)CLASSID_TEST_DEF);
+ CHECK_STR(factory->Get_Name(), "TestDefinition");
+ CHECK(factory->Is_Displayed());
+
+ /* Name lookup is case insensitive. */
+ CHECK_EQ(DefinitionFactoryMgrClass::Find_Factory("testdefinition"), factory);
+ CHECK_EQ(DefinitionFactoryMgrClass::Find_Factory("TESTDEFINITION"), factory);
+
+ CHECK(DefinitionFactoryMgrClass::Find_Factory("no such factory") == NULL);
+ CHECK(DefinitionFactoryMgrClass::Find_Factory((uint32)0x7fffffff) == NULL);
+}
+
+TEST(definition_factory_creates_its_own_type)
+{
+ DefinitionFactoryClass *factory = DefinitionFactoryMgrClass::Find_Factory(CLASSID_TEST_DEF);
+ CHECK(factory != NULL);
+
+ DefinitionClass *def = factory->Create();
+ CHECK(def != NULL);
+ CHECK_EQ(def->Get_Class_ID(), (uint32)CLASSID_TEST_DEF);
+ CHECK_EQ(def->Get_ID(), 0u);
+ delete def;
+}
+
+TEST(definition_factory_enumeration_by_superclass)
+{
+ /* Both test factories live under the same superclass, so walking that
+ superclass has to hand back exactly those two. */
+ int found_a = 0;
+ int found_b = 0;
+
+ for ( DefinitionFactoryClass *f = DefinitionFactoryMgrClass::Get_First(CLASSID_DUMMY_OBJECTS);
+ f != NULL;
+ f = DefinitionFactoryMgrClass::Get_Next(f, CLASSID_DUMMY_OBJECTS))
+ {
+ CHECK_EQ(SuperClassID_From_ClassID(f->Get_Class_ID()), (uint32)CLASSID_DUMMY_OBJECTS);
+ if (f->Get_Class_ID() == CLASSID_TEST_DEF) found_a++;
+ if (f->Get_Class_ID() == CLASSID_TEST_DEF_B) found_b++;
+ }
+
+ CHECK_EQ(found_a, 1);
+ CHECK_EQ(found_b, 1);
+}
+
+TEST(definition_factory_full_enumeration_reaches_both)
+{
+ int count = 0;
+ int found_a = 0;
+
+ for ( DefinitionFactoryClass *f = DefinitionFactoryMgrClass::Get_First();
+ f != NULL;
+ f = DefinitionFactoryMgrClass::Get_Next(f))
+ {
+ count++;
+ if (f->Get_Class_ID() == CLASSID_TEST_DEF) found_a++;
+ }
+
+ CHECK(count >= 2);
+ CHECK_EQ(found_a, 1);
+}
+
+TEST(superclass_id_buckets_by_range)
+{
+ CHECK_EQ(SuperClassID_From_ClassID(CLASSID_TEST_DEF), (uint32)CLASSID_DUMMY_OBJECTS);
+ CHECK_EQ(SuperClassID_From_ClassID(CLASSID_TEST_DEF_B), (uint32)CLASSID_DUMMY_OBJECTS);
+ CHECK_EQ(SuperClassID_From_ClassID(CLASSID_DUMMY_OBJECTS + DEF_CLASSID_RANGE - 1),
+ (uint32)CLASSID_DUMMY_OBJECTS);
+ CHECK_EQ(SuperClassID_From_ClassID(CLASSID_DUMMY_OBJECTS + DEF_CLASSID_RANGE),
+ (uint32)CLASSID_BUILDINGS);
+ CHECK_EQ(SuperClassID_From_ClassID(CLASSID_TERRAIN), (uint32)CLASSID_TERRAIN);
+}
+
+/* ------------------------------------------------------------------ */
+/* DefinitionMgrClass */
+/* ------------------------------------------------------------------ */
+
+TEST(definitions_are_stored_sorted_by_id)
+{
+ /* Registered out of order on purpose - Register_Definition binary
+ searches for the insertion point. */
+ DefinitionClass *c = make_def(300, "Charlie");
+ DefinitionClass *a = make_def(100, "Alpha");
+ DefinitionClass *d = make_def(400, "Delta");
+ DefinitionClass *b = make_def(200, "Bravo");
+
+ DefinitionClass *cur = DefinitionMgrClass::Get_First();
+ CHECK_EQ(cur, a);
+ cur = DefinitionMgrClass::Get_Next(cur);
+ CHECK_EQ(cur, b);
+ cur = DefinitionMgrClass::Get_Next(cur);
+ CHECK_EQ(cur, c);
+ cur = DefinitionMgrClass::Get_Next(cur);
+ CHECK_EQ(cur, d);
+ CHECK(DefinitionMgrClass::Get_Next(cur) == NULL);
+
+ free_def(a);
+ free_def(b);
+ free_def(c);
+ free_def(d);
+ CHECK(DefinitionMgrClass::Get_First() == NULL);
+}
+
+TEST(find_definition_by_id)
+{
+ DefinitionClass *defs[8];
+ for (int i = 0; i < 8; ++i) {
+ char name[32];
+ sprintf(name, "Def%d", i);
+ defs[i] = make_def(1000 + i * 7, name);
+ }
+
+ for (int j = 0; j < 8; ++j) {
+ CHECK_EQ(DefinitionMgrClass::Find_Definition(1000 + j * 7), defs[j]);
+ }
+
+ /* Ids that fall between, before and after the registered ones. */
+ CHECK(DefinitionMgrClass::Find_Definition(1001) == NULL);
+ CHECK(DefinitionMgrClass::Find_Definition(1) == NULL);
+ CHECK(DefinitionMgrClass::Find_Definition(999999) == NULL);
+
+ for (int k = 0; k < 8; ++k)
+ free_def(defs[k]);
+}
+
+TEST(find_definition_with_a_single_entry)
+{
+ DefinitionClass *only = make_def(42, "Only");
+
+ CHECK_EQ(DefinitionMgrClass::Find_Definition(42), only);
+ CHECK(DefinitionMgrClass::Find_Definition(41) == NULL);
+ CHECK(DefinitionMgrClass::Find_Definition(43) == NULL);
+
+ free_def(only);
+ CHECK(DefinitionMgrClass::Find_Definition(42) == NULL);
+}
+
+TEST(find_named_definition_is_case_insensitive)
+{
+ DefinitionClass *a = make_def(10, "Alpha Unit");
+ DefinitionClass *b = make_def(20, "Bravo Unit");
+
+ CHECK_EQ(DefinitionMgrClass::Find_Named_Definition("Alpha Unit"), a);
+ CHECK_EQ(DefinitionMgrClass::Find_Named_Definition("alpha unit"), a);
+ CHECK_EQ(DefinitionMgrClass::Find_Named_Definition("BRAVO UNIT"), b);
+ CHECK(DefinitionMgrClass::Find_Named_Definition("Charlie") == NULL);
+
+ free_def(a);
+ free_def(b);
+}
+
+TEST(find_typed_definition_matches_class_and_superclass)
+{
+ DefinitionClass *a = new TestDefinitionClass;
+ ((TestDefinitionClass *)a)->Set_Name("Typed A");
+ a->Set_ID(500);
+ DefinitionMgrClass::Register_Definition(a);
+
+ DefinitionClass *b = new TestDefinitionBClass;
+ ((TestDefinitionBClass *)b)->Set_Name("Typed B");
+ b->Set_ID(501);
+ DefinitionMgrClass::Register_Definition(b);
+
+ CHECK_EQ(DefinitionMgrClass::Find_Typed_Definition("Typed A", CLASSID_TEST_DEF), a);
+ CHECK_EQ(DefinitionMgrClass::Find_Typed_Definition("typed b", CLASSID_TEST_DEF_B), b);
+
+ /* The superclass matches too - both classes share CLASSID_DUMMY_OBJECTS. */
+ CHECK_EQ(DefinitionMgrClass::Find_Typed_Definition("Typed B", CLASSID_DUMMY_OBJECTS), b);
+
+ /* Wrong class id for that name. This is the path that used to walk the
+ cache vector's uninitialized tail - see the Count()/Length() fix in
+ definitionmgr.cpp. */
+ CHECK(DefinitionMgrClass::Find_Typed_Definition("Typed A", CLASSID_LIGHT) == NULL);
+ CHECK(DefinitionMgrClass::Find_Typed_Definition("No Such Name", CLASSID_TEST_DEF) == NULL);
+
+ free_def(a);
+ free_def(b);
+}
+
+TEST(definition_enumeration_by_class_and_superclass)
+{
+ DefinitionClass *a1 = new TestDefinitionClass;
+ a1->Set_ID(600);
+ DefinitionMgrClass::Register_Definition(a1);
+
+ DefinitionClass *b1 = new TestDefinitionBClass;
+ b1->Set_ID(601);
+ DefinitionMgrClass::Register_Definition(b1);
+
+ DefinitionClass *a2 = new TestDefinitionClass;
+ a2->Set_ID(602);
+ DefinitionMgrClass::Register_Definition(a2);
+
+ /* ID_CLASS sees only the exact class... */
+ int class_count = 0;
+ for ( DefinitionClass *d = DefinitionMgrClass::Get_First(CLASSID_TEST_DEF, DefinitionMgrClass::ID_CLASS);
+ d != NULL;
+ d = DefinitionMgrClass::Get_Next(d, CLASSID_TEST_DEF, DefinitionMgrClass::ID_CLASS))
+ {
+ CHECK_EQ(d->Get_Class_ID(), (uint32)CLASSID_TEST_DEF);
+ class_count++;
+ }
+ CHECK_EQ(class_count, 2);
+
+ /* ...ID_SUPERCLASS sees the whole family. */
+ int super_count = 0;
+ for ( DefinitionClass *d = DefinitionMgrClass::Get_First(CLASSID_DUMMY_OBJECTS, DefinitionMgrClass::ID_SUPERCLASS);
+ d != NULL;
+ d = DefinitionMgrClass::Get_Next(d, CLASSID_DUMMY_OBJECTS, DefinitionMgrClass::ID_SUPERCLASS))
+ {
+ super_count++;
+ }
+ CHECK_EQ(super_count, 3);
+
+ CHECK(DefinitionMgrClass::Get_First(CLASSID_LIGHT, DefinitionMgrClass::ID_CLASS) == NULL);
+
+ free_def(a1);
+ free_def(b1);
+ free_def(a2);
+}
+
+TEST(registering_a_duplicate_id_is_refused)
+{
+ DefinitionClass *first = make_def(900, "First");
+
+ DefinitionClass *dup = new TestDefinitionClass;
+ ((TestDefinitionClass *)dup)->Set_Name("Duplicate");
+ dup->Set_ID(900);
+ DefinitionMgrClass::Register_Definition(dup);
+
+ /* The second registration is dropped, the first one still owns the id. */
+ CHECK_EQ(DefinitionMgrClass::Find_Definition(900), first);
+ CHECK_EQ(DefinitionMgrClass::Get_First(), first);
+ CHECK(DefinitionMgrClass::Get_Next(first) == NULL);
+
+ delete dup;
+ free_def(first);
+}
+
+TEST(a_definition_with_id_zero_is_not_registered)
+{
+ DefinitionClass *def = new TestDefinitionClass;
+ ((TestDefinitionClass *)def)->Set_Name("Unset");
+ DefinitionMgrClass::Register_Definition(def);
+
+ CHECK(DefinitionMgrClass::Get_First() == NULL);
+
+ delete def;
+}
+
+TEST(changing_an_id_relinks_the_definition)
+{
+ DefinitionClass *a = make_def(10, "A");
+ DefinitionClass *b = make_def(20, "B");
+
+ /* Set_ID re-registers, so the sort order has to follow. */
+ a->Set_ID(30);
+
+ CHECK_EQ(DefinitionMgrClass::Get_First(), b);
+ CHECK_EQ(DefinitionMgrClass::Get_Next(b), a);
+ CHECK_EQ(DefinitionMgrClass::Find_Definition(30), a);
+ CHECK(DefinitionMgrClass::Find_Definition(10) == NULL);
+
+ free_def(a);
+ free_def(b);
+}
+
+TEST(unregistering_reindexes_the_rest)
+{
+ DefinitionClass *a = make_def(10, "A");
+ DefinitionClass *b = make_def(20, "B");
+ DefinitionClass *c = make_def(30, "C");
+
+ free_def(b);
+
+ CHECK_EQ(DefinitionMgrClass::Get_First(), a);
+ CHECK_EQ(DefinitionMgrClass::Get_Next(a), c);
+ CHECK(DefinitionMgrClass::Get_Next(c) == NULL);
+ CHECK(DefinitionMgrClass::Find_Definition(20) == NULL);
+
+ /* Unregistering twice is harmless. */
+ DefinitionMgrClass::Unregister_Definition(c);
+ DefinitionMgrClass::Unregister_Definition(c);
+ CHECK_EQ(DefinitionMgrClass::Get_First(), a);
+ delete c;
+
+ free_def(a);
+}
+
+TEST(get_new_id_walks_the_class_id_range)
+{
+ /* Each class owns a block of 10000 ids starting at its offset from
+ DEF_CLASSID_START. */
+ const uint32 range_start = (CLASSID_TEST_DEF - DEF_CLASSID_START) * 10000;
+
+ CHECK_EQ(DefinitionMgrClass::Get_New_ID(CLASSID_TEST_DEF), range_start + 1);
+
+ DefinitionClass *first = make_def(range_start + 1, "First");
+ CHECK_EQ(DefinitionMgrClass::Get_New_ID(CLASSID_TEST_DEF), range_start + 2);
+
+ DefinitionClass *second = make_def(range_start + 2, "Second");
+ CHECK_EQ(DefinitionMgrClass::Get_New_ID(CLASSID_TEST_DEF), range_start + 3);
+
+ /* A hole in the middle gets filled before the tail is extended. */
+ DefinitionClass *fourth = make_def(range_start + 4, "Fourth");
+ CHECK_EQ(DefinitionMgrClass::Get_New_ID(CLASSID_TEST_DEF), range_start + 3);
+
+ free_def(first);
+ free_def(second);
+ free_def(fourth);
+}
+
+TEST(definition_save_load_round_trip)
+{
+ static char storage[2048];
+ int written = 0;
+
+ TestDefinitionClass original;
+ original.Set_Name("Saved Definition");
+ original.Set_ID(4242);
+ original.Set_User_Data(0x99);
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+ original.Get_Factory().Save(csave, &original);
+ written = file.Size();
+ file.Close();
+ }
+
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+ PersistClass *loaded = SaveLoadSystemClass::Find_Persist_Factory(CHUNKID_TEST_DEFINITION)->Load(cload);
+ file.Close();
+
+ CHECK(loaded != NULL);
+ DefinitionClass *def = (DefinitionClass *)(TestDefinitionClass *)loaded;
+ CHECK_EQ(def->Get_ID(), 4242u);
+ CHECK_STR(def->Get_Name(), "Saved Definition");
+
+ /* Only the id and the name are persisted - the user data and the save
+ flag are runtime-only and come back at their defaults. */
+ CHECK_EQ(def->Get_User_Data(), 0u);
+ CHECK(def->Is_Save_Enabled());
+
+ delete loaded;
+}
+
+/* ------------------------------------------------------------------ */
+/* TwiddlerClass */
+/* ------------------------------------------------------------------ */
+
+TEST(twiddler_module_is_linked_and_registered)
+{
+ /* twiddler.obj holds nothing anyone references, so without the force
+ link its static factories never make it into the executable. */
+ FORCE_LINK(Twiddler);
+
+ CHECK(SaveLoadSystemClass::Find_Persist_Factory(CHUNKID_TWIDDLER) != NULL);
+
+ DefinitionFactoryClass *factory = DefinitionFactoryMgrClass::Find_Factory(CLASSID_TWIDDLERS);
+ CHECK(factory != NULL);
+ CHECK_STR(factory->Get_Name(), "Twiddler");
+}
+
+TEST(an_empty_twiddler_twiddles_to_nothing)
+{
+ FORCE_LINK(Twiddler);
+
+ TwiddlerClass twiddler;
+ CHECK_EQ(twiddler.Get_Class_ID(), (uint32)CLASSID_TWIDDLERS);
+ CHECK_EQ(twiddler.Get_Indirect_Class_ID(), 0u);
+
+ /* With no entries in its preset list there is nothing to pick. */
+ CHECK(twiddler.Twiddle() == NULL);
+ CHECK(twiddler.Create() == NULL);
+
+ twiddler.Set_Indirect_Class_ID(CLASSID_TEST_DEF);
+ CHECK_EQ(twiddler.Get_Indirect_Class_ID(), (uint32)CLASSID_TEST_DEF);
+}
+
+TEST(find_definition_indirects_through_a_twiddler)
+{
+ FORCE_LINK(Twiddler);
+
+ TwiddlerClass *twiddler = new TwiddlerClass;
+ twiddler->Set_Name("Empty Twiddler");
+ twiddler->Set_ID(7000);
+ DefinitionMgrClass::Register_Definition(twiddler);
+
+ /* twiddle=true asks the twiddler for a victim, and an empty one has
+ none, so the lookup comes back NULL even though the definition is
+ there. twiddle=false hands back the twiddler itself. */
+ CHECK(DefinitionMgrClass::Find_Definition(7000, true) == NULL);
+ CHECK_EQ(DefinitionMgrClass::Find_Definition(7000, false), (DefinitionClass *)twiddler);
+
+ CHECK(DefinitionMgrClass::Find_Named_Definition("Empty Twiddler", true) == NULL);
+ CHECK_EQ(DefinitionMgrClass::Find_Named_Definition("empty twiddler", false),
+ (DefinitionClass *)twiddler);
+
+ free_def(twiddler);
+}
+
+TEST(twiddler_round_trips_through_its_persist_factory)
+{
+ FORCE_LINK(Twiddler);
+
+ static char storage[2048];
+ int written = 0;
+
+ TwiddlerClass original;
+ original.Set_Name("Round Trip Twiddler");
+ original.Set_ID(7100);
+ original.Set_Indirect_Class_ID(CLASSID_TEST_DEF);
+
+ {
+ RAMFileClass file(storage, sizeof(storage));
+ file.Open(FileClass::WRITE);
+ ChunkSaveClass csave(&file);
+ original.Get_Factory().Save(csave, &original);
+ written = file.Size();
+ file.Close();
+ }
+
+ CHECK(written > 0);
+
+ RAMFileClass file(storage, written);
+ file.Open(FileClass::READ);
+ ChunkLoadClass cload(&file);
+ PersistClass *loaded = SaveLoadSystemClass::Find_Persist_Factory(CHUNKID_TWIDDLER)->Load(cload);
+ file.Close();
+
+ CHECK(loaded != NULL);
+ TwiddlerClass *twiddler = (TwiddlerClass *)loaded;
+ CHECK_EQ(twiddler->Get_ID(), 7100u);
+ CHECK_STR(twiddler->Get_Name(), "Round Trip Twiddler");
+ CHECK_EQ(twiddler->Get_Indirect_Class_ID(), (uint32)CLASSID_TEST_DEF);
+
+ delete loaded;
+}
diff --git a/GeneralsMD/Code/Tests/test_wwutil.cpp b/GeneralsMD/Code/Tests/test_wwutil.cpp
new file mode 100644
index 000000000..9153f1cb1
--- /dev/null
+++ b/GeneralsMD/Code/Tests/test_wwutil.cpp
@@ -0,0 +1,547 @@
+/*
+ * Wwutil coverage: cMathUtil and cMiscUtil, the whole library.
+ *
+ * Both classes are pure static helpers, so everything here is a direct call.
+ * The interesting parts are cMathUtil's hand-rolled angle convention (screen
+ * coordinates, so +y points down and Angle_To_Vector negates dy on the way
+ * out) and the round trip through Vector_To_Angle, which is written as a
+ * chain of quadrant fixups rather than an atan2.
+ */
+#include "test_harness.h"
+
+#include "mathutil.h"
+#include "miscutil.h"
+#include "wwstring.h"
+#include "wwmath.h"
+
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
+
+namespace
+{
+ const char *TEMP_FILE = "wwutil_test_tmp.dat";
+
+ void write_temp_file(const char *text)
+ {
+ FILE *fp = fopen(TEMP_FILE, "wb");
+ CHECK(fp != 0);
+ fwrite(text, 1, strlen(text), fp);
+ fclose(fp);
+ }
+}
+
+/* ------------------------------------------------------------------ */
+/* cMathUtil - angles */
+/* ------------------------------------------------------------------ */
+
+TEST(mathutil_pi_constants)
+{
+ CHECK_NEAR(cMathUtil::PI_1, 3.14159265358979, 1e-6);
+ CHECK_NEAR(cMathUtil::PI_2, cMathUtil::PI_1 / 2.0, 1e-6);
+}
+
+TEST(angle_to_vector_cardinals)
+{
+ /* Screen coordinates: 0 degrees is "up", which is -y. */
+ double dx, dy;
+
+ cMathUtil::Angle_To_Vector(0.0, dx, dy);
+ CHECK_NEAR(dx, 0.0, 1e-6);
+ CHECK_NEAR(dy, -1.0, 1e-6);
+
+ cMathUtil::Angle_To_Vector(90.0, dx, dy);
+ CHECK_NEAR(dx, 1.0, 1e-6);
+ CHECK_NEAR(dy, 0.0, 1e-6);
+
+ cMathUtil::Angle_To_Vector(180.0, dx, dy);
+ CHECK_NEAR(dx, 0.0, 1e-6);
+ CHECK_NEAR(dy, 1.0, 1e-6);
+
+ cMathUtil::Angle_To_Vector(270.0, dx, dy);
+ CHECK_NEAR(dx, -1.0, 1e-6);
+ CHECK_NEAR(dy, 0.0, 1e-6);
+}
+
+TEST(angle_to_vector_is_always_unit_length)
+{
+ /* Each quadrant is a separate branch with its own sin/cos pairing, so
+ walk all four of them. */
+ for (int deg = 0; deg < 360; ++deg)
+ {
+ double dx, dy;
+ cMathUtil::Angle_To_Vector(double(deg), dx, dy);
+ CHECK_NEAR(::sqrt(dx * dx + dy * dy), 1.0, 1e-4);
+ }
+}
+
+TEST(angle_to_vector_turns_clockwise_on_screen)
+{
+ /* Increasing angle sweeps right then down: 45 degrees is right-and-up. */
+ double dx, dy;
+ cMathUtil::Angle_To_Vector(45.0, dx, dy);
+ CHECK(dx > 0.0);
+ CHECK(dy < 0.0);
+
+ cMathUtil::Angle_To_Vector(135.0, dx, dy);
+ CHECK(dx > 0.0);
+ CHECK(dy > 0.0);
+
+ cMathUtil::Angle_To_Vector(225.0, dx, dy);
+ CHECK(dx < 0.0);
+ CHECK(dy > 0.0);
+
+ cMathUtil::Angle_To_Vector(315.0, dx, dy);
+ CHECK(dx < 0.0);
+ CHECK(dy < 0.0);
+}
+
+TEST(vector_to_angle_round_trips_every_degree)
+{
+ for (int deg = 0; deg < 360; ++deg)
+ {
+ double dx, dy, angle;
+ cMathUtil::Angle_To_Vector(double(deg), dx, dy);
+ cMathUtil::Vector_To_Angle(dx, dy, angle);
+ CHECK_NEAR(angle, double(deg), 1e-3);
+ }
+}
+
+TEST(vector_to_angle_ignores_magnitude)
+{
+ double angle_unit, angle_long;
+ cMathUtil::Vector_To_Angle(3.0, -4.0, angle_unit);
+ cMathUtil::Vector_To_Angle(300.0, -400.0, angle_long);
+ CHECK_NEAR(angle_unit, angle_long, 1e-6);
+}
+
+TEST(vector_to_angle_handles_the_axes)
+{
+ double angle;
+
+ /* dx == 0 is its own branch and never reaches the atan. */
+ cMathUtil::Vector_To_Angle(0.0, -1.0, angle);
+ CHECK_NEAR(angle, 0.0, 1e-6);
+
+ cMathUtil::Vector_To_Angle(0.0, 1.0, angle);
+ CHECK_NEAR(angle, 180.0, 1e-6);
+
+ /* The degenerate zero vector reports straight up rather than failing. */
+ cMathUtil::Vector_To_Angle(0.0, 0.0, angle);
+ CHECK_NEAR(angle, 0.0, 1e-6);
+
+ /* Looser here: these two go through the atan/quadrant fixup chain, which
+ mixes PI_1 and PI_2. PI_2 is a separately truncated literal rather than
+ PI_1/2, and the 1.5e-7 difference lands as ~1e-5 degrees of drift. */
+ cMathUtil::Vector_To_Angle(1.0, 0.0, angle);
+ CHECK_NEAR(angle, 90.0, 1e-4);
+
+ cMathUtil::Vector_To_Angle(-1.0, 0.0, angle);
+ CHECK_NEAR(angle, 270.0, 1e-4);
+}
+
+TEST(vector_to_angle_stays_in_range)
+{
+ for (int deg = 0; deg < 360; ++deg)
+ {
+ double dx, dy, angle;
+ cMathUtil::Angle_To_Vector(double(deg), dx, dy);
+ cMathUtil::Vector_To_Angle(dx, dy, angle);
+ CHECK(angle >= 0.0);
+ CHECK(angle < 360.0);
+ }
+}
+
+/* ------------------------------------------------------------------ */
+/* cMathUtil - distance, rounding, rotation */
+/* ------------------------------------------------------------------ */
+
+TEST(simple_distance)
+{
+ CHECK_NEAR(cMathUtil::Simple_Distance(0.0, 0.0, 3.0, 4.0), 5.0, 1e-9);
+ CHECK_NEAR(cMathUtil::Simple_Distance(3.0, 4.0, 0.0, 0.0), 5.0, 1e-9);
+ CHECK_NEAR(cMathUtil::Simple_Distance(-1.0, -1.0, -1.0, -1.0), 0.0, 1e-9);
+ CHECK_NEAR(cMathUtil::Simple_Distance(-2.0, 5.0, 1.0, 1.0), 5.0, 1e-9);
+}
+
+TEST(round_goes_away_from_zero)
+{
+ CHECK_EQ(cMathUtil::Round(0.0), 0);
+ CHECK_EQ(cMathUtil::Round(0.4), 0);
+ CHECK_EQ(cMathUtil::Round(0.5), 1);
+ CHECK_EQ(cMathUtil::Round(1.49), 1);
+ CHECK_EQ(cMathUtil::Round(1.5), 2);
+ CHECK_EQ(cMathUtil::Round(2.5), 3);
+
+ /* Not truncation-toward-negative-infinity: -2.5 goes to -3, not -2. */
+ CHECK_EQ(cMathUtil::Round(-0.4), 0);
+ CHECK_EQ(cMathUtil::Round(-0.5), -1);
+ CHECK_EQ(cMathUtil::Round(-1.5), -2);
+ CHECK_EQ(cMathUtil::Round(-2.5), -3);
+}
+
+TEST(round_has_a_dead_zone_at_the_origin)
+{
+ /* Anything inside +/-MISCUTIL_EPSILON short-circuits to exactly 0. */
+ CHECK_EQ(cMathUtil::Round(MISCUTIL_EPSILON / 2.0), 0);
+ CHECK_EQ(cMathUtil::Round(-MISCUTIL_EPSILON / 2.0), 0);
+ CHECK_EQ(cMathUtil::Round(0.0), 0);
+}
+
+TEST(rotate_vector_quarter_turns)
+{
+ double vx = 1.0, vy = 0.0;
+
+ cMathUtil::Rotate_Vector(vx, vy, 90.0);
+ CHECK_NEAR(vx, 0.0, 1e-6);
+ CHECK_NEAR(vy, 1.0, 1e-6);
+
+ cMathUtil::Rotate_Vector(vx, vy, 90.0);
+ CHECK_NEAR(vx, -1.0, 1e-6);
+ CHECK_NEAR(vy, 0.0, 1e-6);
+
+ cMathUtil::Rotate_Vector(vx, vy, 180.0);
+ CHECK_NEAR(vx, 1.0, 1e-6);
+ CHECK_NEAR(vy, 0.0, 1e-6);
+}
+
+TEST(rotate_vector_preserves_length)
+{
+ for (int deg = 0; deg < 360; deg += 7)
+ {
+ double vx = 3.0, vy = -4.0;
+ cMathUtil::Rotate_Vector(vx, vy, double(deg));
+ CHECK_NEAR(::sqrt(vx * vx + vy * vy), 5.0, 1e-6);
+ }
+}
+
+TEST(rotate_vector_by_zero_and_full_turn_is_identity)
+{
+ double vx = 1.25, vy = -7.5;
+
+ cMathUtil::Rotate_Vector(vx, vy, 0.0);
+ CHECK_NEAR(vx, 1.25, 1e-9);
+ CHECK_NEAR(vy, -7.5, 1e-9);
+
+ cMathUtil::Rotate_Vector(vx, vy, 360.0);
+ CHECK_NEAR(vx, 1.25, 1e-5);
+ CHECK_NEAR(vy, -7.5, 1e-5);
+}
+
+TEST(rotate_vector_composes)
+{
+ double vx = 2.0, vy = 1.0;
+ cMathUtil::Rotate_Vector(vx, vy, 30.0);
+ cMathUtil::Rotate_Vector(vx, vy, 45.0);
+
+ double wx = 2.0, wy = 1.0;
+ cMathUtil::Rotate_Vector(wx, wy, 75.0);
+
+ CHECK_NEAR(vx, wx, 1e-6);
+ CHECK_NEAR(vy, wy, 1e-6);
+}
+
+/* ------------------------------------------------------------------ */
+/* cMathUtil - probability density helpers */
+/* ------------------------------------------------------------------ */
+
+TEST(uniform_pdf_double_stays_in_range)
+{
+ bool saw_low = false;
+ bool saw_high = false;
+
+ for (int i = 0; i < 2000; ++i)
+ {
+ double x = cMathUtil::Get_Uniform_Pdf_Double(-5.0, 15.0);
+ CHECK(x >= -5.0 - MISCUTIL_EPSILON);
+ CHECK(x <= 15.0 + MISCUTIL_EPSILON);
+ if (x < 0.0) saw_low = true;
+ if (x > 10.0) saw_high = true;
+ }
+
+ /* Not a distribution test, just proof it is not pinned to one endpoint. */
+ CHECK(saw_low);
+ CHECK(saw_high);
+}
+
+TEST(uniform_pdf_double_with_empty_range)
+{
+ double x = cMathUtil::Get_Uniform_Pdf_Double(7.0, 7.0);
+ CHECK_NEAR(x, 7.0, 1e-9);
+}
+
+TEST(normalized_uniform_pdf_double_is_zero_to_one)
+{
+ for (int i = 0; i < 2000; ++i)
+ {
+ double x = cMathUtil::Get_Normalized_Uniform_Pdf_Double();
+ CHECK(x >= 0.0);
+ CHECK(x <= 1.0);
+ }
+}
+
+TEST(uniform_pdf_int_covers_its_whole_range)
+{
+ int seen[6] = { 0, 0, 0, 0, 0, 0 };
+
+ for (int i = 0; i < 4000; ++i)
+ {
+ int x = cMathUtil::Get_Uniform_Pdf_Int(10, 15);
+ CHECK(x >= 10);
+ CHECK(x <= 15);
+ seen[x - 10] = 1;
+ }
+
+ /* Both endpoints are inclusive - the +1 in the modulo is load bearing. */
+ for (int j = 0; j < 6; ++j)
+ CHECK_EQ(seen[j], 1);
+}
+
+TEST(uniform_pdf_int_with_single_value_range)
+{
+ for (int i = 0; i < 16; ++i)
+ CHECK_EQ(cMathUtil::Get_Uniform_Pdf_Int(3, 3), 3);
+}
+
+TEST(hat_pdf_double_stays_in_range)
+{
+ for (int i = 0; i < 2000; ++i)
+ {
+ double x = cMathUtil::Get_Hat_Pdf_Double(-2.0, 6.0);
+ CHECK(x >= -2.0 - MISCUTIL_EPSILON);
+ CHECK(x <= 6.0 + MISCUTIL_EPSILON);
+ }
+}
+
+TEST(hat_pdf_double_with_empty_range)
+{
+ double x = cMathUtil::Get_Hat_Pdf_Double(4.0, 4.0);
+ CHECK_NEAR(x, 4.0, 1e-9);
+}
+
+TEST(normalized_hat_pdf_double_is_zero_to_one)
+{
+ for (int i = 0; i < 2000; ++i)
+ {
+ double x = cMathUtil::Get_Normalized_Hat_Pdf_Double();
+ CHECK(x >= 0.0);
+ CHECK(x <= 1.0);
+ }
+}
+
+TEST(hat_pdf_int_stays_in_range)
+{
+ for (int i = 0; i < 2000; ++i)
+ {
+ int x = cMathUtil::Get_Hat_Pdf_Int(0, 10);
+ CHECK(x >= 0);
+ CHECK(x <= 10);
+ }
+}
+
+/* ------------------------------------------------------------------ */
+/* cMiscUtil - time */
+/* ------------------------------------------------------------------ */
+
+TEST(get_text_time_is_a_stripped_ctime_string)
+{
+ LPCSTR text = cMiscUtil::Get_Text_Time();
+ CHECK(text != 0);
+
+ /* ctime's fixed layout "Www Mmm dd hh:mm:ss yyyy" minus the newline. */
+ CHECK_EQ((int)strlen(text), 24);
+ CHECK(strchr(text, '\n') == 0);
+ CHECK_EQ((int)text[13], (int)':');
+ CHECK_EQ((int)text[16], (int)':');
+}
+
+TEST(seconds_to_hms_splits_correctly)
+{
+ int h, m, s;
+
+ cMiscUtil::Seconds_To_Hms(0.0f, h, m, s);
+ CHECK_EQ(h, 0); CHECK_EQ(m, 0); CHECK_EQ(s, 0);
+
+ cMiscUtil::Seconds_To_Hms(59.0f, h, m, s);
+ CHECK_EQ(h, 0); CHECK_EQ(m, 0); CHECK_EQ(s, 59);
+
+ cMiscUtil::Seconds_To_Hms(60.0f, h, m, s);
+ CHECK_EQ(h, 0); CHECK_EQ(m, 1); CHECK_EQ(s, 0);
+
+ cMiscUtil::Seconds_To_Hms(3599.0f, h, m, s);
+ CHECK_EQ(h, 0); CHECK_EQ(m, 59); CHECK_EQ(s, 59);
+
+ cMiscUtil::Seconds_To_Hms(3600.0f, h, m, s);
+ CHECK_EQ(h, 1); CHECK_EQ(m, 0); CHECK_EQ(s, 0);
+
+ cMiscUtil::Seconds_To_Hms(3661.0f, h, m, s);
+ CHECK_EQ(h, 1); CHECK_EQ(m, 1); CHECK_EQ(s, 1);
+
+ /* Hours are unbounded - no wrap at 24. */
+ cMiscUtil::Seconds_To_Hms(86399.0f, h, m, s);
+ CHECK_EQ(h, 23); CHECK_EQ(m, 59); CHECK_EQ(s, 59);
+
+ cMiscUtil::Seconds_To_Hms(360000.0f, h, m, s);
+ CHECK_EQ(h, 100); CHECK_EQ(m, 0); CHECK_EQ(s, 0);
+}
+
+TEST(seconds_to_hms_truncates_fractions)
+{
+ int h, m, s;
+
+ cMiscUtil::Seconds_To_Hms(59.9f, h, m, s);
+ CHECK_EQ(h, 0); CHECK_EQ(m, 0); CHECK_EQ(s, 59);
+
+ cMiscUtil::Seconds_To_Hms(0.5f, h, m, s);
+ CHECK_EQ(h, 0); CHECK_EQ(m, 0); CHECK_EQ(s, 0);
+}
+
+TEST(seconds_to_hms_recomposes)
+{
+ for (int total = 0; total < 200000; total += 997)
+ {
+ int h, m, s;
+ cMiscUtil::Seconds_To_Hms(float(total), h, m, s);
+ CHECK(m >= 0 && m < 60);
+ CHECK(s >= 0 && s < 60);
+ CHECK_EQ(h * 3600 + m * 60 + s, total);
+ }
+}
+
+/* ------------------------------------------------------------------ */
+/* cMiscUtil - string helpers */
+/* ------------------------------------------------------------------ */
+
+TEST(string_compare_is_case_insensitive)
+{
+ CHECK(cMiscUtil::Is_String_Same("Hello", "hello"));
+ CHECK(cMiscUtil::Is_String_Same("", ""));
+ CHECK(cMiscUtil::Is_String_Same("MiXeD123", "mixed123"));
+ CHECK(!cMiscUtil::Is_String_Same("hello", "hello "));
+ CHECK(!cMiscUtil::Is_String_Same("abc", "abd"));
+
+ CHECK(!cMiscUtil::Is_String_Different("Hello", "hello"));
+ CHECK(cMiscUtil::Is_String_Different("abc", "abd"));
+
+ /* The two are strict complements. */
+ CHECK_NE(cMiscUtil::Is_String_Same("a", "b"),
+ cMiscUtil::Is_String_Different("a", "b"));
+}
+
+TEST(character_classes_match_the_c_library)
+{
+ for (int i = 0; i < 128; ++i)
+ {
+ char c = (char)i;
+ CHECK_EQ(cMiscUtil::Is_Alphabetic(c), isalpha(i) != 0);
+ CHECK_EQ(cMiscUtil::Is_Numeric(c), isdigit(i) != 0);
+ CHECK_EQ(cMiscUtil::Is_Alphanumeric(c), isalnum(i) != 0);
+ }
+}
+
+TEST(is_whitespace_is_space_and_tab_only)
+{
+ CHECK(cMiscUtil::Is_Whitespace(' '));
+ CHECK(cMiscUtil::Is_Whitespace('\t'));
+
+ /* Newline and carriage return are deliberately not whitespace here, and
+ Trim_Trailing_Whitespace inherits that. */
+ CHECK(!cMiscUtil::Is_Whitespace('\n'));
+ CHECK(!cMiscUtil::Is_Whitespace('\r'));
+ CHECK(!cMiscUtil::Is_Whitespace('\0'));
+ CHECK(!cMiscUtil::Is_Whitespace('x'));
+}
+
+TEST(trim_trailing_whitespace)
+{
+ char buffer[64];
+
+ strcpy(buffer, "hello ");
+ cMiscUtil::Trim_Trailing_Whitespace(buffer);
+ CHECK_STR(buffer, "hello");
+
+ strcpy(buffer, "hello\t \t");
+ cMiscUtil::Trim_Trailing_Whitespace(buffer);
+ CHECK_STR(buffer, "hello");
+
+ strcpy(buffer, " spaced out ");
+ cMiscUtil::Trim_Trailing_Whitespace(buffer);
+ CHECK_STR(buffer, " spaced out");
+
+ strcpy(buffer, "clean");
+ cMiscUtil::Trim_Trailing_Whitespace(buffer);
+ CHECK_STR(buffer, "clean");
+
+ strcpy(buffer, " ");
+ cMiscUtil::Trim_Trailing_Whitespace(buffer);
+ CHECK_STR(buffer, "");
+
+ strcpy(buffer, "");
+ cMiscUtil::Trim_Trailing_Whitespace(buffer);
+ CHECK_STR(buffer, "");
+
+ /* A trailing newline blocks the trim - it is not in the whitespace set. */
+ strcpy(buffer, "line \n");
+ cMiscUtil::Trim_Trailing_Whitespace(buffer);
+ CHECK_STR(buffer, "line \n");
+}
+
+/* ------------------------------------------------------------------ */
+/* cMiscUtil - files */
+/* ------------------------------------------------------------------ */
+
+TEST(file_exists_and_remove_file)
+{
+ cMiscUtil::Remove_File(TEMP_FILE);
+ CHECK(!cMiscUtil::File_Exists(TEMP_FILE));
+
+ write_temp_file("wwutil");
+ CHECK(cMiscUtil::File_Exists(TEMP_FILE));
+
+ cMiscUtil::Remove_File(TEMP_FILE);
+ CHECK(!cMiscUtil::File_Exists(TEMP_FILE));
+
+ /* Removing something that is not there is a no-op, not a failure. */
+ cMiscUtil::Remove_File(TEMP_FILE);
+ CHECK(!cMiscUtil::File_Exists(TEMP_FILE));
+
+ CHECK(!cMiscUtil::File_Exists("no_such_directory_here\\no_such_file.xyz"));
+}
+
+TEST(file_is_read_only)
+{
+ write_temp_file("wwutil");
+ CHECK(!cMiscUtil::File_Is_Read_Only(TEMP_FILE));
+
+ /* A missing file reports "not read only" rather than failing. */
+ cMiscUtil::Remove_File(TEMP_FILE);
+ CHECK(!cMiscUtil::File_Is_Read_Only(TEMP_FILE));
+}
+
+TEST(get_file_id_string_is_name_size_and_stamp)
+{
+ write_temp_file("0123456789");
+
+ StringClass id;
+ cMiscUtil::Get_File_Id_String(TEMP_FILE, id);
+
+ /* Upper-cased basename, byte count, then the PE timestamp (0 for a file
+ that has no image header). */
+ CHECK_STR(id.Peek_Buffer(), "WWUTIL_TEST_TMP.DAT 10 0");
+
+ cMiscUtil::Remove_File(TEMP_FILE);
+}
+
+TEST(get_file_id_string_strips_the_directory)
+{
+ write_temp_file("abc");
+
+ char with_dot[128];
+ sprintf(with_dot, ".\\%s", TEMP_FILE);
+
+ StringClass id;
+ cMiscUtil::Get_File_Id_String(with_dot, id);
+ CHECK_STR(id.Peek_Buffer(), "WWUTIL_TEST_TMP.DAT 3 0");
+
+ cMiscUtil::Remove_File(TEMP_FILE);
+}