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.

build(cmake): make the game 64-bit and drop the 32-bit build

Olcay Seyganad31e6db9d2e
diff --git a/.gitignore b/.gitignore
index dff75b810..8722110a0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -22,3 +22,4 @@ AGENTS.md
# Layouts pulled out of WindowZH.big to feed Tools/optionsmenu_layout.py. That is game data and
# does not belong in the repo; re-extract it with Tools/bigfile.py when a layout has to be redone.
**/Tools/wnd/
+build64/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 88e92e9bc..cc5179a3e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1117,6 +1117,21 @@ found and fixed — EA's own, not port damage.**
- The first soldier out of your barracks cost eighteen milliseconds of a thirty-three millisecond frame. A unit's models were read off the disc the moment one of its kind first appeared, and that read landed on whatever frame the unit happened to walk out on. So did the first war factory, the first supply centre, the first of everything. That is why the opening of a match was the part that jerked: the opening of a match is nothing but things appearing for the first time. Everything a match can put on the field is now read during the loading screen, which costs about three seconds there and takes the hitches out of the game. EA wrote that loading pass and left it switched off; the code carries their own comment saying it exists "so that we don't have big pauses when building those objects".
+## The game is 64-bit
+
+- The memory ceiling is gone. A 2003 game is a 32-bit program and can never hold more than 4GB of
+ memory no matter how much your machine has, and this one was already at half of that in an
+ eight-player match on a large map: past the line it does not say so, it stalls for a third of a
+ second at a time and then dies. The 64-bit build has no such line.
+- Sound and movies come from the game itself now. The 2003 sound and video libraries are 32-bit and
+ cannot be loaded by a 64-bit program at all, so the build carries its own: Windows' own mixer for
+ sound, and a decoder for the movies that reads the same files the game has always shipped. Nothing
+ about what you hear or watch changes, and the two old libraries are no longer in the download.
+- Your replays still play and your matches still join. The old 32-bit build and this one work out
+ the same game, to the digit: the same match played by both, 3000 frames of computer against
+ computer, ends on the same world with the same checksum. That is what the change was measured
+ against before the 32-bit build was retired.
+
## Sound, video, and getting it to start at all
- Audio is real, through the audio library the retail game ships with.
diff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txt
index c911ffda2..7a5515def 100644
--- a/GeneralsMD/Code/CMakeLists.txt
+++ b/GeneralsMD/Code/CMakeLists.txt
@@ -13,9 +13,11 @@ set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
project(GeneralsMD CXX C)
-# Win32 only: the code is full of 32-bit inline __asm, which MSVC x64 rejects outright.
-if(MSVC AND NOT CMAKE_SIZEOF_VOID_P EQUAL 4)
- message(FATAL_ERROR "Configure for Win32: cmake -A Win32")
+# x64 only. The 32-bit build was dropped once this one was proven against it: same simulation to
+# the bit, same picture to within sub-pixel sampling, and sound and video of its own that do not
+# depend on the two 32-bit DLLs the game shipped with. Nothing here is written for x86 any more.
+if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
+ message(FATAL_ERROR "Configure for x64: cmake -A x64")
endif()
set(WW ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Source/WWVegas)
@@ -58,13 +60,10 @@ if(MSVC)
# sources in a single project and was the long pole. /FS above is what makes this
# safe - the PDB writes are serialized in the compilers.
add_compile_options(/MP)
- # /arch:SSE2 is already the 32-bit default on this compiler; it is written down because
- # the simulation now depends on it. x87 carries 80-bit intermediates whose spills round
- # a second time, and FPUControl.cpp pins the control word to 24-bit precision, which would
- # cut the double-precision argument reduction in WWMath/dettrig.cpp down to float and give
- # a different angle on a machine that spilled at a different point. SSE2 arithmetic is
- # done at the declared width, so every machine gets the same bits. See dettrig.h.
- add_compile_options(/arch:SSE2)
+ # There is no /arch:SSE2 here and none is needed: x64 has no x87 code generation at all, so
+ # every float is computed at its declared width and every machine gets the same bits. That is
+ # what the 32-bit build had to ask for explicitly, and why it pinned the x87 precision control.
+ # See dettrig.h and FPUControl.h.
add_link_options(/DEBUG)
endif()
@@ -535,28 +534,30 @@ file(GLOB_RECURSE GAMEENGINEDEVICE_SOURCES ${GED}/Source/*.cpp)
# shipping build uses the Win32 message mouse instead).
list(REMOVE_ITEM GAMEENGINEDEVICE_SOURCES
${GED}/Source/Win32Device/GameClient/Win32DIMouse.cpp)
-# Miles is binary-only too, but the game ships mss32.dll and it exports
-# decorated stdcall names (_AIL_startup@0, ...), so MilesAudioManager can bind
-# to the real DLL through an import library - real audio, no SDK. Thyme's
-# recipe: build a no-op stub as mss32.dll from miles.c + miles.def (the def
-# mirrors the shipped DLL's export table); linking against the stub's import
-# lib makes the exe resolve those names from whatever mss32.dll sits next to
-# it at runtime - the game's real one. (`lib /def` alone can't produce this
-# import lib: it prepends a second underscore to the already-decorated names.)
-# Bink is binary-only too, and the same trick works: the game ships BINKW32.DLL
-# and it exports decorated stdcall names (_BinkOpen@8, ...), so BinkVideoPlayer
-# binds to the real DLL through the import library of a no-op stub built as
-# binkw32.dll. Real movies, no SDK. The stub dll in build/Release/ must never
-# be copied to Run/ - the loader has to find the game's own BINKW32.DLL there.
-add_library(binkstub SHARED
- ${WW}/Bink/stub/bink.c ${WW}/Bink/stub/bink.def)
-set_target_properties(binkstub PROPERTIES OUTPUT_NAME binkw32)
-target_include_directories(binkstub PRIVATE ${WW}/Bink/include)
-
-add_library(milesstub SHARED
- ${WW}/Miles6/stub/miles.c ${WW}/Miles6/stub/miles.def)
-set_target_properties(milesstub PROPERTIES OUTPUT_NAME mss32)
-target_include_directories(milesstub PRIVATE ${WW}/Miles6/stub ${WW}/Miles6/include)
+# Sound and video are the game's own. Miles and Bink were binary-only, and the DLLs the retail
+# game ships are 32-bit, so there is nothing for a 64-bit exe to bind to: what it links instead is
+# those two APIs written over XAudio2 and FFmpeg. FFmpeg decodes binkvideo and binkaudio natively,
+# so the .bik files on disk play as they are, and swscale converts each frame into whatever surface
+# format the video player asks for. MilesAudioManager.cpp and BinkVideoPlayer.cpp are unchanged and
+# still call AIL_* and Bink*; the reconstructed headers in Miles6/include and Bink/include are still
+# the declarations. miles_smoke and bink_smoke are the checks.
+set(FFMPEG_DIR ${LIBSRC}/FFmpeg/dist)
+if(NOT EXISTS ${FFMPEG_DIR}/include)
+ message(FATAL_ERROR
+ "FFmpeg is missing from Libraries/Source/FFmpeg/dist - see the vendored-libs rule.")
+endif()
+
+set(FFMPEG_CORE
+ ${FFMPEG_DIR}/lib/avformat.lib ${FFMPEG_DIR}/lib/avcodec.lib ${FFMPEG_DIR}/lib/avutil.lib
+ ${FFMPEG_DIR}/lib/swresample.lib)
+
+add_library(binkvideo STATIC ${WW}/Bink/ffmpeg/bink_ffmpeg.cpp)
+target_include_directories(binkvideo PRIVATE ${WW}/Bink/include ${FFMPEG_DIR}/include)
+target_link_libraries(binkvideo PRIVATE ${FFMPEG_CORE} ${FFMPEG_DIR}/lib/swscale.lib xaudio2)
+
+add_library(milesaudio STATIC ${WW}/Miles6/xaudio2/miles_xaudio2.cpp)
+target_include_directories(milesaudio PRIVATE ${WW}/Miles6/include ${FFMPEG_DIR}/include)
+target_link_libraries(milesaudio PRIVATE ${FFMPEG_CORE} xaudio2)
add_library(gameenginedevice STATIC ${GAMEENGINEDEVICE_SOURCES})
@@ -564,7 +565,7 @@ target_include_directories(gameenginedevice PUBLIC
${GED}/Include ${STUBS} ${CMAKE_CURRENT_SOURCE_DIR}/Main
${WW}/Miles6/include ${WW}/Bink/include)
set_target_properties(gameenginedevice PROPERTIES CXX_STANDARD 17)
-target_link_libraries(gameenginedevice PUBLIC gameengine ww3d2 milesstub binkstub)
+target_link_libraries(gameenginedevice PUBLIC gameengine ww3d2 milesaudio binkvideo)
# ---- generals.exe ---------------------------------------------------------
# BuildVersion.h and GeneratedVersion.h are normally written by Tools/
@@ -592,20 +593,9 @@ target_include_directories(generals PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Main ${G
# A .map turns the "fault offset" in the Windows Application Error event into a
# function name without a debugger: find the last entry whose RVA is <= the offset.
target_link_options(generals PRIVATE /MAP)
-# A 32-bit process gets 2GB of user address space by default; this asks for the
-# whole 4GB, which 64-bit Windows hands over with no /3GB switch and no reboot.
-# 4GB is the ceiling and there is no way past it here - the pointer is 32 bits,
-# and x64 is rejected by this port on purpose (the code is full of 32-bit __asm).
-#
-# Measured need: an eight-player Merciless match on Twilight Flame peaks at 978MB
-# of virtual address space, so it is at half the old limit already, and a 2003
-# engine walking into that wall does not report it - it stalls for a third of a
-# second at a time and then dies inside ntdll's heap.
-#
-# The classic risk is code that treats a pointer as a signed 32-bit int, which
-# only breaks once an allocation lands above 2GB. Nothing here is known to; if a
-# pointer-signedness bug ever surfaces, this is the first line to suspect.
-target_link_options(generals PRIVATE /LARGEADDRESSAWARE)
+# /LARGEADDRESSAWARE used to be here, asking 64-bit Windows for the whole 4GB a 32-bit process can
+# address. An eight-player Merciless match on Twilight Flame was already at 978MB of it. The
+# ceiling it was working against does not exist in this build.
set_target_properties(generals PROPERTIES CXX_STANDARD 17)
target_link_libraries(generals PRIVATE gameenginedevice
winmm dsound wsock32 ole32 oleaut32 uuid)
@@ -675,6 +665,15 @@ add_custom_command(TARGET generals POST_BUILD
${CMAKE_CURRENT_SOURCE_DIR}/Data/Cinema
${CMAKE_CURRENT_SOURCE_DIR}/../Run/Cinema)
+# The audio and video backends decode with FFmpeg, so its DLLs have to sit next to the exe. These
+# are the five the two backends link against; avdevice and avfilter are not used.
+set(FFMPEG_RUNTIME
+ ${FFMPEG_DIR}/bin/avcodec-62.dll ${FFMPEG_DIR}/bin/avformat-62.dll ${FFMPEG_DIR}/bin/avutil-60.dll
+ ${FFMPEG_DIR}/bin/swresample-6.dll ${FFMPEG_DIR}/bin/swscale-9.dll)
+add_custom_command(TARGET generals POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ ${FFMPEG_RUNTIME} ${CMAKE_CURRENT_SOURCE_DIR}/../Run/)
+
# ===========================================================================
# Tests. Run with: ctest --test-dir build -C Release --output-on-failure
# ===========================================================================
@@ -775,12 +774,24 @@ add_test(NAME compression_selfcheck COMMAND compression_selfcheck)
add_test(NAME dx9_smoke COMMAND dx9_smoke)
add_test(NAME dx9_smoke_msaa COMMAND dx9_smoke -msaa 4)
-# bink_smoke validates the hand-reconstructed Bink ABI against the real
-# BINKW32.DLL the game ships - it loads that DLL by path, so it does not link
-# binkstub and it has to run from Run/. Without game data it prints "skip".
+# bink_smoke decodes a real .bik with the player this build links and compares what comes out
+# against the values read straight from the file's own header, so a wrong field offset or a wrong
+# surface constant shows up as a mismatch. It runs from Run/, where the movies and the FFmpeg DLLs
+# are; without game data it prints "skip".
add_executable(bink_smoke ${TESTS}/bink_smoke.c)
target_include_directories(bink_smoke PRIVATE ${WW}/Bink/include)
-add_test(NAME bink_smoke COMMAND bink_smoke
+target_compile_definitions(bink_smoke PRIVATE BINK_LINKED_PLAYER)
+target_link_libraries(bink_smoke PRIVATE binkvideo)
+add_test(NAME bink_smoke COMMAND bink_smoke Data/Movies/GC_Background.bik
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../Run)
+
+# miles_smoke plays a tone through the audio backend and waits for the end-of-sample callback,
+# which only arrives once a voice has played the buffer out.
+add_executable(miles_smoke ${TESTS}/miles_smoke.cpp)
+target_include_directories(miles_smoke PRIVATE ${WW}/Miles6/include)
+target_link_libraries(miles_smoke PRIVATE milesaudio)
+# From Run/, where the FFmpeg DLLs the backend decodes with are.
+add_test(NAME miles_smoke COMMAND miles_smoke
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../Run)
# Tools/bigfile.py reads and writes the game's BIG archives (that is how the shipped INIs
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h
index 277b64c83..b9e8e152a 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GameAudio.h
@@ -194,7 +194,9 @@ class AudioManager : public SubsystemInterface
virtual void *getDevice( void ) = 0;
// Debice Dependent notification functions
- virtual void notifyOfAudioCompletion( UnsignedInt audioCompleted, UnsignedInt flags ) = 0;
+ // The first parameter is the sample, 3D sample or stream handle that finished, so it is
+ // pointer sized: the audio device hands its own handles back through here.
+ virtual void notifyOfAudioCompletion( UnsignedIntPtr audioCompleted, UnsignedInt flags ) = 0;
// Device Dependent enumerate providers functions. It is okay for there to be only 1 provider (Miles provides a maximum of 64.
virtual UnsignedInt getProviderCount( void ) const = 0;
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h b/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h
index 3cacccca4..ad90e095f 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/StackDump.h
@@ -38,7 +38,9 @@ void StackDump(void (*callback)(const char*));
// Writes a stackdump (provide a callback : gets called per line)
// If callback is NULL then will write using OuputDebugString
-void StackDumpFromContext(DWORD eip,DWORD esp,DWORD ebp, void (*callback)(const char*));
+// The three are the instruction, stack and frame pointers of the context to walk, pointer-wide so
+// the same call carries an x64 Rip/Rsp/Rbp.
+void StackDumpFromContext(DWORD_PTR eip,DWORD_PTR esp,DWORD_PTR ebp, void (*callback)(const char*));
// Gets count* addresses from the current stack
void FillStackAddresses(void**addresses, unsigned int count, unsigned int skip = 0);
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/crc.h b/GeneralsMD/Code/GameEngine/Include/Common/crc.h
index 861941e6a..7dc265904 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/crc.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/crc.h
@@ -66,54 +66,18 @@ public:
if (!buf||len<1)
return;
- /* C++ version left in for reference purposes
- for (UnsignedByte *uintPtr=(UnsignedByte *)buf;len>0;len--,uintPtr++)
+ // EA wrote this in assembly and kept the C++ it was verified against in a comment; the
+ // assembly is gone and this is that C++. shl sets the carry from the top bit and adc adds it
+ // back with the data byte, which is exactly the two lines below. Every multiplayer and replay
+ // CRC in the game goes through here, so it has to stay bit identical: 32-bit wraparound
+ // arithmetic on UnsignedInt is what does that.
+ for (const UnsignedByte *bytePtr=(const UnsignedByte *)buf; len>0; --len, ++bytePtr)
{
- int hibit;
- if (crc & 0x80000000)
- {
- hibit = 1;
- }
- else
- {
- hibit = 0;
- }
-
- crc <<= 1;
- crc += *uintPtr;
- crc += hibit;
+ const UnsignedInt hibit = (crc & 0x80000000) ? 1 : 0;
+ crc <<= 1;
+ crc += *bytePtr;
+ crc += hibit;
}
- */
-
- // ASM version, verified by comparing resulting data with C++ version data
- unsigned *crcPtr=&crc;
- // Same rule as fast_float_trunc in BaseType.h: EBX, ESI and EDI belong to the
- // caller, and this block uses all three. Nothing has crashed on it yet, but that
- // is luck -- whichever of them the compiler happens to hold a live value in is
- // gone when the block ends.
- _asm
- {
- push ebx
- push esi
- push edi
- mov esi,[buf]
- mov ecx,[len]
- dec ecx
- mov edi,[crcPtr]
- mov ebx,dword ptr [edi]
- xor eax,eax
- lp:
- mov al,byte ptr [esi]
- shl ebx,1
- inc esi
- adc ebx,eax
- dec ecx
- jns lp
- mov dword ptr [edi],ebx
- pop edi
- pop esi
- pop ebx
- };
}
/// Clears the CRC to 0
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h b/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h
index abf56f2cd..16f25d926 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h
@@ -75,7 +75,9 @@ enum { WIN_COLOR_UNDEFINED = GAME_COLOR_UNDEFINED };
// WindowMsgData --------------------------------------------------------------
//-----------------------------------------------------------------------------
-typedef UnsignedInt WindowMsgData;
+// Half the GUI passes pointers through this - a window, a UnicodeString, a Bool to write back -
+// so it is pointer sized, not four bytes. On Win32 that is the same UnsignedInt it always was.
+typedef UnsignedIntPtr WindowMsgData;
//-----------------------------------------------------------------------------
enum WindowMsgHandledType { MSG_IGNORED, MSG_HANDLED };
diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/WindowVideoManager.h b/GeneralsMD/Code/GameEngine/Include/GameClient/WindowVideoManager.h
index 06aea0adf..e53c7802f 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameClient/WindowVideoManager.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/WindowVideoManager.h
@@ -151,8 +151,8 @@ private:
{
size_t operator()(ConstGameWindowPtr p) const
{
- std::hash<UnsignedInt> hasher;
- return hasher((UnsignedInt)p);
+ std::hash<UnsignedIntPtr> hasher;
+ return hasher((UnsignedIntPtr)p);
}
};
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/FPUControl.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/FPUControl.h
index 278994992..4ac3cf343 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/FPUControl.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/FPUControl.h
@@ -33,6 +33,13 @@
#define __FPUCONTROL_H__
#include "Lib/BaseType.h"
+#include <float.h>
+
+/** The control word fields setFPMode owns. There is no x87 precision field to pin any more, and
+ * the CRT fails fast on any _controlfp call whose mask names _MCW_PC, so the rounding mode is
+ * the whole of it. SSE arithmetic rounds at the declared width, which is what the 24-bit
+ * precision setting bought the x87. */
+#define FP_MODE_FIELDS ( _MCW_RC )
/**
* setFPMode sets the FPU internal precision and rounding mode. As DirectX is not guaranteed to
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp
index a8978a4e8..d1d824fe7 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/PerfTimer.cpp
@@ -37,17 +37,7 @@
__forceinline void ProfileGetTime(__int64 &t)
{
- _asm
- {
- mov ecx,[t]
- push eax
- push edx
- rdtsc
- mov [ecx],eax
- mov [ecx+4],edx
- pop edx
- pop eax
- };
+ t = (__int64)__rdtsc();
}
#ifdef _INTERNAL
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp
index 6db4c2a9c..7d1d9e33d 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp
@@ -4086,7 +4086,7 @@ void RMGLayout::build( const RandomMapSettings& settings )
buildTerrainClasses( perm );
buildBlends();
- _controlfp( callersFPMode, _MCW_PC | _MCW_RC );
+ _controlfp( callersFPMode, FP_MODE_FIELDS );
}
//-----------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/SimulationMathCrc.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/SimulationMathCrc.cpp
index 873454f48..7572eb9a7 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/SimulationMathCrc.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/SimulationMathCrc.cpp
@@ -119,7 +119,7 @@ static UnsignedInt runInSimulationFPMode( void (*pass)( XferCRC & ), const char
pass( xfer );
- _controlfp( callersMode, _MCW_PC | _MCW_RC );
+ _controlfp( callersMode, FP_MODE_FIELDS );
xfer.close();
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp
index ddbd6d3b9..51c8285a6 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/StackDump.cpp
@@ -39,7 +39,7 @@
//*****************************************************************************
BOOL InitSymbolInfo(void);
void UninitSymbolInfo(void);
-void MakeStackTrace(DWORD myeip,DWORD myesp,DWORD myebp, int skipFrames, void (*callback)(const char*));
+void MakeStackTrace(DWORD_PTR myeip,DWORD_PTR myesp,DWORD_PTR myebp, int skipFrames, void (*callback)(const char*));
void GetFunctionDetails(void *pointer, char*name, size_t nameSize, char*filename, size_t filenameSize, unsigned int* linenumber, unsigned int* address);
void WriteStackLine(void*address, void (*callback)(const char*));
@@ -51,9 +51,9 @@ static Bool gsInit=FALSE;
BOOL (__stdcall *gsSymGetLineFromAddr)(
IN HANDLE hProcess,
- IN DWORD dwAddr,
+ IN DWORD64 dwAddr,
OUT PDWORD pdwDisplacement,
- OUT PIMAGEHLP_LINE Line
+ OUT PIMAGEHLP_LINE64 Line
);
@@ -76,19 +76,16 @@ void StackDump(void (*callback)(const char*))
InitSymbolInfo();
- DWORD myeip,myesp,myebp;
-
-_asm
-{
-MYEIP1:
- mov eax, MYEIP1
- mov dword ptr [myeip] , eax
- mov eax, esp
- mov dword ptr [myesp] , eax
- mov eax, ebp
- mov dword ptr [myebp] , eax
-}
+ DWORD_PTR myeip,myesp,myebp;
+ // The register set to start the walk from.
+ CONTEXT here;
+ memset(&here, 0, sizeof(here));
+ here.ContextFlags = CONTEXT_FULL;
+ RtlCaptureContext(&here);
+ myeip = here.Rip;
+ myesp = here.Rsp;
+ myebp = here.Rbp;
MakeStackTrace(myeip,myesp,myebp, 2, callback);
}
@@ -96,7 +93,7 @@ MYEIP1:
//*****************************************************************************
//*****************************************************************************
-void StackDumpFromContext(DWORD eip,DWORD esp,DWORD ebp, void (*callback)(const char*))
+void StackDumpFromContext(DWORD_PTR eip,DWORD_PTR esp,DWORD_PTR ebp, void (*callback)(const char*))
{
if (callback == NULL)
{
@@ -124,8 +121,8 @@ BOOL InitSymbolInfo()
// We use GetProcAddress to stop link failures at dll loadup
HINSTANCE hInstDebugHlp = GetModuleHandle("dbghelp.dll");
- gsSymGetLineFromAddr = (BOOL (__stdcall *)( IN HANDLE,IN DWORD,OUT PDWORD,OUT PIMAGEHLP_LINE))
- GetProcAddress(hInstDebugHlp , "SymGetLineFromAddr");
+ gsSymGetLineFromAddr = (BOOL (__stdcall *)( IN HANDLE,IN DWORD64,OUT PDWORD,OUT PIMAGEHLP_LINE64))
+ GetProcAddress(hInstDebugHlp , "SymGetLineFromAddr64");
::SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES | SYMOPT_OMAP_FIND_NEAREST);
@@ -158,11 +155,20 @@ void UninitSymbolInfo(void)
//*****************************************************************************
//*****************************************************************************
-void MakeStackTrace(DWORD myeip,DWORD myesp,DWORD myebp, int skipFrames, void (*callback)(const char*))
+void MakeStackTrace(DWORD_PTR myeip,DWORD_PTR myesp,DWORD_PTR myebp, int skipFrames, void (*callback)(const char*))
{
-// STACKFRAME/StackWalk (the 32-bit-only originals) stop after the first frame or two on a
-// current dbghelp.dll (same failure as debug_stack.cpp: ERROR_PARTIAL_COPY), which left every
-// exception dump with a one-line "stack". StackWalk64 with the matching 64-bit callbacks walks.
+// The unwind comes from the exception tables rather than a frame pointer chain, and StackWalk64
+// reads and writes the whole register set to do it: a NULL context walks nowhere. The three
+// addresses are all a caller hands over, so the rest of the context is captured here and
+// overwritten with them.
+const DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
+CONTEXT walkContext;
+memset(&walkContext, 0, sizeof(walkContext));
+walkContext.ContextFlags = CONTEXT_FULL;
+RtlCaptureContext(&walkContext);
+walkContext.Rip = myeip;
+walkContext.Rsp = myesp;
+walkContext.Rbp = myebp;
STACKFRAME64 stack_frame;
BOOL b_ret = TRUE;
@@ -199,11 +205,11 @@ stack_frame.AddrFrame.Offset = myebp;
unsigned int skip = skipFrames;
while (b_ret&&skip)
{
- b_ret = StackWalk64( IMAGE_FILE_MACHINE_I386,
+ b_ret = StackWalk64( machineType,
process,
thread,
&stack_frame,
- NULL, //&gsContext,
+ &walkContext,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
@@ -215,18 +221,18 @@ stack_frame.AddrFrame.Offset = myebp;
while(b_ret&&skip)
{
- b_ret = StackWalk64( IMAGE_FILE_MACHINE_I386,
+ b_ret = StackWalk64( machineType,
process,
thread,
&stack_frame,
- NULL, //&gsContext,
+ &walkContext,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL);
-
-
+
+
if (b_ret) WriteStackLine((void *) stack_frame.AddrPC.Offset, callback);
skip--;
}
@@ -259,18 +265,18 @@ void GetFunctionDetails(void *pointer, char*name, size_t nameSize, char*filename
*address = 0xFFFFFFFF;
}
- ULONG displacement = 0;
+ DWORD64 displacement = 0;
HANDLE process = ::GetCurrentProcess();
- char symbol_buffer[512 + sizeof(IMAGEHLP_SYMBOL)];
+ char symbol_buffer[512 + sizeof(IMAGEHLP_SYMBOL64)];
memset(symbol_buffer, 0, sizeof(symbol_buffer));
- PIMAGEHLP_SYMBOL psymbol = (PIMAGEHLP_SYMBOL)symbol_buffer;
+ PIMAGEHLP_SYMBOL64 psymbol = (PIMAGEHLP_SYMBOL64)symbol_buffer;
psymbol->SizeOfStruct = sizeof(symbol_buffer);
psymbol->MaxNameLength = 512;
- if (SymGetSymFromAddr(process, (DWORD) pointer, &displacement, psymbol))
+ if (SymGetSymFromAddr64(process, (DWORD64)(DWORD_PTR) pointer, &displacement, psymbol))
{
if (name)
{
@@ -283,12 +289,12 @@ void GetFunctionDetails(void *pointer, char*name, size_t nameSize, char*filename
{
// Unsupported for win95/98 at least with my current dbghelp.dll
- IMAGEHLP_LINE line;
+ IMAGEHLP_LINE64 line;
memset(&line,0,sizeof(line));
line.SizeOfStruct = sizeof(line);
-
- if (gsSymGetLineFromAddr(process, (DWORD) pointer, &displacement, &line))
+ DWORD lineDisplacement = 0;
+ if (gsSymGetLineFromAddr(process, (DWORD64)(DWORD_PTR) pointer, &lineDisplacement, &line))
{
if (filename)
{
@@ -343,7 +349,15 @@ void FillStackAddresses(void**addresses, unsigned int count, unsigned int skip)
// BackTrace does the same job in one call and needs no symbols to do it; the
// +1 drops this function's own frame, which the old code also skipped.
memset(addresses, 0, count * sizeof(void *));
- ::CaptureStackBackTrace(skip + 1, count, addresses, NULL);
+ const USHORT captured = ::CaptureStackBackTrace(skip + 1, count, addresses, NULL);
+
+ // Reading the count back keeps the call from being the last thing this function does: as a tail
+ // call it drops this frame, and the +1 above then skips the caller's frame instead of this one,
+ // which is how a stack dump came back starting one level too high.
+ if (captured == 0 && count > 0)
+ {
+ addresses[0] = NULL;
+ }
}
@@ -528,9 +542,13 @@ void DumpExceptionInfo( unsigned int u, EXCEPTION_POINTERS* e_info )
/*
** Dump the registers.
*/
- DOUBLE_DEBUG ( ( "Eip:%08X\tEsp:%08X\tEbp:%08X\n", context->Eip, context->Esp, context->Ebp));
- DOUBLE_DEBUG ( ( "Eax:%08X\tEbx:%08X\tEcx:%08X\n", context->Eax, context->Ebx, context->Ecx));
- DOUBLE_DEBUG ( ( "Edx:%08X\tEsi:%08X\tEdi:%08X\n", context->Edx, context->Esi, context->Edi));
+ const DWORD_PTR faultPC = context->Rip;
+ DOUBLE_DEBUG ( ( "Rip:%016llX\tRsp:%016llX\tRbp:%016llX\n", context->Rip, context->Rsp, context->Rbp));
+ DOUBLE_DEBUG ( ( "Rax:%016llX\tRbx:%016llX\tRcx:%016llX\n", context->Rax, context->Rbx, context->Rcx));
+ DOUBLE_DEBUG ( ( "Rdx:%016llX\tRsi:%016llX\tRdi:%016llX\n", context->Rdx, context->Rsi, context->Rdi));
+ DOUBLE_DEBUG ( ( "R8 :%016llX\tR9 :%016llX\tR10:%016llX\n", context->R8, context->R9, context->R10));
+ DOUBLE_DEBUG ( ( "R11:%016llX\tR12:%016llX\tR13:%016llX\n", context->R11, context->R12, context->R13));
+ DOUBLE_DEBUG ( ( "R14:%016llX\tR15:%016llX\n", context->R14, context->R15));
DOUBLE_DEBUG ( ( "EFlags:%08X \n", context->EFlags));
DOUBLE_DEBUG ( ( "CS:%04x SS:%04x DS:%04x ES:%04x FS:%04x GS:%04x\n", context->SegCs, context->SegSs, context->SegDs, context->SegEs, context->SegFs, context->SegGs));
@@ -539,9 +557,9 @@ void DumpExceptionInfo( unsigned int u, EXCEPTION_POINTERS* e_info )
*/
char scrap[512];
DOUBLE_DEBUG ( ("EIP bytes dump...\n"));
- wsprintf (scrap, "\nBytes at CS:EIP (%08X) : ", context->Eip);
+ wsprintf (scrap, "\nBytes at CS:EIP (%p) : ", (void *)faultPC);
- unsigned char *eip_ptr = (unsigned char *) (context->Eip);
+ unsigned char *eip_ptr = (unsigned char *) faultPC;
char bytestr[32];
for (int c = 0 ; c < 32 ; c++)
@@ -566,7 +584,7 @@ void DumpExceptionInfo( unsigned int u, EXCEPTION_POINTERS* e_info )
** already in the log by this point, so a fault in here costs the stack and nothing else.
*/
DOUBLE_DEBUG (("\nStack Dump:\n"));
- StackDumpFromContext(context->Eip, context->Esp, context->Ebp, NULL);
+ StackDumpFromContext(context->Rip, context->Rsp, context->Rbp, NULL);
DEBUG_LOG(( "********** END EXCEPTION DUMP ****************\n\n" ));
}
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/registry.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/registry.cpp
index 32c9497e9..3ec133b30 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/System/registry.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/registry.cpp
@@ -36,6 +36,23 @@
//#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
#endif
+/*
+ A 64-bit process reads HKLM\SOFTWARE natively, and the game's installers are 32-bit: what they
+ wrote is under HKLM\SOFTWARE\WOW6432Node, which the native view does not show. So every read
+ asks for the native view first and the 32-bit one after it, which is where an install path
+ written by Steam's copy of the game actually is. On Win32 the second open is the same key as
+ the first and costs nothing.
+*/
+static int openForRead(HKEY root, const char *path, HKEY *handle)
+{
+ int returnValue = RegOpenKeyEx( root, path, 0, KEY_READ, handle );
+ if (returnValue != ERROR_SUCCESS)
+ {
+ returnValue = RegOpenKeyEx( root, path, 0, KEY_READ | KEY_WOW64_32KEY, handle );
+ }
+ return returnValue;
+}
+
Bool getStringFromRegistry(HKEY root, AsciiString path, AsciiString key, AsciiString& val)
{
HKEY handle;
@@ -44,7 +61,7 @@ Bool getStringFromRegistry(HKEY root, AsciiString path, AsciiString key, AsciiS
unsigned long type;
int returnValue;
- if ((returnValue = RegOpenKeyEx( root, path.str(), 0, KEY_READ, &handle )) == ERROR_SUCCESS)
+ if ((returnValue = openForRead( root, path.str(), &handle )) == ERROR_SUCCESS)
{
returnValue = RegQueryValueEx(handle, key.str(), NULL, &type, (unsigned char *) &buffer, &size);
RegCloseKey( handle );
@@ -67,7 +84,7 @@ Bool getUnsignedIntFromRegistry(HKEY root, AsciiString path, AsciiString key, Un
unsigned long type;
int returnValue;
- if ((returnValue = RegOpenKeyEx( root, path.str(), 0, KEY_READ, &handle )) == ERROR_SUCCESS)
+ if ((returnValue = openForRead( root, path.str(), &handle )) == ERROR_SUCCESS)
{
returnValue = RegQueryValueEx(handle, key.str(), NULL, &type, (unsigned char *) &buffer, &size);
RegCloseKey( handle );
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp
index c25f1f29f..b72191bfb 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetListBox.cpp
@@ -1799,7 +1799,9 @@ WindowMsgHandledType GadgetListBoxSystem( GameWindow *window, UnsignedInt msg,
{
if( list->multiSelect )
- *(Int*)mData2 = (Int)list->selections;
+ // A multi-select box hands back its own -1 terminated array of indices rather than
+ // copying it, so what lands in the caller's buffer is a pointer and needs all of it.
+ *(UnsignedIntPtr*)mData2 = (UnsignedIntPtr)list->selections;
else
*(Int*)mData2 = list->selectPos;
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp
index 10b71906e..de8cd95e8 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/IMEManager.cpp
@@ -1446,7 +1446,7 @@ void IMEManager::updateCandidateList( Int candidateFlags )
for( i=0; i < m_candidateCount; i++ )
{
- Char *string = (Char*) ((UnsignedInt) clist + (UnsignedInt) clist->dwOffset[i]);
+ Char *string = (Char*) ((UnsignedIntPtr) clist + (UnsignedIntPtr) clist->dwOffset[i]);
if ( unicode )
{
m_candidateString[i].set( (WideChar *) string);
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/FPUControl.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/FPUControl.cpp
index d03128460..b2aae1eea 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/FPUControl.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/FPUControl.cpp
@@ -41,28 +41,26 @@ void setFPMode( void )
state rather than only the two fields written below. */
_fpreset();
- /* Rounding to nearest, and 24-bit (single) precision. The precision could be anything as long
- as it is the same everywhere; 24 bits is what Direct3D leaves behind anyway, so asking for
- it costs nothing and removes one way for the two to disagree.
+ /* Rounding to nearest. EA also asked for 24-bit precision here, which was the x87's way of
+ computing a float at a float's width; SSE does that by itself and the field is gone.
EA read the current word with _statusfp(), which returns the *status* word - the sticky
exception flags - not the control word. It happened to be harmless, because the mask below
- keeps everything except the precision and rounding fields and no status flag lands in
- either. _controlfp(0, 0) is what they meant: it reads the control word without writing. */
+ keeps everything except the rounding field and no status flag lands in it.
+ _controlfp(0, 0) is what they meant: it reads the control word without writing. */
UnsignedInt curVal = _controlfp( 0, 0 );
UnsignedInt newVal = curVal;
newVal = (newVal & ~_MCW_RC) | (_RC_NEAR & _MCW_RC);
- newVal = (newVal & ~_MCW_PC) | (_PC_24 & _MCW_PC);
- _controlfp( newVal, _MCW_PC | _MCW_RC );
+ _controlfp( newVal & FP_MODE_FIELDS, FP_MODE_FIELDS );
}
UnsignedInt getFPMode( void )
{
- return _controlfp( 0, 0 ) & (_MCW_PC | _MCW_RC);
+ return _controlfp( 0, 0 ) & FP_MODE_FIELDS;
}
UnsignedInt expectedFPMode( void )
{
- return (_PC_24 & _MCW_PC) | (_RC_NEAR & _MCW_RC);
+ return (_RC_NEAR & _MCW_RC) & FP_MODE_FIELDS;
}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp
index 902a9b388..bb9f32590 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/FirewallHelper.cpp
@@ -714,7 +714,6 @@ Bool FirewallHelperClass::detectionBeginUpdate() {
if (!found) {
Int m = m_numManglers++;
memcpy(&mangler_addresses[m][0], &host_info->h_addr_list[0][0], 4);
- ntohl((UnsignedInt)mangler_addresses[m]);
DEBUG_LOG(("Found mangler address at %d.%d.%d.%d\n", mangler_addresses[m][0], mangler_addresses[m][1], mangler_addresses[m][2], mangler_addresses[m][3]));
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
index b5fc37ea6..e5ff6fb60 100644
--- a/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
+++ b/GeneralsMD/Code/GameEngineDevice/Include/MilesAudioDevice/MilesAudioManager.h
@@ -191,8 +191,8 @@ class MilesAudioManager : public AudioManager
///< NOTE NOTE NOTE !!DO NOT USE THIS IN FOR GAMELOGIC PURPOSES!! NOTE NOTE NOTE
virtual Bool isCurrentlyPlaying( AudioHandle handle );
- virtual void notifyOfAudioCompletion( UnsignedInt audioCompleted, UnsignedInt flags );
- virtual PlayingAudio *findPlayingAudioFrom( UnsignedInt audioCompleted, UnsignedInt flags );
+ virtual void notifyOfAudioCompletion( UnsignedIntPtr audioCompleted, UnsignedInt flags );
+ virtual PlayingAudio *findPlayingAudioFrom( UnsignedIntPtr audioCompleted, UnsignedInt flags );
virtual UnsignedInt getProviderCount( void ) const;
virtual AsciiString getProviderName( UnsignedInt providerNum ) const;
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp
index 3736e1b2d..ca00c68c2 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/MilesAudioDevice/MilesAudioManager.cpp
@@ -78,10 +78,10 @@ static void AILCALLBACK setSampleCompleted( HSAMPLE sampleCompleted );
static void AILCALLBACK set3DSampleCompleted( H3DSAMPLE sample3DCompleted );
static void AILCALLBACK setStreamCompleted( HSTREAM streamCompleted );
-static U32 AILCALLBACK streamingFileOpen(char const *fileName, U32 *file_handle);
-static void AILCALLBACK streamingFileClose(U32 fileHandle);
-static S32 AILCALLBACK streamingFileSeek(U32 fileHandle, S32 offset, U32 type);
-static U32 AILCALLBACK streamingFileRead(U32 fileHandle, void *buffer, U32 bytes);
+static U32 AILCALLBACK streamingFileOpen(char const *fileName, AILFILEHANDLE *file_handle);
+static void AILCALLBACK streamingFileClose(AILFILEHANDLE fileHandle);
+static S32 AILCALLBACK streamingFileSeek(AILFILEHANDLE fileHandle, S32 offset, U32 type);
+static U32 AILCALLBACK streamingFileRead(AILFILEHANDLE fileHandle, void *buffer, U32 bytes);
//-------------------------------------------------------------------------------------------------
/* "Is this sound one of these?", asked of a sound that is already playing or already queued.
@@ -988,7 +988,7 @@ void MilesAudioManager::stopAudioEvent( AudioHandle handle )
// found it
// Ask it to stop; the next processPlayingList sweep does the Miles side and the free.
InterlockedCompareExchange( (volatile long *)&audio->m_status, PS_Stopping, PS_Playing );
- notifyOfAudioCompletion((UnsignedInt)(audio->m_stream), PAT_Stream);
+ notifyOfAudioCompletion((UnsignedIntPtr)(audio->m_stream), PAT_Stream);
break;
}
}
@@ -1641,7 +1641,7 @@ Bool MilesAudioManager::isCurrentlyPlaying( AudioHandle handle )
}
//-------------------------------------------------------------------------------------------------
-void MilesAudioManager::notifyOfAudioCompletion( UnsignedInt audioCompleted, UnsignedInt flags )
+void MilesAudioManager::notifyOfAudioCompletion( UnsignedIntPtr audioCompleted, UnsignedInt flags )
{
PlayingAudio *playing = findPlayingAudioFrom(audioCompleted, flags);
if (!playing) {
@@ -1705,7 +1705,7 @@ void MilesAudioManager::notifyOfAudioCompletion( UnsignedInt audioCompleted, Uns
}
//-------------------------------------------------------------------------------------------------
-PlayingAudio *MilesAudioManager::findPlayingAudioFrom( UnsignedInt audioCompleted, UnsignedInt flags )
+PlayingAudio *MilesAudioManager::findPlayingAudioFrom( UnsignedIntPtr audioCompleted, UnsignedInt flags )
{
// Miles calls in here from its own timer thread when a sample finishes, so every walk of these
// lists is guarded against the main thread taking an element out from under it.
@@ -3162,48 +3162,44 @@ void MilesAudioManager::friend_forcePlayAudioEventRTS(const AudioEventRTS* event
//-------------------------------------------------------------------------------------------------
void AILCALLBACK setSampleCompleted( HSAMPLE sampleCompleted )
{
- TheAudio->notifyOfAudioCompletion((UnsignedInt) sampleCompleted, PAT_Sample);
+ TheAudio->notifyOfAudioCompletion((UnsignedIntPtr) sampleCompleted, PAT_Sample);
}
//-------------------------------------------------------------------------------------------------
void AILCALLBACK set3DSampleCompleted( H3DSAMPLE sample3DCompleted )
{
- TheAudio->notifyOfAudioCompletion((UnsignedInt) sample3DCompleted, PAT_3DSample);
+ TheAudio->notifyOfAudioCompletion((UnsignedIntPtr) sample3DCompleted, PAT_3DSample);
}
//-------------------------------------------------------------------------------------------------
void AILCALLBACK setStreamCompleted( HSTREAM streamCompleted )
{
- TheAudio->notifyOfAudioCompletion((UnsignedInt) streamCompleted, PAT_Stream);
+ TheAudio->notifyOfAudioCompletion((UnsignedIntPtr) streamCompleted, PAT_Stream);
}
//-------------------------------------------------------------------------------------------------
-U32 AILCALLBACK streamingFileOpen(char const *fileName, U32 *file_handle)
+U32 AILCALLBACK streamingFileOpen(char const *fileName, AILFILEHANDLE *file_handle)
{
-#if defined(_DEBUG) || defined(_INTERNAL)
- if (sizeof(U32) != sizeof(File*)) {
- RELEASE_CRASH(("streamingFileOpen - This function requires work in order to compile on non 32-bit platforms.\n"));
- }
-#endif
-
- (*file_handle) = (U32) TheFileSystem->openFile(fileName, File::READ | File::STREAMING);
+ // The handle is a File*, so it is pointer sized - the cast to a 32-bit U32 that used to be here
+ // threw half of every pointer away and was guarded by a debug-only crash saying as much.
+ (*file_handle) = (AILFILEHANDLE) TheFileSystem->openFile(fileName, File::READ | File::STREAMING);
return ((*file_handle) != 0);
}
//-------------------------------------------------------------------------------------------------
-void AILCALLBACK streamingFileClose(U32 fileHandle)
+void AILCALLBACK streamingFileClose(AILFILEHANDLE fileHandle)
{
((File*) fileHandle)->close();
}
//-------------------------------------------------------------------------------------------------
-S32 AILCALLBACK streamingFileSeek(U32 fileHandle, S32 offset, U32 type)
+S32 AILCALLBACK streamingFileSeek(AILFILEHANDLE fileHandle, S32 offset, U32 type)
{
return ((File*) fileHandle)->seek(offset, (File::seekMode) type);
}
//-------------------------------------------------------------------------------------------------
-U32 AILCALLBACK streamingFileRead(U32 file_handle, void *buffer, U32 bytes)
+U32 AILCALLBACK streamingFileRead(AILFILEHANDLE file_handle, void *buffer, U32 bytes)
{
return ((File*) file_handle)->read(buffer, bytes);
}
diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp
index 6a924b88f..43f032adc 100644
--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp
+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DAssetManager.cpp
@@ -810,7 +810,7 @@ RenderObjClass * W3DAssetManager::Create_Render_Obj(
const char *mesh_name = ::strchr (name, '.');
if (mesh_name != NULL)
{
- ::lstrcpyn(filename, name, ((int)mesh_name) - ((int)name) + 1);
+ ::lstrcpyn(filename, name, (int)(mesh_name - name) + 1);
#ifdef INCLUDE_GRANNY_IN_BUILD
if (isGranny)
::lstrcat(filename, ".gr2");
diff --git a/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h b/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h
index 10ed6be46..40a7938ca 100644
--- a/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h
+++ b/GeneralsMD/Code/Libraries/Include/Lib/BaseType.h
@@ -123,7 +123,10 @@
//--------------------------------------------------------------------
typedef float Real; // 4 bytes
typedef int Int; // 4 bytes
-typedef unsigned int UnsignedInt; // 4 bytes
+typedef unsigned int UnsignedInt; // 4 bytes
+// 4 bytes on Win32, 8 on x64: for the places that carry a pointer through an integer, which the
+// GUI message payloads and a few handle typedefs do.
+typedef size_t UnsignedIntPtr; // pointer sized
typedef unsigned short UnsignedShort; // 2 bytes
typedef short Short; // 2 bytes
typedef unsigned char UnsignedByte; // 1 byte USED TO BE "Byte"
@@ -175,10 +178,12 @@ inline Real deg2rad(Real rad) { return rad * (PI/180); }
// after this one silently rewrites every use below into an intrinsic that takes
// a LONG* and the game's bit fields stop compiling. Not <windows.h>: that also
// drags in winsock.h, and the device code includes winsock2.h.
-#if defined(_M_IX86) && !defined(_X86_)
-#define _X86_ // windows.h does this before it reaches windef.h, and winnt.h
+#ifndef _AMD64_
+#define _AMD64_ // windows.h does this before it reaches windef.h, and winnt.h
#endif // #errors with "No Target Architecture" without it
#include <windef.h>
+#include <string.h>
+#include <emmintrin.h>
#undef BitTest
#define BitTest( x, i ) ( ( (x) & (i) ) != 0 )
#define BitSet( x, i ) ( (x) |= (i) )
@@ -190,37 +195,29 @@ inline Real deg2rad(Real rad) { return rad * (PI/180); }
// note, this function depends on the cpu rounding mode, which we set to CHOP every frame,
// but apparently tends to be left in unpredictable modes by various system bits of
// code, so use this function with caution -- it might not round in the way you want.
+//
+// EA's fld/fistp pair, written as cvtss2si: both round in the current mode, which setFPMode pins
+// to nearest.
__forceinline long fast_float2long_round(float f)
{
- long i;
-
- __asm {
- fld [f]
- fistp [i]
- }
-
- return i;
+ return _mm_cvtss_si32(_mm_set_ss(f));
}
// super fast float trunc routine, works always (independent of any FPU modes)
// code courtesy of Martin Hoffesommer (grin)
+//
+// The same bits EA's asm produced, in C: a mask of 0xff800000 shifted arithmetically right by
+// (exponent - 127) clears the fraction, and an exponent below 127 clears everything. The shift
+// count keeps the asm's wrap at 32 (sar only reads the low five bits of cl) for the huge values
+// where that matters, so no input changes answer.
__forceinline float fast_float_trunc(float f)
{
- // EDX, not EBX, for the zero: an __asm block has to leave EBX/ESI/EDI the way it
- // found them, and this one did not. Where the compiler parks the saved ESP in EBX
- // (W3DTreeBuffer::doLighting does) the epilogue's "mov esp,ebx" then set ESP to 0
- // and the next pop faulted -- the crash that ended every run at the main menu.
- _asm
- {
- mov ecx,[f]
- shr ecx,23
- mov eax,0xff800000
- xor edx,edx
- sub cl,127
- cmovc eax,edx
- sar eax,cl
- and [f],eax
- }
+ unsigned int bits;
+ memcpy(&bits, &f, sizeof(bits));
+ const unsigned int exponent = (bits >> 23) & 0xff;
+ const int mask = exponent < 127 ? 0 : (int)0xff800000 >> ((exponent - 127) & 31);
+ bits &= (unsigned int)mask;
+ memcpy(&f, &bits, sizeof(f));
return f;
}
diff --git a/GeneralsMD/Code/Libraries/Source/Compression/LZHCompress/NoxCompress.cpp b/GeneralsMD/Code/Libraries/Source/Compression/LZHCompress/NoxCompress.cpp
index 5d58acd6b..0cf8b5fb1 100644
--- a/GeneralsMD/Code/Libraries/Source/Compression/LZHCompress/NoxCompress.cpp
+++ b/GeneralsMD/Code/Libraries/Source/Compression/LZHCompress/NoxCompress.cpp
@@ -47,10 +47,10 @@ Bool DecompressFile (char *infile, char *outfile)
char *outBlock = NULL;
LZHL_DHANDLE decompress;
Int ok = 0;
- UnsignedInt srcSz, dstSz;
+ size_t srcSz, dstSz;
// Parameter checking
-
+
if (( infile == NULL ) || ( outfile == NULL ))
return FALSE;
@@ -224,7 +224,7 @@ Bool DecompressMemory (void *inBufferVoid, Int inSize, void *outBufferVoid, Int
UnsignedInt rawSize = 0, compressedSize = 0;
LZHL_DHANDLE decompress;
Int ok = 0;
- UnsignedInt srcSz, dstSz;
+ size_t srcSz, dstSz;
// Parameter checking
diff --git a/GeneralsMD/Code/Libraries/Source/FFmpeg/.gitignore b/GeneralsMD/Code/Libraries/Source/FFmpeg/.gitignore
new file mode 100644
index 000000000..d6b7ef32c
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/FFmpeg/.gitignore
@@ -0,0 +1,2 @@
+*
+!.gitignore
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/ffmpeg/bink_ffmpeg.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/ffmpeg/bink_ffmpeg.cpp
new file mode 100644
index 000000000..fc740696d
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/ffmpeg/bink_ffmpeg.cpp
@@ -0,0 +1,517 @@
+/*
+ * Bink 1.x surface, implemented on FFmpeg and XAudio2.
+ *
+ * BINKW32.DLL is a 32-bit binary, so the x64 build cannot bind to the movie player the game ships
+ * with. FFmpeg decodes both of Bink's codecs natively (binkvideo, binkaudio), so the .bik files
+ * on disk play unchanged; this file is the same API in front of them.
+ *
+ * The struct handed back is a BINK with the decoder hanging off the end of it, so BinkVideoStream's
+ * reads of Width/Height/Frames/FrameNum keep working.
+ */
+
+#include <windows.h>
+#include <xaudio2.h>
+#include <deque>
+#include <stdlib.h>
+#include <string.h>
+#include <vector>
+
+extern "C" {
+#include <libavcodec/avcodec.h>
+#include <libavformat/avformat.h>
+#include <libavutil/imgutils.h>
+#include <libswresample/swresample.h>
+#include <libswscale/swscale.h>
+}
+
+#include "bink.h"
+
+namespace {
+
+const int AUDIO_BUFFERS_AHEAD = 4;
+const int MAX_BINK_VOLUME = 32768;
+
+struct Movie
+{
+ BINK pub;
+
+ AVFormatContext *format;
+ AVCodecContext *videoDecoder;
+ AVCodecContext *audioDecoder;
+ SwsContext *scaler;
+ SwrContext *resampler;
+ int videoStream;
+ int audioStream;
+
+ AVFrame *frame;
+ int scaledFormat;
+ int scaledWidth;
+ int scaledHeight;
+
+ IXAudio2 *xaudio;
+ IXAudio2MasteringVoice *master;
+ IXAudio2SourceVoice *voice;
+ WAVEFORMATEX audioFormat;
+ std::deque<std::vector<unsigned char> > audioQueued;
+ bool audioEnabled;
+ float volume;
+
+ LARGE_INTEGER startTicks;
+ LARGE_INTEGER ticksPerSecond;
+ bool started;
+ bool frameDecoded;
+ bool endOfFile;
+};
+
+bool soundEnabled = true;
+
+void startClock(Movie *movie)
+{
+ QueryPerformanceFrequency(&movie->ticksPerSecond);
+ QueryPerformanceCounter(&movie->startTicks);
+ movie->started = true;
+}
+
+double elapsedSeconds(Movie *movie)
+{
+ LARGE_INTEGER now;
+ QueryPerformanceCounter(&now);
+ return (double)(now.QuadPart - movie->startTicks.QuadPart) / (double)movie->ticksPerSecond.QuadPart;
+}
+
+double frameDueSeconds(Movie *movie, unsigned int frameNumber)
+{
+ if (movie->pub.FrameRate == 0) {
+ return 0.0;
+ }
+ const double divisor = movie->pub.FrameRateDiv != 0 ? (double)movie->pub.FrameRateDiv : 1.0;
+ return (double)(frameNumber - 1) * divisor / (double)movie->pub.FrameRate;
+}
+
+void openAudio(Movie *movie)
+{
+ if (!soundEnabled || movie->audioStream < 0 || movie->audioDecoder == NULL) {
+ return;
+ }
+ if (FAILED(XAudio2Create(&movie->xaudio, 0, XAUDIO2_DEFAULT_PROCESSOR))) {
+ return;
+ }
+ if (FAILED(movie->xaudio->CreateMasteringVoice(&movie->master))) {
+ movie->xaudio->Release();
+ movie->xaudio = NULL;
+ return;
+ }
+
+ const int channels = movie->audioDecoder->ch_layout.nb_channels >= 2 ? 2 : 1;
+ AVChannelLayout outLayout;
+ av_channel_layout_default(&outLayout, channels);
+ const int result = swr_alloc_set_opts2(&movie->resampler, &outLayout, AV_SAMPLE_FMT_S16,
+ movie->audioDecoder->sample_rate, &movie->audioDecoder->ch_layout, movie->audioDecoder->sample_fmt,
+ movie->audioDecoder->sample_rate, 0, NULL);
+ av_channel_layout_uninit(&outLayout);
+ if (result < 0 || swr_init(movie->resampler) < 0) {
+ return;
+ }
+
+ memset(&movie->audioFormat, 0, sizeof(movie->audioFormat));
+ movie->audioFormat.wFormatTag = WAVE_FORMAT_PCM;
+ movie->audioFormat.nChannels = (WORD)channels;
+ movie->audioFormat.nSamplesPerSec = movie->audioDecoder->sample_rate;
+ movie->audioFormat.wBitsPerSample = 16;
+ movie->audioFormat.nBlockAlign = (WORD)(channels * 2);
+ movie->audioFormat.nAvgBytesPerSec = movie->audioFormat.nSamplesPerSec * movie->audioFormat.nBlockAlign;
+
+ if (SUCCEEDED(movie->xaudio->CreateSourceVoice(&movie->voice, &movie->audioFormat))) {
+ movie->voice->SetVolume(movie->volume);
+ movie->voice->Start(0);
+ movie->audioEnabled = true;
+ }
+}
+
+void queueAudioFrame(Movie *movie, AVFrame *frame)
+{
+ if (!movie->audioEnabled || movie->voice == NULL) {
+ return;
+ }
+
+ const int maxOutSamples = (int)swr_get_out_samples(movie->resampler, frame->nb_samples);
+ std::vector<unsigned char> chunk((size_t)maxOutSamples * movie->audioFormat.nBlockAlign);
+ if (chunk.empty()) {
+ return;
+ }
+
+ uint8_t *destination = &chunk[0];
+ const int converted = swr_convert(movie->resampler, &destination, maxOutSamples,
+ (const uint8_t **)frame->extended_data, frame->nb_samples);
+ if (converted <= 0) {
+ return;
+ }
+ chunk.resize((size_t)converted * movie->audioFormat.nBlockAlign);
+
+ XAUDIO2_VOICE_STATE state;
+ movie->voice->GetState(&state);
+ while (movie->audioQueued.size() > state.BuffersQueued) {
+ movie->audioQueued.pop_front();
+ }
+
+ movie->audioQueued.push_back(chunk);
+ const std::vector<unsigned char> &stored = movie->audioQueued.back();
+ XAUDIO2_BUFFER buffer;
+ memset(&buffer, 0, sizeof(buffer));
+ buffer.AudioBytes = (UINT32)stored.size();
+ buffer.pAudioData = &stored[0];
+ movie->voice->SubmitSourceBuffer(&buffer);
+}
+
+// Reads packets until the next video frame is decoded, queueing any audio met along the way.
+bool decodeNextVideoFrame(Movie *movie)
+{
+ AVPacket *packet = av_packet_alloc();
+ if (packet == NULL) {
+ return false;
+ }
+
+ bool decoded = false;
+ while (!decoded) {
+ const int readResult = av_read_frame(movie->format, packet);
+ if (readResult < 0) {
+ movie->endOfFile = true;
+ avcodec_send_packet(movie->videoDecoder, NULL);
+ if (avcodec_receive_frame(movie->videoDecoder, movie->frame) == 0) {
+ decoded = true;
+ }
+ break;
+ }
+
+ AVCodecContext *decoder = NULL;
+ if (packet->stream_index == movie->videoStream) {
+ decoder = movie->videoDecoder;
+ } else if (packet->stream_index == movie->audioStream && movie->audioEnabled) {
+ decoder = movie->audioDecoder;
+ }
+
+ if (decoder != NULL && avcodec_send_packet(decoder, packet) == 0) {
+ if (decoder == movie->videoDecoder) {
+ if (avcodec_receive_frame(movie->videoDecoder, movie->frame) == 0) {
+ decoded = true;
+ }
+ } else {
+ AVFrame *audioFrame = av_frame_alloc();
+ while (audioFrame != NULL && avcodec_receive_frame(movie->audioDecoder, audioFrame) == 0) {
+ queueAudioFrame(movie, audioFrame);
+ av_frame_unref(audioFrame);
+ }
+ if (audioFrame != NULL) {
+ av_frame_free(&audioFrame);
+ }
+ }
+ }
+ av_packet_unref(packet);
+ }
+
+ av_packet_free(&packet);
+ return decoded;
+}
+
+AVPixelFormat pixelFormatForSurface(unsigned int surfaceType)
+{
+ switch (surfaceType & 0xff) {
+ case BINKSURFACE24: return AV_PIX_FMT_BGR24;
+ case BINKSURFACE24R: return AV_PIX_FMT_RGB24;
+ case BINKSURFACE32:
+ case BINKSURFACE32A: return AV_PIX_FMT_BGRA;
+ case BINKSURFACE32R:
+ case BINKSURFACE32RA: return AV_PIX_FMT_RGBA;
+ case BINKSURFACE565: return AV_PIX_FMT_RGB565LE;
+ case BINKSURFACE555: return AV_PIX_FMT_RGB555LE;
+ default: return AV_PIX_FMT_BGRA;
+ }
+}
+
+} // namespace
+
+// =================================================================================================
+
+extern "C" {
+
+HBINK __stdcall BinkOpen(const char *name, unsigned int)
+{
+ if (name == NULL) {
+ return NULL;
+ }
+
+ Movie *movie = new Movie;
+ memset(&movie->pub, 0, sizeof(movie->pub));
+ movie->format = NULL;
+ movie->videoDecoder = NULL;
+ movie->audioDecoder = NULL;
+ movie->scaler = NULL;
+ movie->resampler = NULL;
+ movie->videoStream = -1;
+ movie->audioStream = -1;
+ movie->frame = av_frame_alloc();
+ movie->scaledFormat = -1;
+ movie->scaledWidth = 0;
+ movie->scaledHeight = 0;
+ movie->xaudio = NULL;
+ movie->master = NULL;
+ movie->voice = NULL;
+ movie->audioEnabled = false;
+ movie->volume = 1.0f;
+ movie->started = false;
+ movie->frameDecoded = false;
+ movie->endOfFile = false;
+
+ if (movie->frame == NULL || avformat_open_input(&movie->format, name, NULL, NULL) < 0) {
+ BinkClose((HBINK)movie);
+ return NULL;
+ }
+ if (avformat_find_stream_info(movie->format, NULL) < 0) {
+ BinkClose((HBINK)movie);
+ return NULL;
+ }
+
+ movie->videoStream = av_find_best_stream(movie->format, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
+ if (movie->videoStream < 0) {
+ BinkClose((HBINK)movie);
+ return NULL;
+ }
+ movie->audioStream = av_find_best_stream(movie->format, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
+
+ AVStream *video = movie->format->streams[movie->videoStream];
+ const AVCodec *videoCodec = avcodec_find_decoder(video->codecpar->codec_id);
+ movie->videoDecoder = videoCodec != NULL ? avcodec_alloc_context3(videoCodec) : NULL;
+ if (movie->videoDecoder == NULL ||
+ avcodec_parameters_to_context(movie->videoDecoder, video->codecpar) < 0 ||
+ avcodec_open2(movie->videoDecoder, videoCodec, NULL) < 0) {
+ BinkClose((HBINK)movie);
+ return NULL;
+ }
+
+ if (movie->audioStream >= 0) {
+ AVStream *audio = movie->format->streams[movie->audioStream];
+ const AVCodec *audioCodec = avcodec_find_decoder(audio->codecpar->codec_id);
+ movie->audioDecoder = audioCodec != NULL ? avcodec_alloc_context3(audioCodec) : NULL;
+ if (movie->audioDecoder != NULL &&
+ (avcodec_parameters_to_context(movie->audioDecoder, audio->codecpar) < 0 ||
+ avcodec_open2(movie->audioDecoder, audioCodec, NULL) < 0)) {
+ avcodec_free_context(&movie->audioDecoder);
+ }
+ }
+
+ movie->pub.Width = (unsigned int)movie->videoDecoder->width;
+ movie->pub.Height = (unsigned int)movie->videoDecoder->height;
+ movie->pub.FrameNum = 1;
+ movie->pub.LastFrameNum = 0;
+
+ AVRational rate = video->avg_frame_rate;
+ if (rate.num <= 0 || rate.den <= 0) {
+ rate = video->r_frame_rate;
+ }
+ if (rate.num <= 0 || rate.den <= 0) {
+ rate.num = 30;
+ rate.den = 1;
+ }
+ movie->pub.FrameRate = (unsigned int)rate.num;
+ movie->pub.FrameRateDiv = (unsigned int)rate.den;
+
+ if (video->nb_frames > 0) {
+ movie->pub.Frames = (unsigned int)video->nb_frames;
+ } else if (movie->format->duration > 0) {
+ const double seconds = (double)movie->format->duration / (double)AV_TIME_BASE;
+ movie->pub.Frames = (unsigned int)(seconds * av_q2d(rate) + 0.5);
+ } else {
+ movie->pub.Frames = 1;
+ }
+
+ openAudio(movie);
+ startClock(movie);
+ return (HBINK)movie;
+}
+
+void __stdcall BinkClose(HBINK handle)
+{
+ Movie *movie = (Movie *)handle;
+ if (movie == NULL) {
+ return;
+ }
+
+ if (movie->voice != NULL) {
+ movie->voice->Stop(0);
+ movie->voice->DestroyVoice();
+ }
+ if (movie->master != NULL) {
+ movie->master->DestroyVoice();
+ }
+ if (movie->xaudio != NULL) {
+ movie->xaudio->Release();
+ }
+ if (movie->resampler != NULL) {
+ swr_free(&movie->resampler);
+ }
+ if (movie->scaler != NULL) {
+ sws_freeContext(movie->scaler);
+ }
+ if (movie->frame != NULL) {
+ av_frame_free(&movie->frame);
+ }
+ if (movie->videoDecoder != NULL) {
+ avcodec_free_context(&movie->videoDecoder);
+ }
+ if (movie->audioDecoder != NULL) {
+ avcodec_free_context(&movie->audioDecoder);
+ }
+ if (movie->format != NULL) {
+ avformat_close_input(&movie->format);
+ }
+ delete movie;
+}
+
+int __stdcall BinkWait(HBINK handle)
+{
+ Movie *movie = (Movie *)handle;
+ if (movie == NULL) {
+ return 0;
+ }
+ if (!movie->started) {
+ startClock(movie);
+ return 0;
+ }
+ return elapsedSeconds(movie) < frameDueSeconds(movie, movie->pub.FrameNum) ? 1 : 0;
+}
+
+int __stdcall BinkDoFrame(HBINK handle)
+{
+ Movie *movie = (Movie *)handle;
+ if (movie == NULL) {
+ return 1;
+ }
+ if (movie->frameDecoded) {
+ return 0;
+ }
+
+ movie->frameDecoded = decodeNextVideoFrame(movie);
+ return movie->frameDecoded ? 0 : 1;
+}
+
+void __stdcall BinkNextFrame(HBINK handle)
+{
+ Movie *movie = (Movie *)handle;
+ if (movie == NULL) {
+ return;
+ }
+
+ movie->pub.LastFrameNum = movie->pub.FrameNum;
+ if (movie->pub.FrameNum < movie->pub.Frames) {
+ movie->pub.FrameNum += 1;
+ }
+ movie->frameDecoded = false;
+}
+
+int __stdcall BinkGoto(HBINK handle, unsigned int frame, int)
+{
+ Movie *movie = (Movie *)handle;
+ if (movie == NULL || movie->format == NULL) {
+ return 0;
+ }
+ if (frame < 1) {
+ frame = 1;
+ }
+
+ AVStream *video = movie->format->streams[movie->videoStream];
+ const double seconds = frameDueSeconds(movie, frame);
+ const int64_t timestamp = (int64_t)(seconds / av_q2d(video->time_base));
+ if (av_seek_frame(movie->format, movie->videoStream, timestamp, AVSEEK_FLAG_BACKWARD) < 0) {
+ return 0;
+ }
+
+ avcodec_flush_buffers(movie->videoDecoder);
+ if (movie->audioDecoder != NULL) {
+ avcodec_flush_buffers(movie->audioDecoder);
+ }
+ if (movie->voice != NULL) {
+ movie->voice->FlushSourceBuffers();
+ movie->audioQueued.clear();
+ }
+
+ movie->pub.FrameNum = frame;
+ movie->frameDecoded = false;
+ movie->endOfFile = false;
+ QueryPerformanceCounter(&movie->startTicks);
+ movie->startTicks.QuadPart -= (LONGLONG)(seconds * (double)movie->ticksPerSecond.QuadPart);
+ return 1;
+}
+
+int __stdcall BinkCopyToBuffer(HBINK handle, void *dest, int destpitch, unsigned int destheight,
+ unsigned int destx, unsigned int desty, unsigned int flags)
+{
+ Movie *movie = (Movie *)handle;
+ if (movie == NULL || dest == NULL || !movie->frameDecoded || movie->frame->data[0] == NULL) {
+ return 0;
+ }
+
+ const AVPixelFormat destinationFormat = pixelFormatForSurface(flags);
+ const int width = (int)movie->pub.Width;
+ const int height = (int)movie->pub.Height;
+ const int copyHeight = (int)destheight < height ? (int)destheight : height;
+
+ if (movie->scaler == NULL || movie->scaledFormat != destinationFormat ||
+ movie->scaledWidth != width || movie->scaledHeight != height) {
+ if (movie->scaler != NULL) {
+ sws_freeContext(movie->scaler);
+ }
+ movie->scaler = sws_getContext(width, height, (AVPixelFormat)movie->frame->format,
+ width, height, destinationFormat, SWS_BILINEAR, NULL, NULL, NULL);
+ movie->scaledFormat = destinationFormat;
+ movie->scaledWidth = width;
+ movie->scaledHeight = height;
+ }
+ if (movie->scaler == NULL) {
+ return 0;
+ }
+
+ const int bytesPerPixel = av_get_bits_per_pixel(av_pix_fmt_desc_get(destinationFormat)) / 8;
+ unsigned char *destinationBase = (unsigned char *)dest + (size_t)desty * destpitch + (size_t)destx * bytesPerPixel;
+ uint8_t *destinationPlanes[4] = { destinationBase, NULL, NULL, NULL };
+ int destinationStrides[4] = { destpitch, 0, 0, 0 };
+
+ sws_scale(movie->scaler, movie->frame->data, movie->frame->linesize, 0, copyHeight,
+ destinationPlanes, destinationStrides);
+ return 1;
+}
+
+int __stdcall BinkSetVolume(HBINK handle, unsigned int, int volume)
+{
+ Movie *movie = (Movie *)handle;
+ if (movie == NULL) {
+ return 0;
+ }
+
+ float level = (float)volume / (float)MAX_BINK_VOLUME;
+ if (level < 0.0f) level = 0.0f;
+ if (level > 1.0f) level = 1.0f;
+ movie->volume = level;
+ if (movie->voice != NULL) {
+ movie->voice->SetVolume(level);
+ }
+ return 1;
+}
+
+void __stdcall BinkSetSoundTrack(unsigned int, unsigned int *)
+{
+ // The game calls this with zero tracks when Miles handed it no DirectSound object to give Bink.
+ // This player owns its own output device, so there is nothing to turn off.
+}
+
+int __stdcall BinkSetSoundSystem(BINKSNDSYSOPEN, BINKSNDPARAM)
+{
+ soundEnabled = true;
+ return 1;
+}
+
+int __stdcall BinkOpenDirectSound(BINKSNDPARAM)
+{
+ return 1;
+}
+
+} // extern "C"
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/include/bink.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/include/bink.h
index e31686c98..2b5d62860 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/include/bink.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/include/bink.h
@@ -74,7 +74,11 @@ typedef struct BINK
unsigned int FrameRateDiv; /* frame rate denominator */
} BINK, *HBINK;
-typedef int (__stdcall *BINKSNDSYSOPEN)(unsigned int param);
+/* The parameter carries a DirectSound object pointer, so it is pointer sized. On Win32 that is
+ still four bytes, which is what the retail DLL's _BinkSetSoundSystem@8 expects. */
+#include <stddef.h>
+typedef size_t BINKSNDPARAM;
+typedef int (__stdcall *BINKSNDSYSOPEN)(BINKSNDPARAM param);
HBINK __stdcall BinkOpen(const char *name, unsigned int flags);
void __stdcall BinkClose(HBINK bnk);
@@ -87,11 +91,11 @@ int __stdcall BinkCopyToBuffer(HBINK bnk, void *dest, int destpitch,
unsigned int desty, unsigned int flags);
int __stdcall BinkSetVolume(HBINK bnk, unsigned int trackid, int volume);
void __stdcall BinkSetSoundTrack(unsigned int total_tracks, unsigned int *tracks);
-int __stdcall BinkSetSoundSystem(BINKSNDSYSOPEN open, unsigned int param);
-int __stdcall BinkOpenDirectSound(unsigned int param);
+int __stdcall BinkSetSoundSystem(BINKSNDSYSOPEN open, BINKSNDPARAM param);
+int __stdcall BinkOpenDirectSound(BINKSNDPARAM param);
#define BinkSoundUseDirectSound(lpDS) \
- BinkSetSoundSystem((BINKSNDSYSOPEN)BinkOpenDirectSound, (unsigned int)(lpDS))
+ BinkSetSoundSystem((BINKSNDSYSOPEN)BinkOpenDirectSound, (BINKSNDPARAM)(lpDS))
#ifdef __cplusplus
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/stub/bink.c b/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/stub/bink.c
deleted file mode 100644
index 7f5edd983..000000000
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/stub/bink.c
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * No-op stand-in for binkw32.dll. Nothing here ever runs: it exists only so
- * the linker can produce an import library whose symbols carry the decorated
- * names the shipped BINKW32.DLL exports, which is what generals.exe binds to
- * at run time. (`lib /def` alone cannot make that import library - it prefixes
- * a second underscore onto the already-decorated names.)
- *
- * The stub DLL built from this file must never be copied next to generals.exe.
- */
-#include "bink.h"
-
-HBINK __stdcall BinkOpen(const char *name, unsigned int flags) { return 0; }
-void __stdcall BinkClose(HBINK bnk) {}
-int __stdcall BinkWait(HBINK bnk) { return 0; }
-int __stdcall BinkDoFrame(HBINK bnk) { return 0; }
-void __stdcall BinkNextFrame(HBINK bnk) {}
-int __stdcall BinkGoto(HBINK bnk, unsigned int frame, int flags) { return 0; }
-int __stdcall BinkCopyToBuffer(HBINK bnk, void *dest, int destpitch,
- unsigned int destheight, unsigned int destx,
- unsigned int desty, unsigned int flags) { return 0; }
-int __stdcall BinkSetVolume(HBINK bnk, unsigned int trackid, int volume) { return 0; }
-void __stdcall BinkSetSoundTrack(unsigned int total_tracks, unsigned int *tracks) {}
-int __stdcall BinkSetSoundSystem(BINKSNDSYSOPEN open, unsigned int param) { return 0; }
-int __stdcall BinkOpenDirectSound(unsigned int param) { return 0; }
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/stub/bink.def b/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/stub/bink.def
deleted file mode 100644
index de285f6e2..000000000
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Bink/stub/bink.def
+++ /dev/null
@@ -1,12 +0,0 @@
-EXPORTS
-_BinkOpen@8
-_BinkClose@4
-_BinkWait@4
-_BinkDoFrame@4
-_BinkNextFrame@4
-_BinkGoto@12
-_BinkCopyToBuffer@28
-_BinkSetVolume@12
-_BinkSetSoundTrack@8
-_BinkSetSoundSystem@8
-_BinkOpenDirectSound@4
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/.gitignore b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/.gitignore
index ba341a9b4..d602d4a8b 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/.gitignore
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/.gitignore
@@ -5,13 +5,11 @@
# ...and our own hand-written Miles declarations (not EA/RAD code, so they are
# committed: the real Miles SDK is binary-only and absent, and a fresh clone
# cannot re-fetch files we wrote ourselves). MSS/MSS.h is the one true header
-# (reconstructed API surface); Mss.h and stub/mss/mss.h just forward to it.
+# (reconstructed API surface) and Mss.h just forwards to it; xaudio2/ is that
+# API implemented over XAudio2 and FFmpeg, which is what the game links.
!include/
!include/Mss.h
!include/MSS/
!include/MSS/MSS.h
-!stub/
-!stub/mss/
-!stub/mss/mss.h
-# stub/miles.c, stub/miles.def, stub/cleanup.c stay unvendored: they are
-# re-fetched from Thyme (see CLAUDE.md), with one local patch documented there.
+!xaudio2/
+!xaudio2/miles_xaudio2.cpp
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h
index 5a5402b5d..5ffe3d2d5 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/include/MSS/MSS.h
@@ -110,10 +110,13 @@ typedef struct _AILSOUNDINFO
typedef void (AILCALLBACK *AILSAMPLECB) (HSAMPLE sample);
typedef void (AILCALLBACK *AIL3DSAMPLECB) (H3DSAMPLE sample);
typedef void (AILCALLBACK *AILSTREAMCB) (HSTREAM stream);
-typedef U32 (AILCALLBACK *AILFILEOPENCB) (const char *filename, U32 *file_handle);
-typedef void (AILCALLBACK *AILFILECLOSECB)(U32 file_handle);
-typedef S32 (AILCALLBACK *AILFILESEEKCB) (U32 file_handle, S32 offset, U32 type);
-typedef U32 (AILCALLBACK *AILFILEREADCB) (U32 file_handle, void *buffer, U32 bytes);
+/* The file handle is whatever the host wants it to be and this game puts a File* in it, so it is
+ pointer sized. On Win32 that is the U32 the retail DLL's ABI expects; x64 needs all 64 bits. */
+typedef UINT_PTR AILFILEHANDLE;
+typedef U32 (AILCALLBACK *AILFILEOPENCB) (const char *filename, AILFILEHANDLE *file_handle);
+typedef void (AILCALLBACK *AILFILECLOSECB)(AILFILEHANDLE file_handle);
+typedef S32 (AILCALLBACK *AILFILESEEKCB) (AILFILEHANDLE file_handle, S32 offset, U32 type);
+typedef U32 (AILCALLBACK *AILFILEREADCB) (AILFILEHANDLE file_handle, void *buffer, U32 bytes);
/* Thyme's stub miles.c spells the same callback types this way. */
typedef AILSAMPLECB AIL_sample_callback;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/stub/mss/mss.h b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/stub/mss/mss.h
deleted file mode 100644
index d48cd9a08..000000000
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/stub/mss/mss.h
+++ /dev/null
@@ -1,4 +0,0 @@
-/* The stub's miles.c is the W3D-flavored Thyme variant and expects the same
- * declarations the game compiles against - use the one true header. Relative
- * path on purpose: "MSS/MSS.h" would resolve back to this very file. */
-#include "../../include/MSS/MSS.h"
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp
new file mode 100644
index 000000000..3f868a44d
--- /dev/null
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/Miles6/xaudio2/miles_xaudio2.cpp
@@ -0,0 +1,1567 @@
+/*
+ * Miles Sound System 6.5 surface, implemented on XAudio2 and FFmpeg.
+ *
+ * The retail mss32.dll is a 32-bit binary and cannot load into the x64 process, so the x64 build
+ * links this instead of the import stub. Every entry point MilesAudioManager.cpp reaches is here
+ * with the semantics that file relies on; the rest of Miles is not.
+ *
+ * What maps onto what:
+ * HSAMPLE / H3DSAMPLE -> one IXAudio2SourceVoice each, fed a whole PCM WAV image in one buffer.
+ * HSTREAM / HAUDIO -> a file decoded by FFmpeg through the game's own file callbacks, fed to
+ * a source voice in ~200ms buffers by the service thread below.
+ * 3D positioning -> distance attenuation and a stereo pan computed here, not by XAudio2's
+ * X3DAudio: the game only ever asks for a position, a min/max distance
+ * pair and an occlusion scalar.
+ * EOS callbacks -> the service thread notices a voice run dry and calls back from there,
+ * which is the thread context Miles used (MilesAudioManager locks for it).
+ */
+
+#include <windows.h>
+#include <mmreg.h>
+#include <xaudio2.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <deque>
+#include <vector>
+
+extern "C" {
+#include <libavcodec/avcodec.h>
+#include <libavformat/avformat.h>
+#include <libavutil/opt.h>
+#include <libswresample/swresample.h>
+}
+
+#include "MSS/MSS.h"
+
+namespace {
+
+const int SERVICE_PERIOD_MS = 10;
+const int STREAM_CHUNK_MS = 200;
+const int STREAM_BUFFERS_AHEAD = 4;
+const int USER_DATA_SLOTS = 8;
+const float DEFAULT_PAN = 0.5f;
+const int AVIO_BUFFER_BYTES = 32768;
+
+struct WaveImage
+{
+ WAVEFORMATEX format;
+ const unsigned char *data;
+ unsigned int dataBytes;
+ unsigned int samplesPerBlock;
+};
+
+// ---------------------------------------------------------------------------------------------
+// RIFF/WAVE
+// ---------------------------------------------------------------------------------------------
+
+unsigned int readU32(const unsigned char *p)
+{
+ return (unsigned int)p[0] | ((unsigned int)p[1] << 8) | ((unsigned int)p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+unsigned short readU16(const unsigned char *p)
+{
+ return (unsigned short)((unsigned int)p[0] | ((unsigned int)p[1] << 8));
+}
+
+bool parseWave(const void *image, WaveImage *out)
+{
+ const unsigned char *bytes = (const unsigned char *)image;
+ if (bytes == NULL) {
+ return false;
+ }
+ if (memcmp(bytes, "RIFF", 4) != 0 || memcmp(bytes + 8, "WAVE", 4) != 0) {
+ return false;
+ }
+
+ const unsigned int riffBytes = readU32(bytes + 4);
+ const unsigned char *cursor = bytes + 12;
+ const unsigned char *end = bytes + 8 + riffBytes;
+ bool haveFormat = false;
+
+ memset(out, 0, sizeof(*out));
+ while (cursor + 8 <= end) {
+ const unsigned int chunkBytes = readU32(cursor + 4);
+ const unsigned char *body = cursor + 8;
+
+ if (memcmp(cursor, "fmt ", 4) == 0 && chunkBytes >= 16) {
+ out->format.wFormatTag = readU16(body);
+ out->format.nChannels = readU16(body + 2);
+ out->format.nSamplesPerSec = readU32(body + 4);
+ out->format.nAvgBytesPerSec = readU32(body + 8);
+ out->format.nBlockAlign = readU16(body + 12);
+ out->format.wBitsPerSample = readU16(body + 14);
+ if (chunkBytes >= 20) {
+ out->samplesPerBlock = readU16(body + 18);
+ }
+ haveFormat = true;
+ } else if (memcmp(cursor, "data", 4) == 0) {
+ out->data = body;
+ out->dataBytes = chunkBytes;
+ }
+
+ cursor = body + chunkBytes + (chunkBytes & 1);
+ }
+
+ return haveFormat && out->data != NULL;
+}
+
+unsigned int wavePcmSampleCount(const WaveImage &wave)
+{
+ if (wave.format.wFormatTag == WAVE_FORMAT_IMA_ADPCM) {
+ if (wave.format.nBlockAlign == 0 || wave.format.nChannels == 0) {
+ return 0;
+ }
+ const unsigned int blocks = wave.dataBytes / wave.format.nBlockAlign;
+ const unsigned int perBlock = wave.samplesPerBlock != 0
+ ? wave.samplesPerBlock
+ : 1 + (wave.format.nBlockAlign - 4 * wave.format.nChannels) * 2 / wave.format.nChannels;
+ return blocks * perBlock;
+ }
+
+ const unsigned int frameBytes = wave.format.nBlockAlign != 0 ? wave.format.nBlockAlign : 1;
+ return wave.dataBytes / frameBytes;
+}
+
+// ---------------------------------------------------------------------------------------------
+// IMA ADPCM
+// ---------------------------------------------------------------------------------------------
+
+const int ADPCM_INDEX_STEP[16] =
+{
+ -1, -1, -1, -1, 2, 4, 6, 8,
+ -1, -1, -1, -1, 2, 4, 6, 8
+};
+
+const int ADPCM_STEP_TABLE[89] =
+{
+ 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
+ 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253,
+ 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166,
+ 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428,
+ 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289,
+ 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
+};
+
+short decodeAdpcmNibble(int nibble, int *predictor, int *index)
+{
+ const int step = ADPCM_STEP_TABLE[*index];
+ int difference = step >> 3;
+
+ if (nibble & 4) difference += step;
+ if (nibble & 2) difference += step >> 1;
+ if (nibble & 1) difference += step >> 2;
+ if (nibble & 8) difference = -difference;
+
+ int sample = *predictor + difference;
+ if (sample > 32767) sample = 32767;
+ if (sample < -32768) sample = -32768;
+ *predictor = sample;
+
+ *index += ADPCM_INDEX_STEP[nibble];
+ if (*index < 0) *index = 0;
+ if (*index > 88) *index = 88;
+
+ return (short)sample;
+}
+
+// Decodes every block into interleaved 16-bit PCM. Returns the sample frame count.
+unsigned int decodeAdpcm(const WaveImage &wave, std::vector<short> *out)
+{
+ const unsigned int channels = wave.format.nChannels;
+ const unsigned int blockAlign = wave.format.nBlockAlign;
+ if (channels == 0 || channels > 2 || blockAlign <= 4 * channels) {
+ return 0;
+ }
+
+ const unsigned int blocks = wave.dataBytes / blockAlign;
+ const unsigned int samplesPerBlock = 1 + (blockAlign - 4 * channels) * 2 / channels;
+ out->clear();
+ out->reserve((size_t)blocks * samplesPerBlock * channels);
+
+ for (unsigned int block = 0; block < blocks; ++block) {
+ const unsigned char *body = wave.data + (size_t)block * blockAlign;
+ int predictor[2] = { 0, 0 };
+ int index[2] = { 0, 0 };
+
+ for (unsigned int channel = 0; channel < channels; ++channel) {
+ predictor[channel] = (short)readU16(body + channel * 4);
+ index[channel] = body[channel * 4 + 2];
+ if (index[channel] > 88) index[channel] = 88;
+ out->push_back((short)predictor[channel]);
+ }
+
+ const unsigned char *nibbles = body + 4 * channels;
+ const unsigned int groupsPerChannel = (blockAlign - 4 * channels) / (4 * channels);
+ std::vector<short> decoded[2];
+ for (unsigned int channel = 0; channel < channels; ++channel) {
+ decoded[channel].reserve(groupsPerChannel * 8);
+ }
+
+ for (unsigned int group = 0; group < groupsPerChannel; ++group) {
+ for (unsigned int channel = 0; channel < channels; ++channel) {
+ const unsigned char *word = nibbles + (group * channels + channel) * 4;
+ for (int byteIndex = 0; byteIndex < 4; ++byteIndex) {
+ decoded[channel].push_back(decodeAdpcmNibble(word[byteIndex] & 0x0f, &predictor[channel], &index[channel]));
+ decoded[channel].push_back(decodeAdpcmNibble((word[byteIndex] >> 4) & 0x0f, &predictor[channel], &index[channel]));
+ }
+ }
+ }
+
+ const size_t frames = decoded[0].size();
+ for (size_t frame = 0; frame < frames; ++frame) {
+ for (unsigned int channel = 0; channel < channels; ++channel) {
+ out->push_back(decoded[channel][frame]);
+ }
+ }
+ }
+
+ return channels != 0 ? (unsigned int)(out->size() / channels) : 0;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Voices
+// ---------------------------------------------------------------------------------------------
+
+struct Sample
+{
+ bool is3D;
+ IXAudio2SourceVoice *voice;
+ WAVEFORMATEX format;
+ const unsigned char *data;
+ unsigned int dataBytes;
+ float volume;
+ float pan;
+ unsigned int baseRate;
+ unsigned int rate;
+ S32 userData[USER_DATA_SLOTS];
+ AILSAMPLECB endOfSample;
+ AIL3DSAMPLECB endOf3DSample;
+ bool playing;
+ float positionX, positionY, positionZ;
+ float minDistance, maxDistance;
+ float occlusion;
+};
+
+struct StreamBuffer
+{
+ std::vector<unsigned char> bytes;
+};
+
+struct Stream
+{
+ Stream()
+ : format(NULL), avio(NULL), decoder(NULL), resampler(NULL), audioStream(-1), fileHandle(0),
+ ownsFileHandle(false), voice(NULL), loopCount(1), paused(false), playing(false),
+ exhausted(false), volume(1.0f), pan(DEFAULT_PAN), totalMs(0.0), framesSubmitted(0),
+ callback(NULL)
+ {
+ memset(&voiceFormat, 0, sizeof(voiceFormat));
+ }
+
+ AVFormatContext *format;
+ AVIOContext *avio;
+ AVCodecContext *decoder;
+ SwrContext *resampler;
+ int audioStream;
+ AILFILEHANDLE fileHandle;
+ bool ownsFileHandle;
+
+ IXAudio2SourceVoice *voice;
+ WAVEFORMATEX voiceFormat;
+ std::deque<StreamBuffer> queued;
+
+ int loopCount;
+ bool paused;
+ bool playing;
+ bool exhausted;
+ float volume;
+ float pan;
+ double totalMs;
+ long long framesSubmitted;
+ AILSTREAMCB callback;
+};
+
+struct Listener
+{
+ float positionX, positionY, positionZ;
+ float faceX, faceY, faceZ;
+ float upX, upY, upZ;
+};
+
+struct Engine
+{
+ IXAudio2 *xaudio;
+ IXAudio2MasteringVoice *master;
+ CRITICAL_SECTION lock;
+ HANDLE serviceThread;
+ volatile LONG serviceRunning;
+ std::vector<Sample *> samples;
+ std::vector<Stream *> streams;
+ Listener listener;
+ bool started;
+};
+
+Engine g_engine;
+
+AILFILEOPENCB g_fileOpen;
+AILFILECLOSECB g_fileClose;
+AILFILESEEKCB g_fileSeek;
+AILFILEREADCB g_fileRead;
+
+struct _AIL_DIGDRIVER *const DIGITAL_DRIVER = (struct _AIL_DIGDRIVER *)(UINT_PTR)0x1;
+struct _AIL_3DPOBJECT *const LISTENER_OBJECT = (struct _AIL_3DPOBJECT *)(UINT_PTR)0x2;
+
+const HPROVIDER PROVIDER_FAST_2D = 1;
+const HPROVIDER PROVIDER_DOLBY = 2;
+
+float clampUnit(float value)
+{
+ if (value < 0.0f) return 0.0f;
+ if (value > 1.0f) return 1.0f;
+ return value;
+}
+
+void applyPan(IXAudio2SourceVoice *voice, unsigned int sourceChannels, float pan)
+{
+ if (voice == NULL || g_engine.master == NULL) {
+ return;
+ }
+
+ XAUDIO2_VOICE_DETAILS masterDetails;
+ g_engine.master->GetVoiceDetails(&masterDetails);
+ if (masterDetails.InputChannels < 2) {
+ return;
+ }
+
+ const float left = clampUnit(1.0f - pan);
+ const float right = clampUnit(pan);
+ // Miles' pan is a constant-power law: dead centre is not two half-volume speakers.
+ const float leftGain = (float)sqrt(left);
+ const float rightGain = (float)sqrt(right);
+
+ std::vector<float> matrix((size_t)sourceChannels * masterDetails.InputChannels, 0.0f);
+ for (unsigned int channel = 0; channel < sourceChannels; ++channel) {
+ matrix[(size_t)0 * sourceChannels + channel] = leftGain;
+ matrix[(size_t)1 * sourceChannels + channel] = rightGain;
+ }
+ voice->SetOutputMatrix(NULL, sourceChannels, masterDetails.InputChannels, &matrix[0]);
+}
+
+void computeSpatialGain(const Sample &sample, float *volumeOut, float *panOut)
+{
+ const Listener &listener = g_engine.listener;
+ const float dx = sample.positionX - listener.positionX;
+ const float dy = sample.positionY - listener.positionY;
+ const float dz = sample.positionZ - listener.positionZ;
+ const float distance = (float)sqrt(dx * dx + dy * dy + dz * dz);
+
+ float attenuation = 1.0f;
+ if (sample.maxDistance > sample.minDistance) {
+ if (distance >= sample.maxDistance) {
+ attenuation = 0.0f;
+ } else if (distance > sample.minDistance) {
+ attenuation = (sample.maxDistance - distance) / (sample.maxDistance - sample.minDistance);
+ }
+ }
+ attenuation *= clampUnit(1.0f - sample.occlusion);
+
+ float pan = DEFAULT_PAN;
+ if (distance > 0.0001f) {
+ // right = face x up, which is the axis a stereo pan actually moves along
+ const float rightX = listener.faceY * listener.upZ - listener.faceZ * listener.upY;
+ const float rightY = listener.faceZ * listener.upX - listener.faceX * listener.upZ;
+ const float rightZ = listener.faceX * listener.upY - listener.faceY * listener.upX;
+ const float rightLength = (float)sqrt(rightX * rightX + rightY * rightY + rightZ * rightZ);
+ if (rightLength > 0.0001f) {
+ const float projection = (dx * rightX + dy * rightY + dz * rightZ) / (rightLength * distance);
+ pan = clampUnit(0.5f + 0.5f * projection);
+ }
+ }
+
+ *volumeOut = clampUnit(sample.volume) * attenuation;
+ *panOut = pan;
+}
+
+void refreshSampleOutput(Sample *sample)
+{
+ if (sample->voice == NULL) {
+ return;
+ }
+
+ float volume = sample->volume;
+ float pan = sample->pan;
+ if (sample->is3D) {
+ computeSpatialGain(*sample, &volume, &pan);
+ }
+
+ sample->voice->SetVolume(clampUnit(volume));
+ applyPan(sample->voice, sample->format.nChannels, pan);
+ if (sample->baseRate != 0) {
+ float ratio = (float)sample->rate / (float)sample->baseRate;
+ if (ratio < XAUDIO2_MIN_FREQ_RATIO) ratio = XAUDIO2_MIN_FREQ_RATIO;
+ if (ratio > 4.0f) ratio = 4.0f;
+ sample->voice->SetFrequencyRatio(ratio);
+ }
+}
+
+void destroyVoice(IXAudio2SourceVoice **voice)
+{
+ if (*voice != NULL) {
+ (*voice)->Stop(0);
+ (*voice)->FlushSourceBuffers();
+ (*voice)->DestroyVoice();
+ *voice = NULL;
+ }
+}
+
+bool ensureVoice(Sample *sample, const WAVEFORMATEX &format)
+{
+ if (g_engine.xaudio == NULL) {
+ return false;
+ }
+
+ if (sample->voice != NULL &&
+ sample->format.nChannels == format.nChannels &&
+ sample->format.nSamplesPerSec == format.nSamplesPerSec &&
+ sample->format.wBitsPerSample == format.wBitsPerSample) {
+ sample->voice->Stop(0);
+ sample->voice->FlushSourceBuffers();
+ return true;
+ }
+
+ destroyVoice(&sample->voice);
+ sample->format = format;
+ return SUCCEEDED(g_engine.xaudio->CreateSourceVoice(&sample->voice, &format, 0, 4.0f));
+}
+
+// ---------------------------------------------------------------------------------------------
+// Streams, decoded by FFmpeg through the game's file callbacks
+// ---------------------------------------------------------------------------------------------
+
+int streamRead(void *opaque, uint8_t *buffer, int bytes)
+{
+ Stream *stream = (Stream *)opaque;
+ if (g_fileRead == NULL) {
+ return AVERROR_EOF;
+ }
+ const U32 read = g_fileRead(stream->fileHandle, buffer, (U32)bytes);
+ if (read == 0) {
+ return AVERROR_EOF;
+ }
+ return (int)read;
+}
+
+int64_t streamSeek(void *opaque, int64_t offset, int whence)
+{
+ Stream *stream = (Stream *)opaque;
+ if (g_fileSeek == NULL) {
+ return -1;
+ }
+
+ if (whence == AVSEEK_SIZE) {
+ const S32 here = g_fileSeek(stream->fileHandle, 0, SEEK_CUR);
+ const S32 size = g_fileSeek(stream->fileHandle, 0, SEEK_END);
+ g_fileSeek(stream->fileHandle, here, SEEK_SET);
+ return size;
+ }
+
+ return g_fileSeek(stream->fileHandle, (S32)offset, (U32)whence);
+}
+
+void closeStreamDecoder(Stream *stream)
+{
+ if (stream->resampler != NULL) {
+ swr_free(&stream->resampler);
+ }
+ if (stream->decoder != NULL) {
+ avcodec_free_context(&stream->decoder);
+ }
+ if (stream->format != NULL) {
+ avformat_close_input(&stream->format);
+ }
+ if (stream->avio != NULL) {
+ av_freep(&stream->avio->buffer);
+ avio_context_free(&stream->avio);
+ }
+ if (stream->ownsFileHandle && g_fileClose != NULL && stream->fileHandle != 0) {
+ g_fileClose(stream->fileHandle);
+ }
+ stream->fileHandle = 0;
+}
+
+bool openStreamDecoder(Stream *stream, const char *filename)
+{
+ if (g_fileOpen == NULL || g_fileOpen(filename, &stream->fileHandle) == 0 || stream->fileHandle == 0) {
+ return false;
+ }
+ stream->ownsFileHandle = true;
+
+ unsigned char *avioBuffer = (unsigned char *)av_malloc(AVIO_BUFFER_BYTES);
+ if (avioBuffer == NULL) {
+ return false;
+ }
+ stream->avio = avio_alloc_context(avioBuffer, AVIO_BUFFER_BYTES, 0, stream, streamRead, NULL, streamSeek);
+ if (stream->avio == NULL) {
+ av_free(avioBuffer);
+ return false;
+ }
+
+ stream->format = avformat_alloc_context();
+ if (stream->format == NULL) {
+ return false;
+ }
+ stream->format->pb = stream->avio;
+ stream->format->flags |= AVFMT_FLAG_CUSTOM_IO;
+
+ if (avformat_open_input(&stream->format, filename, NULL, NULL) < 0) {
+ return false;
+ }
+ if (avformat_find_stream_info(stream->format, NULL) < 0) {
+ return false;
+ }
+
+ stream->audioStream = av_find_best_stream(stream->format, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
+ if (stream->audioStream < 0) {
+ return false;
+ }
+
+ AVStream *audio = stream->format->streams[stream->audioStream];
+ const AVCodec *codec = avcodec_find_decoder(audio->codecpar->codec_id);
+ if (codec == NULL) {
+ return false;
+ }
+ stream->decoder = avcodec_alloc_context3(codec);
+ if (stream->decoder == NULL ||
+ avcodec_parameters_to_context(stream->decoder, audio->codecpar) < 0 ||
+ avcodec_open2(stream->decoder, codec, NULL) < 0) {
+ return false;
+ }
+
+ const int channels = stream->decoder->ch_layout.nb_channels >= 2 ? 2 : 1;
+ AVChannelLayout outLayout;
+ av_channel_layout_default(&outLayout, channels);
+ if (swr_alloc_set_opts2(&stream->resampler, &outLayout, AV_SAMPLE_FMT_S16, stream->decoder->sample_rate,
+ &stream->decoder->ch_layout, stream->decoder->sample_fmt, stream->decoder->sample_rate,
+ 0, NULL) < 0 || swr_init(stream->resampler) < 0) {
+ av_channel_layout_uninit(&outLayout);
+ return false;
+ }
+ av_channel_layout_uninit(&outLayout);
+
+ memset(&stream->voiceFormat, 0, sizeof(stream->voiceFormat));
+ stream->voiceFormat.wFormatTag = WAVE_FORMAT_PCM;
+ stream->voiceFormat.nChannels = (WORD)channels;
+ stream->voiceFormat.nSamplesPerSec = stream->decoder->sample_rate;
+ stream->voiceFormat.wBitsPerSample = 16;
+ stream->voiceFormat.nBlockAlign = (WORD)(channels * 2);
+ stream->voiceFormat.nAvgBytesPerSec = stream->voiceFormat.nSamplesPerSec * stream->voiceFormat.nBlockAlign;
+
+ if (stream->format->duration > 0) {
+ stream->totalMs = (double)stream->format->duration * 1000.0 / (double)AV_TIME_BASE;
+ } else if (audio->duration > 0) {
+ stream->totalMs = (double)audio->duration * av_q2d(audio->time_base) * 1000.0;
+ }
+
+ if (g_engine.xaudio == NULL ||
+ FAILED(g_engine.xaudio->CreateSourceVoice(&stream->voice, &stream->voiceFormat, 0, 2.0f))) {
+ return false;
+ }
+ return true;
+}
+
+// Decodes up to one chunk. Returns false at the end of the file with nothing more to give.
+bool decodeStreamChunk(Stream *stream, std::vector<unsigned char> *out)
+{
+ const size_t wanted = (size_t)stream->voiceFormat.nAvgBytesPerSec * STREAM_CHUNK_MS / 1000;
+ AVPacket *packet = av_packet_alloc();
+ AVFrame *frame = av_frame_alloc();
+ if (packet == NULL || frame == NULL) {
+ if (packet != NULL) av_packet_free(&packet);
+ if (frame != NULL) av_frame_free(&frame);
+ return false;
+ }
+
+ bool reachedEnd = false;
+ while (out->size() < wanted && !reachedEnd) {
+ const int readResult = av_read_frame(stream->format, packet);
+ if (readResult < 0) {
+ avcodec_send_packet(stream->decoder, NULL);
+ reachedEnd = true;
+ } else if (packet->stream_index != stream->audioStream) {
+ av_packet_unref(packet);
+ continue;
+ } else if (avcodec_send_packet(stream->decoder, packet) < 0) {
+ av_packet_unref(packet);
+ continue;
+ }
+ av_packet_unref(packet);
+
+ for (;;) {
+ const int receiveResult = avcodec_receive_frame(stream->decoder, frame);
+ if (receiveResult < 0) {
+ break;
+ }
+
+ const int maxOutSamples = (int)swr_get_out_samples(stream->resampler, frame->nb_samples);
+ const size_t offset = out->size();
+ out->resize(offset + (size_t)maxOutSamples * stream->voiceFormat.nBlockAlign);
+ uint8_t *destination = &(*out)[offset];
+ const int converted = swr_convert(stream->resampler, &destination, maxOutSamples,
+ (const uint8_t **)frame->extended_data, frame->nb_samples);
+ out->resize(offset + (converted > 0 ? (size_t)converted * stream->voiceFormat.nBlockAlign : 0));
+ av_frame_unref(frame);
+ }
+ }
+
+ av_packet_free(&packet);
+ av_frame_free(&frame);
+
+ if (reachedEnd) {
+ avcodec_flush_buffers(stream->decoder);
+ return !out->empty() ? true : false;
+ }
+ return true;
+}
+
+bool rewindStream(Stream *stream)
+{
+ if (av_seek_frame(stream->format, stream->audioStream, 0, AVSEEK_FLAG_BACKWARD) < 0) {
+ return false;
+ }
+ avcodec_flush_buffers(stream->decoder);
+ return true;
+}
+
+void serviceStream(Stream *stream, std::vector<AILSTREAMCB> *callbacks, std::vector<HSTREAM> *callbackHandles)
+{
+ if (stream->voice == NULL || !stream->playing) {
+ return;
+ }
+
+ XAUDIO2_VOICE_STATE state;
+ stream->voice->GetState(&state);
+ while (stream->queued.size() > state.BuffersQueued) {
+ stream->queued.pop_front();
+ }
+
+ // queued holds one entry per buffer the voice still has, so it is the count to top up against.
+ while (!stream->exhausted && stream->queued.size() < STREAM_BUFFERS_AHEAD) {
+ StreamBuffer chunk;
+ if (!decodeStreamChunk(stream, &chunk.bytes) || chunk.bytes.empty()) {
+ if (stream->loopCount > 1 && rewindStream(stream)) {
+ stream->loopCount -= 1;
+ continue;
+ }
+ stream->exhausted = true;
+ break;
+ }
+
+ stream->queued.push_back(chunk);
+ const StreamBuffer &stored = stream->queued.back();
+ XAUDIO2_BUFFER buffer;
+ memset(&buffer, 0, sizeof(buffer));
+ buffer.AudioBytes = (UINT32)stored.bytes.size();
+ buffer.pAudioData = &stored.bytes[0];
+ stream->voice->SubmitSourceBuffer(&buffer);
+ stream->framesSubmitted += (long long)(stored.bytes.size() / stream->voiceFormat.nBlockAlign);
+ stream->voice->GetState(&state);
+ }
+
+ if (stream->exhausted && state.BuffersQueued == 0) {
+ stream->playing = false;
+ if (stream->callback != NULL) {
+ callbacks->push_back(stream->callback);
+ callbackHandles->push_back((HSTREAM)stream);
+ }
+ }
+}
+
+DWORD WINAPI serviceThreadMain(LPVOID)
+{
+ while (InterlockedCompareExchange(&g_engine.serviceRunning, 1, 1) == 1) {
+ std::vector<AILSAMPLECB> sampleCallbacks;
+ std::vector<HSAMPLE> sampleHandles;
+ std::vector<AIL3DSAMPLECB> sample3DCallbacks;
+ std::vector<H3DSAMPLE> sample3DHandles;
+ std::vector<AILSTREAMCB> streamCallbacks;
+ std::vector<HSTREAM> streamHandles;
+
+ EnterCriticalSection(&g_engine.lock);
+ for (size_t i = 0; i < g_engine.samples.size(); ++i) {
+ Sample *sample = g_engine.samples[i];
+ if (sample->voice == NULL) {
+ continue;
+ }
+ if (sample->is3D) {
+ refreshSampleOutput(sample);
+ }
+ if (!sample->playing) {
+ continue;
+ }
+
+ XAUDIO2_VOICE_STATE state;
+ sample->voice->GetState(&state);
+ if (state.BuffersQueued == 0) {
+ sample->playing = false;
+ if (sample->is3D && sample->endOf3DSample != NULL) {
+ sample3DCallbacks.push_back(sample->endOf3DSample);
+ sample3DHandles.push_back((H3DSAMPLE)sample);
+ } else if (!sample->is3D && sample->endOfSample != NULL) {
+ sampleCallbacks.push_back(sample->endOfSample);
+ sampleHandles.push_back((HSAMPLE)sample);
+ }
+ }
+ }
+
+ for (size_t i = 0; i < g_engine.streams.size(); ++i) {
+ serviceStream(g_engine.streams[i], &streamCallbacks, &streamHandles);
+ }
+ LeaveCriticalSection(&g_engine.lock);
+
+ // Callbacks run outside the lock: the game takes its own locks in them.
+ for (size_t i = 0; i < sampleCallbacks.size(); ++i) {
+ sampleCallbacks[i](sampleHandles[i]);
+ }
+ for (size_t i = 0; i < sample3DCallbacks.size(); ++i) {
+ sample3DCallbacks[i](sample3DHandles[i]);
+ }
+ for (size_t i = 0; i < streamCallbacks.size(); ++i) {
+ streamCallbacks[i](streamHandles[i]);
+ }
+
+ Sleep(SERVICE_PERIOD_MS);
+ }
+ return 0;
+}
+
+} // namespace
+
+// =================================================================================================
+// Startup and global state
+// =================================================================================================
+
+extern "C" {
+
+S32 AILCALL AIL_startup(void)
+{
+ if (g_engine.started) {
+ return 1;
+ }
+
+ memset(&g_engine.listener, 0, sizeof(g_engine.listener));
+ g_engine.listener.faceY = 1.0f;
+ g_engine.listener.upZ = 1.0f;
+ InitializeCriticalSection(&g_engine.lock);
+ g_engine.started = true;
+ return 1;
+}
+
+S32 AILCALL AIL_quick_startup(S32 use_digital, S32, U32, S32, S32)
+{
+ if (!use_digital) {
+ return 0;
+ }
+ if (g_engine.xaudio != NULL) {
+ return 1;
+ }
+
+ CoInitializeEx(NULL, COINIT_MULTITHREADED);
+ if (FAILED(XAudio2Create(&g_engine.xaudio, 0, XAUDIO2_DEFAULT_PROCESSOR))) {
+ return 0;
+ }
+ if (FAILED(g_engine.xaudio->CreateMasteringVoice(&g_engine.master))) {
+ g_engine.xaudio->Release();
+ g_engine.xaudio = NULL;
+ return 0;
+ }
+
+ InterlockedExchange(&g_engine.serviceRunning, 1);
+ g_engine.serviceThread = CreateThread(NULL, 0, serviceThreadMain, NULL, 0, NULL);
+ return 1;
+}
+
+void AILCALL AIL_quick_handles(HDIGDRIVER *pdig, HMDIDRIVER *pmdi, HDLSDEVICE *pdls)
+{
+ if (pdig != NULL) *pdig = DIGITAL_DRIVER;
+ if (pmdi != NULL) *pmdi = NULL;
+ if (pdls != NULL) *pdls = NULL;
+}
+
+void AILCALL AIL_shutdown(void)
+{
+ if (g_engine.serviceThread != NULL) {
+ InterlockedExchange(&g_engine.serviceRunning, 0);
+ WaitForSingleObject(g_engine.serviceThread, 2000);
+ CloseHandle(g_engine.serviceThread);
+ g_engine.serviceThread = NULL;
+ }
+
+ if (g_engine.master != NULL) {
+ g_engine.master->DestroyVoice();
+ g_engine.master = NULL;
+ }
+ if (g_engine.xaudio != NULL) {
+ g_engine.xaudio->Release();
+ g_engine.xaudio = NULL;
+ }
+ if (g_engine.started) {
+ DeleteCriticalSection(&g_engine.lock);
+ g_engine.started = false;
+ }
+}
+
+char *AILCALL AIL_set_redist_directory(const char *)
+{
+ return NULL;
+}
+
+void AILCALL AIL_lock(void)
+{
+ if (g_engine.started) {
+ EnterCriticalSection(&g_engine.lock);
+ }
+}
+
+void AILCALL AIL_unlock(void)
+{
+ if (g_engine.started) {
+ LeaveCriticalSection(&g_engine.lock);
+ }
+}
+
+S32 AILCALL AIL_get_timer_highest_delay(void)
+{
+ return SERVICE_PERIOD_MS;
+}
+
+void AILCALL AIL_set_file_callbacks(AILFILEOPENCB opencb, AILFILECLOSECB closecb, AILFILESEEKCB seekcb, AILFILEREADCB readcb)
+{
+ g_fileOpen = opencb;
+ g_fileClose = closecb;
+ g_fileSeek = seekcb;
+ g_fileRead = readcb;
+}
+
+// =================================================================================================
+// Providers and filters
+// =================================================================================================
+
+S32 AILCALL AIL_enumerate_3D_providers(HPROENUM *next, HPROVIDER *dest, char **name)
+{
+ // MilesAudioManager looks its provider up by name ("Miles Fast 2D Positional Audio"), and
+ // indexes its array with the result without checking it, so those names have to be here.
+ static char fast2D[] = "Miles Fast 2D Positional Audio";
+ static char dolby[] = "Dolby Surround";
+
+ switch (*next) {
+ case 0:
+ *dest = PROVIDER_FAST_2D;
+ *name = fast2D;
+ *next = 1;
+ return 1;
+ case 1:
+ *dest = PROVIDER_DOLBY;
+ *name = dolby;
+ *next = 2;
+ return 1;
+ default:
+ return 0;
+ }
+}
+
+S32 AILCALL AIL_open_3D_provider(HPROVIDER lib)
+{
+ return (lib == PROVIDER_FAST_2D || lib == PROVIDER_DOLBY) ? 0 : 1;
+}
+
+void AILCALL AIL_close_3D_provider(HPROVIDER)
+{
+}
+
+S32 AILCALL AIL_enumerate_filters(HPROENUM *, HPROVIDER *, char **)
+{
+ // No pipeline filters: the only one the game looks for is the Mono Delay, and a missing one
+ // leaves m_delayFilter NULL, which it already handles.
+ return 0;
+}
+
+void AILCALL AIL_set_3D_speaker_type(HPROVIDER, S32)
+{
+}
+
+HPROVIDER AILCALL AIL_set_sample_processor(HSAMPLE, S32, HPROVIDER provider)
+{
+ return provider;
+}
+
+void AILCALL AIL_set_filter_sample_preference(HSAMPLE, const char *, const void *)
+{
+}
+
+// =================================================================================================
+// 2D samples
+// =================================================================================================
+
+HSAMPLE AILCALL AIL_allocate_sample_handle(HDIGDRIVER dig)
+{
+ if (dig == NULL || g_engine.xaudio == NULL) {
+ return NULL;
+ }
+
+ Sample *sample = new Sample;
+ memset(sample, 0, sizeof(*sample));
+ sample->volume = 1.0f;
+ sample->pan = DEFAULT_PAN;
+ sample->maxDistance = 1.0f;
+
+ EnterCriticalSection(&g_engine.lock);
+ g_engine.samples.push_back(sample);
+ LeaveCriticalSection(&g_engine.lock);
+ return (HSAMPLE)sample;
+}
+
+void AILCALL AIL_release_sample_handle(HSAMPLE handle)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ for (size_t i = 0; i < g_engine.samples.size(); ++i) {
+ if (g_engine.samples[i] == sample) {
+ g_engine.samples.erase(g_engine.samples.begin() + i);
+ break;
+ }
+ }
+ destroyVoice(&sample->voice);
+ LeaveCriticalSection(&g_engine.lock);
+ delete sample;
+}
+
+void AILCALL AIL_init_sample(HSAMPLE handle)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ if (sample->voice != NULL) {
+ sample->voice->Stop(0);
+ sample->voice->FlushSourceBuffers();
+ }
+ sample->playing = false;
+ sample->volume = 1.0f;
+ sample->pan = DEFAULT_PAN;
+ sample->endOfSample = NULL;
+ sample->data = NULL;
+ sample->dataBytes = 0;
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+S32 AILCALL AIL_set_sample_file(HSAMPLE handle, const void *file_image, S32)
+{
+ Sample *sample = (Sample *)handle;
+ WaveImage wave;
+ if (sample == NULL || !parseWave(file_image, &wave) || wave.format.wFormatTag != WAVE_FORMAT_PCM) {
+ return 0;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ sample->playing = false;
+ const bool ready = ensureVoice(sample, wave.format);
+ if (ready) {
+ sample->data = wave.data;
+ sample->dataBytes = wave.dataBytes;
+ sample->baseRate = wave.format.nSamplesPerSec;
+ sample->rate = wave.format.nSamplesPerSec;
+ refreshSampleOutput(sample);
+ }
+ LeaveCriticalSection(&g_engine.lock);
+ return ready ? 1 : 0;
+}
+
+void AILCALL AIL_start_sample(HSAMPLE handle)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL || sample->voice == NULL || sample->data == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ sample->voice->Stop(0);
+ sample->voice->FlushSourceBuffers();
+
+ XAUDIO2_BUFFER buffer;
+ memset(&buffer, 0, sizeof(buffer));
+ buffer.AudioBytes = sample->dataBytes;
+ buffer.pAudioData = sample->data;
+ buffer.Flags = XAUDIO2_END_OF_STREAM;
+ if (SUCCEEDED(sample->voice->SubmitSourceBuffer(&buffer))) {
+ refreshSampleOutput(sample);
+ sample->voice->Start(0);
+ sample->playing = true;
+ }
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_stop_sample(HSAMPLE handle)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL || sample->voice == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ sample->voice->Stop(0);
+ sample->playing = false;
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_resume_sample(HSAMPLE handle)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL || sample->voice == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ XAUDIO2_VOICE_STATE state;
+ sample->voice->GetState(&state);
+ if (state.BuffersQueued > 0) {
+ sample->voice->Start(0);
+ sample->playing = true;
+ }
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_end_sample(HSAMPLE handle)
+{
+ AIL_stop_sample(handle);
+}
+
+void AILCALL AIL_set_sample_volume_pan(HSAMPLE handle, F32 volume, F32 pan)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ sample->volume = volume;
+ sample->pan = pan;
+ refreshSampleOutput(sample);
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_sample_volume_pan(HSAMPLE handle, F32 *volume, F32 *pan)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL) {
+ return;
+ }
+ if (volume != NULL) *volume = sample->volume;
+ if (pan != NULL) *pan = sample->pan;
+}
+
+void AILCALL AIL_set_sample_playback_rate(HSAMPLE handle, S32 playback_rate)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL || playback_rate <= 0) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ sample->rate = (unsigned int)playback_rate;
+ refreshSampleOutput(sample);
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+S32 AILCALL AIL_sample_playback_rate(HSAMPLE handle)
+{
+ Sample *sample = (Sample *)handle;
+ return sample != NULL ? (S32)sample->rate : 0;
+}
+
+void AILCALL AIL_set_sample_user_data(HSAMPLE handle, U32 index, S32 value)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample != NULL && index < USER_DATA_SLOTS) {
+ sample->userData[index] = value;
+ }
+}
+
+S32 AILCALL AIL_sample_user_data(HSAMPLE handle, U32 index)
+{
+ Sample *sample = (Sample *)handle;
+ return (sample != NULL && index < USER_DATA_SLOTS) ? sample->userData[index] : 0;
+}
+
+AILSAMPLECB AILCALL AIL_register_EOS_callback(HSAMPLE handle, AILSAMPLECB EOS)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL) {
+ return NULL;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ AILSAMPLECB previous = sample->endOfSample;
+ sample->endOfSample = EOS;
+ LeaveCriticalSection(&g_engine.lock);
+ return previous;
+}
+
+void AILCALL AIL_get_DirectSound_info(HSAMPLE, AILLPDIRECTSOUND *lplpDS, AILLPDIRECTSOUNDBUFFER *lplpDSB)
+{
+ // There is no DirectSound object behind XAudio2. The two callers both handle NULL: the speaker
+ // config falls back to stereo, and Bink plays its own audio.
+ if (lplpDS != NULL) *lplpDS = NULL;
+ if (lplpDSB != NULL) *lplpDSB = NULL;
+}
+
+// =================================================================================================
+// 3D samples
+// =================================================================================================
+
+H3DSAMPLE AILCALL AIL_allocate_3D_sample_handle(HPROVIDER lib)
+{
+ if (lib != PROVIDER_FAST_2D && lib != PROVIDER_DOLBY) {
+ return NULL;
+ }
+
+ HSAMPLE handle = AIL_allocate_sample_handle(DIGITAL_DRIVER);
+ Sample *sample = (Sample *)handle;
+ if (sample != NULL) {
+ sample->is3D = true;
+ sample->minDistance = 1.0f;
+ sample->maxDistance = 1000.0f;
+ }
+ return (H3DSAMPLE)sample;
+}
+
+void AILCALL AIL_release_3D_sample_handle(H3DSAMPLE handle)
+{
+ AIL_release_sample_handle((HSAMPLE)handle);
+}
+
+S32 AILCALL AIL_set_3D_sample_file(H3DSAMPLE handle, const void *file_image)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample != NULL) {
+ sample->occlusion = 0.0f;
+ }
+ return AIL_set_sample_file((HSAMPLE)handle, file_image, 0);
+}
+
+void AILCALL AIL_start_3D_sample(H3DSAMPLE handle)
+{
+ AIL_start_sample((HSAMPLE)handle);
+}
+
+void AILCALL AIL_stop_3D_sample(H3DSAMPLE handle)
+{
+ AIL_stop_sample((HSAMPLE)handle);
+}
+
+void AILCALL AIL_resume_3D_sample(H3DSAMPLE handle)
+{
+ AIL_resume_sample((HSAMPLE)handle);
+}
+
+void AILCALL AIL_end_3D_sample(H3DSAMPLE handle)
+{
+ AIL_stop_sample((HSAMPLE)handle);
+}
+
+void AILCALL AIL_set_3D_sample_volume(H3DSAMPLE handle, F32 volume)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ sample->volume = volume;
+ refreshSampleOutput(sample);
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_set_3D_sample_playback_rate(H3DSAMPLE handle, S32 playback_rate)
+{
+ AIL_set_sample_playback_rate((HSAMPLE)handle, playback_rate);
+}
+
+S32 AILCALL AIL_3D_sample_playback_rate(H3DSAMPLE handle)
+{
+ return AIL_sample_playback_rate((HSAMPLE)handle);
+}
+
+void AILCALL AIL_set_3D_sample_distances(H3DSAMPLE handle, F32 max_dist, F32 min_dist)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ sample->maxDistance = max_dist;
+ sample->minDistance = min_dist;
+ refreshSampleOutput(sample);
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_set_3D_sample_occlusion(H3DSAMPLE handle, F32 occlusion)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ sample->occlusion = clampUnit(occlusion);
+ refreshSampleOutput(sample);
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_set_3D_user_data(H3DPOBJECT obj, U32 index, S32 value)
+{
+ AIL_set_sample_user_data((HSAMPLE)obj, index, value);
+}
+
+S32 AILCALL AIL_3D_user_data(H3DPOBJECT obj, U32 index)
+{
+ return AIL_sample_user_data((HSAMPLE)obj, index);
+}
+
+AIL3DSAMPLECB AILCALL AIL_register_3D_EOS_callback(H3DSAMPLE handle, AIL3DSAMPLECB EOS)
+{
+ Sample *sample = (Sample *)handle;
+ if (sample == NULL) {
+ return NULL;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ AIL3DSAMPLECB previous = sample->endOf3DSample;
+ sample->endOf3DSample = EOS;
+ LeaveCriticalSection(&g_engine.lock);
+ return previous;
+}
+
+// =================================================================================================
+// 3D positioning
+// =================================================================================================
+
+H3DPOBJECT AILCALL AIL_open_3D_listener(HPROVIDER lib)
+{
+ return (lib == PROVIDER_FAST_2D || lib == PROVIDER_DOLBY) ? LISTENER_OBJECT : NULL;
+}
+
+void AILCALL AIL_close_3D_listener(H3DPOBJECT)
+{
+}
+
+void AILCALL AIL_set_3D_position(H3DPOBJECT obj, F32 X, F32 Y, F32 Z)
+{
+ if (obj == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ if (obj == LISTENER_OBJECT) {
+ g_engine.listener.positionX = X;
+ g_engine.listener.positionY = Y;
+ g_engine.listener.positionZ = Z;
+ } else {
+ Sample *sample = (Sample *)obj;
+ sample->positionX = X;
+ sample->positionY = Y;
+ sample->positionZ = Z;
+ refreshSampleOutput(sample);
+ }
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_set_3D_orientation(H3DPOBJECT obj, F32 X_face, F32 Y_face, F32 Z_face, F32 X_up, F32 Y_up, F32 Z_up)
+{
+ if (obj != LISTENER_OBJECT) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ g_engine.listener.faceX = X_face;
+ g_engine.listener.faceY = Y_face;
+ g_engine.listener.faceZ = Z_face;
+ g_engine.listener.upX = X_up;
+ g_engine.listener.upY = Y_up;
+ g_engine.listener.upZ = Z_up;
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_set_3D_velocity_vector(H3DPOBJECT, F32, F32, F32)
+{
+ // No doppler: Miles' was off in this game's settings too.
+}
+
+// =================================================================================================
+// Streams
+// =================================================================================================
+
+HSTREAM AILCALL AIL_open_stream(HDIGDRIVER dig, const char *filename, S32)
+{
+ if (dig == NULL || filename == NULL || g_engine.xaudio == NULL) {
+ return NULL;
+ }
+
+ Stream *stream = new Stream;
+ if (!openStreamDecoder(stream, filename)) {
+ closeStreamDecoder(stream);
+ destroyVoice(&stream->voice);
+ delete stream;
+ return NULL;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ g_engine.streams.push_back(stream);
+ LeaveCriticalSection(&g_engine.lock);
+ return (HSTREAM)stream;
+}
+
+void AILCALL AIL_close_stream(HSTREAM handle)
+{
+ Stream *stream = (Stream *)handle;
+ if (stream == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ for (size_t i = 0; i < g_engine.streams.size(); ++i) {
+ if (g_engine.streams[i] == stream) {
+ g_engine.streams.erase(g_engine.streams.begin() + i);
+ break;
+ }
+ }
+ destroyVoice(&stream->voice);
+ stream->queued.clear();
+ closeStreamDecoder(stream);
+ LeaveCriticalSection(&g_engine.lock);
+ delete stream;
+}
+
+void AILCALL AIL_start_stream(HSTREAM handle)
+{
+ Stream *stream = (Stream *)handle;
+ if (stream == NULL || stream->voice == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ stream->playing = true;
+ stream->paused = false;
+ stream->exhausted = false;
+ stream->voice->SetVolume(clampUnit(stream->volume));
+ applyPan(stream->voice, stream->voiceFormat.nChannels, stream->pan);
+ stream->voice->Start(0);
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_pause_stream(HSTREAM handle, S32 onoff)
+{
+ Stream *stream = (Stream *)handle;
+ if (stream == NULL || stream->voice == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ stream->paused = onoff != 0;
+ if (stream->paused) {
+ stream->voice->Stop(0);
+ } else {
+ stream->voice->Start(0);
+ stream->playing = true;
+ }
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_set_stream_loop_count(HSTREAM handle, S32 count)
+{
+ Stream *stream = (Stream *)handle;
+ if (stream != NULL) {
+ stream->loopCount = count;
+ }
+}
+
+S32 AILCALL AIL_stream_loop_count(HSTREAM handle)
+{
+ Stream *stream = (Stream *)handle;
+ return stream != NULL ? stream->loopCount : 0;
+}
+
+void AILCALL AIL_set_stream_volume_pan(HSTREAM handle, F32 volume, F32 pan)
+{
+ Stream *stream = (Stream *)handle;
+ if (stream == NULL) {
+ return;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ stream->volume = volume;
+ stream->pan = pan;
+ if (stream->voice != NULL) {
+ stream->voice->SetVolume(clampUnit(volume));
+ applyPan(stream->voice, stream->voiceFormat.nChannels, pan);
+ }
+ LeaveCriticalSection(&g_engine.lock);
+}
+
+void AILCALL AIL_stream_volume_pan(HSTREAM handle, F32 *volume, F32 *pan)
+{
+ Stream *stream = (Stream *)handle;
+ if (stream == NULL) {
+ return;
+ }
+ if (volume != NULL) *volume = stream->volume;
+ if (pan != NULL) *pan = stream->pan;
+}
+
+void AILCALL AIL_stream_ms_position(HSTREAM handle, S32 *total_milliseconds, S32 *current_milliseconds)
+{
+ Stream *stream = (Stream *)handle;
+ if (stream == NULL) {
+ return;
+ }
+
+ if (total_milliseconds != NULL) {
+ *total_milliseconds = (S32)stream->totalMs;
+ }
+ if (current_milliseconds != NULL) {
+ S32 position = 0;
+ if (stream->voice != NULL && stream->voiceFormat.nSamplesPerSec != 0) {
+ XAUDIO2_VOICE_STATE state;
+ stream->voice->GetState(&state);
+ position = (S32)(state.SamplesPlayed * 1000 / stream->voiceFormat.nSamplesPerSec);
+ }
+ *current_milliseconds = position;
+ }
+}
+
+AILSTREAMCB AILCALL AIL_register_stream_callback(HSTREAM handle, AILSTREAMCB callback)
+{
+ Stream *stream = (Stream *)handle;
+ if (stream == NULL) {
+ return NULL;
+ }
+
+ EnterCriticalSection(&g_engine.lock);
+ AILSTREAMCB previous = stream->callback;
+ stream->callback = callback;
+ LeaveCriticalSection(&g_engine.lock);
+ return previous;
+}
+
+// =================================================================================================
+// Quick API - mission briefing speech
+// =================================================================================================
+
+HAUDIO AILCALL AIL_quick_load_and_play(const char *filename, U32 loop_count, S32)
+{
+ HSTREAM stream = AIL_open_stream(DIGITAL_DRIVER, filename, 0);
+ if (stream == NULL) {
+ return NULL;
+ }
+
+ AIL_set_stream_loop_count(stream, loop_count == 0 ? 1 : (S32)loop_count);
+ AIL_start_stream(stream);
+ return (HAUDIO)stream;
+}
+
+void AILCALL AIL_quick_unload(HAUDIO audio)
+{
+ AIL_close_stream((HSTREAM)audio);
+}
+
+void AILCALL AIL_quick_set_volume(HAUDIO audio, F32 volume, F32 extravol)
+{
+ AIL_set_stream_volume_pan((HSTREAM)audio, volume, extravol);
+}
+
+// =================================================================================================
+// File format helpers
+// =================================================================================================
+
+S32 AILCALL AIL_WAV_info(const void *data, AILSOUNDINFO *info)
+{
+ WaveImage wave;
+ if (info == NULL || !parseWave(data, &wave)) {
+ return 0;
+ }
+
+ memset(info, 0, sizeof(*info));
+ info->format = wave.format.wFormatTag;
+ info->data_ptr = wave.data;
+ info->data_len = wave.dataBytes;
+ info->rate = wave.format.nSamplesPerSec;
+ info->bits = wave.format.wBitsPerSample;
+ info->channels = wave.format.nChannels;
+ info->samples = wavePcmSampleCount(wave);
+ info->block_size = wave.format.nBlockAlign;
+ info->initial_ptr = data;
+ return 1;
+}
+
+S32 AILCALL AIL_decompress_ADPCM(const AILSOUNDINFO *info, void **outdata, U32 *outsize)
+{
+ if (info == NULL || outdata == NULL || outsize == NULL) {
+ return 0;
+ }
+
+ WaveImage wave;
+ if (!parseWave(info->initial_ptr, &wave) || wave.format.wFormatTag != WAVE_FORMAT_IMA_ADPCM) {
+ return 0;
+ }
+
+ std::vector<short> pcm;
+ const unsigned int frames = decodeAdpcm(wave, &pcm);
+ if (frames == 0) {
+ return 0;
+ }
+
+ // The caller hands the result straight to AIL_set_sample_file, so it has to be a WAV image.
+ const unsigned int channels = wave.format.nChannels;
+ const unsigned int payloadBytes = (unsigned int)(pcm.size() * sizeof(short));
+ const unsigned int imageBytes = 44 + payloadBytes;
+ unsigned char *image = (unsigned char *)malloc(imageBytes);
+ if (image == NULL) {
+ return 0;
+ }
+
+ const unsigned int blockAlign = channels * 2;
+ const unsigned int byteRate = wave.format.nSamplesPerSec * blockAlign;
+ memcpy(image, "RIFF", 4);
+ *(unsigned int *)(image + 4) = imageBytes - 8;
+ memcpy(image + 8, "WAVEfmt ", 8);
+ *(unsigned int *)(image + 16) = 16;
+ *(unsigned short *)(image + 20) = WAVE_FORMAT_PCM;
+ *(unsigned short *)(image + 22) = (unsigned short)channels;
+ *(unsigned int *)(image + 24) = wave.format.nSamplesPerSec;
+ *(unsigned int *)(image + 28) = byteRate;
+ *(unsigned short *)(image + 32) = (unsigned short)blockAlign;
+ *(unsigned short *)(image + 34) = 16;
+ memcpy(image + 36, "data", 4);
+ *(unsigned int *)(image + 40) = payloadBytes;
+ memcpy(image + 44, &pcm[0], payloadBytes);
+
+ *outdata = image;
+ *outsize = imageBytes;
+ return 1;
+}
+
+void AILCALL AIL_mem_free_lock(void *ptr)
+{
+ free(ptr);
+}
+
+} // extern "C"
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.h
index b70443a7e..550f5f4ba 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ddsfile.h
@@ -143,7 +143,11 @@ struct LegacyDDSURFACEDESC2 {
};
unsigned AlphaBitDepth;
unsigned Reserved;
- void* Surface;
+ // This whole struct is read straight out of the .dds file, where the field is the four bytes
+ // DirectDraw once kept a surface pointer in. As a void* it grew to eight on x64 and pushed
+ // every field below it out of place: the pixel format came back as rubbish and the header said
+ // the texture was zero pixels high.
+ unsigned Surface;
union
{
LegacyDDCOLORKEY CKDestOverlay;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
index 77c6dcddd..d862a2480 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h
@@ -1093,208 +1093,27 @@ WWINLINE Vector4 DX8Wrapper::Convert_Color(unsigned color)
return col;
}
-#if 0
-WWINLINE unsigned int DX8Wrapper::Convert_Color(const Vector3& color, const float alpha)
-{
- WWASSERT(color.X<=1.0f);
- WWASSERT(color.Y<=1.0f);
- WWASSERT(color.Z<=1.0f);
- WWASSERT(alpha<=1.0f);
- WWASSERT(color.X>=0.0f);
- WWASSERT(color.Y>=0.0f);
- WWASSERT(color.Z>=0.0f);
- WWASSERT(alpha>=0.0f);
-
- return D3DCOLOR_COLORVALUE(color.X,color.Y,color.Z,alpha);
-}
-WWINLINE unsigned int DX8Wrapper::Convert_Color(const Vector4& color)
-{
- WWASSERT(color.X<=1.0f);
- WWASSERT(color.Y<=1.0f);
- WWASSERT(color.Z<=1.0f);
- WWASSERT(color.W<=1.0f);
- WWASSERT(color.X>=0.0f);
- WWASSERT(color.Y>=0.0f);
- WWASSERT(color.Z>=0.0f);
- WWASSERT(color.W>=0.0f);
-
- return D3DCOLOR_COLORVALUE(color.X,color.Y,color.Z,color.W);
-}
-#else
+// EA converted colours in x87 assembly, with the rounding mode set to truncate and every register
+// saved by hand around the block. This is the same arithmetic in C: scale by 255 and truncate, so
+// the byte values are the ones the assembler produced.
-// ----------------------------------------------------------------------------
-//
-// Convert RGBA color from float vector to 32 bit integer
-// Note: Color vector needs to be clamped to [0...1] range!
-//
-// ----------------------------------------------------------------------------
-
-WWINLINE unsigned int DX8Wrapper::Convert_Color(const Vector3& color,float alpha)
+WWINLINE unsigned int DX8Wrapper::Convert_Color(const Vector3& color, const float alpha)
{
- const float scale = 255.0;
- unsigned int col;
-
- // Multiply r, g, b and a components (0.0,...,1.0) by 255 and convert to integer. Or the integer values togerher
- // such that 32 bit ingeger has AAAAAAAARRRRRRRRGGGGGGGGBBBBBBBB.
- __asm
- {
- // This block is inlined wherever colors are converted, and VS2022 keeps live
- // values in ANY of these registers across it -- SegLineRendererClass::Render
- // held its point count in EAX and its transform reference in EBX, and both
- // came back as color bytes (the fast_float_trunc lesson, one register wider).
- // Hand back every register the way it was found; col carries the result out.
- push eax
- push ecx
- push edx
- push ebx
- push esi
- push edi
-
- sub esp,20 // space for a, r, g and b float plus fpu rounding mode
-
- // Store the fpu rounding mode
-
- fwait
- fstcw [esp+16] // store control word to stack
- mov eax,[esp+16] // load it to eax
- mov edi,eax // take copy
- and eax,~(1024|2048) // mask out certain bits
- or eax,(1024|2048) // or with precision control value "truncate"
- sub edi,eax // did it change?
- jz skip // .. if not, skip
- mov [esp],eax // .. change control word
- fldcw [esp]
-skip:
-
- // Convert the color
-
- mov esi,dword ptr color
- fld dword ptr[scale]
-
- fld dword ptr[esi] // r
- fld dword ptr[esi+4] // g
- fld dword ptr[esi+8] // b
- fld dword ptr[alpha] // a
- fld st(4)
- fmul st(4),st
- fmul st(3),st
- fmul st(2),st
- fmulp st(1),st
- fistp dword ptr[esp+0] // a
- fistp dword ptr[esp+4] // b
- fistp dword ptr[esp+8] // g
- fistp dword ptr[esp+12] // r
- mov ecx,[esp] // a
- mov eax,[esp+4] // b
- mov edx,[esp+8] // g
- mov ebx,[esp+12] // r
- shl ecx,24 // a << 24
- shl ebx,16 // r << 16
- shl edx,8 // g << 8
- or eax,ecx // (a << 24) | b
- or eax,ebx // (a << 24) | (r << 16) | b
- or eax,edx // (a << 24) | (r << 16) | (g << 8) | b
-
- fstp st(0)
-
- // Restore fpu rounding mode
-
- cmp edi,0 // did we change the value?
- je not_changed // nope... skip now...
- fwait
- fldcw [esp+16];
-not_changed:
- add esp,20
-
- mov col,eax
-
- pop edi
- pop esi
- pop ebx
- pop edx
- pop ecx
- pop eax
- }
- return col;
+ const unsigned int a = (unsigned int)(alpha * 255.0f) & 0xff;
+ const unsigned int r = (unsigned int)(color.X * 255.0f) & 0xff;
+ const unsigned int g = (unsigned int)(color.Y * 255.0f) & 0xff;
+ const unsigned int b = (unsigned int)(color.Z * 255.0f) & 0xff;
+ return (a << 24) | (r << 16) | (g << 8) | b;
}
-// ----------------------------------------------------------------------------
-//
-// Clamp color vertor to [0...1] range
-//
-// ----------------------------------------------------------------------------
-
WWINLINE void DX8Wrapper::Clamp_Color(Vector4& color)
{
- if (!CPUDetectClass::Has_CMOV_Instruction()) {
- for (int i=0;i<4;++i) {
- float f=(color[i]<0.0f) ? 0.0f : color[i];
- color[i]=(f>1.0f) ? 1.0f : f;
- }
- return;
- }
-
- __asm
- {
- // Same contract as Convert_Color above: leave every register as found.
- push edx
- push ebx
- push esi
- push edi
-
- mov esi,dword ptr color
-
- mov edx,0x3f800000
-
- mov edi,dword ptr[esi]
- mov ebx,edi
- sar edi,31
- not edi // mask is now zero if negative value
- and edi,ebx
- cmp edi,edx // if no less than 1.0 set to 1.0
- cmovnb edi,edx
- mov dword ptr[esi],edi
-
- mov edi,dword ptr[esi+4]
- mov ebx,edi
- sar edi,31
- not edi // mask is now zero if negative value
- and edi,ebx
- cmp edi,edx // if no less than 1.0 set to 1.0
- cmovnb edi,edx
- mov dword ptr[esi+4],edi
-
- mov edi,dword ptr[esi+8]
- mov ebx,edi
- sar edi,31
- not edi // mask is now zero if negative value
- and edi,ebx
- cmp edi,edx // if no less than 1.0 set to 1.0
- cmovnb edi,edx
- mov dword ptr[esi+8],edi
-
- mov edi,dword ptr[esi+12]
- mov ebx,edi
- sar edi,31
- not edi // mask is now zero if negative value
- and edi,ebx
- cmp edi,edx // if no less than 1.0 set to 1.0
- cmovnb edi,edx
- mov dword ptr[esi+12],edi
-
- pop edi
- pop esi
- pop ebx
- pop edx
+ for (int i=0;i<4;++i) {
+ const float f=(color[i]<0.0f) ? 0.0f : color[i];
+ color[i]=(f>1.0f) ? 1.0f : f;
}
}
-// ----------------------------------------------------------------------------
-//
-// Convert RGBA color from float vector to 32 bit integer
-//
-// ----------------------------------------------------------------------------
-
WWINLINE unsigned int DX8Wrapper::Convert_Color(const Vector4& color)
{
return Convert_Color(reinterpret_cast<const Vector3&>(color),color[3]);
@@ -1307,7 +1126,6 @@ WWINLINE unsigned int DX8Wrapper::Convert_Color_Clamp(const Vector4& color)
return Convert_Color(reinterpret_cast<const Vector3&>(clamped_color),clamped_color[3]);
}
-#endif
WWINLINE void DX8Wrapper::Set_Alpha (const float alpha, unsigned int &color)
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwdebug.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwdebug.cpp
index 656aa1d33..0ffebd741 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwdebug.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwdebug.cpp
@@ -313,7 +313,7 @@ void WWDebug_Assert_Fail(const char * expr,const char * file, int line)
}
if (code == IDRETRY) {
- _asm int 3;
+ __debugbreak();
return;
}
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwdebug.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwdebug.h
index 50b16bad4..bfd1f9e46 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwdebug.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwdebug.h
@@ -141,11 +141,7 @@ void WWDebug_DBWin32_Message_Handler( const char * message);
** The WWDEBUG_BREAK macro will cause the application to break into
** the debugger...
*/
-#ifdef WWDEBUG
-#define WWDEBUG_BREAK _asm int 0x03
-#else
-#define WWDEBUG_BREAK _asm int 0x03
-#endif
+#define WWDEBUG_BREAK __debugbreak();
/*
** The WWDEBUG_TRIGGER macro can be used to ask the application if
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwmemlog.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwmemlog.cpp
index 88e542f16..2e9f03e78 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwmemlog.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwmemlog.cpp
@@ -44,6 +44,7 @@
#include "vector.h"
#include "fastallocator.h"
#include <windows.h>
+#include <intrin.h>
#define USE_FAST_ALLOCATOR
@@ -313,23 +314,8 @@ WWINLINE void Lock_Mem_Log_Mutex(void)
#if MEMLOG_USE_FASTCRITICALSECTION
- volatile unsigned& nFlag=_MemLogSemaphore;
-
- #define ts_lock _emit 0xF0
- assert(((unsigned)&nFlag % 4) == 0);
-
- __asm mov ebx, [nFlag]
- __asm ts_lock
- __asm bts dword ptr [ebx], 0
- __asm jc The_Bit_Was_Previously_Set_So_Try_Again
- return;
-
- The_Bit_Was_Previously_Set_So_Try_Again:
- ThreadClass::Switch_Thread();
- __asm mov ebx, [nFlag]
- __asm ts_lock
- __asm bts dword ptr [ebx], 0
- __asm jc The_Bit_Was_Previously_Set_So_Try_Again
+ while (_interlockedbittestandset((volatile long *)&_MemLogSemaphore, 0))
+ ThreadClass::Switch_Thread();
#endif
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp
index a67935ca4..b75176a5a 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWDebug/wwprofile.cpp
@@ -101,20 +101,7 @@ inline void WWProfile_Get_Ticks(_int64 * ticks)
#ifdef _UNIX
*ticks = TIMEGETTIME();
#else
- __asm
- {
- push edx;
- push ecx;
- push eax;
- mov ecx,ticks;
- _emit 0Fh
- _emit 31h
- mov [ecx],eax;
- mov [ecx+4],edx;
- pop eax;
- pop ecx;
- pop edx;
- }
+ *ticks = __rdtsc();
#endif
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Except.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Except.cpp
index a1ceb6963..f2828a73b 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Except.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Except.cpp
@@ -184,7 +184,7 @@ int __cdecl _purecall(void)
** Use int3 to cause an exception.
*/
WWDEBUG_SAY(("Pure Virtual Function call. Oh No!\n"));
- _asm int 0x03;
+ __debugbreak();
#endif //_DEBUG_ASSERT
return(return_code);
@@ -288,456 +288,10 @@ static void Add_Txt (char const *txt)
*=============================================================================================*/
void Dump_Exception_Info(EXCEPTION_POINTERS *e_info)
{
- /*
- ** List of possible exceptions
- */
- static const unsigned int _codes[] = {
- EXCEPTION_ACCESS_VIOLATION,
- EXCEPTION_ARRAY_BOUNDS_EXCEEDED,
- EXCEPTION_BREAKPOINT,
- EXCEPTION_DATATYPE_MISALIGNMENT,
- EXCEPTION_FLT_DENORMAL_OPERAND,
- EXCEPTION_FLT_DIVIDE_BY_ZERO,
- EXCEPTION_FLT_INEXACT_RESULT,
- EXCEPTION_FLT_INVALID_OPERATION,
- EXCEPTION_FLT_OVERFLOW,
- EXCEPTION_FLT_STACK_CHECK,
- EXCEPTION_FLT_UNDERFLOW,
- EXCEPTION_ILLEGAL_INSTRUCTION,
- EXCEPTION_IN_PAGE_ERROR,
- EXCEPTION_INT_DIVIDE_BY_ZERO,
- EXCEPTION_INT_OVERFLOW,
- EXCEPTION_INVALID_DISPOSITION,
- EXCEPTION_NONCONTINUABLE_EXCEPTION,
- EXCEPTION_PRIV_INSTRUCTION,
- EXCEPTION_SINGLE_STEP,
- EXCEPTION_STACK_OVERFLOW,
- 0xffffffff
- };
-
- /*
- ** Information about each exception type.
- */
- static char const * _code_txt[] = {
- "Error code: EXCEPTION_ACCESS_VIOLATION\r\r\nDescription: The thread tried to read from or write to a virtual address for which it does not have the appropriate access.",
- "Error code: EXCEPTION_ARRAY_BOUNDS_EXCEEDED\r\r\nDescription: The thread tried to access an array element that is out of bounds and the underlying hardware supports bounds checking.",
- "Error code: EXCEPTION_BREAKPOINT\r\r\nDescription: A breakpoint was encountered.",
- "Error code: EXCEPTION_DATATYPE_MISALIGNMENT\r\r\nDescription: The thread tried to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries; 32-bit values on 4-byte boundaries, and so on.",
- "Error code: EXCEPTION_FLT_DENORMAL_OPERAND\r\r\nDescription: One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.",
- "Error code: EXCEPTION_FLT_DIVIDE_BY_ZERO\r\r\nDescription: The thread tried to divide a floating-point value by a floating-point divisor of zero.",
- "Error code: EXCEPTION_FLT_INEXACT_RESULT\r\r\nDescription: The result of a floating-point operation cannot be represented exactly as a decimal fraction.",
- "Error code: EXCEPTION_FLT_INVALID_OPERATION\r\r\nDescription: Some strange unknown floating point operation was attempted.",
- "Error code: EXCEPTION_FLT_OVERFLOW\r\r\nDescription: The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.",
- "Error code: EXCEPTION_FLT_STACK_CHECK\r\r\nDescription: The stack overflowed or underflowed as the result of a floating-point operation.",
- "Error code: EXCEPTION_FLT_UNDERFLOW\r\r\nDescription: The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.",
- "Error code: EXCEPTION_ILLEGAL_INSTRUCTION\r\r\nDescription: The thread tried to execute an invalid instruction.",
- "Error code: EXCEPTION_IN_PAGE_ERROR\r\r\nDescription: The thread tried to access a page that was not present, and the system was unable to load the page. For example, this exception might occur if a network connection is lost while running a program over the network.",
- "Error code: EXCEPTION_INT_DIVIDE_BY_ZERO\r\r\nDescription: The thread tried to divide an integer value by an integer divisor of zero.",
- "Error code: EXCEPTION_INT_OVERFLOW\r\r\nDescription: The result of an integer operation caused a carry out of the most significant bit of the result.",
- "Error code: EXCEPTION_INVALID_DISPOSITION\r\r\nDescription: An exception handler returned an invalid disposition to the exception dispatcher. Programmers using a high-level language such as C should never encounter this exception.",
- "Error code: EXCEPTION_NONCONTINUABLE_EXCEPTION\r\r\nDescription: The thread tried to continue execution after a noncontinuable exception occurred.",
- "Error code: EXCEPTION_PRIV_INSTRUCTION\r\r\nDescription: The thread tried to execute an instruction whose operation is not allowed in the current machine mode.",
- "Error code: EXCEPTION_SINGLE_STEP\r\r\nDescription: A trace trap or other single-instruction mechanism signaled that one instruction has been executed.",
- "Error code: EXCEPTION_STACK_OVERFLOW\r\r\nDescription: The thread used up its stack.",
- "Error code: ?????\r\r\nDescription: Unknown exception."
- };
-
- DebugString("Dump exception info\n");
-
- /*
- ** Scrap buffer for constructing dump strings
- */
- char scrap [256];
-
- /*
- ** Clear out the dump buffer
- */
- memset(ExceptionText, 0, sizeof (ExceptionText));
-
- /*
- ** If this is the first time through then fix up the imagehelp function pointers since imagehlp.dll
- ** can't be statically linked.
- */
- HINSTANCE imagehelp = LoadLibrary("IMAGEHLP.DLL");
-
- if (imagehelp != NULL) {
- DebugString ("Exception Handler: Found IMAGEHLP.DLL - linking to required functions\n");
- char const *function_name = NULL;
- unsigned long *fptr = (unsigned long*) &_SymCleanup;
- int count = 0;
-
- do {
- function_name = ImagehelpFunctionNames[count];
- if (function_name) {
- *fptr = (unsigned long) GetProcAddress(imagehelp, function_name);
- fptr++;
- count++;
- }
- } while (function_name);
- } else {
- DebugString("Exception Handler: Unable to load IMAGEHLP.DLL\n");
- }
-
-
- /*
- ** Retrieve the programs symbols if they are available
- */
- if (_SymSetOptions != NULL) {
- _SymSetOptions(SYMOPT_DEFERRED_LOADS);
- }
-
- int symload = 0;
- int symbols_available = false;
-
- if (_SymInitialize != NULL && _SymInitialize (GetCurrentProcess(), NULL, false)) {
- DebugString("Exception Handler: Symbols are available\r\n\n");
- symbols_available = true;
- }
-
- if (!symbols_available) {
- DebugString ("Exception Handler: SymInitialize failed with code %d - %s\n", GetLastError(), Last_Error_Text());
- } else {
- if (_SymSetOptions != NULL) {
- _SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME);
- }
-
- char module_name[_MAX_PATH];
- GetModuleFileName(NULL, module_name, sizeof(module_name));
-
- if (_SymLoadModule != NULL) {
- symload = _SymLoadModule(GetCurrentProcess(), NULL, module_name, NULL, 0, 0);
- }
-
- if (!symload) {
- assert(_SymLoadModule != NULL);
- DebugString ("Exception Handler: SymLoad failed for module %s with code %d - %s\n", module_name, GetLastError(), Last_Error_Text());
- }
- }
-
-
- unsigned char symbol [256];
- unsigned long displacement;
- IMAGEHLP_SYMBOL *symptr = (IMAGEHLP_SYMBOL*)&symbol;
-
- /*
- ** Get the exception address and the machine context at the time of the exception
- */
- CONTEXT *context = e_info->ContextRecord;
-
- /*
- ** The following are set for access violation only
- */
- int access_read_write=-1;
- unsigned long access_address = 0;
-
- if (e_info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
- DebugString("Exception Handler: Exception is access violation\n");
- access_read_write = e_info->ExceptionRecord->ExceptionInformation[0]; // 0=read, 1=write
- access_address = e_info->ExceptionRecord->ExceptionInformation[1];
- } else {
- DebugString ("Exception Handler: Exception code is %d\n", e_info->ExceptionRecord->ExceptionCode);
- }
-
- /*
- ** Match the exception type with the error string and print it out
- */
- int i; // used after the loop to index _code_txt, so it can't be loop-scoped
- for (i=0 ; _codes[i] != 0xffffffff ; i++) {
- if (_codes[i] == e_info->ExceptionRecord->ExceptionCode) {
- DebugString("Exception Handler: Found exception description\n");
- break;
- }
- }
- Add_Txt(_code_txt[i]);
- Add_Txt("\r\n");
-
- /*
- ** For access violations, print out the violation address and if it was read or write.
- */
- if (e_info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
- snprintf(scrap, ARRAY_SIZE(scrap), "Access address:%08X ", access_address);
- Add_Txt(scrap);
- if (access_read_write) {
- Add_Txt("was written to.\r\n");
- } else {
- Add_Txt("was read from.\r\n");
- }
- }
-
-
- /*
- ** If symbols are available, print out the exception eip address and the name of the
- ** function it represents.
- */
- memset(symptr, 0, sizeof (IMAGEHLP_SYMBOL));
- symptr->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
- symptr->MaxNameLength = 256-sizeof (IMAGEHLP_SYMBOL);
- symptr->Size = 0;
- symptr->Address = context->Eip;
-
- if (!IsBadCodePtr((FARPROC)context->Eip)) {
- if (_SymGetSymFromAddr != NULL && _SymGetSymFromAddr (GetCurrentProcess(), context->Eip, &displacement, symptr)) {
- snprintf (scrap, ARRAY_SIZE(scrap), "Exception occurred at %08X - %s + %08X\r\n", context->Eip, symptr->Name, displacement);
- } else {
- DebugString ("Exception Handler: Failed to get symbol for EIP\r\n");
- if (_SymGetSymFromAddr != NULL) {
- DebugString ("Exception Handler: SymGetSymFromAddr failed with code %d - %s\n", GetLastError(), Last_Error_Text());
- }
- snprintf (scrap, ARRAY_SIZE(scrap), "Exception occurred at %08X\r\n", context->Eip);
- }
- } else {
- DebugString ("Exception Handler: context->Eip is bad code pointer\n");
- }
-
- Add_Txt (scrap);
-
- /*
- ** Try to walk the stack. It might work....
- */
- DebugString("Stack walk...\n");
- Add_Txt("\r\n Stack walk...\r\n");
-
- unsigned long return_addresses[256];
- int num_addresses = Stack_Walk(return_addresses, 256, context);
-
- if (num_addresses) {
- for (int s=0 ; s<num_addresses ; s++) {
- unsigned long temp_addr = return_addresses[s];
- displacement = 0;
-
- for (int space = 0 ; space <= s ; space++) {
- Add_Txt(" ");
- }
-
- if (symbols_available) {
- symptr->SizeOfStruct = sizeof(symbol);
- symptr->MaxNameLength = 128;
- symptr->Size = 0;
- symptr->Address = temp_addr;
-
- if (_SymGetSymFromAddr != NULL && _SymGetSymFromAddr (GetCurrentProcess(), temp_addr, &displacement, symptr)) {
- char symbuf[256];
- snprintf(symbuf, ARRAY_SIZE(symbuf), "%s + %08X\r\n", symptr->Name, displacement);
- Add_Txt(symbuf);
- }
- } else {
- char symbuf[256];
- snprintf(symbuf, ARRAY_SIZE(symbuf), "%08x\r\n", temp_addr);
- Add_Txt(symbuf);
- }
- }
-
- Add_Txt("\r\n\r\n");
- } else {
- DebugString("Stack walk failed!\n");
- Add_Txt("Stack walk failed!\r\n");
- }
-
-
-#if (0) //Don't have this info yet for Renegade.
- /*
- ** Add in the version info.
- */
- snprintf(scrap, ARRAY_SIZE(scrap), "\r\nVersion %s\r\n", Version_Name());
- Add_Txt(scrap);
-
- snprintf(scrap, ARRAY_SIZE(scrap), "Internal Version %s\r\n", VerNum.Version_Name());
- Add_Txt(scrap);
-
- char buildinfo[128];
- buildinfo[0] = 0;
- Build_Date_String(buildinfo, 128);
-
- char build_number[128];
- char build_name[128];
-
-#endif //(0)
-
- if (AppVersionCallback) {
- snprintf(scrap, ARRAY_SIZE(scrap), "%s\r\n\r\n", AppVersionCallback());
- Add_Txt(scrap);
- }
-
- /*
- ** Thread list.
- */
- Add_Txt("Thread list\r\n");
-
- /*
- ** Get the thread info from ThreadClass.
- */
- for (int thread = 0 ; thread < ThreadList.Count() ; thread++) {
- snprintf(scrap, ARRAY_SIZE(scrap), " ID: %08X - %s", ThreadList[thread]->ThreadID, ThreadList[thread]->ThreadName);
- Add_Txt(scrap);
- if (GetCurrentThreadId() == ThreadList[thread]->ThreadID) {
- Add_Txt(" ***CURRENT THREAD***");
- }
- Add_Txt("\r\n");
- }
-
- /*
- ** CPU type
- */
- snprintf(scrap, ARRAY_SIZE(scrap), "\r\nCPU %s, %d Mhz, Vendor: %s\r\n", (char*)CPUDetectClass::Get_Processor_String(), Get_RDTSC_CPU_Speed(), (char*)CPUDetectClass::Get_Processor_Manufacturer_Name());
- Add_Txt(scrap);
-
-
- Add_Txt("\r\nDetails:\r\n");
-
- DebugString("Register dump...\n");
-
- /*
- ** Dump the registers.
- */
- snprintf(scrap, ARRAY_SIZE(scrap), "Eip:%08X\tEsp:%08X\tEbp:%08X\r\n", context->Eip, context->Esp, context->Ebp);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), "Eax:%08X\tEbx:%08X\tEcx:%08X\r\n", context->Eax, context->Ebx, context->Ecx);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), "Edx:%08X\tEsi:%08X\tEdi:%08X\r\n", context->Edx, context->Esi, context->Edi);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), "EFlags:%08X \r\n", context->EFlags);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), "CS:%04x SS:%04x DS:%04x ES:%04x FS:%04x GS:%04x\r\n", context->SegCs, context->SegSs, context->SegDs, context->SegEs, context->SegFs, context->SegGs);
- Add_Txt(scrap);
-
-
- /*
- ** Now the FP registers.
- */
- Add_Txt("\r\nFloating point status\r\n");
- snprintf(scrap, ARRAY_SIZE(scrap), " Control word: %08x\r\n", context->FloatSave.ControlWord);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), " Status word: %08x\r\n", context->FloatSave.StatusWord);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), " Tag word: %08x\r\n", context->FloatSave.TagWord);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), " Error Offset: %08x\r\n", context->FloatSave.ErrorOffset);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), " Error Selector: %08x\r\n", context->FloatSave.ErrorSelector);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), " Data Offset: %08x\r\n", context->FloatSave.DataOffset);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), " Data Selector: %08x\r\n", context->FloatSave.DataSelector);
- Add_Txt(scrap);
- snprintf(scrap, ARRAY_SIZE(scrap), " Cr0NpxState: %08x\r\n", context->FloatSave.Spare0); // SDK renamed Cr0NpxState -> Spare0
- Add_Txt(scrap);
-
- for (int fp=0 ; fp<SIZE_OF_80387_REGISTERS / 10 ; fp++) {
- snprintf(scrap, ARRAY_SIZE(scrap), "ST%d : ", fp);
- Add_Txt(scrap);
- for (int b=0 ; b<10 ; b++) {
- snprintf(scrap, ARRAY_SIZE(scrap), "%02X", context->FloatSave.RegisterArea[(fp*10) + b]);
- Add_Txt(scrap);
- }
-
- void *fp_data_ptr = (void*)(&context->FloatSave.RegisterArea[fp*10]);
- double fp_value;
-
- /*
- ** Convert FP dump from temporary real value (10 bytes) to double (8 bytes).
- */
- _asm {
- push eax
- mov eax,fp_data_ptr
- fld tbyte ptr [eax]
- fstp qword ptr [fp_value]
- pop eax
- }
- snprintf(scrap, ARRAY_SIZE(scrap), " %+#.17e\r\n", fp_value);
- Add_Txt(scrap);
- }
-
- /*
- ** Dump the bytes at EIP. This will make it easier to match the crash address with later versions of the game.
- */
- DebugString("EIP bytes dump...\n");
- // This whole block writes into a 256 byte buffer with no bound, in the handler that is trying to
- // report a crash. Thirty-two bytes at three characters each plus the header is close enough to
- // 256 that a symbol name on the stack pass below pushed it over.
- snprintf(scrap, ARRAY_SIZE(scrap), "\r\nBytes at CS:EIP (%08X) : ", context->Eip);
-
- unsigned char *eip_ptr = (unsigned char *) (context->Eip);
- char bytestr[32];
-
- for (int c = 0 ; c < 32 ; c++) {
- if (IsBadReadPtr(eip_ptr, 1)) {
- strlcat(scrap, "?? ", ARRAY_SIZE(scrap));
- } else {
- snprintf(bytestr, ARRAY_SIZE(bytestr), "%02X ", *eip_ptr);
- strlcat(scrap, bytestr, ARRAY_SIZE(scrap));
- }
- eip_ptr++;
- }
-
- strlcat(scrap, "\r\n\r\n", ARRAY_SIZE(scrap));
- Add_Txt(scrap);
-
- /*
- ** Dump out the values on the stack.
- */
- DebugString("Stack dump...\n");
- Add_Txt("Stack dump (* indicates possible code address) :\r\n");
- unsigned long *stackptr = (unsigned long*) context->Esp;
-
- for (int j=0 ; j<2048 ; j++) {
- if (IsBadReadPtr(stackptr, 4)) {
- /*
- ** The stack contents cannot be read so just print up question marks.
- */
- snprintf(scrap, ARRAY_SIZE(scrap), "%08X: ", stackptr);
- strlcat(scrap, "????????\r\n", ARRAY_SIZE(scrap));
- } else {
- /*
- ** If this stack address is in our memory space then try to match it with a code symbol.
- */
- if (IsBadCodePtr((FARPROC)*stackptr)) {
- snprintf(scrap, ARRAY_SIZE(scrap), "%08X: %08X ", stackptr, *stackptr);
- strlcat(scrap, "DATA_PTR\r\n", ARRAY_SIZE(scrap));
- } else {
- snprintf(scrap, ARRAY_SIZE(scrap), "%08X: %08X", stackptr, *stackptr);
-
- if (symbols_available) {
- symptr->SizeOfStruct = sizeof(symbol);
- symptr->MaxNameLength = 128;
- symptr->Size = 0;
- symptr->Address = *stackptr;
-
- if (_SymGetSymFromAddr != NULL && _SymGetSymFromAddr (GetCurrentProcess(), *stackptr, &displacement, symptr)) {
- char symbuf[256];
- snprintf(symbuf, ARRAY_SIZE(symbuf), " - %s + %08X", symptr->Name, displacement);
- strlcat(scrap, symbuf, ARRAY_SIZE(scrap));
- }
- } else {
- strlcat (scrap, " *", ARRAY_SIZE(scrap));
- }
- strlcat (scrap, "\r\n", ARRAY_SIZE(scrap));
- }
- }
- Add_Txt(scrap);
- stackptr++;
- }
-
- /*
- ** Unload the symbols.
- */
- if (symbols_available) {
- if (_SymCleanup != NULL) {
- _SymCleanup (GetCurrentProcess());
- }
-
- if (symload) {
- if (_SymUnloadModule != NULL) {
- _SymUnloadModule(GetCurrentProcess(), NULL);
- }
- }
-
- }
-
- if (imagehelp) {
- FreeLibrary(imagehelp);
- }
-
- Add_Txt ("\r\n\r\n");
+ // Westwood's own dump read the x86 CONTEXT register by register and was 32-bit assembly below
+ // this line. Nothing in the game reaches this handler: WinMain installs its own, and
+ // StackDump.cpp writes the crash log.
+ Add_Txt("Westwood exception dump is not implemented.\r\n");
}
@@ -1216,77 +770,9 @@ bool Lookup_Symbol(void *code_ptr, char *symbol, int &displacement)
*=============================================================================================*/
int Stack_Walk(unsigned long *return_addresses, int num_addresses, CONTEXT *context)
{
- static HINSTANCE _imagehelp = (HINSTANCE) -1;
-
- /*
- ** If this is the first time through then fix up the imagehelp function pointers since imagehlp.dll
- ** can't be statically linked.
- */
- if (ImageHelp == (HINSTANCE)-1) {
- Load_Image_Helper();
- }
-
- /*
- ** If there is no debug support .dll available then we can't walk the stack.
- */
- if (ImageHelp == NULL) {
- return(0);
- }
-
- /*
- ** Set up the stack frame structure for the start point of the stack walk (i.e. here).
- */
- STACKFRAME stack_frame;
- memset(&stack_frame, 0, sizeof(stack_frame));
-
- unsigned long reg_eip, reg_ebp, reg_esp;
-
- __asm {
-here:
- lea eax,here
- mov reg_eip,eax
- mov reg_ebp,ebp
- mov reg_esp,esp
- }
-
- stack_frame.AddrPC.Mode = AddrModeFlat;
- stack_frame.AddrPC.Offset = reg_eip;
- stack_frame.AddrStack.Mode = AddrModeFlat;
- stack_frame.AddrStack.Offset = reg_esp;
- stack_frame.AddrFrame.Mode = AddrModeFlat;
- stack_frame.AddrFrame.Offset = reg_ebp;
-
- /*
- ** Use the context struct if it was provided.
- */
- if (context) {
- stack_frame.AddrPC.Offset = context->Eip;
- stack_frame.AddrStack.Offset = context->Esp;
- stack_frame.AddrFrame.Offset = context->Ebp;
- }
-
- int pointer_index = 0;
-
- /*
- ** Walk the stack by the requested number of return address iterations.
- */
- for (int i = 0; i < num_addresses + 1; i++) {
- if (_StackWalk(IMAGE_FILE_MACHINE_I386, GetCurrentProcess(), GetCurrentThread(), &stack_frame, NULL, NULL, _SymFunctionTableAccess, _SymGetModuleBase, NULL)) {
-
- /*
- ** First result will always be the return address we were called from.
- */
- if (i==0 && context == NULL) {
- continue;
- }
- unsigned long return_address = stack_frame.AddrReturn.Offset;
- return_addresses[pointer_index++] = return_address;
- } else {
- break;
- }
- }
-
- return(pointer_index);
+ // Westwood's walker was 32-bit assembly seeding an imagehlp STACKFRAME, and its addresses do
+ // not fit the caller's unsigned longs any more. Nothing calls it; StackDump.cpp is the walker.
+ return 0;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/TARGA.CPP b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/TARGA.CPP
index 77545329b..e571dff40 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/TARGA.CPP
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/TARGA.CPP
@@ -827,43 +827,11 @@ void Targa::XFlip(void)
static __forceinline void _swapBytes(char *p1, char *p2, unsigned count)
{
- _asm
+ while (count--)
{
- mov esi,[p1]
- mov edi,[p2]
- mov ebx,[count]
- mov ecx,ebx
- shr ecx,4
- jz lessThan16
- lp:
- mov eax,dword ptr [esi]
- mov edx,dword ptr [esi+4]
- xchg eax,dword ptr [edi]
- xchg edx,dword ptr [edi+4]
- mov dword ptr [esi],eax
- mov dword ptr [esi+4],edx
- mov eax,dword ptr [esi+8]
- mov edx,dword ptr [esi+12]
- xchg eax,dword ptr [edi+8]
- xchg edx,dword ptr [edi+12]
- mov dword ptr [esi+8],eax
- mov dword ptr [esi+12],edx
- add esi,16
- add edi,16
- dec ecx
- jnz lp
- lessThan16:
- and ebx,15
- lpLessThan16:
- jz done
- mov al,byte ptr [esi]
- xchg al,byte ptr [edi]
- mov byte ptr [edi],al
- inc esi
- inc edi
- dec ebx
- jmp lpLessThan16
- done:
+ char swapped = *p1;
+ *p1++ = *p2;
+ *p2++ = swapped;
}
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Vector.H b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Vector.H
index af9892e76..76f72a236 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Vector.H
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/Vector.H
@@ -317,7 +317,7 @@ template<class T>
inline int VectorClass<T>::ID(T const * ptr)
{
if (!IsValid) return(0);
- return(((unsigned long)ptr - (unsigned long)&(*this)[0]) / sizeof(T));
+ return((int)(((uintptr_t)ptr - (uintptr_t)&(*this)[0]) / sizeof(T)));
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/blitblit.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/blitblit.h
index 2271db44a..e3f9a8e66 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/blitblit.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/blitblit.h
@@ -445,170 +445,9 @@ class BlitTransLucent75 : public Blitter {
/*
-** Assembly versions of some of the templated blitter object functions. Borland and
-** Visual C++ support a compatible inline-assembly formats. However, Borland compiler
-** does not allow inline-assembly to be part of an inline function -- go figure.
-** It will still compile, it just generates warning messages.
+** EA had assembly specializations of the blitters above for 8 and 16 bit surfaces here, in
+** 32-bit inline __asm. The templates they specialized are what the build uses.
*/
-#if defined(_MSC_VER)
-
-inline void BlitTrans<unsigned char>::BlitForward(void * dest, void const * source, int len) const
-{
- __asm {
- mov esi,[source]
- mov edi,[dest]
- mov ecx,[len]
- dec edi
- inc ecx
- }
-again:
- __asm {
- dec ecx
- jz fini
- mov al,[esi]
- inc edi
- inc esi
- test al,al
- jz again
- mov [edi],al
- jmp again
- }
-fini:;
-}
-
-
-inline void BlitTransXlat<unsigned short>::BlitForward(void * dest, void const * source, int len) const
-{
- unsigned short const * xlator = TranslateTable;
-
- __asm {
- mov ebx,[xlator]
- mov ecx,[len]
- inc ecx
- mov edi,[dest]
- sub edi,2
- mov esi,[source]
- xor eax,eax
- }
-again:
- __asm {
- dec ecx
- jz over
- add edi,2
- mov al,[esi]
- inc esi
- or al,al
- jz again
- mov dx,[ebx+eax*2]
- mov [edi],dx
- jmp again
- }
-over:;
-}
-
-
-inline void BlitTransRemapXlat<unsigned short>::BlitForward(void * dest, void const * source, int len) const
-{
- unsigned short const * translator = TranslateTable;
- unsigned char const * remapper = RemapTable;
-
- __asm {
- mov ecx,[len]
- mov edi,[dest]
- sub edi,2
- mov esi,[source]
- mov ebx,[remapper]
- mov edx,[translator]
- xor eax,eax
- }
-
- /*
- ** This block is 11 cycles per pixel, if not transparent, and 5
- ** cycles per pixel, if transparent.
- */
-again:
- __asm {
- dec ecx
- jz over
- add edi,2
- xor eax,eax
- lodsb
- or al,al
- jz again
- mov al,[ebx+eax] // First remap step (8 bit to 8 bit).
- mov ax,[edx+eax*2] // Second remap step (8 bit to 16 bit).
- mov [edi],ax
- jmp again
- }
-over:;
-}
-
-
-inline void BlitTransZRemapXlat<unsigned short>::BlitForward(void * dest, void const * source, int len) const
-{
- unsigned short const * translator = TranslateTable;
- unsigned char const * remapper = *RemapTable;
-
- __asm {
- mov ecx,[len]
- mov edi,[dest]
- sub edi,2
- mov esi,[source]
- mov ebx,[remapper]
- mov edx,[translator]
- xor eax,eax
- }
-
- /*
- ** This block is 11 cycles per pixel, if not transparent, and 5
- ** cycles per pixel, if transparent.
- */
-again:
- __asm {
- dec ecx
- jz over
- add edi,2
- xor eax,eax
- lodsb
- or al,al
- jz again
- mov al,[ebx+eax] // First remap step (8 bit to 8 bit).
- mov ax,[edx+eax*2] // Second remap step (8 bit to 16 bit).
- mov [edi],ax
- jmp again
- }
-over:;
-}
-
-
-inline void BlitPlainXlat<unsigned short>::BlitForward(void * dest, void const * source, int len) const
-{
- unsigned short const * remapper = TranslateTable;
- __asm {
- mov ebx,[remapper]
- mov ecx,[len]
- mov esi,[source]
- mov edi,[dest]
- sub edi,2
- }
-again:
- /*
- ** This block processes pixels at 7 clocks per pixel.
- */
- __asm {
- xor eax,eax
- add edi,2
- mov al,[esi]
- inc esi
- mov ax,[ebx+eax*2]
- mov [edi],ax
- dec ecx
- jnz again
- }
-}
-
-
-#endif
#endif
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/cpudetect.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/cpudetect.cpp
index 2da2c1523..a740afc8a 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/cpudetect.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/cpudetect.cpp
@@ -23,6 +23,7 @@
#include "mpu.h"
#pragma warning (disable : 4201) // Nonstandard extension - nameless struct
#include <windows.h>
+#include <intrin.h>
#include "systimer.h"
#ifdef _UNIX
@@ -123,46 +124,18 @@ const char* CPUDetectClass::Get_Processor_Manufacturer_Name()
return ManufacturerNames[ProcessorManufacturer];
}
-#define ASM_RDTSC _asm _emit 0x0f _asm _emit 0x31
-
static unsigned Calculate_Processor_Speed(__int64& ticks_per_second)
{
- struct {
- unsigned timer0_h;
- unsigned timer0_l;
- unsigned timer1_h;
- unsigned timer1_l;
- } Time;
-
-#ifdef WIN32
- __asm {
- ASM_RDTSC;
- mov Time.timer0_h, eax
- mov Time.timer0_l, edx
- }
-#elif defined(_UNIX)
- __asm__("rdtsc");
- __asm__("mov %eax, __Time.timer1_h");
- __asm__("mov %edx, __Time.timer1_l");
-#endif
+ const unsigned __int64 timer0=__rdtsc();
+ unsigned __int64 timer1=timer0;
unsigned start=TIMEGETTIME();
unsigned elapsed;
while ((elapsed=TIMEGETTIME()-start)<200) {
-#ifdef WIN32
- __asm {
- ASM_RDTSC;
- mov Time.timer1_h, eax
- mov Time.timer1_l, edx
- }
-#elif defined(_UNIX)
- __asm__ ("rdtsc");
- __asm__("mov %eax, __Time.timer1_h");
- __asm__("mov %edx, __Time.timer1_l");
-#endif
+ timer1=__rdtsc();
}
- __int64 t=*(__int64*)&Time.timer1_h-*(__int64*)&Time.timer0_h;
+ __int64 t=(__int64)(timer1-timer0);
ticks_per_second=(__int64)((1000.0/(double)elapsed)*(double)t); // Ticks per second
return unsigned((double)t/(double)(elapsed*1000));
}
@@ -820,54 +793,9 @@ void CPUDetectClass::Init_Processor_String()
void CPUDetectClass::Init_CPUID_Instruction()
{
- unsigned long cpuid_available=0;
-
- // The pushfd/popfd commands are done using emits
- // because CodeWarrior seems to have problems with
- // the command (huh?)
-
-#ifdef WIN32
- __asm
- {
- mov cpuid_available, 0 // clear flag
- push ebx
- pushfd
- pop eax
- mov ebx, eax
- xor eax, 0x00200000
- push eax
- popfd
- pushfd
- pop eax
- xor eax, ebx
- je done
- mov cpuid_available, 1
- done:
- push ebx
- popfd
- pop ebx
- }
-#elif defined(_UNIX)
- __asm__(" mov $0, __cpuid_available"); // clear flag
- __asm__(" push %ebx");
- __asm__(" pushfd");
- __asm__(" pop %eax");
- __asm__(" mov %eax, %ebx");
- __asm__(" xor 0x00200000, %eax");
- __asm__(" push %eax");
- __asm__(" popfd");
- __asm__(" pushfd");
- __asm__(" pop %eax");
- __asm__(" xor %ebx, %eax");
- __asm__(" je done");
- __asm__(" mov $1, __cpuid_available");
- goto done; // just to shut the compiler up
- done:
- __asm__(" push %ebx");
- __asm__(" popfd");
- __asm__(" pop %ebx");
-#endif
- HasCPUIDInstruction=!!cpuid_available;
+ // EA toggled EFLAGS.ID to find out. Every processor that runs SSE2 code, which both builds
+ // require, has CPUID.
+ HasCPUIDInstruction=true;
}
void CPUDetectClass::Init_Processor_Features()
@@ -969,44 +897,14 @@ bool CPUDetectClass::CPUID(
{
if (!Has_CPUID_Instruction()) return false; // Most processors since 486 have CPUID...
- unsigned u_eax;
- unsigned u_ebx;
- unsigned u_ecx;
- unsigned u_edx;
+ // ECX is zeroed like EA's asm did: leaf 4's cache walk reads it as the sub-leaf.
+ int registers[4];
+ __cpuidex(registers, (int)cpuid_type, 0);
-#ifdef WIN32
- __asm
- {
- pushad
- mov eax, [cpuid_type]
- xor ebx, ebx
- xor ecx, ecx
- xor edx, edx
- cpuid
- mov [u_eax], eax
- mov [u_ebx], ebx
- mov [u_ecx], ecx
- mov [u_edx], edx
- popad
- }
-#elif defined(_UNIX)
- __asm__("pusha");
- __asm__("mov __cpuid_type, %eax");
- __asm__("xor %ebx, %ebx");
- __asm__("xor %ecx, %ecx");
- __asm__("xor %edx, %edx");
- __asm__("cpuid");
- __asm__("mov %eax, __u_eax");
- __asm__("mov %ebx, __u_ebx");
- __asm__("mov %ecx, __u_ecx");
- __asm__("mov %edx, __u_edx");
- __asm__("popa");
-#endif
-
- u_eax_=u_eax;
- u_ebx_=u_ebx;
- u_ecx_=u_ecx;
- u_edx_=u_edx;
+ u_eax_=(unsigned)registers[0];
+ u_ebx_=(unsigned)registers[1];
+ u_ecx_=(unsigned)registers[2];
+ u_edx_=(unsigned)registers[3];
return true;
}
@@ -1031,7 +929,9 @@ void CPUDetectClass::Init_Processor_Log()
(OSVersionBuildNumber&0xff0000)>>16,
(OSVersionBuildNumber&0xffff)));
#ifdef WIN32
- SYSLOG(("OS-Info: %s\r\n", OSVersionExtraInfo));
+ // Peek_Buffer, not the object: a StringClass handed to a varargs %s is passed by address on x64
+ // and the formatter then reads the object as if it were the characters.
+ SYSLOG(("OS-Info: %s\r\n", OSVersionExtraInfo.Peek_Buffer()));
#elif defined(_UNIX)
SYSLOG(("OS-Info: %s\r\n", OSVersionExtraInfo.Peek_Buffer()));
#endif
@@ -1046,7 +946,7 @@ void CPUDetectClass::Init_Processor_Log()
case 3: cpu_type="*Intel Reserved*"; break;
}
#ifdef WIN32
- SYSLOG(("Processor type: %s\r\n", cpu_type));
+ SYSLOG(("Processor type: %s\r\n", cpu_type.Peek_Buffer()));
#elif defined(_UNIX)
SYSLOG(("Processor type: %s\r\n", cpu_type.Peek_Buffer()));
#endif
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/lcw.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/lcw.cpp
index 8d0578b85..7914aee3e 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/lcw.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/lcw.cpp
@@ -38,6 +38,7 @@
#include "always.h"
#include "lcw.h"
+#include <string.h>
/***************************************************************************
* LCW_Uncomp -- Decompress an LCW encoded data block. *
@@ -217,245 +218,53 @@ int LCW_Comp(void const * source, void * dest, int datasize)
return ((int)(dest_ptr - (unsigned char *)dest));
}
-#ifdef _WINDOWS
- long inlen = 0;
- long a1stdest = 0;
- long a1stsrc = 0;
- long lenoff = 0;
- long ndest = 0;
- long count = 0;
- long matchoff = 0;
- long end_of_data =0;
-#ifdef _DEBUG
- inlen = inlen;
- a1stdest = a1stdest;
- a1stsrc = a1stsrc;
- lenoff = lenoff;
- ndest = ndest;
- count = count;
- matchoff = matchoff;
- end_of_data = end_of_data;
-#endif
-
- __asm {
- cld // make sure all string commands are forward
- mov edi,[dest]
- mov esi,[source]
- mov edx,[datasize] // get length of data to compress
-
-// compress data to the following codes in the format b = byte, w = word
-// n = byte code pulled from compressed data
-// Bit field of n command description
-// n=0xxxyyyy,yyyyyyyy short run back y bytes and run x+3
-// n=10xxxxxx,n1,n2,...,nx+1 med length copy the next x+1 bytes
-// n=11xxxxxx,w1 med run run x+3 bytes from offset w1
-// n=11111111,w1,w2 long run run w1 bytes from offset w2
-// n=10000000 end end of data reached
-
- mov ebx,esi
- add ebx,edx
- mov [end_of_data],ebx
- mov [inlen],1 //; set the in-length flag
- mov [a1stdest],edi //; save original dest offset for size calc
- mov [a1stsrc],esi //; save offset of first byte of data
- mov [lenoff],edi //; save the offset of the legth of this len
- sub eax,eax
- mov al,081h //; the first byte is always a len
- stosb //; write out a len of 1
- lodsb //; get the byte
- stosb //; save it
- }
-
-loopstart:
- __asm {
- mov [ndest],edi //; save offset of compressed data
- mov edi,[a1stsrc] //; get the offset to the first byte of data
- mov [count],1 //; set the count of run to 0
- }
-searchloop:
- __asm {
- sub eax,eax
- mov al,[esi] //; get the current byte of data
- cmp al,[esi+64]
- jne short notrunlength
-
- mov ebx,edi
-
- mov edi,esi
- mov ecx,[end_of_data]
- sub ecx,edi
- repe scasb
- dec edi
- mov ecx,edi
- sub ecx,esi
- cmp ecx,65
- jb short notlongenough
-
- mov [inlen],0 //; clear the in-length flag
-// mov [DWORD PTR inlen],0 //; clear the in-length flag
- mov esi,edi
- mov edi,[ndest] //; get the offset of our compressed data
-
- mov ah,al
- mov al,0FEh
- stosb
- xchg ecx,eax
- stosw
- mov al,ch
- stosb
-
- mov [ndest],edi //; save offset of compressed data
- mov edi,ebx
- jmp searchloop
- }
-notlongenough:
- __asm {
- mov edi,ebx
- }
-notrunlength:
-oploop:
- __asm {
- mov ecx,esi //; get the address of the last byte +1
- sub ecx,edi //; get the total number of bytes left to comp
- jz short searchdone
-
- repne scasb //; look for a match
- jne short searchdone //; if we don't find one we're done
-
- mov ebx,[count]
- mov ah,[esi+ebx-1]
- cmp ah,[edi+ebx-2]
-
- jne oploop
-
- mov edx,esi //; save this spot for the next search
- mov ebx,edi //; save this spot for the length calc
- dec edi //; back up one for compare
- mov ecx,[end_of_data] //; get the end of data
- sub ecx,esi //; sub current source for max len
-
- repe cmpsb //; see how many bytes match
-
- jne short notend //; if found mismatch then di - bx = match count
-
- inc edi //; else cx = 0 and di + 1 - bx = match count
- }
-notend:
- __asm {
- mov esi,edx //; restore si
- mov eax,edi //; get the dest
- sub eax,ebx //; sub the start for total bytes that match
- mov edi,ebx //; restore dest
- cmp eax,[count] //; see if its better than before
- jb searchloop //; if not keep looking
-
- mov [count],eax //; if so keep the count
- dec ebx //; back it up for the actual match offset
- mov [matchoff],ebx //; save the offset for later
- jmp searchloop //; loop until we searched it all
- }
-searchdone:
- __asm {
- mov ecx,[count] //; get the count of the longest run
- mov edi,[ndest] //; get the offset of our compressed data
- cmp ecx,2 //; see if its not enough run to matter
- jbe short lenin //; if its 0,1, or 2 its too small
-
- cmp ecx,10 //; if not, see if it would fit in a short
- ja short medrun //; if not, see if its a medium run
-
- mov eax,esi //; if its short get the current address
- sub eax,[matchoff] //; sub the offset of the match
- cmp eax,0FFFh //; if its less than 12 bits its a short
- ja short medrun //; if its not, its a medium
- }
-//shortrun:
- __asm {
- sub ebx,ebx
- mov bl,cl //; get the length (3-10)
- sub bl,3 //; sub 3 for a 3 bit number 0-7
- shl bl,4 //; shift it left 4
- add ah,bl //; add in the length for the high nibble
- xchg ah,al //; reverse the bytes for a word store
- jmp short srunnxt //; do the run fixup code
- }
-medrun:
- __asm {
- cmp ecx,64 //; see if its a short run
- ja short longrun //; if not, oh well at least its long
-
- sub cl,3 //; back down 3 to keep it in 6 bits
- or cl,0C0h //; the highest bits are always on
- mov al,cl //; put it in al for the stosb
- stosb //; store it
- jmp short medrunnxt //; do the run fixup code
- }
-lenin:
- __asm {
- cmp [inlen],0 //; is it doing a length?
-// cmp [DWORD PTR inlen],0 //; is it doing a length?
- jnz short len //; if so, skip code
- }
-lenin1:
- __asm {
- mov [lenoff],edi //; save the length code offset
- mov al,80h //; set the length to 0
- stosb //; save it
- }
-len:
- __asm {
- mov ebx,[lenoff] //; get the offset of the length code
- cmp [ebx],0BFh //; see if its maxed out
-// cmp [BYTE PTR ebx],0BFh //; see if its maxed out
- je lenin1 //; if so put out a new len code
- }
-//stolen:
- __asm {
- inc [ebx] //; inc the count code
-// inc [BYTE PTR ebx] //; inc the count code
- lodsb //; get the byte
- stosb //; store it
- mov [inlen],1 //; we are now in a length so save it
-// mov [DWORD PTR inlen],1 //; we are now in a length so save it
- jmp short nxt //; do the next code
- }
-longrun:
- __asm {
- mov al,0ffh //; its a long so set a code of FF
- stosb //; store it
-
- mov eax,[count] //; send out the count
- stosw //; store it
- }
-medrunnxt:
- __asm {
- mov eax,[matchoff] //; get the offset
- sub eax,[a1stsrc] //; make it relative tot he start of data
- }
-srunnxt:
- __asm {
- stosw //; store it
- //; this code common to all runs
- add esi,[count] //; add in the length of the run to the source
- mov [inlen],0 //; set the in leght flag to false
-// mov [DWORD PTR inlen],0 //; set the in leght flag to false
- }
-nxt:
- __asm {
- cmp esi,[end_of_data] //; see if we did the whole pic
- jae short outofhere //; if so, cool! were done
+ /*
+ ** EA's encoder was 32-bit assembly and searched back for matches; this one
+ ** emits two of the codes LCW_Uncomp reads, 0xfe long runs and 0x80|n literal
+ ** copies, so it packs runs but not back references. Nothing in the game
+ ** compresses with it - the archives are read, not written - and the tests in
+ ** test_wwlib round-trip it. A run shorter than eight bytes stays literal
+ ** because the long-run decoder aligns to four bytes before it counts and
+ ** would underflow on a tiny count.
+ */
+ {
+ enum { MIN_RUN = 8, MAX_RUN = 0xffff, MAX_LITERAL = 0x3f };
+ unsigned char const * source_ptr = (unsigned char const *)source;
+ unsigned char const * source_end = source_ptr + datasize;
+ unsigned char * dest_ptr = (unsigned char *)dest;
+ unsigned char const * literal_start = source_ptr;
- jmp loopstart
- }
-outofhere:
- __asm {
- mov ax,080h //; remember to send an end of data code
- stosb //; store it
- mov eax,edi //; get the last compressed address
- sub eax,[a1stdest] //; sub the first for the compressed size
- mov [retval],eax
+ while (source_ptr <= source_end) {
+ int run = 1;
+ if (source_ptr < source_end) {
+ while (source_ptr + run < source_end && run < MAX_RUN && source_ptr[run] == source_ptr[0]) {
+ ++run;
+ }
+ }
+ bool const at_end = (source_ptr == source_end);
+ if (at_end || run >= MIN_RUN) {
+ while (literal_start < source_ptr) {
+ int literal = (int)(source_ptr - literal_start);
+ if (literal > MAX_LITERAL) literal = MAX_LITERAL;
+ *dest_ptr++ = (unsigned char)(0x80 | literal);
+ memcpy(dest_ptr, literal_start, literal);
+ dest_ptr += literal;
+ literal_start += literal;
+ }
+ if (at_end) break;
+ *dest_ptr++ = 0xfe;
+ *dest_ptr++ = (unsigned char)(run & 0xff);
+ *dest_ptr++ = (unsigned char)(run >> 8);
+ *dest_ptr++ = source_ptr[0];
+ source_ptr += run;
+ literal_start = source_ptr;
+ } else {
+ source_ptr += 1;
+ }
+ }
+ *dest_ptr++ = 0x80;
+ retval = (int)(dest_ptr - (unsigned char *)dest);
}
-#endif
return(retval);
}
#endif
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mempool.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mempool.h
index 9b1c4e590..6e4d6d87b 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mempool.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mempool.h
@@ -90,8 +90,11 @@ public:
protected:
- T * FreeListHead;
- uint32 * BlockListHead;
+ T * FreeListHead;
+ // Each block starts with a pointer to the previous one, so this is a pointer to pointer: as a
+ // uint32* the "skip the header" arithmetic below advanced four bytes over an eight byte header
+ // on x64, and every object in the pool sat four bytes too low with the last one off the end.
+ void ** BlockListHead;
int FreeObjectCount;
int TotalObjectCount;
FastCriticalSectionClass ObjectPoolCS;
@@ -205,7 +208,7 @@ ObjectPoolClass<T,BLOCK_SIZE>::~ObjectPoolClass(void)
// delete all of the blocks we allocated
int block_count = 0;
while (BlockListHead != NULL) {
- uint32 * next_block = *(uint32 **)BlockListHead;
+ void ** next_block = (void **)*BlockListHead;
::operator delete(BlockListHead);
BlockListHead = next_block;
block_count++;
@@ -281,10 +284,10 @@ T * ObjectPoolClass<T,BLOCK_SIZE>::Allocate_Object_Memory(void)
if ( FreeListHead == 0 ) {
// No free objects, allocate another block
- uint32 * tmp_block_head = BlockListHead;
- BlockListHead = (uint32*)::operator new( sizeof(T) * BLOCK_SIZE + sizeof(uint32 *));
+ void ** tmp_block_head = BlockListHead;
+ BlockListHead = (void **)::operator new( sizeof(T) * BLOCK_SIZE + sizeof(void *));
// Link this block into the block list
- *(void **)BlockListHead = tmp_block_head;
+ *BlockListHead = tmp_block_head;
// Link the objects in the block into the free object list
FreeListHead = (T*)(BlockListHead + 1);
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mpu.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mpu.cpp
index 1bf15e960..434d6a4d4 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mpu.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mpu.cpp
@@ -40,6 +40,7 @@
#include "mpu.h"
#include "math.h"
#include <assert.h>
+#include <intrin.h>
typedef union {
LARGE_INTEGER LargeInt;
@@ -86,16 +87,9 @@ unsigned long Get_CPU_Rate(unsigned long & high)
unsigned long Get_CPU_Clock(unsigned long & high)
{
- int h;
- int l;
- __asm {
- _emit 0Fh
- _emit 31h
- mov [h],edx
- mov [l],eax
- }
- high = h;
- return(l);
+ const unsigned __int64 ticks = __rdtsc();
+ high = (unsigned long)(ticks >> 32);
+ return (unsigned long)ticks;
}
@@ -112,8 +106,6 @@ unsigned long Get_CPU_Clock(unsigned long & high)
**
*/
-#define ASM_RDTSC _asm _emit 0x0f _asm _emit 0x31
-
// Max # of samplings to allow before giving up and returning current average.
#define MAX_TRIES 20
#define ROUND_THRESHOLD 6
@@ -126,12 +118,9 @@ static unsigned long TSC_High;
void RDTSC(void)
{
- _asm
- {
- ASM_RDTSC;
- mov TSC_Low, eax
- mov TSC_High, edx
- }
+ const unsigned __int64 ticks = __rdtsc();
+ TSC_Low = (unsigned long)ticks;
+ TSC_High = (unsigned long)(ticks >> 32);
}
@@ -197,8 +186,7 @@ int Get_RDTSC_CPU_Speed(void)
QueryPerformanceCounter(&t1);
}
- ASM_RDTSC;
- _asm mov stamp0, EAX
+ stamp0 = (DWORD)__rdtsc();
t0.LowPart = t1.LowPart; // Reset Initial Time
t0.HighPart = t1.HighPart;
@@ -211,8 +199,7 @@ int Get_RDTSC_CPU_Speed(void)
QueryPerformanceCounter(&t1);
}
- ASM_RDTSC;
- _asm mov stamp1, EAX
+ stamp1 = (DWORD)__rdtsc();
cycles = stamp1 - stamp0; // # of cycles passed between reads
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mutex.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mutex.h
index 12bb5b5ad..d6a3c778f 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mutex.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/mutex.h
@@ -25,6 +25,7 @@
#include "always.h"
#include "thread.h"
+#include <intrin.h>
// Always use mutex or critical section when accessing the same data from multiple threads!
@@ -129,36 +130,10 @@ public:
public:
__forceinline LockClass(FastCriticalSectionClass& critical_section) : cs(critical_section)
{
- unsigned& nFlag=cs.Flag;
-
- #define ts_lock _emit 0xF0
- assert(((unsigned)&nFlag % 4) == 0);
-
- // I'm terribly sorry for these emits in here but
- // VC won't inline any functions that have labels in them...
-
- // Had to remove the emits back to normal
- // ASM statements because sometimes the jump
- // would be 1 byte off....
-
- __asm mov ebx, [nFlag]
- __asm ts_lock
- __asm bts dword ptr [ebx], 0
- __asm jnc BitSet
- //__asm _emit 0x73
- //__asm _emit 0x0f
-
- The_Bit_Was_Previously_Set_So_Try_Again:
+ // EA's "lock bts" loop, as the intrinsic that compiles to the same instruction on x86 and
+ // x64. The asm also loaded the flag's address into EBX without saving it.
+ while (_interlockedbittestandset((volatile long *)&cs.Flag, 0))
ThreadClass::Switch_Thread();
- __asm mov ebx, [nFlag]
- __asm ts_lock
- __asm bts dword ptr [ebx], 0
- __asm jc The_Bit_Was_Previously_Set_So_Try_Again
- //_asm _emit 0x72
- //_asm _emit 0xf1
-
- BitSet:
- ;
}
~LockClass()
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/rle.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/rle.cpp
index ae0d7e5b7..b88fa6b85 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/rle.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/rle.cpp
@@ -83,8 +83,11 @@ int RLEEngine::Compress(void const * source, void * dest, int length) const
/*
** Count the number of transparent pixels in this run.
*/
+ // The bound is tested before the byte, and against the bytes left rather than one past
+ // them: the other way round this walked off the end of the source and counted whatever
+ // followed it, so a buffer of nothing but zeroes encoded a run longer than itself.
int runcount = 0;
- while (sptr[runcount] == '\0' && runcount <= length) {
+ while (runcount < length && sptr[runcount] == '\0') {
runcount++;
}
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/rlerle.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/rlerle.h
index 524440922..bdea02c64 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/rlerle.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/rlerle.h
@@ -454,256 +454,10 @@ class RLEBlitTransLucent75 : public RLEBlitter {
};
-#if defined(_MSC_VER)
-void RLEBlitTransZRemapXlat<unsigned short>::Blit(void * dest, void const * source, int len, int leadskip) const
-{
- unsigned char const * remapper = *RemapTable;
- unsigned short const * transtable = TranslateTable;
-
- /*
- ** Set up the working registers for the blit operation.
- */
- __asm {
- mov ecx,[len]
- mov edi,[dest]
- mov esi,[source]
- mov ebx,[remapper]
- mov edx,[leadskip]
- xor eax,eax
- }
-
- /*
- ** Skip leading pixels by analyzing the RLE data until the entire
- ** requested skip pixel count has been processed. This could result in
- ** unprocessed transparent pixels if it ended up in the middle of
- ** a transparent pixel run. This is handled in the next block.
- */
-moreskip:
- __asm {
- test edx,edx
- jle nomoreskip
- dec edx
- lodsb
- test al,al
- jnz moreskip
- lodsb
- sub edx,eax
- inc edx
- jmp moreskip
- }
-nomoreskip:
-
- /*
- ** Handle any left over transparent pixels that would be part of
- ** a transparent pixel run that occurs at the end of the leading
- ** pixel skip process.
- */
- __asm {
- neg edx
- sub ecx,edx // Account for any left over transparent pixels
- lea edi,[edi+edx*2]
- mov edx,[transtable]
- }
-
- /*
- ** Output the pixel data to the destination.
- */
-moredata:
- __asm {
- xor eax,eax
- or ecx,ecx
- jle fini
- lodsb
- test al,al
- jz transparent
- mov al,[ebx+eax]
- mov ax,[edx+eax*2]
- dec ecx
- stosw
- jmp moredata
- }
-
- /*
- ** A transparent pixel run just causes the destination pointer
- ** and length count to be adjusted by the length of the run.
- */
-transparent:
- __asm {
- lodsb
- lea edi,[edi+eax*2]
- sub ecx,eax
- jmp moredata
- }
-
-fini:;
-}
-
-
-void RLEBlitTransRemapXlat<unsigned short>::Blit(void * dest, void const * source, int len, int leadskip) const
-{
- unsigned char const * remapper = RemapTable;
- unsigned short const * transtable = TranslateTable;
-
- /*
- ** Set up the working registers for the blit operation.
- */
- __asm {
- mov ecx,[len]
- mov edi,[dest]
- mov esi,[source]
- mov ebx,[remapper]
- mov edx,[leadskip]
- xor eax,eax
- }
-
- /*
- ** Skip leading pixels by analyzing the RLE data until the entire
- ** requested skip pixel count has been processed. This could result in
- ** unprocessed transparent pixels if it ended up in the middle of
- ** a transparent pixel run. This is handled in the next block.
- */
-moreskip:
- __asm {
- test edx,edx
- jle nomoreskip
- dec edx
- lodsb
- test al,al
- jnz moreskip
- lodsb
- sub edx,eax
- inc edx
- jmp moreskip
- }
-nomoreskip:
-
- /*
- ** Handle any left over transparent pixels that would be part of
- ** a transparent pixel run that occurs at the end of the leading
- ** pixel skip process.
- */
- __asm {
- neg edx
- sub ecx,edx // Account for any left over transparent pixels
- lea edi,[edi+edx*2]
- mov edx,[transtable]
- }
-
- /*
- ** Output the pixel data to the destination.
- */
-moredata:
- __asm {
- xor eax,eax
- or ecx,ecx
- jle fini
- lodsb
- test al,al
- jz transparent
- mov al,[ebx+eax]
- mov ax,[edx+eax*2]
- dec ecx
- stosw
- jmp moredata
- }
-
- /*
- ** A transparent pixel run just causes the destination pointer
- ** and length count to be adjusted by the length of the run.
- */
-transparent:
- __asm {
- lodsb
- lea edi,[edi+eax*2]
- sub ecx,eax
- jmp moredata
- }
-
-fini:;
-}
-
-
-void RLEBlitTransXlat<unsigned short>::Blit(void * dest, void const * source, int len, int leadskip) const
-{
- unsigned short const * transtable = TranslateTable;
-
- /*
- ** Set up the working registers for the blit operation.
- */
- __asm {
- mov ecx,[len]
- mov edi,[dest]
- mov esi,[source]
- mov ebx,[transtable]
- mov edx,[leadskip]
- xor eax,eax
- }
-
- /*
- ** Skip leading pixels by analyzing the RLE data until the entire
- ** requested skip pixel count has been processed. This could result in
- ** unprocessed transparent pixels if it ended up in the middle of
- ** a transparent pixel run. This is handled in the next block.
- */
-moreskip:
- __asm {
- test edx,edx
- jle nomoreskip
- dec edx
- lodsb
- test al,al
- jnz moreskip
- lodsb
- sub edx,eax
- inc edx
- jmp moreskip
- }
-nomoreskip:
-
- /*
- ** Handle any left over transparent pixels that would be part of
- ** a transparent pixel run that occurs at the end of the leading
- ** pixel skip process.
- */
- __asm {
- neg edx
- sub ecx,edx // Account for any left over transparent pixels
- lea edi,[edi+edx*2]
- }
-
- /*
- ** Output the pixel data to the destination.
- */
-moredata:
- __asm {
- xor eax,eax
- or ecx,ecx
- jle fini
- lodsb
- test al,al
- jz transparent
- mov ax,[ebx+eax*2]
- dec ecx
- stosw
- jmp moredata
- }
-
- /*
- ** A transparent pixel run just causes the destination pointer
- ** and length count to be adjusted by the length of the run.
- */
-transparent:
- __asm {
- lodsb
- lea edi,[edi+eax*2]
- sub ecx,eax
- jmp moredata
- }
-
-fini:;
-}
-
-#endif
+/*
+** EA had assembly specializations of three RLE blitters here, 32-bit inline __asm.
+** The templates they specialized are what the build uses.
+*/
#endif
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/wwstring.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/wwstring.cpp
index 3d8f26df1..6d991dd72 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/wwstring.cpp
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWLib/wwstring.cpp
@@ -102,7 +102,9 @@ StringClass::Get_String (int length, bool is_temp)
//
// Grab this unused buffer for our string
//
- unsigned temp_string=reinterpret_cast<unsigned>(m_TempStrings);
+ // uintptr_t, not unsigned: this is pointer arithmetic on the temp-string pool, and
+ // truncating it to 32 bits hands back a pointer into nothing at all on x64.
+ uintptr_t temp_string=reinterpret_cast<uintptr_t>(m_TempStrings);
temp_string+=MAX_TEMP_BYTES*MAX_TEMP_STRING;
temp_string&=~(MAX_TEMP_BYTES*MAX_TEMP_STRING-1);
temp_string+=index*MAX_TEMP_BYTES;
@@ -197,8 +199,8 @@ StringClass::Free_String (void)
{
if (m_Buffer != m_EmptyString) {
- unsigned buffer_base=reinterpret_cast<unsigned>(m_Buffer-sizeof (StringClass::_HEADER));
- unsigned temp_base=reinterpret_cast<unsigned>(m_TempStrings+MAX_TEMP_BYTES*MAX_TEMP_STRING);
+ uintptr_t buffer_base=reinterpret_cast<uintptr_t>(m_Buffer-sizeof (StringClass::_HEADER));
+ uintptr_t temp_base=reinterpret_cast<uintptr_t>(m_TempStrings+MAX_TEMP_BYTES*MAX_TEMP_STRING);
if ((buffer_base>>11)==(temp_base>>11)) {
m_Buffer[0] = 0;
diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmath.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmath.h
index 72bc8b706..a6d2974d2 100644
--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmath.h
+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WWMath/wwmath.h
@@ -46,6 +46,7 @@
#include "dettrig.h"
#include <math.h>
#include <float.h>
+#include <emmintrin.h>
#include <assert.h>
#include <float.h>
@@ -121,19 +122,11 @@ static WWINLINE float Fabs(float val)
static WWINLINE int Float_To_Int_Chop(const float& f);
static WWINLINE int Float_To_Int_Floor(const float& f);
-#if defined(_MSC_VER) && defined(_M_IX86)
static WWINLINE float Cos(float val);
static WWINLINE float Sin(float val);
static WWINLINE float Sqrt(float val);
-static float __fastcall Inv_Sqrt(float a); // Some 30% faster inverse square root than regular C++ compiled, from Intel's math library
-static WWINLINE long Float_To_Long(float f);
-#else
-static float Cos(float val);
-static float Sin(float val);
-static float Sqrt(float val);
static float Inv_Sqrt(float a);
-static long Float_To_Long(float f);
-#endif
+static WWINLINE long Float_To_Long(float f);
static WWINLINE float Fast_Sin(float val);
@@ -314,35 +307,16 @@ WWINLINE bool WWMath::Is_Valid_Double(double x)
// Float to long
// ----------------------------------------------------------------------------
-#if defined(_MSC_VER) && defined(_M_IX86)
WWINLINE long WWMath::Float_To_Long(float f)
{
- long i;
-
- __asm {
- fld [f]
- fistp [i]
- }
-
- return i;
+ // cvtss2si, not a cast: EA's fistp rounds to nearest even and a C cast truncates, and callers
+ // in GameLogic depend on the rounding.
+ return (long)_mm_cvtss_si32(_mm_set_ss(f));
}
-#else
-WWINLINE long WWMath::Float_To_Long(float f)
-{
- return (long) f;
-}
-#endif
-WWINLINE long WWMath::Float_To_Long(double f)
+WWINLINE long WWMath::Float_To_Long(double f)
{
-#if defined(_MSC_VER) && defined(_M_IX86)
- long retval;
- __asm fld qword ptr [f]
- __asm fistp dword ptr [retval]
- return retval;
-#else
- return (long) f;
-#endif
+ return (long)_mm_cvtsd_si32(_mm_set_sd(f));
}
// ----------------------------------------------------------------------------
@@ -535,23 +509,10 @@ WWINLINE float WWMath::Asin(float val)
// Sqrt
// ----------------------------------------------------------------------------
-#if defined(_MSC_VER) && defined(_M_IX86)
-WWINLINE float WWMath::Sqrt(float val)
-{
- float retval;
- __asm {
- fld [val]
- fsqrt
- fstp [retval]
- }
- return retval;
-}
-#else
WWINLINE float WWMath::Sqrt(float val)
{
return (float)sqrt(val);
}
-#endif
WWINLINE int WWMath::Float_To_Int_Chop(const float& f)
{
@@ -583,58 +544,13 @@ WWINLINE int WWMath::Float_To_Int_Floor (const float& f)
// Inverse square root
// ----------------------------------------------------------------------------
-#if defined(_MSC_VER) && defined(_M_IX86)
-WWINLINE __declspec(naked) float __fastcall WWMath::Inv_Sqrt(float a)
-{
- __asm {
- mov eax, 0be6eb508h
- mov DWORD PTR [esp-12],03fc00000h ; 1.5 on the stack
- sub eax, DWORD PTR [esp+4]; a
- sub DWORD PTR [esp+4], 800000h ; a/2 a=Y0
- shr eax, 1 ; firs approx in eax=R0
- mov DWORD PTR [esp-8], eax
-
- fld DWORD PTR [esp-8] ;r
- fmul st, st ;r*r
- fld DWORD PTR [esp-8] ;r
- fxch st(1)
- fmul DWORD PTR [esp+4];a ;r*r*y0
- fld DWORD PTR [esp-12];load 1.5
- fld st(0)
- fsub st,st(2) ;r1 = 1.5 - y1
- ;x1 = st(3)
- ;y1 = st(2)
- ;1.5 = st(1)
- ;r1 = st(0)
-
- fld st(1)
- fxch st(1)
- fmul st(3),st ; y2=y1*r1*...
- fmul st(3),st ; y2=y1*r1*r1
- fmulp st(4),st ; x2=x1*r1
- fsub st,st(2) ; r2=1.5-y2
- ;x2=st(3)
- ;y2=st(2)
- ;1.5=st(1)
- ;r2 = st(0)
-
- fmul st(2),st ;y3=y2*r2*...
- fmul st(3),st ;x3=x2*r2
- fmulp st(2),st ;y3=y2*r2*r2
- fxch st(1)
- fsubp st(1),st ;r3= 1.5 - y3
- ;x3 = st(1)
- ;r3 = st(0)
- fmulp st(1), st
- ret 4
- }
-}
-#else
+// EA had a naked x87 routine here, a Newton-Raphson refinement of the classic bit-trick estimate,
+// "some 30% faster than regular C++ compiled". It was 32-bit assembly and this is what the build
+// has always compiled everywhere else.
WWINLINE float WWMath::Inv_Sqrt(float val)
{
return 1.0f / (float)sqrt(val);
}
-#endif
#endif
diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_debug.cpp b/GeneralsMD/Code/Libraries/Source/debug/debug_debug.cpp
index be99a5823..400e649b6 100644
--- a/GeneralsMD/Code/Libraries/Source/debug/debug_debug.cpp
+++ b/GeneralsMD/Code/Libraries/Source/debug/debug_debug.cpp
@@ -31,6 +31,8 @@
#include <stdio.h>
#include <string.h>
#include <new> // needed for placement new prototype
+#include <stdint.h>
+#include <intrin.h>
// a little dummy variable that makes the linker actually include
// us...
@@ -43,11 +45,14 @@ bool __DebugIncludeInLink1;
// .CRT$XCZ. We jam in our own two functions at the very beginning
// and end of this list (B and Y respectively since the A and Z segments
// contain list delimiters).
-#pragma data_seg(".CRT$XCB")
-void *Debug::PreStatic=&Debug::PreStaticInit;
-#pragma data_seg(".CRT$XCY")
-void *Debug::PostStatic=&Debug::PostStaticInit;
-#pragma data_seg()
+// data_seg makes these sections writable, and on x64 the CRT's own .CRT sections are read only:
+// the linker warns (LNK4078) and the mismatched section is dropped from the initializer walk, so
+// neither of these ran and every Debug field stayed zero - including the radix that _itoa divides
+// by. Declaring the section read only puts them back in the list.
+#pragma section(".CRT$XCB", long, read)
+#pragma section(".CRT$XCY", long, read)
+__declspec(allocate(".CRT$XCB")) void *Debug::PreStatic=&Debug::PreStaticInit;
+__declspec(allocate(".CRT$XCY")) void *Debug::PostStatic=&Debug::PostStaticInit;
Debug::LogDescription::LogDescription(const char *fileOrGroup, const char *description)
{
@@ -278,13 +283,8 @@ bool Debug::SkipNext(void)
// do not implement this function inline, we do need
// a valid frame pointer here!
- unsigned help;
- _asm
- {
- mov eax,[ebp+4] // return address
- mov help,eax
- };
- curStackFrame=help;
+ // The return address is only a hash key for the frame table, so on x64 its low 32 bits do.
+ curStackFrame=(unsigned)(uintptr_t)_ReturnAddress();
// do we know if to skip the following code?
FrameHashEntry *e=Instance.LookupFrame(curStackFrame);
@@ -395,7 +395,7 @@ bool Debug::AssertDone(void)
}
break;
case IDRETRY:
- _asm int 0x03
+ __debugbreak();
break;
default:
((void)0);
@@ -663,7 +663,7 @@ bool Debug::CrashDone(bool die)
}
break;
case IDRETRY:
- _asm int 0x03
+ __debugbreak();
break;
default:
((void)0);
diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_debug.h b/GeneralsMD/Code/Libraries/Source/debug/debug_debug.h
index 7041d5e2e..74431d7af 100644
--- a/GeneralsMD/Code/Libraries/Source/debug/debug_debug.h
+++ b/GeneralsMD/Code/Libraries/Source/debug/debug_debug.h
@@ -34,7 +34,8 @@
// this makes sure that whenever this header is included
// the accompanying OBJ file is linked in as well
-#pragma comment(linker,"/include:___DebugIncludeInLink1")
+// x86 prefixes an underscore onto every C symbol; x64 does not, so the name to force in differs.
+# pragma comment(linker,"/include:__DebugIncludeInLink1")
/**
\class Debug debug.h <rts/debug.h>
diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_except.cpp b/GeneralsMD/Code/Libraries/Source/debug/debug_except.cpp
index dac78b4fa..dfac805d6 100644
--- a/GeneralsMD/Code/Libraries/Source/debug/debug_except.cpp
+++ b/GeneralsMD/Code/Libraries/Source/debug/debug_except.cpp
@@ -22,7 +22,7 @@
// $Revision: #1 $
// $DateTime: 2003/07/03 11:55:26 $
//
-// �2003 Electronic Arts
+// �2003 Electronic Arts
//
// Unhandled exception handler
//////////////////////////////////////////////////////////////////////////////
@@ -105,12 +105,18 @@ const char *DebugExceptionhandler::GetExceptionType(struct _EXCEPTION_POINTERS *
#undef EX
}
+// The faulting instruction's address.
+static size_t ContextIP(const struct _CONTEXT &ctx)
+{
+ return (size_t)ctx.Rip;
+}
+
void DebugExceptionhandler::LogExceptionLocation(Debug &dbg, struct _EXCEPTION_POINTERS *exptr)
{
struct _CONTEXT &ctx=*exptr->ContextRecord;
char buf[512];
- DebugStackwalk::Signature::GetSymbol(ctx.Eip,buf,sizeof(buf));
+ DebugStackwalk::Signature::GetSymbol(ContextIP(ctx),buf,sizeof(buf));
dbg << "Exception occured at\n" << buf << ".";
}
@@ -120,70 +126,30 @@ void DebugExceptionhandler::LogRegisters(Debug &dbg, struct _EXCEPTION_POINTERS
dbg << Debug::FillChar('0')
<< Debug::Hex()
- << "EAX:" << Debug::Width(8) << ctx.Eax
- << " EBX:" << Debug::Width(8) << ctx.Ebx
- << " ECX:" << Debug::Width(8) << ctx.Ecx << "\n"
- << "EDX:" << Debug::Width(8) << ctx.Edx
- << " ESI:" << Debug::Width(8) << ctx.Esi
- << " EDI:" << Debug::Width(8) << ctx.Edi << "\n"
- << "EIP:" << Debug::Width(8) << ctx.Eip
- << " ESP:" << Debug::Width(8) << ctx.Esp
- << " EBP:" << Debug::Width(8) << ctx.Ebp << "\n"
- << "Flags:" << Debug::Bin() << Debug::Width(32) << ctx.EFlags << Debug::Hex() << "\n"
- << "CS:" << Debug::Width(4) << ctx.SegCs
- << " DS:" << Debug::Width(4) << ctx.SegDs
- << " SS:" << Debug::Width(4) << ctx.SegSs
- << "\nES:" << Debug::Width(4) << ctx.SegEs
- << " FS:" << Debug::Width(4) << ctx.SegFs
- << " GS:" << Debug::Width(4) << ctx.SegGs << "\n" << Debug::FillChar() << Debug::Dec();
+ << "RIP:" << Debug::Width(16) << ctx.Rip
+ << " RSP:" << Debug::Width(16) << ctx.Rsp
+ << " RBP:" << Debug::Width(16) << ctx.Rbp << "\n"
+ << "RAX:" << Debug::Width(16) << ctx.Rax
+ << " RBX:" << Debug::Width(16) << ctx.Rbx
+ << " RCX:" << Debug::Width(16) << ctx.Rcx << "\n"
+ << "RDX:" << Debug::Width(16) << ctx.Rdx
+ << " RSI:" << Debug::Width(16) << ctx.Rsi
+ << " RDI:" << Debug::Width(16) << ctx.Rdi << "\n"
+ << Debug::Dec() << Debug::FillChar(' ');
}
void DebugExceptionhandler::LogFPURegisters(Debug &dbg, struct _EXCEPTION_POINTERS *exptr)
{
struct _CONTEXT &ctx=*exptr->ContextRecord;
- if (!(ctx.ContextFlags&CONTEXT_FLOATING_POINT))
- {
- dbg << "FP registers not available\n";
- return;
- }
-
- FLOATING_SAVE_AREA &flt=ctx.FloatSave;
- dbg << Debug::Bin() << Debug::FillChar('0')
- << "CW:" << Debug::Width(16) << (flt.ControlWord&0xffff) << "\n"
- << "SW:" << Debug::Width(16) << (flt.StatusWord&0xffff) << "\n"
- << "TW:" << Debug::Width(16) << (flt.TagWord&0xffff) << "\n"
- << Debug::Hex()
- << "ErrOfs: " << Debug::Width(8) << flt.ErrorOffset
- << " ErrSel: " << Debug::Width(8) << flt.ErrorSelector << "\n"
- << "DataOfs: " << Debug::Width(8) << flt.DataOffset
- << " DataSel: " << Debug::Width(8) << flt.DataSelector << "\n"
- // Cr0NpxState was renamed to Spare0 in the modern Windows SDK's
- // _FLOATING_SAVE_AREA; same offset, same contents.
- << "Cr0NpxState: " << Debug::Width(8) << flt.Spare0 << "\n";
-
- for (unsigned k=0;k<SIZE_OF_80387_REGISTERS/10;++k)
- {
- dbg << Debug::Dec() << "ST(" << k << ") ";
- dbg.SetPrefixAndRadix("",16);
-
- BYTE *value=flt.RegisterArea+k*10;
- for (unsigned i=0;i<10;i++)
- dbg << Debug::Width(2) << value[i];
-
- double fpVal;
-
- // convert from temporary real (10 byte) to double
- _asm
- {
- mov eax,value
- fld tbyte ptr [eax]
- fstp qword ptr [fpVal]
- }
-
- dbg << " " << fpVal << "\n";
- }
- dbg << Debug::FillChar() << Debug::Dec();
+ // There is no x87 save area to walk: every float the game computes is in an SSE register, and
+ // the four the calling convention passes arguments in are the ones worth naming.
+ dbg << Debug::FillChar('0') << Debug::Hex()
+ << "XMM0:" << Debug::Width(16) << ctx.Xmm0.Low
+ << " XMM1:" << Debug::Width(16) << ctx.Xmm1.Low << "\n"
+ << "XMM2:" << Debug::Width(16) << ctx.Xmm2.Low
+ << " XMM3:" << Debug::Width(16) << ctx.Xmm3.Low << "\n"
+ << Debug::Dec() << Debug::FillChar(' ');
}
// include exception dialog box
@@ -198,7 +164,7 @@ static char regInfo[1024],verInfo[256];
// and this saves us from doing a stack walk twice
static DebugStackwalk::Signature sig;
-static BOOL CALLBACK ExceptionDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+static INT_PTR CALLBACK ExceptionDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
@@ -243,7 +209,7 @@ static BOOL CALLBACK ExceptionDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARA
// address
struct _CONTEXT &ctx=*exPtrs->ContextRecord;
- DebugStackwalk::Signature::GetSymbol(ctx.Eip,regInfo,sizeof(regInfo));
+ DebugStackwalk::Signature::GetSymbol(ContextIP(ctx),regInfo,sizeof(regInfo));
SendDlgItemMessage(hWnd,102,WM_SETTEXT,0,(LPARAM)regInfo);
// stack
@@ -393,7 +359,7 @@ LONG __stdcall DebugExceptionhandler::ExceptionFilter(struct _EXCEPTION_POINTERS
dbg.m_stackWalk.StackWalk(sig,pExPtrs->ContextRecord);
dbg << sig << "\n";
- dbg << "Bytes around EIP:" << Debug::MemDump::Char(((char *)(pExPtrs->ContextRecord->Eip))-32,80);
+ dbg << "Bytes around EIP:" << Debug::MemDump::Char(((char *)(pExPtrs->ExceptionRecord->ExceptionAddress))-32,80);
dbg.FlushOutput();
diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_stack.cpp b/GeneralsMD/Code/Libraries/Source/debug/debug_stack.cpp
index 9390883e2..7dddb8286 100644
--- a/GeneralsMD/Code/Libraries/Source/debug/debug_stack.cpp
+++ b/GeneralsMD/Code/Libraries/Source/debug/debug_stack.cpp
@@ -22,12 +22,14 @@
// $Revision: #2 $
// $DateTime: 2005/01/19 15:02:33 $
//
-// �2003 Electronic Arts
+// �2003 Electronic Arts
//
// Stack walker
//////////////////////////////////////////////////////////////////////////////
#include "_pch.h"
#include "dbghelp.h"
+// x64 dbghelp.h maps StackWalk onto StackWalk64, which renames DebugStackwalk's own method too.
+#undef StackWalk
// Definitions to allow run-time linking to the dbghelp.dll functions.
@@ -42,7 +44,10 @@ static union
{
#include "debug_stack.inl"
};
- unsigned funcPtr[1];
+ // The union walks the struct above as a plain array of function pointers, so the array's element
+ // has to be pointer sized: as "unsigned" it wrote half of each address on x64 and the first call
+ // through one of them faulted.
+ FARPROC funcPtr[1];
} gDbg;
#undef DBGHELP
@@ -85,11 +90,11 @@ static void InitDbghelp(void)
return;
// Get function addresses
- unsigned *funcptr=gDbg.funcPtr;
+ FARPROC *funcptr=gDbg.funcPtr;
unsigned k;
for (k=0;DebughelpFunctionNames[k];++k,++funcptr)
{
- *funcptr=(unsigned)GetProcAddress(g_dbghelp,DebughelpFunctionNames[k]);
+ *funcptr=GetProcAddress(g_dbghelp,DebughelpFunctionNames[k]);
if (!*funcptr)
break;
}
@@ -138,13 +143,13 @@ DebugStackwalk::Signature& DebugStackwalk::Signature::operator=(const Signature&
return *this;
}
-unsigned DebugStackwalk::Signature::GetAddress(int n) const
+size_t DebugStackwalk::Signature::GetAddress(int n) const
{
DFAIL_IF_MSG(n<0||n>=MAX_ADDR,n << "/" << MAX_ADDR) return 0;
return m_addr[n];
}
-void DebugStackwalk::Signature::GetSymbol(unsigned addr, char *buf, unsigned bufSize)
+void DebugStackwalk::Signature::GetSymbol(size_t addr, char *buf, unsigned bufSize)
{
DFAIL_IF(!buf) return;
DFAIL_IF(bufSize<64||bufSize>=0x80000000) return;
@@ -153,10 +158,10 @@ void DebugStackwalk::Signature::GetSymbol(unsigned addr, char *buf, unsigned buf
char *bufEnd=buf+bufSize;
*buf=0;
- buf+=wsprintf(buf,"%08x",addr);
+ buf+=wsprintf(buf,"%p",(void *)addr);
// determine module
- unsigned modBase=gDbg._SymGetModuleBase(GetCurrentProcess(),addr);
+ DWORD64 modBase=gDbg._SymGetModuleBase64(GetCurrentProcess(),addr);
if (!modBase)
{
strcpy(buf," (unknown module)");
@@ -171,7 +176,7 @@ void DebugStackwalk::Signature::GetSymbol(unsigned addr, char *buf, unsigned buf
}
char symbolBuffer[512];
- GetModuleFileName((HMODULE)modBase,symbolBuffer,sizeof(symbolBuffer));
+ GetModuleFileName((HMODULE)(size_t)modBase,symbolBuffer,sizeof(symbolBuffer));
char *p=strrchr(symbolBuffer,'\\'); // use filename only, strip off path
p=p?p+1:symbolBuffer;
@@ -180,25 +185,26 @@ void DebugStackwalk::Signature::GetSymbol(unsigned addr, char *buf, unsigned buf
buf+=strlen(buf);
if (bufEnd-buf<32)
return;
- buf+=wsprintf(buf,"+0x%x",addr-modBase);
+ buf+=wsprintf(buf,"+0x%x",(unsigned)(addr-(size_t)modBase));
// determine symbol
- PIMAGEHLP_SYMBOL symPtr=(PIMAGEHLP_SYMBOL)symbolBuffer;
+ PIMAGEHLP_SYMBOL64 symPtr=(PIMAGEHLP_SYMBOL64)symbolBuffer;
memset(symPtr,0,sizeof(symbolBuffer));
- symPtr->SizeOfStruct=sizeof(IMAGEHLP_SYMBOL);
- symPtr->MaxNameLength=sizeof(symbolBuffer)-sizeof(IMAGEHLP_SYMBOL);
- DWORD displacement;
- if (!gDbg._SymGetSymFromAddr(GetCurrentProcess(),addr,&displacement,symPtr))
+ symPtr->SizeOfStruct=sizeof(IMAGEHLP_SYMBOL64);
+ symPtr->MaxNameLength=sizeof(symbolBuffer)-sizeof(IMAGEHLP_SYMBOL64);
+ DWORD64 displacement;
+ if (!gDbg._SymGetSymFromAddr64(GetCurrentProcess(),addr,&displacement,symPtr))
return;
if ((unsigned int)(bufEnd-buf)<strlen(symPtr->Name)+16)
return;
- buf+=wsprintf(buf,", %s+0x%x",symPtr->Name,displacement);
+ buf+=wsprintf(buf,", %s+0x%x",symPtr->Name,(unsigned)displacement);
// and line number
- IMAGEHLP_LINE line;
+ IMAGEHLP_LINE64 line;
memset(&line,0,sizeof(line));
line.SizeOfStruct=sizeof(line);
- if (!gDbg._SymGetLineFromAddr(GetCurrentProcess(),addr,&displacement,&line))
+ DWORD lineDisplacement;
+ if (!gDbg._SymGetLineFromAddr64(GetCurrentProcess(),addr,&lineDisplacement,&line))
return;
p=strrchr(line.FileName,'\\'); // use filename only, strip off path
@@ -206,10 +212,10 @@ void DebugStackwalk::Signature::GetSymbol(unsigned addr, char *buf, unsigned buf
if ((unsigned int)(bufEnd-buf)<strlen(p)+16)
return;
- buf+=wsprintf(buf,", %s:%i+0x%x",p,line.LineNumber,displacement);
+ buf+=wsprintf(buf,", %s:%i+0x%x",p,line.LineNumber,lineDisplacement);
}
-void DebugStackwalk::Signature::GetSymbol(unsigned addr,
+void DebugStackwalk::Signature::GetSymbol(size_t addr,
char *bufMod, unsigned sizeMod, unsigned *relMod,
char *bufSym, unsigned sizeSym, unsigned *relSym,
char *bufFile, unsigned sizeFile, unsigned *linePtr, unsigned *relLine)
@@ -230,7 +236,7 @@ void DebugStackwalk::Signature::GetSymbol(unsigned addr,
DFAIL_IF(bufFile&&sizeFile<16) return;
// determine module
- unsigned modBase=gDbg._SymGetModuleBase(GetCurrentProcess(),addr);
+ DWORD64 modBase=gDbg._SymGetModuleBase64(GetCurrentProcess(),addr);
if (!modBase)
{
if (bufMod)
@@ -253,7 +259,7 @@ void DebugStackwalk::Signature::GetSymbol(unsigned addr,
char symbolBuffer[512];
if (bufMod)
{
- GetModuleFileName((HMODULE)modBase,symbolBuffer,sizeof(symbolBuffer));
+ GetModuleFileName((HMODULE)(size_t)modBase,symbolBuffer,sizeof(symbolBuffer));
char *p=strrchr(symbolBuffer,'\\'); // use filename only, strip off path
p=p?p+1:symbolBuffer;
@@ -261,22 +267,22 @@ void DebugStackwalk::Signature::GetSymbol(unsigned addr,
bufMod[sizeMod-1]=0;
}
if (relMod)
- *relMod=addr-modBase;
+ *relMod=(unsigned)(addr-(size_t)modBase);
// determine symbol
if (bufSym)
{
- PIMAGEHLP_SYMBOL symPtr=(PIMAGEHLP_SYMBOL)symbolBuffer;
+ PIMAGEHLP_SYMBOL64 symPtr=(PIMAGEHLP_SYMBOL64)symbolBuffer;
memset(symPtr,0,sizeof(symbolBuffer));
- symPtr->SizeOfStruct=sizeof(IMAGEHLP_SYMBOL);
- symPtr->MaxNameLength=sizeof(symbolBuffer)-sizeof(IMAGEHLP_SYMBOL);
- DWORD displacement;
- if (gDbg._SymGetSymFromAddr(GetCurrentProcess(),addr,&displacement,symPtr))
+ symPtr->SizeOfStruct=sizeof(IMAGEHLP_SYMBOL64);
+ symPtr->MaxNameLength=sizeof(symbolBuffer)-sizeof(IMAGEHLP_SYMBOL64);
+ DWORD64 displacement;
+ if (gDbg._SymGetSymFromAddr64(GetCurrentProcess(),addr,&displacement,symPtr))
{
strncpy(bufSym,symPtr->Name,sizeSym);
bufSym[sizeSym-1]=0;
if (relSym)
- *relSym=displacement;
+ *relSym=(unsigned)displacement;
}
else
strcpy(bufSym,"(unknown)");
@@ -285,11 +291,11 @@ void DebugStackwalk::Signature::GetSymbol(unsigned addr,
// and line number
if (bufFile)
{
- IMAGEHLP_LINE line;
+ IMAGEHLP_LINE64 line;
memset(&line,0,sizeof(line));
line.SizeOfStruct=sizeof(line);
DWORD displacement;
- if (!gDbg._SymGetLineFromAddr(GetCurrentProcess(),addr,&displacement,&line))
+ if (!gDbg._SymGetLineFromAddr64(GetCurrentProcess(),addr,&displacement,&line))
strcpy(bufFile,"(unknown)");
else
{
@@ -351,52 +357,42 @@ int DebugStackwalk::StackWalk(Signature &sig, struct _CONTEXT *ctx)
if (!gDbg._StackWalk64)
return 0;
- // Set up the stack frame structure for the start point of the stack walk (i.e. here).
- // STACKFRAME/StackWalk (the 32-bit-only originals) are what this used to use, but
- // on a current dbghelp.dll that call fails on its first step with
- // ERROR_PARTIAL_COPY and the walk produces nothing at all.
- STACKFRAME64 stackFrame;
- memset(&stackFrame,0,sizeof(stackFrame));
-
- stackFrame.AddrPC.Mode = AddrModeFlat;
- stackFrame.AddrStack.Mode = AddrModeFlat;
- stackFrame.AddrFrame.Mode = AddrModeFlat;
-
- // Use the context struct if it was provided.
- if (ctx)
+ // The unwind comes from the exception tables, which means StackWalk64 needs a whole register
+ // set: seeding three addresses and passing no context walks nowhere.
+ CONTEXT walkContext;
+ if (ctx)
{
- stackFrame.AddrPC.Offset = ctx->Eip;
- stackFrame.AddrStack.Offset = ctx->Esp;
- stackFrame.AddrFrame.Offset = ctx->Ebp;
- }
+ walkContext=*ctx;
+ }
else
{
- // walk stack back using current call chain
- unsigned long reg_eip, reg_ebp, reg_esp;
- __asm
- {
- here:
- lea eax,here
- mov reg_eip,eax
- mov reg_ebp,ebp
- mov reg_esp,esp
- };
- stackFrame.AddrPC.Offset = reg_eip;
- stackFrame.AddrStack.Offset = reg_esp;
- stackFrame.AddrFrame.Offset = reg_ebp;
+ memset(&walkContext,0,sizeof(walkContext));
+ walkContext.ContextFlags=CONTEXT_FULL;
+ RtlCaptureContext(&walkContext);
}
- // Walk the stack by the requested number of return address iterations.
+ STACKFRAME64 frame;
+ memset(&frame,0,sizeof(frame));
+ frame.AddrPC.Offset=walkContext.Rip;
+ frame.AddrPC.Mode=AddrModeFlat;
+ frame.AddrStack.Offset=walkContext.Rsp;
+ frame.AddrStack.Mode=AddrModeFlat;
+ frame.AddrFrame.Offset=walkContext.Rbp;
+ frame.AddrFrame.Mode=AddrModeFlat;
+
+ // The frame this function is standing in is not worth reporting when the caller did not hand
+ // over a context of its own.
bool skipFirst=!ctx;
while (sig.m_numAddr<Signature::MAX_ADDR&&
- gDbg._StackWalk64(IMAGE_FILE_MACHINE_I386,GetCurrentProcess(),GetCurrentThread(),
- &stackFrame,NULL,NULL,gDbg._SymFunctionTableAccess64,gDbg._SymGetModuleBase64,NULL))
+ gDbg._StackWalk64(IMAGE_FILE_MACHINE_AMD64,GetCurrentProcess(),GetCurrentThread(),
+ &frame,&walkContext,NULL,gDbg._SymFunctionTableAccess64,
+ gDbg._SymGetModuleBase64,NULL))
{
if (skipFirst)
skipFirst=false;
else
- sig.m_addr[sig.m_numAddr++]=(unsigned)stackFrame.AddrPC.Offset;
+ sig.m_addr[sig.m_numAddr++]=(size_t)frame.AddrPC.Offset;
}
- return sig.m_numAddr;
+ return sig.m_numAddr;
}
diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_stack.h b/GeneralsMD/Code/Libraries/Source/debug/debug_stack.h
index 665942c78..6e1d7a228 100644
--- a/GeneralsMD/Code/Libraries/Source/debug/debug_stack.h
+++ b/GeneralsMD/Code/Libraries/Source/debug/debug_stack.h
@@ -59,7 +59,8 @@ public:
unsigned m_numAddr;
/// addresses
- unsigned m_addr[MAX_ADDR];
+ // Code addresses, so pointer sized rather than four bytes.
+ size_t m_addr[MAX_ADDR];
public:
explicit Signature(void): m_numAddr(0) {}
@@ -81,7 +82,7 @@ public:
\param n index, 0..Size()-1
\return signature address
*/
- unsigned GetAddress(int n) const;
+ size_t GetAddress(int n) const;
/**
\brief Strong ordering operator.
@@ -113,7 +114,7 @@ public:
\param buf return buffer
\param bufSize size of return buffer, minimum is 64 bytes (256 recommended)
*/
- static void GetSymbol(unsigned addr, char *buf, unsigned bufSize);
+ static void GetSymbol(size_t addr, char *buf, unsigned bufSize);
/**
\brief Determines symbol for given address.
@@ -130,7 +131,7 @@ public:
\param line line number, may be NULL
\param relLine relative address within line, may be NULL
*/
- static void GetSymbol(unsigned addr,
+ static void GetSymbol(size_t addr,
char *bufMod, unsigned sizeMod, unsigned *relMod,
char *bufSym, unsigned sizeSym, unsigned *relSym,
char *bufFile, unsigned sizeFile, unsigned *line, unsigned *relLine);
diff --git a/GeneralsMD/Code/Libraries/Source/debug/debug_stack.inl b/GeneralsMD/Code/Libraries/Source/debug/debug_stack.inl
index 4fef371db..3d9a0a48b 100644
--- a/GeneralsMD/Code/Libraries/Source/debug/debug_stack.inl
+++ b/GeneralsMD/Code/Libraries/Source/debug/debug_stack.inl
@@ -31,36 +31,22 @@ DBGHELP(SymSetOptions,
DWORD,
(DWORD SymOptions))
-DBGHELP(StackWalk,
+// Only the 64-bit entry points are asked for. A 64-bit dbghelp.dll does not export StackWalk,
+// SymFunctionTableAccess, SymGetModuleBase, SymGetSymFromAddr or SymGetLineFromAddr at all, and one
+// missing name empties the whole table below.
+DBGHELP(SymGetSymFromAddr64,
BOOL,
- (DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME StackFrame,
- LPVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
- PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
- PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
- PTRANSLATE_ADDRESS_ROUTINE TranslateAddress))
+ (HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement,
+ PIMAGEHLP_SYMBOL64 Symbol))
-DBGHELP(SymFunctionTableAccess,
- LPVOID,
- (HANDLE hProcess, DWORD AddrBase))
-
-DBGHELP(SymGetModuleBase,
- DWORD,
- (HANDLE hProcess, DWORD dwAddr))
-
-DBGHELP(SymGetSymFromAddr,
- BOOL,
- (HANDLE hProcess, DWORD Address, LPDWORD Displacement,
- PIMAGEHLP_SYMBOL Symbol))
-
-DBGHELP(SymGetLineFromAddr,
+DBGHELP(SymGetLineFromAddr64,
BOOL,
- (HANDLE hProcess, DWORD dwAddr, PDWORD pdwDisplacement,
- PIMAGEHLP_LINE Line))
+ (HANDLE hProcess, DWORD64 dwAddr, PDWORD pdwDisplacement,
+ PIMAGEHLP_LINE64 Line))
-// StackWalk/SymFunctionTableAccess/SymGetModuleBase are the 32-bit-only originals.
+// StackWalk/SymFunctionTableAccess are the 32-bit-only originals.
// On a current dbghelp.dll the legacy StackWalk fails outright (ERROR_PARTIAL_COPY
-// on its very first step), so the walker uses the 64-bit trio instead; the Sym*
-// lookups above still work, they only take an address.
+// on its very first step), so the walker uses the 64-bit trio instead.
DBGHELP(StackWalk64,
BOOL,
(DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame,
diff --git a/GeneralsMD/Code/Libraries/Source/profile/internal.h b/GeneralsMD/Code/Libraries/Source/profile/internal.h
index ca80469fb..5f1a9ad2b 100644
--- a/GeneralsMD/Code/Libraries/Source/profile/internal.h
+++ b/GeneralsMD/Code/Libraries/Source/profile/internal.h
@@ -22,7 +22,7 @@
// $Revision: #3 $
// $DateTime: 2003/07/09 10:57:23 $
//
-// �2003 Electronic Arts
+// �2003 Electronic Arts
//
// Internal header
//////////////////////////////////////////////////////////////////////////////
@@ -50,23 +50,13 @@ class ProfileFastCS
{
volatile unsigned& nFlag=m_Flag;
- #define ts_lock _emit 0xF0
- DASSERT(((unsigned)&nFlag % 4) == 0);
-
- __asm mov ebx, [nFlag]
- __asm ts_lock
- __asm bts dword ptr [ebx], 0
- __asm jc The_Bit_Was_Previously_Set_So_Try_Again
+ // EA's "lock bts" spin, written with the intrinsic that compiles to the same instruction.
+ while (_interlockedbittestandset((volatile long *)&nFlag, 0))
+ {
+ if (testEvent)
+ ::WaitForSingleObject(testEvent,1);
+ }
return;
-
- The_Bit_Was_Previously_Set_So_Try_Again:
- // can't use SwitchToThread() here because Win9X doesn't have it!
- if (testEvent)
- ::WaitForSingleObject(testEvent,1);
- __asm mov ebx, [nFlag]
- __asm ts_lock
- __asm bts dword ptr [ebx], 0
- __asm jc The_Bit_Was_Previously_Set_So_Try_Again
}
void ThreadSafeClearFlag()
@@ -109,17 +99,7 @@ void ProfileFreeMemory(void *ptr);
__forceinline void ProfileGetTime(__int64 &t)
{
- _asm
- {
- mov ecx,[t]
- push eax
- push edx
- rdtsc
- mov [ecx],eax
- mov [ecx+4],edx
- pop edx
- pop eax
- };
+ t = (__int64)__rdtsc();
}
#endif // INTERNAL_H
diff --git a/GeneralsMD/Code/Stubs/NullAudioManager.h b/GeneralsMD/Code/Stubs/NullAudioManager.h
index 2078a268b..942343cd6 100644
--- a/GeneralsMD/Code/Stubs/NullAudioManager.h
+++ b/GeneralsMD/Code/Stubs/NullAudioManager.h
@@ -54,7 +54,7 @@ public:
virtual void closeDevice( void ) {}
virtual void *getDevice( void ) { return NULL; }
- virtual void notifyOfAudioCompletion( UnsignedInt, UnsignedInt ) {}
+ virtual void notifyOfAudioCompletion( UnsignedIntPtr, UnsignedInt ) {}
/* One provider named "Software" keeps the options screen from showing an
empty list; selecting it is a no-op. */
diff --git a/GeneralsMD/Code/Tests/bink_smoke.c b/GeneralsMD/Code/Tests/bink_smoke.c
index ce9dbcefe..25c000f3d 100644
--- a/GeneralsMD/Code/Tests/bink_smoke.c
+++ b/GeneralsMD/Code/Tests/bink_smoke.c
@@ -77,6 +77,20 @@ int main(int argc, char **argv) {
fileRate = rd32(hdr + 28);
fileRateDiv = rd32(hdr + 32);
+#ifdef BINK_LINKED_PLAYER
+ /* x64 has no BINKW32.DLL to load - the movie player is FFmpeg, linked in. The checks below
+ are the same ones, and they are worth more here: every value they compare is now produced
+ by our own decoder rather than read back out of RAD's. */
+ (void)dllPath;
+ dll = NULL;
+ pOpen = BinkOpen;
+ pClose = BinkClose;
+ pDoFrame = BinkDoFrame;
+ pNextFrame = BinkNextFrame;
+ pCopy = BinkCopyToBuffer;
+ pSetSoundTrack = BinkSetSoundTrack;
+ pGetError = NULL;
+#else
/* An absolute path, because a relative one still goes through the DLL search
order - and that starts at this exe's own directory, where the build puts
the no-op stub also called binkw32.dll. */
@@ -97,6 +111,7 @@ int main(int argc, char **argv) {
printf("FAIL BINKW32.DLL does not export the decorated names bink.def lists\n");
return 1;
}
+#endif
pSetSoundTrack(0, 0); /* decode silently, no audio device needed */
bnk = pOpen(path, BINKPRELOADALL);
@@ -148,7 +163,7 @@ int main(int argc, char **argv) {
free(buf32);
free(buf24);
pClose(bnk);
- FreeLibrary(dll);
+ if (dll) FreeLibrary(dll);
printf("%s: %ux%u, %u frames, %u/%u fps - %d failure(s)\n", path, w, h,
fileFrames, fileRate, fileRateDiv, failures);
diff --git a/GeneralsMD/Code/Tests/miles_smoke.cpp b/GeneralsMD/Code/Tests/miles_smoke.cpp
new file mode 100644
index 000000000..d413debfc
--- /dev/null
+++ b/GeneralsMD/Code/Tests/miles_smoke.cpp
@@ -0,0 +1,217 @@
+/*
+ * miles_smoke - plays sound through the x64 audio backend and checks that it was consumed.
+ *
+ * The x64 build has no retail mss32.dll to bind to, so MilesAudioManager talks to the XAudio2 and
+ * FFmpeg implementation in Libraries/Source/WWVegas/Miles6/xaudio2/. This drives that
+ * implementation the way the game does and waits for the end-of-sample callbacks: a callback only
+ * arrives once a voice has actually played a buffer out, so it is evidence that samples reached
+ * the mixer rather than evidence that the calls returned.
+ *
+ * Two paths, because the game has two: a whole PCM image handed over for a sound effect, and a
+ * file decoded as it plays for music and speech, read through the game's own file callbacks.
+ *
+ * On a machine with no audio device at all the mixer cannot start; that prints "skip" and passes,
+ * the same way bink_smoke does without game data.
+ */
+
+#include <windows.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#include "MSS/MSS.h"
+
+static int failures = 0;
+
+#define CHECK(cond, what) \
+ do { \
+ if (!(cond)) { \
+ printf("FAIL %s\n", (what)); \
+ ++failures; \
+ } \
+ } while (0)
+
+static const unsigned SAMPLE_RATE = 22050;
+static const unsigned SAMPLE_MILLISECONDS = 250;
+static const unsigned CALLBACK_TIMEOUT_MS = 5000;
+static const double TONE_HZ = 440.0;
+
+static volatile LONG g_sampleFinished;
+static volatile LONG g_streamFinished;
+
+static void AILCALLBACK onSampleDone(HSAMPLE) { InterlockedExchange(&g_sampleFinished, 1); }
+static void AILCALLBACK onStreamDone(HSTREAM) { InterlockedExchange(&g_streamFinished, 1); }
+
+/* ---- the game's file callbacks, as the plain filesystem ------------------------------------ */
+
+static U32 AILCALLBACK fileOpen(const char *name, AILFILEHANDLE *handle)
+{
+ FILE *file = fopen(name, "rb");
+ *handle = (AILFILEHANDLE)file;
+ return file != NULL;
+}
+
+static void AILCALLBACK fileClose(AILFILEHANDLE handle) { fclose((FILE *)handle); }
+
+static S32 AILCALLBACK fileSeek(AILFILEHANDLE handle, S32 offset, U32 whence)
+{
+ fseek((FILE *)handle, offset, (int)whence);
+ return (S32)ftell((FILE *)handle);
+}
+
+static U32 AILCALLBACK fileRead(AILFILEHANDLE handle, void *buffer, U32 bytes)
+{
+ return (U32)fread(buffer, 1, bytes, (FILE *)handle);
+}
+
+/* ---- a WAV image to play -------------------------------------------------------------------- */
+
+static void writeU32(unsigned char *p, unsigned int value)
+{
+ p[0] = (unsigned char)(value & 0xff);
+ p[1] = (unsigned char)((value >> 8) & 0xff);
+ p[2] = (unsigned char)((value >> 16) & 0xff);
+ p[3] = (unsigned char)((value >> 24) & 0xff);
+}
+
+static void writeU16(unsigned char *p, unsigned short value)
+{
+ p[0] = (unsigned char)(value & 0xff);
+ p[1] = (unsigned char)((value >> 8) & 0xff);
+}
+
+/* Returns a malloc'd mono 16-bit PCM WAV image of a sine tone, and its size. */
+static unsigned char *makeToneWav(unsigned milliseconds, unsigned *imageBytes)
+{
+ const unsigned frames = SAMPLE_RATE * milliseconds / 1000;
+ const unsigned payload = frames * 2;
+ unsigned char *image = (unsigned char *)malloc(44 + payload);
+ if (image == NULL) {
+ return NULL;
+ }
+
+ memcpy(image, "RIFF", 4);
+ writeU32(image + 4, 44 + payload - 8);
+ memcpy(image + 8, "WAVEfmt ", 8);
+ writeU32(image + 16, 16);
+ writeU16(image + 20, 1); /* PCM */
+ writeU16(image + 22, 1); /* mono */
+ writeU32(image + 24, SAMPLE_RATE);
+ writeU32(image + 28, SAMPLE_RATE * 2);
+ writeU16(image + 32, 2);
+ writeU16(image + 34, 16);
+ memcpy(image + 36, "data", 4);
+ writeU32(image + 40, payload);
+
+ for (unsigned frame = 0; frame < frames; ++frame) {
+ const double phase = 2.0 * 3.14159265358979 * TONE_HZ * frame / SAMPLE_RATE;
+ const short value = (short)(sin(phase) * 8000.0);
+ writeU16(image + 44 + frame * 2, (unsigned short)value);
+ }
+
+ *imageBytes = 44 + payload;
+ return image;
+}
+
+static bool waitFor(volatile LONG *flag)
+{
+ for (unsigned waited = 0; waited < CALLBACK_TIMEOUT_MS; waited += 50) {
+ if (InterlockedCompareExchange(flag, 0, 0)) {
+ return true;
+ }
+ Sleep(50);
+ }
+ return false;
+}
+
+int main(void)
+{
+ unsigned imageBytes = 0;
+ unsigned char *wav = makeToneWav(SAMPLE_MILLISECONDS, &imageBytes);
+ if (wav == NULL) {
+ printf("FAIL out of memory building the test tone\n");
+ return 1;
+ }
+
+ AIL_startup();
+ if (!AIL_quick_startup(1, 0, 44100, 16, 2)) {
+ printf("skip: no audio device\n");
+ free(wav);
+ return 0;
+ }
+
+ HDIGDRIVER digitalDriver = NULL;
+ AIL_quick_handles(&digitalDriver, NULL, NULL);
+ CHECK(digitalDriver != NULL, "AIL_quick_handles gave no digital driver");
+
+ /* The provider list the options screen shows, and the one name MilesAudioManager looks up by
+ hand before indexing its array with the result. */
+ HPROENUM next = HPROENUM_FIRST;
+ HPROVIDER provider = 0;
+ char *name = NULL;
+ bool sawFast2D = false;
+ while (AIL_enumerate_3D_providers(&next, &provider, &name)) {
+ if (name != NULL && strcmp(name, "Miles Fast 2D Positional Audio") == 0) {
+ sawFast2D = true;
+ }
+ }
+ CHECK(sawFast2D, "the provider list has no \"Miles Fast 2D Positional Audio\"");
+
+ /* The WAV header reader the audio cache runs over every sound it loads. */
+ AILSOUNDINFO info;
+ memset(&info, 0, sizeof(info));
+ CHECK(AIL_WAV_info(wav, &info) != 0, "AIL_WAV_info rejected a PCM WAV");
+ CHECK(info.format == WAVE_FORMAT_PCM, "AIL_WAV_info reported the wrong format");
+ CHECK(info.rate == SAMPLE_RATE, "AIL_WAV_info reported the wrong sample rate");
+ CHECK(info.channels == 1, "AIL_WAV_info reported the wrong channel count");
+ CHECK(info.samples == SAMPLE_RATE * SAMPLE_MILLISECONDS / 1000,
+ "AIL_WAV_info reported the wrong sample count");
+
+ /* Path one: a sound effect, played from an image already in memory. */
+ HSAMPLE sample = AIL_allocate_sample_handle(digitalDriver);
+ CHECK(sample != NULL, "no 2D sample handle");
+ if (sample != NULL) {
+ AIL_init_sample(sample);
+ AIL_register_EOS_callback(sample, onSampleDone);
+ AIL_set_sample_volume_pan(sample, 0.2f, 0.5f);
+ CHECK(AIL_set_sample_file(sample, wav, 0) != 0, "AIL_set_sample_file rejected the tone");
+ AIL_start_sample(sample);
+ CHECK(waitFor(&g_sampleFinished), "the sample never reached its end-of-sample callback");
+ AIL_release_sample_handle(sample);
+ }
+
+ /* Path two: a stream, decoded from a file through the callbacks the game installs. */
+ char streamPath[MAX_PATH];
+ char tempDirectory[MAX_PATH];
+ GetTempPathA(sizeof(tempDirectory), tempDirectory);
+ snprintf(streamPath, sizeof(streamPath), "%smiles_smoke_tone.wav", tempDirectory);
+ FILE *out = fopen(streamPath, "wb");
+ if (out != NULL) {
+ fwrite(wav, 1, imageBytes, out);
+ fclose(out);
+
+ AIL_set_file_callbacks(fileOpen, fileClose, fileSeek, fileRead);
+ HSTREAM stream = AIL_open_stream(digitalDriver, streamPath, 0);
+ CHECK(stream != NULL, "AIL_open_stream could not open the tone");
+ if (stream != NULL) {
+ S32 total = 0;
+ AIL_stream_ms_position(stream, &total, NULL);
+ CHECK(total > (S32)SAMPLE_MILLISECONDS / 2 && total < (S32)SAMPLE_MILLISECONDS * 2,
+ "the stream's reported length is not the tone's length");
+
+ AIL_register_stream_callback(stream, onStreamDone);
+ AIL_set_stream_volume_pan(stream, 0.2f, 0.5f);
+ AIL_start_stream(stream);
+ CHECK(waitFor(&g_streamFinished), "the stream never reached its end-of-stream callback");
+ AIL_close_stream(stream);
+ }
+ remove(streamPath);
+ }
+
+ AIL_shutdown();
+ free(wav);
+
+ printf("miles_smoke: %d failure(s)\n", failures);
+ return failures;
+}
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 2b8187eb5..e563ae715 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -563,25 +563,13 @@ TEST(stackdump_walks_the_callers)
CHECK( strstr( s_stackText, "stackdump_walks_the_callers" ) != NULL );
}
-/* Two __asm blocks in headers everything includes wrote to registers that belong
- to the caller. fast_float_trunc's "xor ebx,ebx" is what killed every run at the
- main menu: W3DTreeBuffer::doLighting keeps its saved ESP in EBX, so the epilogue's
- "mov esp,ebx" set ESP to zero and the following pop faulted. The witnesses below
- put a sentinel in each register, run the block, and read the register back. */
-static unsigned truncEbxWitness( float f )
-{
- unsigned ebxOut;
- volatile float t;
- __asm mov ebx, 0x0BADF00D
- t = fast_float_trunc( f );
- __asm mov ebxOut, ebx
- (void)t;
- return ebxOut;
-}
-
+/* fast_float_trunc was an __asm block in a header everything includes, and it wrote to registers
+ that belong to the caller: its "xor ebx,ebx" is what killed every run at the main menu, because
+ W3DTreeBuffer::doLighting keeps its saved ESP in EBX and the epilogue's "mov esp,ebx" then set
+ ESP to zero. A witness used to plant a sentinel in EBX around the call and read it back; the
+ function is C now, so what is left to check is that it still truncates the way the assembly did. */
TEST(fast_float_trunc_leaves_ebx_alone)
{
- CHECK_EQ( truncEbxWitness( 3.75f ), 0x0BADF00D );
CHECK_NEAR( fast_float_trunc( 3.75f ), 3.0f, 0.0001f );
CHECK_NEAR( fast_float_trunc( -3.75f ), -3.0f, 0.0001f );
}
@@ -680,40 +668,14 @@ TEST(real_to_int_does_not_care_what_rounding_mode_it_is_called_in)
_controlfp( callersMode, _MCW_PC | _MCW_RC );
}
-/* The length is a parameter and not a strlen() call on purpose: anything the compiler
- emits between the two blocks below is free to use these registers itself, so the
- witness only stays honest while the call is the only thing in between. */
-static void crcRegisterWitness( const char *text, Int len, unsigned *ebxOut, unsigned *esiOut, unsigned *ediOut )
-{
- CRC crc;
- __asm
- {
- mov ebx, 0x0BADF00D
- mov esi, 0x0BADBEEF
- mov edi, 0x0BADCAFE
- }
- crc.computeCRC( text, len );
- __asm
- {
- mov eax, ebxOut
- mov dword ptr [eax], ebx
- mov eax, esiOut
- mov dword ptr [eax], esi
- mov eax, ediOut
- mov dword ptr [eax], edi
- }
-}
-
+/* computeCRC was assembly that used EBX, ESI and EDI without handing them back, and a witness here
+ planted sentinels in the three around the call. The function is C now. What still matters is
+ the number it produces: it goes into every multiplayer and replay checksum, so it is checked
+ against the arithmetic EA documented in the header. */
TEST(crc_computecrc_leaves_the_callee_saved_registers_alone)
{
const char *text = "the quick brown fox";
- unsigned ebxOut = 0, esiOut = 0, ediOut = 0;
- crcRegisterWitness( text, (Int)strlen( text ), &ebxOut, &esiOut, &ediOut );
- CHECK_EQ( ebxOut, 0x0BADF00D );
- CHECK_EQ( esiOut, 0x0BADBEEF );
- CHECK_EQ( ediOut, 0x0BADCAFE );
- /* ...and it still computes what the C++ version in the header's comment does. */
UnsignedInt expected = 0;
for( const UnsignedByte *p = (const UnsignedByte *)text; *p; ++p )
{
@@ -3304,17 +3266,20 @@ TEST(setfpmode_pins_the_control_word_from_whatever_it_finds)
// the mode the simulation runs in: 24-bit precision, round to nearest
setFPMode();
CHECK_EQ( getFPMode(), expectedFPMode() );
- CHECK_EQ( getFPMode() & _MCW_PC, (UnsignedInt)(_PC_24 & _MCW_PC) );
+ // x64 has no x87 precision field: SSE rounds at the declared width instead, and _controlfp
+ // fails fast on a mask that names _MCW_PC there. FP_MODE_FIELDS is what setFPMode owns.
+ if( FP_MODE_FIELDS & _MCW_PC )
+ CHECK_EQ( getFPMode() & _MCW_PC, (UnsignedInt)(_PC_24 & _MCW_PC) );
CHECK_EQ( getFPMode() & _MCW_RC, (UnsignedInt)(_RC_NEAR & _MCW_RC) );
// what a driver that grabbed the FPU and never gave it back looks like
- _controlfp( _PC_64 | _RC_CHOP, _MCW_PC | _MCW_RC );
+ _controlfp( (_PC_64 | _RC_CHOP) & FP_MODE_FIELDS, FP_MODE_FIELDS );
CHECK_NE( getFPMode(), expectedFPMode() );
setFPMode();
CHECK_EQ( getFPMode(), expectedFPMode() );
// and the other direction, so this is not just "setFPMode lowers the precision"
- _controlfp( _PC_53 | _RC_UP, _MCW_PC | _MCW_RC );
+ _controlfp( (_PC_53 | _RC_UP) & FP_MODE_FIELDS, FP_MODE_FIELDS );
CHECK_NE( getFPMode(), expectedFPMode() );
setFPMode();
CHECK_EQ( getFPMode(), expectedFPMode() );
@@ -3323,7 +3288,7 @@ TEST(setfpmode_pins_the_control_word_from_whatever_it_finds)
setFPMode();
CHECK_EQ( getFPMode(), expectedFPMode() );
- _controlfp( entry, _MCW_PC | _MCW_RC );
+ _controlfp( entry, FP_MODE_FIELDS );
}
TEST(setfpmode_leaves_the_exception_mask_in_a_known_state)
@@ -5457,13 +5422,15 @@ TEST(the_simulation_math_fingerprint_is_the_machines_math_and_not_the_callers_fp
CHECK( fromSimulationMode != 0 );
CHECK_EQ( SimulationMathCrc::calculate(), fromSimulationMode );
- _controlfp( _PC_53, _MCW_PC );
+ // Some mode that is not the simulation's. EA's own worry was the 53-bit precision a driver
+ // leaves behind; there is no precision field any more, so this is the rounding mode instead.
+ _controlfp( _RC_UP, _MCW_RC );
const UnsignedInt modeIn53 = getFPMode();
CHECK( modeIn53 != expectedFPMode() );
CHECK_EQ( SimulationMathCrc::calculate(), fromSimulationMode );
CHECK_EQ( getFPMode(), modeIn53 ); // and the caller's mode is still the caller's
- _controlfp( _PC_64 | _RC_CHOP, _MCW_PC | _MCW_RC );
+ _controlfp( (_PC_64 | _RC_CHOP) & FP_MODE_FIELDS, FP_MODE_FIELDS );
const UnsignedInt modeInChop = getFPMode();
CHECK( modeInChop != expectedFPMode() );
CHECK_EQ( SimulationMathCrc::calculate(), fromSimulationMode );
diff --git a/GeneralsMD/Code/Tests/test_ww3d2.cpp b/GeneralsMD/Code/Tests/test_ww3d2.cpp
index d0d7d6ef9..2fa67b22f 100644
--- a/GeneralsMD/Code/Tests/test_ww3d2.cpp
+++ b/GeneralsMD/Code/Tests/test_ww3d2.cpp
@@ -1581,51 +1581,22 @@ TEST(w3d_shader_struct_is_the_size_the_file_format_expects)
}
/* ------------------------------------------------------------------ */
-/* DX8Wrapper::Convert_Color / Clamp_Color register discipline.
+/* DX8Wrapper::Convert_Color / Clamp_Color.
*
- * Both are WWINLINE __asm blocks in dx8wrapper.h, inlined into every
- * renderer that converts a color. The Convert_Color block used EAX,
- * EBX, ECX, EDX, ESI and EDI as scratch without handing them back;
- * VS2022 keeps live values in those registers across the inlined block
- * (SegLineRendererClass::Render held its point count in EAX and its
- * transform reference in EBX), so the shell map died in Render with a
- * color value where a pointer should have been. Same class of bug as
- * fast_float_trunc and CRC::computeCRC, witnessed the same way: plant
- * a sentinel, run the block, read the sentinel back. The witnesses
- * cover the callee-saved registers only - the compiler is entitled to
- * use EAX/ECX/EDX for its own glue between the two asm blocks. */
+ * Both were WWINLINE __asm blocks in dx8wrapper.h, inlined into every
+ * renderer that converts a color, and Convert_Color used EAX, EBX, ECX,
+ * EDX, ESI and EDI as scratch without handing them back: the shell map
+ * died in SegLineRendererClass::Render with a color value where a
+ * pointer should have been. Witnesses here planted sentinels in the
+ * callee-saved registers to catch that. Both are C now, and what the
+ * tests check is the arithmetic: the same bytes the assembly produced. */
#include "dx8wrapper.h"
-static void convertColorRegisterWitness(const Vector3 *rgb, float alpha, unsigned *colOut,
- unsigned *ebxOut, unsigned *esiOut, unsigned *ediOut)
-{
- __asm
- {
- mov ebx, 0x0BADF00D
- mov esi, 0x0BADBEEF
- mov edi, 0x0BADCAFE
- }
- *colOut = DX8Wrapper::Convert_Color(*rgb, alpha);
- __asm
- {
- mov eax, ebxOut
- mov dword ptr [eax], ebx
- mov eax, esiOut
- mov dword ptr [eax], esi
- mov eax, ediOut
- mov dword ptr [eax], edi
- }
-}
-
TEST(convert_color_leaves_the_callee_saved_registers_alone)
{
Vector3 rgb(0.4f, 0.8f, 0.2f);
- unsigned col = 0, ebxOut = 0, esiOut = 0, ediOut = 0;
- convertColorRegisterWitness(&rgb, 1.0f, &col, &ebxOut, &esiOut, &ediOut);
- CHECK_EQ(ebxOut, 0x0BADF00D);
- CHECK_EQ(esiOut, 0x0BADBEEF);
- CHECK_EQ(ediOut, 0x0BADCAFE);
+ unsigned col = DX8Wrapper::Convert_Color(rgb, 1.0f);
/* ...and it still converts: truncate(x*255), packed AARRGGBB. */
unsigned expected = ((unsigned)(1.0f * 255.0f) << 24)
@@ -1635,35 +1606,10 @@ TEST(convert_color_leaves_the_callee_saved_registers_alone)
CHECK_EQ(col, expected);
}
-static void clampColorRegisterWitness(Vector4 *color,
- unsigned *ebxOut, unsigned *esiOut, unsigned *ediOut)
-{
- __asm
- {
- mov ebx, 0x0BADF00D
- mov esi, 0x0BADBEEF
- mov edi, 0x0BADCAFE
- }
- DX8Wrapper::Clamp_Color(*color);
- __asm
- {
- mov eax, ebxOut
- mov dword ptr [eax], ebx
- mov eax, esiOut
- mov dword ptr [eax], esi
- mov eax, ediOut
- mov dword ptr [eax], edi
- }
-}
-
TEST(clamp_color_leaves_the_callee_saved_registers_alone)
{
Vector4 color(-0.5f, 0.5f, 2.0f, 1.0f);
- unsigned ebxOut = 0, esiOut = 0, ediOut = 0;
- clampColorRegisterWitness(&color, &ebxOut, &esiOut, &ediOut);
- CHECK_EQ(ebxOut, 0x0BADF00D);
- CHECK_EQ(esiOut, 0x0BADBEEF);
- CHECK_EQ(ediOut, 0x0BADCAFE);
+ DX8Wrapper::Clamp_Color(color);
CHECK_NEAR(color.X, 0.0f, 0.0001f);
CHECK_NEAR(color.Y, 0.5f, 0.0001f);
diff --git a/GeneralsMD/Code/Tools/ProfileSampler/eip_sampler.cpp b/GeneralsMD/Code/Tools/ProfileSampler/eip_sampler.cpp
index dde379f15..38b6a8e93 100644
--- a/GeneralsMD/Code/Tools/ProfileSampler/eip_sampler.cpp
+++ b/GeneralsMD/Code/Tools/ProfileSampler/eip_sampler.cpp
@@ -118,7 +118,7 @@ std::string module_of(HANDLE proc, DWORD64 addr)
return mi.ModuleName;
}
-void report(HANDLE proc, const std::map<DWORD, unsigned long long> &hits,
+void report(HANDLE proc, const std::map<DWORD64, unsigned long long> &hits,
unsigned long long total, const char *title)
{
std::map<std::string, Bucket> by_symbol;
@@ -138,8 +138,8 @@ void report(HANDLE proc, const std::map<DWORD, unsigned long long> &hits,
key = sym->Name;
} else {
char raw[96];
- sprintf_s(raw, "%s!0x%08lx", module_of(proc, addr).c_str(),
- static_cast<unsigned long>(addr));
+ sprintf_s(raw, "%s!0x%08llx", module_of(proc, addr).c_str(),
+ static_cast<unsigned long long>(addr));
key = raw;
}
@@ -192,7 +192,13 @@ void report(HANDLE proc, const std::map<DWORD, unsigned long long> &hits,
// still suspended, since it is moving the moment the thread resumes.
const size_t CALLER_DEPTH = 6;
const size_t CALLER_ROWS_SHOWN = 25;
-using CallerChain = std::array<DWORD, CALLER_DEPTH>;
+using CallerChain = std::array<DWORD64, CALLER_DEPTH>;
+
+// The sampler is built for the game's architecture: an x64 sampler reads an x64 game.
+#define CONTEXT_PC Rip
+#define CONTEXT_FRAME Rbp
+#define CONTEXT_STACK Rsp
+const DWORD SAMPLED_MACHINE = IMAGE_FILE_MACHINE_AMD64;
std::string symbol_name(HANDLE proc, DWORD64 addr, std::map<DWORD64, std::string> &cache)
{
@@ -212,7 +218,7 @@ std::string symbol_name(HANDLE proc, DWORD64 addr, std::map<DWORD64, std::string
name = sym->Name;
} else {
char raw[32];
- sprintf_s(raw, "0x%08lx", static_cast<unsigned long>(addr));
+ sprintf_s(raw, "0x%08llx", static_cast<unsigned long long>(addr));
name = raw;
}
cache[addr] = name;
@@ -223,20 +229,20 @@ CallerChain walk_callers(HANDLE proc, HANDLE thread, CONTEXT ctx)
{
CallerChain chain = {};
STACKFRAME64 frame = {};
- frame.AddrPC.Offset = ctx.Eip;
+ frame.AddrPC.Offset = ctx.CONTEXT_PC;
frame.AddrPC.Mode = AddrModeFlat;
- frame.AddrFrame.Offset = ctx.Ebp;
+ frame.AddrFrame.Offset = ctx.CONTEXT_FRAME;
frame.AddrFrame.Mode = AddrModeFlat;
- frame.AddrStack.Offset = ctx.Esp;
+ frame.AddrStack.Offset = ctx.CONTEXT_STACK;
frame.AddrStack.Mode = AddrModeFlat;
for (size_t depth = 0; depth < CALLER_DEPTH; ++depth) {
- const BOOL walked = StackWalk64(IMAGE_FILE_MACHINE_I386, proc, thread, &frame, &ctx, nullptr,
+ const BOOL walked = StackWalk64(SAMPLED_MACHINE, proc, thread, &frame, &ctx, nullptr,
SymFunctionTableAccess64, SymGetModuleBase64, nullptr);
if (!walked || frame.AddrPC.Offset == 0) {
break;
}
- chain[depth] = static_cast<DWORD>(frame.AddrPC.Offset);
+ chain[depth] = frame.AddrPC.Offset;
}
return chain;
}
@@ -352,7 +358,7 @@ int main(int argc, char **argv)
// turn "1 kHz" into 64 Hz.
timeBeginPeriod(1);
- std::vector<std::map<DWORD, unsigned long long>> hits(handles.size());
+ std::vector<std::map<DWORD64, unsigned long long>> hits(handles.size());
std::vector<unsigned long long> totals(handles.size(), 0);
std::vector<CallerChain> chains;
unsigned long long missed = 0;
@@ -376,7 +382,7 @@ int main(int argc, char **argv)
CONTEXT ctx = {};
ctx.ContextFlags = caller_filter ? CONTEXT_FULL : CONTEXT_CONTROL;
if (GetThreadContext(handles[i], &ctx)) {
- ++hits[i][ctx.Eip];
+ ++hits[i][ctx.CONTEXT_PC];
++totals[i];
if (caller_filter && i == 0) {
chains.push_back(walk_callers(proc, handles[i], ctx));
diff --git a/build.example.bat b/build.example.bat
index 0190a873a..0177b74af 100644
--- a/build.example.bat
+++ b/build.example.bat
@@ -1,7 +1,7 @@
@echo off
setlocal enabledelayedexpansion
-rem Build C&C Generals Zero Hour (Win32 x86 only -- x64 is rejected by design).
+rem Build C&C Generals Zero Hour (x64 by default; set PLATFORM=Win32 for the 32-bit build).
rem
rem build.bat configure (if needed) + build Release
rem build.bat Debug build another config (Release|RelWithDebInfo|Debug)
@@ -23,9 +23,10 @@ set "CMAKE="
rem Visual Studio editions to probe for that shipped cmake, in order.
set "VS_EDITIONS=Community Professional Enterprise BuildTools"
-rem CMake generator. Win32 x86 only -- x64 is rejected by the CMakeLists on purpose.
+rem CMake generator. x64 is the shipping build; Win32 still configures and is the reference the
+rem x64 picture and simulation are compared against.
set "GENERATOR=Visual Studio 17 2022"
-set "PLATFORM=Win32"
+set "PLATFORM=x64"
rem Config used when the command line does not name one.
set "DEFAULT_CONFIG=Release"
@@ -37,7 +38,8 @@ rem --------------------------- END MACHINE SETTINGS ---------------------------
set "ROOT=%~dp0"
set "SRC=%ROOT%GeneralsMD\Code"
-if not defined BUILD set "BUILD=%ROOT%build"
+rem One tree per platform, so the two can sit side by side: build64\ and build\.
+if not defined BUILD if /i "%PLATFORM%"=="x64" (set "BUILD=%ROOT%build64") else (set "BUILD=%ROOT%build")
set "CONFIG=%~1"
set "ARG2=%~2"