Compare commits

..

25 Commits

Author SHA1 Message Date
bicarus 4879a35eb8 overlay: remove keyboard / gamepad tab navigation (#755)
Tired of constantly fighting unintentional keyboard navigation behavior.

Also, remove `ImGuiConfigFlags_IsTouchScreen` which literally does
nothing.
2026-06-12 21:28:34 -07:00
bicarus fd7e850789 ccj: fix mouse wheel input in overlay (#754)
## Link to GitHub Issue or related Pull Request, if one exists
#251 

## Description of change
CCJ registers for rawinput mouse. We allowed the rawinput registration
to go through to the OS, which prevents spice's rawinput stack from
using the mouse. This caused the overlay to not accept mouse input. Fix
it by not letting the rawinput registration through. Luckily, mouse
input continues to work properly in CCJ (for touch).

Also, fix a bug in DX11 overlay when toggling the main menu.

## Testing
2026-06-12 03:42:59 -07:00
bicarus 0cf07c38da overlay: left nav for cards tab (#753)
Enable left nav for Card tab, splitting the single page into multiple
sub tabs.

Card Manager is now embedded in this UI (but can still be launched as a
separate window)
2026-06-12 00:57:52 -07:00
bicarus 1f073b2d75 overlay: combine buttons/analogs/overlay/lights (#752)
Same idea as #747 except for input/output binding.
2026-06-11 23:38:09 -07:00
jessemarthin 3037214932 Fix capture.get_jpg blocking during game load for Companion Mirror (#750)
Add a timeout and skip signalling to the D3D9 capture path so the API
thread no longer waits indefinitely when Present stops during loading.
Return the last successful JPEG frame as a fallback.

## Link to GitHub Issue or related Pull Request, if one exists
#746

## Description of change
* Fix `capture.get_jpg` blocking indefinitely when D3D9 screen capture
cannot
  complete during game loading (e.g. no Present calls).
* Add a 2-second timeout to `graphics_capture_receive_jpeg()` and cancel
  pending capture requests on timeout.
* Signal capture skip from D3D9 failure paths via
`graphics_capture_skip()`.
* Cache the last successful JPEG per screen and return it as a fallback
  when a new capture fails.
Tested with **stock iOS Spice Companion** only. I have not tested
Android or
other Companion clients. The iOS client implementation differs from the
others; this fix is server-side only.
No config file, CLI option, or API schema changes.

## Testing
* Built locally with llvm-mingw cross-compiler (WSL).
* Docker build (`src/spice2x/build_docker.sh`): Pending
* Tested with stock iOS Spice Companion on iPad: Mirror remains
connected
  during game loading instead of returning to KeyPad.
2026-06-11 19:14:47 -07:00
drmext 18d6d9783a overlay: fix Options tab contents jitter (#751)
## Link to GitHub Issue or related Pull Request, if one exists
#747

## Description of change
The old approach called ImGui’s `SetScrollHereY()` while the options
list was still being laid out. That caused one-frame scroll corrections
and edge-snap jitter near scroll boundaries.

The new approach in `build_options_tab()`:

1. **On click** - set a flag (`options_scroll_pending` for categories,
`options_scroll_top` for group headers).
2. **During layout** - when building the target category, record its
content position with `GetCursorPosY()` (don’t scroll yet).
3. **After all options are built** - apply scroll once by setting
`window->Scroll.y` directly, and only if the position actually needs to
change (0.5px threshold).

That deferred, single-pass scroll avoids the shake while still
supporting scroll-up, scroll-down, and re-click-to-recenter.


## Testing
In spicecfg.exe and in-game overlay, Options tab:

Open groups with many categories

Scroll content down manually, then click a higher category in the left
nav - content scrolls up to that section

Re-click the same category after manual scroll - jumps back without
shake

Rapid re-clicks when already aligned - no jitter

Switch group headers - still scrolls to top; re-click at top - no shake
2026-06-11 14:03:33 -07:00
bicarus 267add3227 iidx: set SOUND_OUTPUT_DEVICE even when -iidx is not enabled (#749)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change
For cab usage, when `-exec bm2dx.dll` is used without `-iidx` then
SOUND_OUTPUT_DEVICE never gets set.

Change this so that `SOUND_OUTPUT_DEVICE` gets set unconditionally if
`-iidxsounddevice` is set.

## Testing
2026-06-11 00:40:53 -07:00
bicarus a170627f52 overlay: redesign Options tab(s) (#747)
## Link to GitHub Issue or related Pull Request, if one exists
#0

## Description of change
Combine API/Options/Advanced/Development/Search tabs into one Options
tab and add a left nav for navigation categories.

Reduce information density for options table by making each row double
the height and slightly increasing widget sizes.

## Testing
2026-06-11 00:17:54 -07:00
drmext 5c244eaca7 improve E004 card generation and placeholder pcbid (#748)
## Link to GitHub Issue or related Pull Request, if one exists
#73

## Description of change
Generated cards now start with E0040100 to fully match real cards. The
placeholder example `E004010000000000` is replaced with
`E0040100FFFFFFFF`.

The invalid placeholder/fallback PCBID `04040000000000000000` is
replaced with `01201000000000010101`, which contains a valid
header/checksum, making it closer resemble a real PCBID while still
clearly being an example.
2026-06-10 23:24:43 -07:00
bicarus 6bcadccf09 audio: WASAPI Force Shared Mode option (#745)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change
This new option, `-wasapishared`, detects when the game opens WASAPI
Exclusive stream and forcibly opens a shared mode stream instead on the
real device.

#### Benefits of this:

1. No need for `force wasapi shared` patches
2. No need to change sample rate of audio devices before starting up
games
3. Adds ability to boot in shared mode even for games that do not have
shared wasapi changes (old GITADORA, popn HC)

As a result, this option is strictly better than `shared wasapi` patches
available for many games.

#### Downsides:
1. OS resampling will add a small latency, but not big enough to be
noticeable.
2. Using shared mode instead of exclusive mode adds latency, of course.

(If you cared about latency, you would use the low latency option, or
use exclusive or asio)

Basically it's the "make things work" button for audio that should work
for almost all games that we support.

The option has no effect if the game opens in shared mode.

## Testing
SDVX7 - ok
GITADORA GW - ok
popn HC - ok
IIDX - ok
2026-06-10 00:20:59 -07:00
bicarus-dev ccb3bac48c defer error for -exec 2026-06-09 00:09:00 -07:00
bicarus 0a7ecf82a9 build: produce shared objects for spice.exe / spice_laa.exe, disable 64-bit winxp builds (#744)
to speed up clean builds. GitHub CI time went from 20 minutes -> 10
minutes.
2026-06-08 17:42:41 -07:00
bicarus-dev 1c6929dd84 Move full screen Monitor options to Graphics (Full Screen) 2026-06-08 15:53:54 -07:00
bicarus 1d3d9040f2 Update bug_report.md 2026-06-08 00:51:48 -07:00
bicarus 8f1069628e Update bug_report.md 2026-06-08 00:50:33 -07:00
bicarus-dev f8c585a9d1 update main menu layout 2026-06-08 00:27:42 -07:00
bicarus 9651051990 overlay: make overlay toggle behavior more consistent (#743)
Clean up how various overlay toggle shortcuts work with the main menu
visible.
2026-06-07 21:56:06 -07:00
bicarus a54a62d0d7 overlay: fix dummy marker spacing (#741)
Fix alignment in patches tab
2026-06-07 19:14:43 -07:00
bicarus 100caa0f5c overlay: refactor overlay layering (#739)
## Link to GitHub Issue or related Pull Request, if one exists
n/a

## Description of change

Create three distinct layers for the overlay:

1. Bottommost persistent layer - non-interactable layer that is always
on. This was only for notifications, but now the FPS widget lives here
as well.
2. Overlay windows layer - most interactable windows go here.
3. Topmost main menu - this is reserved for the main menu (escape key)
and this is a modal dialog that occludes the layers below.

Why? 

- `toggle overlay` behavior with FPS widget *also* toggling on/off was a
bit confusing (now they're two separate keys)
- FPS widget is popular, but it caused the entire overlay to be active,
which affects how input is handled
- the main menu being a standalone window was a little awkward (now it's
a modal)

## Testing
2026-06-07 17:23:08 -07:00
bicarus-dev bb87aa2944 add placeholder text for ea url option 2026-06-07 01:48:52 -07:00
bicarus 2e2968d1bc overlay: remove dependency on d3dcompiler (#738)
## Link to GitHub Issue or related Pull Request, if one exists
Fixes #737, regressed by #707

## Description of change
ImGui backend for DX11 pulled in dependency on a specific version of
`d3dcompiler_47.dll` which is not present on stock Win7 OS image.

Change this to a runtime load of the DLL and disable the overlay if we
can't find one.

## Testing
- [x] Win11, DX11 overlay
- [x] Win11, DX9 overlay
- [x] Win7, DX9 overlay
2026-06-06 14:06:37 -07:00
bicarus 0457262472 audio: asio "downmix" 7.1 to stereo (#736)
## Link to GitHub Issue or related Pull Request, if one exists
#730 

## Description of change
Add an option that extracts channels from 7.1 ASIO and presents to 2-ch
ASIO. Same idea as the SDVX 2ch fix except for gitadora we are
duplicating the center channel to front.

## Testing
Tested SDVX and GFDM Arena.
2026-06-06 03:11:40 -07:00
bicarus-dev f23c359114 minify patches json again 2026-06-05 18:05:48 -07:00
bicarus-dev 81e74dcb97 remove museca difficulty patches 2026-06-05 17:45:36 -07:00
bicarus-dev 8ead941c6c format patches json 2026-06-05 17:22:38 -07:00
47 changed files with 2265 additions and 919 deletions
+5 -3
View File
@@ -11,9 +11,7 @@ assignees: ''
*name of game, version of game*
## Version of spice2x
*version of spice, this can be seen in the About tab, and in log.txt*
*please remember to test the LATEST beta version before posting a bug about it**
*please remember to test the LATEST beta version before posting a bug about it*
## Describe the issue
*what's the issue?*
@@ -22,3 +20,7 @@ assignees: ''
> [!WARNING]
> Please make sure you remove any personally identifiable information from the log file.
> Please set `-loglevel` to `all` before launching the game for more verbose logs.
## A note on issue management
`Closed as not planned` means exactly that - it's closed, because it's not on our plans to address them any time soon. It doesn't mean your issue is invalid, it just means it's not a priority, and we can always revisit them later.
+27 -16
View File
@@ -236,7 +236,7 @@ add_compile_definitions(
)
# SPICE_XP: set by build_all.sh for the WinXP-compat toolchains. Gates out
# the DX11 overlay backend (WinXP lacks D3DCOMPILER_47.dll).
# the DX11 overlay backend
option(SPICE_XP "Build for the WinXP-compat toolchain" OFF)
if(SPICE_XP)
add_compile_definitions(SPICE_XP=1)
@@ -510,6 +510,7 @@ set(SOURCE_FILES ${SOURCE_FILES}
hooks/audio/backends/wasapi/audio_render_client.cpp
hooks/audio/backends/wasapi/downmix.cpp
hooks/audio/backends/wasapi/resample.cpp
hooks/audio/backends/wasapi/shared.cpp
hooks/audio/backends/wasapi/dummy_audio_client.cpp
hooks/audio/backends/wasapi/dummy_audio_clock.cpp
hooks/audio/backends/wasapi/dummy_audio_render_client.cpp
@@ -670,37 +671,47 @@ set(SOURCE_FILES ${SOURCE_FILES}
source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} PREFIX "Source Files" FILES ${SOURCE_FILES})
# spice.exe / spice_laa.exe shared objects
###########################################
# spice.exe and spice_laa.exe are compiled identically; the only difference is
# the large-address-aware bit, which is set at link time. Compile the sources
# once into a shared OBJECT library so spice_laa.exe only costs an extra link
# instead of a full recompile.
add_library(spicetools_spice_objs OBJECT ${SOURCE_FILES})
target_link_libraries(spicetools_spice_objs
PUBLIC d3d9 ws2_32 version comctl32 shlwapi iphlpapi hid secur32 setupapi psapi winmm winhttp
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook imm32 dwmapi CpuFeatures::cpu_features)
target_link_libraries(spicetools_spice_objs PUBLIC winscard)
if(NOT MSVC)
set_target_properties(spicetools_spice_objs PROPERTIES COMPILE_FLAGS "-m32")
endif()
# spice.exe
###########
set(RESOURCE_FILES build/manifest.manifest build/manifest.rc build/icon.rc cfg/Win32D.rc)
add_executable(spicetools_spice ${SOURCE_FILES} ${RESOURCE_FILES})
target_link_libraries(spicetools_spice
PUBLIC d3d9 ws2_32 version comctl32 shlwapi iphlpapi hid secur32 setupapi psapi winmm winhttp
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook imm32 dwmapi CpuFeatures::cpu_features)
target_link_libraries(spicetools_spice PUBLIC winscard)
add_executable(spicetools_spice ${RESOURCE_FILES})
target_link_libraries(spicetools_spice PRIVATE spicetools_spice_objs)
set_target_properties(spicetools_spice PROPERTIES PREFIX "")
set_target_properties(spicetools_spice PROPERTIES OUTPUT_NAME "spice")
IF(NOT MSVC)
set_target_properties(spicetools_spice PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")
set_target_properties(spicetools_spice PROPERTIES LINK_FLAGS "-m32")
endif()
# spice_laa.exe
###########
set(RESOURCE_FILES build/manifest.manifest build/manifest.rc build/icon.rc cfg/Win32D.rc)
add_executable(spicetools_spice_laa ${SOURCE_FILES} ${RESOURCE_FILES})
target_link_libraries(spicetools_spice_laa
PUBLIC d3d9 ws2_32 version comctl32 shlwapi iphlpapi hid secur32 setupapi psapi winmm winhttp
PRIVATE fmt::fmt-header-only discord-rpc imgui hash-library minhook imm32 dwmapi CpuFeatures::cpu_features)
target_link_libraries(spicetools_spice_laa PUBLIC winscard)
add_executable(spicetools_spice_laa ${RESOURCE_FILES})
target_link_libraries(spicetools_spice_laa PRIVATE spicetools_spice_objs)
set_target_properties(spicetools_spice_laa PROPERTIES PREFIX "")
set_target_properties(spicetools_spice_laa PROPERTIES OUTPUT_NAME "spice_laa")
target_compile_definitions(spicetools_spice_laa PRIVATE SPICE32_LARGE_ADDRESS_AWARE=1)
IF(NOT MSVC)
set_target_properties(spicetools_spice_laa PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32 -Wl,--large-address-aware")
set_target_properties(spicetools_spice_laa PROPERTIES LINK_FLAGS "-m32 -Wl,--large-address-aware")
endif()
# spice_linux.exe
@@ -734,7 +745,7 @@ set_target_properties(spicetools_spice64 PROPERTIES PREFIX "")
set_target_properties(spicetools_spice64 PROPERTIES OUTPUT_NAME "spice64")
target_compile_definitions(spicetools_spice64 PRIVATE SPICE64=1)
if(NOT SPICE_XP)
target_link_libraries(spicetools_spice64 PUBLIC d3d11 dxgi d3dcompiler)
target_link_libraries(spicetools_spice64 PUBLIC d3d11 dxgi)
target_compile_definitions(spicetools_spice64 PRIVATE SPICE_D3D11=1)
endif()
@@ -757,7 +768,7 @@ set_target_properties(spicetools_spice64_linux PROPERTIES OUTPUT_NAME "spice64_l
target_compile_definitions(spicetools_spice64_linux PRIVATE SPICE64=1)
target_compile_definitions(spicetools_spice64_linux PRIVATE NO_SCARD=1 PRIVATE SPICE_LINUX=1)
# spice64_linux is never built under the WinXP toolchain, so dx11 is always on.
target_link_libraries(spicetools_spice64_linux PUBLIC d3d11 dxgi d3dcompiler)
target_link_libraries(spicetools_spice64_linux PUBLIC d3d11 dxgi)
target_compile_definitions(spicetools_spice64_linux PRIVATE SPICE_D3D11=1)
IF(NOT MSVC)
+59 -15
View File
@@ -1,5 +1,7 @@
#include "capture.h"
#include <functional>
#include <mutex>
#include <unordered_map>
#include "external/rapidjson/document.h"
#include "hooks/graphics/graphics.h"
#include "util/crypt.h"
@@ -14,6 +16,56 @@ namespace api::modules {
static thread_local std::vector<uint8_t> CAPTURE_BUFFER;
struct CachedFrame {
std::vector<uint8_t> jpeg;
uint64_t timestamp = 0;
int width = 0;
int height = 0;
};
static std::mutex FRAME_CACHE_M;
static std::unordered_map<int, CachedFrame> FRAME_CACHE;
static void add_jpeg_response(
int screen,
uint64_t timestamp,
int width,
int height,
const std::vector<uint8_t> &jpeg,
Response &res) {
auto encoded = crypt::base64_encode(jpeg.data(), jpeg.size());
Value data;
data.SetString(encoded.c_str(), encoded.length(), res.doc()->GetAllocator());
res.add_data(timestamp);
res.add_data(width);
res.add_data(height);
res.add_data(data);
std::lock_guard<std::mutex> lock(FRAME_CACHE_M);
FRAME_CACHE[screen] = {jpeg, timestamp, width, height};
}
static bool try_cached_response(int screen, Response &res) {
std::lock_guard<std::mutex> lock(FRAME_CACHE_M);
const auto pos = FRAME_CACHE.find(screen);
if (pos == FRAME_CACHE.end() || pos->second.jpeg.empty()) {
return false;
}
const auto &cached = pos->second;
auto encoded = crypt::base64_encode(cached.jpeg.data(), cached.jpeg.size());
Value data;
data.SetString(encoded.c_str(), encoded.length(), res.doc()->GetAllocator());
res.add_data(cached.timestamp);
res.add_data(cached.width);
res.add_data(cached.height);
res.add_data(data);
return true;
}
Capture::Capture() : Module("capture") {
functions["get_screens"] = std::bind(&Capture::get_screens, this, _1, _2);
functions["get_jpg"] = std::bind(&Capture::get_jpg, this, _1, _2);
@@ -41,6 +93,7 @@ namespace api::modules {
* reduce: uint for dividing image size
*/
void Capture::get_jpg(Request &req, Response &res) {
CAPTURE_BUFFER.clear();
CAPTURE_BUFFER.reserve(1024 * 128);
// settings
@@ -71,24 +124,15 @@ namespace api::modules {
bool success = graphics_capture_receive_jpeg(screen, [] (uint8_t byte) {
CAPTURE_BUFFER.push_back(byte);
}, true, quality, true, divide, &timestamp, &width, &height);
if (!success) {
if (success) {
add_jpeg_response(screen, timestamp, width, height, CAPTURE_BUFFER, res);
CAPTURE_BUFFER.clear();
return;
}
// encode to base64
auto encoded = crypt::base64_encode(
CAPTURE_BUFFER.data(),
CAPTURE_BUFFER.size());
// clear buffer
// fall back to the last successful frame while the game is busy loading
CAPTURE_BUFFER.clear();
// add data to response
Value data;
data.SetString(encoded.c_str(), encoded.length(), res.doc()->GetAllocator());
res.add_data(timestamp);
res.add_data(width);
res.add_data(height);
res.add_data(data);
try_cached_response(screen, res);
}
}
+2 -2
View File
@@ -390,8 +390,8 @@ namespace avs {
// fall back to default PCBID if node is not found
if (!EA3_PCBID[0] && PCBID_CUSTOM.empty()) {
log_warning("avs-ea3", "no PCBID set, falling back to default PCBID value (04040000000000000000)");
PCBID_CUSTOM = "04040000000000000000";
log_warning("avs-ea3", "no PCBID set, falling back to default PCBID value (01201000000000010101)");
PCBID_CUSTOM = "01201000000000010101";
}
// custom PCBID
File diff suppressed because one or more lines are too long
+42 -16
View File
@@ -91,14 +91,20 @@ fi
# is the XP-compatible toolchain installed?
XP_MUST_BUILD=0
BUILD_XP=0
if [ -f "$TOOLCHAIN_WINXP_32" ] && [ -f "$TOOLCHAIN_WINXP_64" ]; then
BUILD_XP=1;
# 64-bit WinXP builds are disabled by default; set to 1 to opt in
BUILD_XP_64_ENABLE=0
BUILD_XP_32=0
BUILD_XP_64=0
if [ -f "$TOOLCHAIN_WINXP_32" ]; then
BUILD_XP_32=1;
elif ((XP_MUST_BUILD > 0))
then
echo "WinXP toolchain not available, aborting"
echo "WinXP 32bit toolchain not available, aborting"
exit 1
fi
if ((BUILD_XP_64_ENABLE > 0)) && [ -f "$TOOLCHAIN_WINXP_64" ]; then
BUILD_XP_64=1;
fi
# determine number of cores
CORES=$(nproc)
@@ -113,12 +119,17 @@ echo "Git Branch: $GIT_BRANCH"
echo "Git Head: $GIT_HEAD"
echo "Toolchain for 32bit targets: $TOOLCHAIN_32"
echo "Toolchain for 64bit targets: $TOOLCHAIN_64"
if ((BUILD_XP > 0))
if ((BUILD_XP_32 > 0))
then
echo "Toolchain for WinXP 32bit targets: $TOOLCHAIN_WINXP_32"
else
echo "WinXP 32bit toolchain not available, skipping WinXP 32bit builds"
fi
if ((BUILD_XP_64 > 0))
then
echo "Toolchain for WinXP 64bit targets: $TOOLCHAIN_WINXP_64"
else
echo "WinXP toolchain not available, skipping WinXP builds"
echo "WinXP 64bit builds disabled, skipping WinXP 64bit builds"
fi
echo "Distribution Name: $DIST_NAME"
echo "Build Type: $BUILD_TYPE"
@@ -160,7 +171,7 @@ time (
cmake -G "Ninja" -DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN_64} -DCMAKE_BUILD_TYPE=${BUILD_TYPE} "$OLDPWD" && ninja ${TARGETS_64}
popd > /dev/null
if ((BUILD_XP > 0))
if ((BUILD_XP_32 > 0))
then
# 32 bit Windows XP
echo ""
@@ -174,7 +185,13 @@ time (
pushd ${BUILDDIR_WINXP_32} > /dev/null
cmake -G "Ninja" -DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN_WINXP_32} -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DSPICE_XP=ON "$OLDPWD" && ninja ${TARGETS_XP32}
popd > /dev/null
else
echo ""
echo "Skipping WinXP 32bit builds, toolchain not specified"
fi
if ((BUILD_XP_64 > 0))
then
# 64 bit Windows XP
echo ""
echo "Building 64bit targets (WinXP toolchain)..."
@@ -189,7 +206,7 @@ time (
popd > /dev/null
else
echo ""
echo "Skipping WinXP builds, toolchain not specified"
echo "Skipping WinXP 64bit builds"
fi
echo ""
@@ -197,7 +214,7 @@ time (
echo "==========================="
)
if ((BUILD_XP > 0))
if ((BUILD_XP_32 > 0)) || ((BUILD_XP_64 > 0))
then
echo ""
echo "Checking XP compatibility..."
@@ -205,11 +222,17 @@ then
if ! command -v windows_dll_compat_checker &> /dev/null; then
echo "WARNING: windows_dll_compat_checker not found, skipping XP compatibility check"
else
windows_dll_compat_checker -s PREMADE/winxp_x86_64.ini \
${BUILDDIR_WINXP_64}/spicetools/64/spice64.exe
windows_dll_compat_checker -s PREMADE/winxp_x86_64_32bit_dlls.ini \
${BUILDDIR_WINXP_32}/spicetools/spicecfg.exe \
${BUILDDIR_WINXP_32}/spicetools/32/spice.exe
if ((BUILD_XP_64 > 0))
then
windows_dll_compat_checker -s PREMADE/winxp_x86_64.ini \
${BUILDDIR_WINXP_64}/spicetools/64/spice64.exe
fi
if ((BUILD_XP_32 > 0))
then
windows_dll_compat_checker -s PREMADE/winxp_x86_64_32bit_dlls.ini \
${BUILDDIR_WINXP_32}/spicetools/spicecfg.exe \
${BUILDDIR_WINXP_32}/spicetools/32/spice.exe
fi
fi
fi
@@ -271,7 +294,7 @@ mkdir -p ${OUTDIR_EXTRAS}/largeaddressaware
mkdir -p ${OUTDIR_EXTRAS}/linux
mkdir -p ${OUTDIR_EXTRAS}/sdk/samples/32
mkdir -p ${OUTDIR_EXTRAS}/sdk/samples/64
if ((BUILD_XP > 0))
if ((BUILD_XP_32 > 0)) || ((BUILD_XP_64 > 0))
then
mkdir -p ${OUTDIR_EXTRAS}/winxp
fi
@@ -301,10 +324,13 @@ else
cp ${BUILDDIR_32}/spicetools/32/sdk_sample_v0_flat_c.dll ${OUTDIR_EXTRAS}/sdk/samples/32/v0_flat_c.dll 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/sdk_sample_v0_flat_c.dll ${OUTDIR_EXTRAS}/sdk/samples/64/v0_flat_c.dll 2>/dev/null
cp ${BUILDDIR_64}/spicetools/64/sdk_sample_v0_cpp.dll ${OUTDIR_EXTRAS}/sdk/samples/64/v0_cpp.dll 2>/dev/null
if ((BUILD_XP > 0))
if ((BUILD_XP_32 > 0))
then
cp ${BUILDDIR_WINXP_32}/spicetools/spicecfg.exe ${OUTDIR_EXTRAS}/winxp 2>/dev/null
cp ${BUILDDIR_WINXP_32}/spicetools/32/spice.exe ${OUTDIR_EXTRAS}/winxp 2>/dev/null
fi
if ((BUILD_XP_64 > 0))
then
cp ${BUILDDIR_WINXP_64}/spicetools/64/spice64.exe ${OUTDIR_EXTRAS}/winxp 2>/dev/null
fi
fi
-1
View File
@@ -93,7 +93,6 @@ namespace cfg {
overlay::create_software(this->wnd.hWnd);
}
overlay::OVERLAY->set_active(true);
overlay::OVERLAY->hotkeys_enable = false;
ImGui::GetIO().MouseDrawCursor = false;
// run window
+2
View File
@@ -46,6 +46,8 @@ struct OptionDefinition {
// for OptionPickerType::FilePath
std::string file_extension = "";
std::string quick_setting_category = "";
};
class Option {
+1 -2
View File
@@ -21,8 +21,7 @@ set(IMGUI_SOURCES
misc/cpp/imgui_stdlib.cpp
)
# spice2x: DX11 backend is only built for non-XP toolchains. WinXP lacks
# D3DCOMPILER_47.dll, and including this TU would pull in D3DCompile imports.
# spice2x: DX11 backend is only built for non-XP toolchains
if(NOT SPICE_XP)
list(APPEND IMGUI_HEADERS backends/imgui_impl_dx11.h)
list(APPEND IMGUI_SOURCES backends/imgui_impl_dx11.cpp)
+37 -5
View File
@@ -50,9 +50,35 @@
#include <stdio.h>
#include <d3d11.h>
#include <d3dcompiler.h>
#ifdef _MSC_VER
#pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
#endif
// #ifdef _MSC_VER
// #pragma comment(lib, "d3dcompiler") // Automatically link with d3dcompiler.lib as we are using D3DCompile() below.
// #endif
// spice2x: resolve D3DCompile at runtime rather than static-linking d3dcompiler,
// which would hardwire an import on d3dcompiler_47.dll (absent on stock Win7).
static pD3DCompile ImGui_ImplDX11_GetD3DCompile()
{
static pD3DCompile fn = []() -> pD3DCompile {
static const char *dlls[] = {
"d3dcompiler_47.dll",
"d3dcompiler_46.dll",
"d3dcompiler_43.dll" };
for (const char *dll : dlls) {
HMODULE mod = GetModuleHandleA(dll);
if (!mod) {
mod = LoadLibraryA(dll);
}
if (mod) {
if (auto p = (pD3DCompile) GetProcAddress(mod, "D3DCompile")) {
return p;
}
}
}
return nullptr;
}();
return fn;
}
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
@@ -442,6 +468,12 @@ bool ImGui_ImplDX11_CreateDeviceObjects()
// 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
// See https://github.com/ocornut/imgui/pull/638 for sources and details.
// spice2x: dynamically resolved; see ImGui_ImplDX11_GetD3DCompile.
pD3DCompile D3DCompile_fn = ImGui_ImplDX11_GetD3DCompile();
if (!D3DCompile_fn) {
return false;
}
// Create the vertex shader
{
static const char* vertexShader =
@@ -473,7 +505,7 @@ bool ImGui_ImplDX11_CreateDeviceObjects()
}";
ID3DBlob* vertexShaderBlob;
if (FAILED(D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
if (FAILED(D3DCompile_fn(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &vertexShaderBlob, nullptr)))
return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
if (bd->pd3dDevice->CreateVertexShader(vertexShaderBlob->GetBufferPointer(), vertexShaderBlob->GetBufferSize(), nullptr, &bd->pVertexShader) != S_OK)
{
@@ -530,7 +562,7 @@ bool ImGui_ImplDX11_CreateDeviceObjects()
}";
ID3DBlob* pixelShaderBlob;
if (FAILED(D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
if (FAILED(D3DCompile_fn(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &pixelShaderBlob, nullptr)))
return false; // NB: Pass ID3DBlob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
if (bd->pd3dDevice->CreatePixelShader(pixelShaderBlob->GetBufferPointer(), pixelShaderBlob->GetBufferSize(), nullptr, &bd->pPixelShader) != S_OK)
{
+12 -3
View File
@@ -203,10 +203,19 @@ namespace games::ccj {
}
static BOOL WINAPI RegisterRawInputDevices_hook(PCRAWINPUTDEVICE pRawInputDevices, UINT uiNumDevices, UINT cbSize) {
if (uiNumDevices == 2 && pRawInputDevices[1].usUsage == HID_USAGE_GENERIC_GAMEPAD)
uiNumDevices = 1;
return RegisterRawInputDevices_orig(pRawInputDevices, uiNumDevices, cbSize);
// if the caller is spice itself, then pass through.
if (pRawInputDevices &&
(uiNumDevices > 0) &&
(pRawInputDevices[0].hwndTarget == RI_MGR->input_hwnd)) {
return RegisterRawInputDevices_orig(pRawInputDevices, uiNumDevices, cbSize);
}
// otherwise, it must be the game; prevent the game from registering for raw input
// and hijacking WM_INPUT messages; we need that for rawinput to work.
// even if we drop this, trackball emulation and mouse-as-touch input still work
return TRUE;
}
+1 -5
View File
@@ -543,11 +543,7 @@ namespace games::iidx {
// if the user specified a value (other than auto), use it as the environment var
// probably "wasapi" or "asio", but it's not explicitly checked here for forward compat
if (SOUND_OUTPUT_DEVICE.has_value() && SOUND_OUTPUT_DEVICE.value() != "auto") {
log_info(
"iidx",
"using user-supplied \"{}\" for SOUND_OUTPUT_DEVICE",
SOUND_OUTPUT_DEVICE.value());
SetEnvironmentVariable("SOUND_OUTPUT_DEVICE", SOUND_OUTPUT_DEVICE.value().c_str());
// the environemnt variable was already set in launcher.cpp
SOUND_OUTPUT_DEVICE_IN_EFFECT = SOUND_OUTPUT_DEVICE;
return;
}
+3 -1
View File
@@ -444,6 +444,8 @@ namespace games {
// overlay button definitions
names.emplace_back("Screenshot");
vkey_defaults.push_back(VK_SNAPSHOT);
names.emplace_back("Toggle All Windows");
vkey_defaults.push_back(VK_OEM_3); // backtick `
names.emplace_back("Toggle Main Menu");
vkey_defaults.push_back(VK_ESCAPE);
names.emplace_back("Toggle Sub Screen");
@@ -468,7 +470,7 @@ namespace games {
vkey_defaults.push_back(VK_F10);
names.emplace_back("Toggle Screen Resize");
vkey_defaults.push_back(VK_F11);
names.emplace_back("Toggle Overlay");
names.emplace_back("Toggle FPS");
vkey_defaults.push_back(VK_F12);
names.emplace_back("Toggle Camera Control");
vkey_defaults.push_back(0xFF);
+2 -1
View File
@@ -8,6 +8,7 @@ namespace games {
namespace OverlayButtons {
enum {
Screenshot,
ToggleAllWindows,
ToggleMainMenu,
ToggleSubScreen,
InsertCoin,
@@ -20,7 +21,7 @@ namespace games {
ToggleControl,
TogglePatchManager,
ToggleScreenResize,
ToggleOverlay,
ToggleFps,
ToggleCameraControl,
TriggerPinMacroP1,
TriggerPinMacroP2,
+258 -57
View File
@@ -40,6 +40,49 @@ namespace {
}
}
// bytes occupied by one sample of the given ASIO type, or 0 for formats we cannot size
// (used to compute the byte length of a planar channel buffer for raw copies)
int asio_sample_bytes(AsioSampleType type) {
switch (type) {
case ASIOSTInt16LSB:
case ASIOSTInt16MSB:
return 2;
case ASIOSTInt24LSB:
case ASIOSTInt24MSB:
return 3;
case ASIOSTInt32LSB:
case ASIOSTInt32MSB:
case ASIOSTInt32LSB16:
case ASIOSTInt32LSB18:
case ASIOSTInt32LSB20:
case ASIOSTInt32LSB24:
case ASIOSTInt32MSB16:
case ASIOSTInt32MSB18:
case ASIOSTInt32MSB20:
case ASIOSTInt32MSB24:
case ASIOSTFloat32LSB:
case ASIOSTFloat32MSB:
return 4;
case ASIOSTFloat64LSB:
case ASIOSTFloat64MSB:
return 8;
default:
return 0;
}
}
// readable name for a stereo downmix selection, used in our logs
const char *stereo_downmix_name(WrappedAsio::StereoDownmix mode) {
switch (mode) {
case WrappedAsio::StereoDownmix::None: return "none";
case WrappedAsio::StereoDownmix::Front: return "front";
case WrappedAsio::StereoDownmix::Center: return "center";
case WrappedAsio::StereoDownmix::Rear: return "rear";
case WrappedAsio::StereoDownmix::Side: return "side";
default: return "unknown";
}
}
// duration in milliseconds of a buffer of the given frame count at a sample rate, or a
// negative sentinel when the frame count or sample rate is unusable
double frames_to_ms(long frames, AsioSampleRate sample_rate) {
@@ -195,13 +238,27 @@ namespace hooks::audio::asio {
}
#pragma region IUnknown
bool WrappedAsio::FORCE_TWO_CHANNELS = false;
std::atomic<WrappedAsio *> WrappedAsio::volume_active_instance {nullptr};
WrappedAsio::StereoDownmix WrappedAsio::STEREO_DOWNMIX = WrappedAsio::StereoDownmix::None;
std::atomic<WrappedAsio *> WrappedAsio::active_instance {nullptr};
WrappedAsio::StereoDownmix WrappedAsio::name_to_stereo_downmix(const char *name) {
if (_stricmp(name, "front") == 0) {
return StereoDownmix::Front;
} else if (_stricmp(name, "center") == 0) {
return StereoDownmix::Center;
} else if (_stricmp(name, "rear") == 0) {
return StereoDownmix::Rear;
} else if (_stricmp(name, "side") == 0) {
return StereoDownmix::Side;
}
return StereoDownmix::None;
}
WrappedAsio::~WrappedAsio() {
unregister_wrapper(this);
this->detach_volume();
this->detach_post_process();
// our refcount is decoupled from the host's (see AddRef/Release), so pReal's count is
// exactly one here and this releases/unloads it deterministically
@@ -318,7 +375,7 @@ AsioError __thiscall WrappedAsio::get_channels(long *num_input_channels, long *n
return result;
}
if (FORCE_TWO_CHANNELS
if (force_two_channels()
&& num_output_channels != nullptr
&& *num_output_channels < FORCED_OUTPUT_CHANNELS)
{
@@ -456,16 +513,31 @@ AsioError __thiscall WrappedAsio::get_channel_info(AsioChannelInfo *info) {
// beyond the device without touching the real driver - they are discarded in
// create_buffers anyway
long real_in = 0, real_out = 0;
if (FORCE_TWO_CHANNELS
if (force_two_channels()
&& info != nullptr
&& info->is_input == AsioFalse
&& this->pReal->get_channels(&real_in, &real_out) == ASE_OK
&& info->channel >= real_out)
{
const long channel = info->channel;
// report the real device's output sample format rather than a fixed type: when
// stereo downmix is active the game writes these dummy channels in this format and
// we raw-copy the selected pair onto the device's front channels, so the formats
// must match or the copy produces static. the guard above already proved the device
// has output channels, so query channel 0's format directly (avoiding a redundant
// get_channels) and fall back to Int32LSB if that query fails
AsioChannelInfo real_ci {};
real_ci.channel = 0;
real_ci.is_input = AsioFalse;
AsioSampleType fake_type = ASIOSTInt32LSB;
if (this->pReal->get_channel_info(&real_ci) == ASE_OK) {
fake_type = real_ci.type;
}
info->is_active = AsioTrue;
info->channel_group = 0;
info->type = ASIOSTInt32LSB;
info->type = fake_type;
snprintf(info->name, sizeof(info->name), "Fake ASIO OUT %ld", channel);
log_info(
"audio::wrappedasio",
@@ -496,34 +568,61 @@ AsioError __thiscall WrappedAsio::get_channel_info(AsioChannelInfo *info) {
return result;
}
AsioCallbacks *WrappedAsio::install_volume_callbacks(AsioCallbacks *game_callbacks) {
AsioCallbacks *WrappedAsio::install_proxy_callbacks(AsioCallbacks *game_callbacks) {
const float gain = hooks::audio::VOLUME_BOOST;
// start from a clean slate; a previous buffer set may have left state behind
this->volume_channels.clear();
this->volume_active = false;
this->downmix_active = false;
// no boost configured (or no callbacks to wrap): pass the game's callbacks straight
// through and do zero realtime work, exactly as before
if (gain == 1.0f || game_callbacks == nullptr) {
const bool want_volume = (gain != 1.0f);
// front is the device's own pair, so selecting it (or None) means no copy is needed
const bool want_downmix = (STEREO_DOWNMIX != StereoDownmix::None
&& STEREO_DOWNMIX != StereoDownmix::Front);
// no post-processing configured (or no callbacks to wrap): pass the game's callbacks
// straight through and do zero realtime work, exactly as before
if ((!want_volume && !want_downmix) || game_callbacks == nullptr) {
return game_callbacks;
}
this->volume_active = true;
this->volume_gain = gain;
this->volume_game_callbacks = *game_callbacks;
if (want_volume) {
this->volume_active = true;
this->volume_gain = gain;
}
// wrap only the buffer-switch callbacks, where the audio data lives and we apply the
// gain. the other two carry no data we touch, so forward the game's own pointers
// unchanged - the driver expects them non-null and the game already owns their context
this->volume_proxy_callbacks = {};
this->volume_proxy_callbacks.buffer_switch = &WrappedAsio::volume_buffer_switch;
this->volume_proxy_callbacks.sample_rate_did_change = game_callbacks->sample_rate_did_change;
this->volume_proxy_callbacks.asio_message = game_callbacks->asio_message;
this->volume_proxy_callbacks.buffer_switch_time_info =
game_callbacks->buffer_switch_time_info ? &WrappedAsio::volume_buffer_switch_time_info : nullptr;
// the trampolines reach the game's buffer_switch through this copy, regardless of which
// effect is active
this->game_callbacks = *game_callbacks;
return &this->volume_proxy_callbacks;
// wrap only the buffer-switch callbacks, where the audio data lives and we rework it.
// the other two carry no data we touch, so forward the game's own pointers unchanged -
// the driver expects them non-null and the game already owns their context
this->proxy_callbacks = {};
this->proxy_callbacks.buffer_switch = &WrappedAsio::proxy_buffer_switch;
this->proxy_callbacks.sample_rate_did_change = game_callbacks->sample_rate_did_change;
this->proxy_callbacks.asio_message = game_callbacks->asio_message;
this->proxy_callbacks.buffer_switch_time_info =
game_callbacks->buffer_switch_time_info ? &WrappedAsio::proxy_buffer_switch_time_info : nullptr;
return &this->proxy_callbacks;
}
AsioSampleType WrappedAsio::device_output_sample_type() {
long real_in = 0, real_out = 0;
if (this->pReal->get_channels(&real_in, &real_out) != ASE_OK || real_out <= 0) {
return ASIOSTLastEntry;
}
AsioChannelInfo ci {};
ci.channel = 0;
ci.is_input = AsioFalse;
if (this->pReal->get_channel_info(&ci) != ASE_OK) {
return ASIOSTLastEntry;
}
return ci.type;
}
void WrappedAsio::record_volume_output_channel(const AsioBufferInfo &info) {
@@ -548,26 +647,97 @@ void WrappedAsio::record_volume_output_channel(const AsioBufferInfo &info) {
this->volume_channels.push_back(ch);
}
void WrappedAsio::publish_volume(long buffer_size) {
if (!this->volume_active) {
void WrappedAsio::record_downmix_channels(
AsioBufferInfo *buffer_infos, long num_channels, long buffer_size)
{
// map the selected pair to source channel indices (0-indexed, standard 7.1 layout);
// None and Front need no copy
long src_left = 0, src_right = 0;
switch (STEREO_DOWNMIX) {
case StereoDownmix::Center: src_left = 2; src_right = 2; break;
case StereoDownmix::Rear: src_left = 4; src_right = 5; break;
case StereoDownmix::Side: src_left = 6; src_right = 7; break;
default: return;
}
// find the double-buffer pair for a given output channel among those the game created,
// or nullptr if the device does not expose it
auto find_output = [&](long channel) -> void ** {
for (long i = 0; i < num_channels; i++) {
AsioBufferInfo &bi = buffer_infos[i];
if (bi.is_input == AsioFalse && bi.channel_num == channel) {
return bi.buffers;
}
}
return nullptr;
};
// destinations are device channels 0/1; sources are the selected pair
void **dst0 = find_output(0);
void **dst1 = find_output(1);
void **src_l = find_output(src_left);
void **src_r = find_output(src_right);
if (dst0 == nullptr || dst1 == nullptr || src_l == nullptr || src_r == nullptr) {
log_warning(
"audio::wrappedasio",
"stereo downmix disabled: device is missing the front pair or source channels "
"{}/{} (game created {} channel(s))",
src_left,
src_right,
num_channels);
return;
}
// all device output channels share one sample format; query it to size the copy
const AsioSampleType type = this->device_output_sample_type();
const int sample_bytes = asio_sample_bytes(type);
if (sample_bytes <= 0) {
log_warning(
"audio::wrappedasio",
"stereo downmix disabled: unsupported sample format {} ({})",
asio_sample_type_name(type),
static_cast<long>(type));
return;
}
this->downmix_copies[0] = {{dst0[0], dst0[1]}, {src_l[0], src_l[1]}};
this->downmix_copies[1] = {{dst1[0], dst1[1]}, {src_r[0], src_r[1]}};
this->downmix_bytes = static_cast<size_t>(buffer_size) * sample_bytes;
this->downmix_active = true;
log_info(
"audio::wrappedasio",
"stereo downmix active: pair={} (src {}/{} -> device 0/1), {} frames, {} byte(s)/sample",
stereo_downmix_name(STEREO_DOWNMIX),
src_left,
src_right,
buffer_size,
sample_bytes);
}
void WrappedAsio::publish_post_process(long buffer_size) {
if (!this->volume_active && !this->downmix_active) {
return;
}
// everything the realtime thread reads is now in place; make ourselves reachable
this->volume_buffer_size = buffer_size;
WrappedAsio::volume_active_instance.store(this, std::memory_order_release);
log_info(
"audio::wrappedasio",
"volume boost active: gain={}, scaling {} output channel(s)",
this->volume_gain,
this->volume_channels.size());
WrappedAsio::active_instance.store(this, std::memory_order_release);
if (this->volume_active) {
log_info(
"audio::wrappedasio",
"volume boost active: gain={}, scaling {} output channel(s)",
this->volume_gain,
this->volume_channels.size());
}
}
void WrappedAsio::detach_volume() {
void WrappedAsio::detach_post_process() {
// stop our realtime trampolines from reaching this wrapper, but only if we are the
// currently published instance
WrappedAsio *expected = this;
WrappedAsio::volume_active_instance.compare_exchange_strong(expected, nullptr);
WrappedAsio::active_instance.compare_exchange_strong(expected, nullptr);
}
void WrappedAsio::apply_output_volume(long double_buffer_index) {
@@ -581,35 +751,57 @@ void WrappedAsio::apply_output_volume(long double_buffer_index) {
}
}
void __cdecl WrappedAsio::volume_buffer_switch(long double_buffer_index, AsioBool direct_process) {
WrappedAsio *self = WrappedAsio::volume_active_instance.load(std::memory_order_acquire);
void WrappedAsio::apply_downmix(long double_buffer_index) {
if (!this->downmix_active) {
return;
}
if (double_buffer_index != 0 && double_buffer_index != 1) {
return;
}
// raw planar copy of the selected source channels onto device channels 0/1; for the
// center selection both copies share one source. skip self-copies (front)
for (const DownmixCopy &copy : this->downmix_copies) {
void *dst = copy.dst[double_buffer_index];
const void *src = copy.src[double_buffer_index];
if (dst != nullptr && src != nullptr && dst != src) {
std::memcpy(dst, src, this->downmix_bytes);
}
}
}
void __cdecl WrappedAsio::proxy_buffer_switch(long double_buffer_index, AsioBool direct_process) {
WrappedAsio *self = WrappedAsio::active_instance.load(std::memory_order_acquire);
if (self == nullptr) {
return;
}
// let the game write its samples into the driver buffers first, then scale them before
// the driver plays this half on the next switch
if (self->volume_game_callbacks.buffer_switch != nullptr) {
self->volume_game_callbacks.buffer_switch(double_buffer_index, direct_process);
// let the game write its samples into the driver buffers first, then rework them before
// the driver plays this half on the next switch: downmix first (arrange channels 0/1),
// then scale the device outputs by the volume boost
if (self->game_callbacks.buffer_switch != nullptr) {
self->game_callbacks.buffer_switch(double_buffer_index, direct_process);
}
self->apply_downmix(double_buffer_index);
self->apply_output_volume(double_buffer_index);
}
AsioTime * __cdecl WrappedAsio::volume_buffer_switch_time_info(
AsioTime * __cdecl WrappedAsio::proxy_buffer_switch_time_info(
AsioTime *params, long double_buffer_index, AsioBool direct_process)
{
WrappedAsio *self = WrappedAsio::volume_active_instance.load(std::memory_order_acquire);
WrappedAsio *self = WrappedAsio::active_instance.load(std::memory_order_acquire);
if (self == nullptr) {
return params;
}
AsioTime *ret = params;
if (self->volume_game_callbacks.buffer_switch_time_info != nullptr) {
ret = self->volume_game_callbacks.buffer_switch_time_info(
if (self->game_callbacks.buffer_switch_time_info != nullptr) {
ret = self->game_callbacks.buffer_switch_time_info(
params, double_buffer_index, direct_process);
} else if (self->volume_game_callbacks.buffer_switch != nullptr) {
self->volume_game_callbacks.buffer_switch(double_buffer_index, direct_process);
} else if (self->game_callbacks.buffer_switch != nullptr) {
self->game_callbacks.buffer_switch(double_buffer_index, direct_process);
}
self->apply_downmix(double_buffer_index);
self->apply_output_volume(double_buffer_index);
return ret;
}
@@ -620,11 +812,11 @@ AsioError __thiscall WrappedAsio::create_buffers(
long buffer_size,
AsioCallbacks *callbacks)
{
// swap in our buffer-switch trampolines if a volume boost is configured, so the real
// driver calls us and we scale its output after the game fills it (no-op otherwise)
AsioCallbacks *effective = this->install_volume_callbacks(callbacks);
// swap in our buffer-switch trampolines if any post-processing is configured, so the
// real driver calls us and we rework its output after the game fills it (no-op otherwise)
AsioCallbacks *effective = this->install_proxy_callbacks(callbacks);
if (FORCE_TWO_CHANNELS) {
if (force_two_channels()) {
return this->create_buffers_front_pair(buffer_infos, num_channels, buffer_size, effective);
}
@@ -636,14 +828,16 @@ AsioError __thiscall WrappedAsio::create_buffers(
num_channels,
buffer_size);
// capture the device output channels we will scale, then publish ourselves to the
// realtime thread once everything is in place
// capture the post-process state now the buffers exist, then publish ourselves to
// the realtime thread once everything is in place. downmix is not recorded here: any
// active stereo extraction forces the front-pair path above, so this path only ever
// runs the volume boost
if (this->volume_active) {
for (long i = 0; i < num_channels; i++) {
this->record_volume_output_channel(buffer_infos[i]);
}
this->publish_volume(buffer_size);
}
this->publish_post_process(buffer_size);
} else {
log_warning(
"audio::wrappedasio",
@@ -667,8 +861,9 @@ AsioError WrappedAsio::create_buffers_front_pair(
// device actually provides (channel 0/1 = front L/R) and hand the game throwaway
// buffers for the rest, so its front mix lands on the device and the surround
// channels are discarded. the game writes directly into the driver/dummy buffers
// from its own bufferSwitch; the only realtime work we do is the volume boost (if
// configured), which scales the forwarded device channels via our trampolines
// from its own bufferSwitch; the realtime work we do is the optional volume boost
// (scaling the forwarded device channels) and, if a non-front stereo downmix is
// selected, copying that pair from its dummy buffers onto the device's front pair
long real_in = 0, real_out = 0;
const AsioError ch_result = this->pReal->get_channels(&real_in, &real_out);
if (ch_result != ASE_OK) {
@@ -724,8 +919,6 @@ AsioError WrappedAsio::create_buffers_front_pair(
}
}
this->publish_volume(buffer_size);
// hand throwaway double buffers to the discarded channels. sized generously at
// 8 bytes/sample (covers every ASIO sample type) so the game can never overrun them
// regardless of the negotiated format
@@ -741,6 +934,13 @@ AsioError WrappedAsio::create_buffers_front_pair(
}
}
// record the downmix source/destination buffers now the array is fully patched: the
// selected pair (e.g. rear) lives in the dummy buffers above, the device front pair in
// the forwarded driver buffers, so the realtime copy lands the chosen pair on the
// device's 2.0 output. then publish ourselves to the realtime thread
this->record_downmix_channels(buffer_infos, num_channels, buffer_size);
this->publish_post_process(buffer_size);
log_info(
"audio::wrappedasio",
"create_buffers: front-pair extraction - forwarded {} channel(s) to device, "
@@ -755,12 +955,13 @@ AsioError WrappedAsio::create_buffers_front_pair(
AsioError __thiscall WrappedAsio::dispose_buffers() {
// stop our realtime trampolines from touching buffers the driver is about to free
this->detach_volume();
this->detach_post_process();
const AsioError result = this->pReal->dispose_buffers();
this->dummy_buffers.clear();
this->volume_channels.clear();
this->volume_active = false;
this->downmix_active = false;
return result;
}
+82 -26
View File
@@ -33,17 +33,38 @@ struct WrappedAsio final : IAsio {
virtual ~WrappedAsio();
// when set, the proxy presents the game's expected multichannel layout to the host so
// it proceeds to create_buffers, then forwards only the device's real front pair and
// discards the rest (see create_buffers). set once at boot, before any wrapper exists,
// so it needs no synchronization
static bool FORCE_TWO_CHANNELS;
// selects which source channel pair of a multichannel ASIO output reaches the device's
// 2.0 front pair. when not None, the proxy presents the game's expected multichannel
// layout to the host so it proceeds to create_buffers, then opens only a two-channel
// stream on the real device and routes the selected pair onto it (see create_buffers).
// Front is the plain "force two channel" case (forward the device's own front pair);
// the others copy a different pair onto 0/1. assumes a standard 7.1 layout (0-indexed).
// set once at boot, before any wrapper exists, so it needs no synchronization
enum class StereoDownmix {
None, // feature disabled - full multichannel passthrough
Front, // channels 0/1 - the device front pair is forwarded as-is (no copy)
Center, // channel 2 duplicated to both 0 and 1
Rear, // channels 4/5 -> 0/1
Side, // channels 6/7 -> 0/1
};
static StereoDownmix STEREO_DOWNMIX;
// true when a stereo extraction is configured, i.e. the real device should open a 2.0
// stream and only the selected pair should reach it. the former standalone
// FORCE_TWO_CHANNELS flag is now just the Front case of this
static bool force_two_channels() {
return STEREO_DOWNMIX != StereoDownmix::None;
}
// some games hardcode a multichannel ASIO output and bail before create_buffers if
// get_channels reports fewer, so we report at least this many output channels when
// FORCE_TWO_CHANNELS is active
// get_channels reports fewer, so we report at least this many output channels when a
// stereo extraction is active
static constexpr long FORCED_OUTPUT_CHANNELS = 8;
// maps an option string ("front", "center", "rear", "side") to a StereoDownmix value,
// returning None for anything unrecognized
static StereoDownmix name_to_stereo_downmix(const char *name);
#pragma region IUnknown
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv) override;
ULONG STDMETHODCALLTYPE AddRef() override;
@@ -83,7 +104,7 @@ struct WrappedAsio final : IAsio {
#pragma endregion
private:
// create_buffers implementation used when FORCE_TWO_CHANNELS is active: forwards only
// create_buffers implementation used when a stereo extraction is active: forwards only
// the channels the real device has and hands the game throwaway buffers for the rest
AsioError create_buffers_front_pair(
AsioBufferInfo *buffer_infos,
@@ -91,40 +112,56 @@ private:
long buffer_size,
AsioCallbacks *callbacks);
// if hooks::audio::VOLUME_BOOST is set, saves the game's callbacks and returns a proxy
// callback set (our buffer-switch trampolines) to hand the real driver instead, so we
// can scale its output buffers after the game fills them. otherwise returns the game's
// callbacks unchanged. called at create_buffers time, before the stream starts
AsioCallbacks *install_volume_callbacks(AsioCallbacks *game_callbacks);
// if any post-processing effect (volume boost or stereo downmix) is active, saves the
// game's callbacks and returns a proxy callback set (our buffer-switch trampolines) to
// hand the real driver instead, so we can rework its output buffers after the game
// fills them. otherwise returns the game's callbacks unchanged. called at create_buffers
// time, before the stream starts
AsioCallbacks *install_proxy_callbacks(AsioCallbacks *game_callbacks);
// records a device output channel whose buffers we scale by the volume boost. queries
// the real driver for the channel's sample format. called at create_buffers time
void record_volume_output_channel(const AsioBufferInfo &info);
// publishes the captured volume state to the realtime thread once the buffers exist,
// making our trampolines start scaling. called at the end of either create_buffers path
void publish_volume(long buffer_size);
// the real device's output sample format, queried from its first output channel. all
// output channels of a device share one format, so this characterizes them all. returns
// ASIOSTLastEntry if the device has no output channels or the query fails
AsioSampleType device_output_sample_type();
// locates the destination pair (device channels 0/1) and the configured source channels
// in the game's buffer set so the realtime path can copy the selected pair onto 0/1.
// a no-op unless STEREO_DOWNMIX selects a non-front pair. called at create_buffers time
void record_downmix_channels(AsioBufferInfo *buffer_infos, long num_channels, long buffer_size);
// publishes the captured post-process state to the realtime thread once the buffers
// exist, making our trampolines start reworking output. called at the end of either
// create_buffers path
void publish_post_process(long buffer_size);
// detaches this instance from the realtime trampolines so they stop touching its
// buffers. called from dispose_buffers and the destructor
void detach_volume();
void detach_post_process();
// multiplies every recorded output channel's buffer for the given double-buffer index
// by the volume boost. runs on the driver's realtime thread from our buffer switch
void apply_output_volume(long double_buffer_index);
// copies the configured source channel pair onto device channels 0/1 for the given
// double-buffer index. runs on the driver's realtime thread from our buffer switch
void apply_downmix(long double_buffer_index);
// realtime-thread trampolines for the buffer-switch callbacks, handed to the real
// driver in place of the game's; ASIO callbacks carry no user data, so they reach the
// active wrapper through volume_active_instance, call the game's original, then scale.
// active wrapper through active_instance, call the game's original, then rework output.
// the other two callbacks (sample_rate_did_change, asio_message) are forwarded as the
// game's own pointers, so they need no trampoline
static void __cdecl volume_buffer_switch(long double_buffer_index, AsioBool direct_process);
static AsioTime * __cdecl volume_buffer_switch_time_info(
static void __cdecl proxy_buffer_switch(long double_buffer_index, AsioBool direct_process);
static AsioTime * __cdecl proxy_buffer_switch_time_info(
AsioTime *params, long double_buffer_index, AsioBool direct_process);
// the single wrapper whose proxy callbacks are installed (ASIO is single-instance with
// one running stream); read by the static trampolines to reach the right wrapper
static std::atomic<WrappedAsio *> volume_active_instance;
static std::atomic<WrappedAsio *> active_instance;
IAsio *const pReal;
const CLSID clsid;
@@ -137,7 +174,7 @@ private:
// drops to zero
std::atomic<ULONG> ref_count {1};
// throwaway double buffers handed to the channels we discard when FORCE_TWO_CHANNELS
// throwaway double buffers handed to the channels we discard when a stereo extraction
// is active (see create_buffers). owned for the lifetime of the buffer set and freed
// in dispose_buffers; only read by the game from its own bufferSwitch, never by us
std::vector<std::unique_ptr<uint8_t[]>> dummy_buffers;
@@ -148,13 +185,32 @@ private:
AsioSampleType type;
};
// the game's original callbacks (captured when we install our proxy set) and the proxy
// set we hand the real driver; the realtime trampolines reach the game's buffer_switch
// through game_callbacks regardless of which effect is active
AsioCallbacks game_callbacks {};
AsioCallbacks proxy_callbacks {};
// volume boost state, captured at create_buffers time and published to the realtime
// thread via volume_active_instance once fully built; untouched while the stream runs.
// volume_active gates whether we install our proxy callbacks at all
// thread via active_instance once fully built; untouched while the stream runs.
// volume_active gates whether the realtime path scales any buffers
bool volume_active = false;
float volume_gain = 1.0f;
long volume_buffer_size = 0;
AsioCallbacks volume_game_callbacks {};
AsioCallbacks volume_proxy_callbacks {};
std::vector<VolumeOutputChannel> volume_channels;
// one device channel (0 or 1) fed by a source channel during stereo downmix; both
// buffer pointers are indexed by the ASIO double-buffer index, the same as the channels
struct DownmixCopy {
void *dst[2];
void *src[2];
};
// stereo downmix state, captured at create_buffers time and published alongside the
// volume state; untouched while the stream runs. downmix_active gates whether the
// realtime path copies the selected source pair onto device channels 0/1. copies[0]
// feeds device channel 0, copies[1] feeds device channel 1
bool downmix_active = false;
DownmixCopy downmix_copies[2] {};
size_t downmix_bytes = 0;
};
+1
View File
@@ -44,6 +44,7 @@ namespace hooks::audio {
float VOLUME_BOOST = 1.0f;
std::optional<uint32_t> RESAMPLE_RATE = std::nullopt;
std::optional<uint32_t> EXCLUSIVE_BUFFER_MS = std::nullopt;
bool WASAPI_COMPATIBILITY_MODE = false;
bool USE_DUMMY = false;
WAVEFORMATEXTENSIBLE FORMAT {};
std::optional<Backend> BACKEND = std::nullopt;
+6
View File
@@ -37,6 +37,12 @@ namespace hooks::audio {
// minimum WASAPI exclusive buffer duration (milliseconds), if set. enlarges the device buffer
// to avoid underrun crackle on endpoints that cannot service a tiny buffer in time.
extern std::optional<uint32_t> EXCLUSIVE_BUFFER_MS;
// when true, WASAPI compatibility mode is active: exclusive-mode streams are redirected to
// shared mode. the Windows audio engine performs any required sample-rate / channel / bit-depth
// conversion, so the game's format is passed through unchanged and other applications can play
// audio simultaneously.
extern bool WASAPI_COMPATIBILITY_MODE;
extern bool USE_DUMMY;
extern WAVEFORMATEXTENSIBLE FORMAT;
extern std::optional<Backend> BACKEND;
@@ -167,31 +167,46 @@ HRESULT STDMETHODCALLTYPE WrappedIAudioClient::Initialize(
fix_rec_format(const_cast<WAVEFORMATEX *>(pFormat));
}
// when downmixing, open the real device as stereo while the game keeps writing its native
// multi-channel format into the scratch buffer.
WAVEFORMATEXTENSIBLE stereo_storage = {};
const WAVEFORMATEX *device_format = pFormat;
if (auto algorithm = resolve_downmix(pFormat)) {
this->downmix.setup(pFormat, &stereo_storage, *algorithm);
device_format = reinterpret_cast<const WAVEFORMATEX *>(&stereo_storage);
log_info("audio::wasapi", "downmix enabled: {} channels -> 2 channels ({})",
pFormat->nChannels, hooks::audio::Downmix::algorithm_name(*algorithm));
} else if (games::gitadora::is_arena_model()) {
games::gitadora::fix_audio_channel_mask(const_cast<WAVEFORMATEX *>(pFormat));
// apply the -wasapishared option: redirect an exclusive request to shared mode. once redirected,
// spice's own downmix/resample paths below are skipped (gated on redirected_from_exclusive) and
// the shared engine handles any format conversion via AUTOCONVERTPCM (PCM / float only).
if (hooks::audio::SharedRedirect::wants(ShareMode, pFormat)) {
this->shared.apply(&ShareMode, &StreamFlags, &hnsPeriodicity);
} else if (hooks::audio::WASAPI_COMPATIBILITY_MODE && ShareMode == AUDCLNT_SHAREMODE_SHARED) {
log_warning(
"audio::wasapi",
"-wasapishared is enabled but the game is already opening a shared-mode stream; "
"the option has no effect");
}
// when resampling, open the real device at the target rate while the game keeps writing its
// native-rate audio into the scratch buffer. this runs on whatever device_format is now: the
// game's native format, or the stereo format produced above when downmix is also active, so
// the two stages chain as multi-channel -> stereo -> resampled stereo.
WAVEFORMATEXTENSIBLE stereo_storage = {};
WAVEFORMATEXTENSIBLE resample_storage = {};
if (auto target_rate = hooks::audio::Resampler::resolve(device_format)) {
const uint32_t src_rate = device_format->nSamplesPerSec;
this->resample.setup(device_format, &resample_storage, *target_rate);
device_format = reinterpret_cast<const WAVEFORMATEX *>(&resample_storage);
log_info("audio::wasapi", "resample enabled: {} Hz -> {} Hz{}",
src_rate, *target_rate, this->downmix.enabled ? " (after downmix)" : "");
const WAVEFORMATEX *device_format = pFormat;
if (!this->shared.redirected_from_exclusive) {
// when downmixing, open the real device as stereo while the game keeps writing its native
// multi-channel format into the scratch buffer.
if (auto algorithm = resolve_downmix(pFormat)) {
this->downmix.setup(pFormat, &stereo_storage, *algorithm);
device_format = reinterpret_cast<const WAVEFORMATEX *>(&stereo_storage);
log_info("audio::wasapi", "downmix enabled: {} channels -> 2 channels ({})",
pFormat->nChannels, hooks::audio::Downmix::algorithm_name(*algorithm));
} else if (games::gitadora::is_arena_model()) {
games::gitadora::fix_audio_channel_mask(const_cast<WAVEFORMATEX *>(pFormat));
}
// when resampling, open the real device at the target rate while the game keeps writing its
// native-rate audio into the scratch buffer. this runs on whatever device_format is now: the
// game's native format, or the stereo format produced above when downmix is also active, so
// the two stages chain as multi-channel -> stereo -> resampled stereo.
if (auto target_rate = hooks::audio::Resampler::resolve(device_format)) {
const uint32_t src_rate = device_format->nSamplesPerSec;
this->resample.setup(device_format, &resample_storage, *target_rate);
device_format = reinterpret_cast<const WAVEFORMATEX *>(&resample_storage);
log_info("audio::wasapi", "resample enabled: {} Hz -> {} Hz{}",
src_rate, *target_rate, this->downmix.enabled ? " (after downmix)" : "");
}
}
// verbose output
@@ -308,6 +323,12 @@ HRESULT STDMETHODCALLTYPE WrappedIAudioClient::GetBufferSize(UINT32 *pNumBufferF
*pNumBufferFrames = this->resample.frames_device_to_game(*pNumBufferFrames);
}
// redirected to shared mode: clamp the reported buffer to one device period (see SharedRedirect).
if (SUCCEEDED(ret) && this->shared.redirected_from_exclusive && pNumBufferFrames) {
*pNumBufferFrames = this->shared.clamp_buffer_size(
pReal, this->device_format.Format.nSamplesPerSec, *pNumBufferFrames);
}
CHECK_RESULT(ret);
}
HRESULT STDMETHODCALLTYPE WrappedIAudioClient::GetStreamLatency(REFERENCE_TIME *phnsLatency) {
@@ -380,6 +401,16 @@ HRESULT STDMETHODCALLTYPE WrappedIAudioClient::IsFormatSupported(
log_info("audio::wasapi", "IAudioClient::IsFormatSupported hook hit");
print_format(ShareMode, pFormat);
// under the exclusive->shared redirect, report the exclusive format as supported so the game
// doesn't fall back before reaching Initialize.
if (hooks::audio::SharedRedirect::wants(ShareMode, pFormat)) {
log_info("audio::wasapi", "... reporting supported (will redirect to shared mode)");
if (ppClosestMatch) {
*ppClosestMatch = nullptr;
}
return S_OK;
}
// when downmixing, the real device is opened as stereo, so check whether the equivalent
// stereo format is supported instead of the multi-channel one. when resampling is also active
// it chains onto that stereo format, so check the resampled stereo format.
@@ -10,6 +10,7 @@
#include "downmix.h"
#include "resample.h"
#include "shared.h"
#include "audio_render_client.h"
// {1FBC8530-AF3E-4128-B418-115DE72F76B6}
@@ -94,6 +95,10 @@ struct WrappedIAudioClient : IAudioClient3 {
IAudioClient3 *const pReal3;
AudioBackend *const backend;
bool exclusive_mode = false;
// -wasapishared redirect state: when an exclusive request was redirected to shared mode, the
// engine converts the native format and the reported buffer size is clamped (see SharedRedirect).
hooks::audio::SharedRedirect shared;
int frame_size = 0;
// the format the real device was opened with (after any downmix). used to scale the final
@@ -0,0 +1,78 @@
#include "shared.h"
#include <audioclient.h>
#include "hooks/audio/audio.h"
#include "util/logging.h"
#include "defs.h"
namespace hooks::audio {
// whether the engine's PCM converter can handle this format. PCM / float only; non-PCM
// bitstream (AC-3 / DTS passthrough) must be left alone.
static bool is_pcm_or_float(const WAVEFORMATEX *format) {
if (format == nullptr) {
return false;
}
switch (format->wFormatTag) {
case WAVE_FORMAT_PCM:
case WAVE_FORMAT_IEEE_FLOAT:
return true;
case WAVE_FORMAT_EXTENSIBLE: {
// SubFormat is only valid when the extra-bytes block is large enough
if (format->cbSize < sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX)) {
return false;
}
const auto *ext = reinterpret_cast<const WAVEFORMATEXTENSIBLE *>(format);
return ext->SubFormat == GUID_KSDATAFORMAT_SUBTYPE_PCM
|| ext->SubFormat == GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
}
default:
return false;
}
}
bool SharedRedirect::wants(AUDCLNT_SHAREMODE share_mode, const WAVEFORMATEX *format) {
// only redirect PCM / float exclusive streams: the engine converter (AUTOCONVERTPCM) can
// handle those, but non-PCM bitstream (AC-3 / DTS passthrough) would fail in shared mode,
// so leave it in exclusive untouched.
return hooks::audio::WASAPI_COMPATIBILITY_MODE
&& share_mode == AUDCLNT_SHAREMODE_EXCLUSIVE
&& is_pcm_or_float(format);
}
void SharedRedirect::apply(AUDCLNT_SHAREMODE *share_mode, DWORD *stream_flags,
REFERENCE_TIME *periodicity) {
// shared mode requires periodicity == 0; AUTOCONVERTPCM lets the engine accept the game's
// native format (else shared Initialize returns AUDCLNT_E_UNSUPPORTED_FORMAT).
log_info("audio::wasapi", "redirecting exclusive WASAPI to shared mode");
*share_mode = AUDCLNT_SHAREMODE_SHARED;
*periodicity = 0;
*stream_flags |= AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
this->redirected_from_exclusive = true;
}
UINT32 SharedRedirect::clamp_buffer_size(IAudioClient *real, uint32_t sample_rate,
UINT32 device_frames) const {
if (!this->redirected_from_exclusive || real == nullptr || sample_rate == 0 || device_frames == 0) {
return device_frames;
}
// GetDevicePeriod returns REFERENCE_TIME units (100 ns), 10^7 per second, so
// period_frames = period * sample_rate / 10^7.
REFERENCE_TIME period = 0;
if (SUCCEEDED(real->GetDevicePeriod(&period, nullptr)) && period > 0) {
const UINT32 period_frames = (UINT32) ((period * sample_rate) / 10000000);
if (period_frames > 0 && period_frames < device_frames) {
return period_frames;
}
}
return device_frames;
}
}
@@ -0,0 +1,31 @@
#pragma once
#include <cstdint>
#include <windows.h>
#include <audioclient.h>
namespace hooks::audio {
// The -wasapishared option redirects an exclusive WASAPI stream to shared mode. lets other apps
// play sound and works on devices that can't open the exclusive format, at the cost of some
// latency. Only PCM / float is converted; bitstream (AC-3 / DTS) is left alone.
struct SharedRedirect {
// true once apply() has redirected an exclusive request. gates the buffer clamp; stays false
// for a natively-shared stream (it paces itself, so must not be clamped).
bool redirected_from_exclusive = false;
// whether an exclusive-mode request should be redirected, given the -wasapishared option.
// only PCM / float is eligible; bitstream (AC-3 / DTS) is left in exclusive mode.
static bool wants(AUDCLNT_SHAREMODE share_mode, const WAVEFORMATEX *format);
// redirect an exclusive request to shared mode. caller must have checked wants() first.
void apply(AUDCLNT_SHAREMODE *share_mode, DWORD *stream_flags, REFERENCE_TIME *periodicity);
// clamp a reported buffer size to one device period. some games write the whole buffer per
// event, which overflows shared-mode buffering (AUDCLNT_E_BUFFER_TOO_LARGE -> stutter); one
// period always fits. a no-op unless an exclusive request was redirected.
UINT32 clamp_buffer_size(IAudioClient *real, uint32_t sample_rate, UINT32 device_frames) const;
};
}
@@ -213,6 +213,27 @@ void poll_thread() {
}
}
// the overlay's imgui dx11 backend needs D3DCompile (d3dcompiler_XX.dll) to
// build its shaders. _43 ships with the DX June 2010 redist on stock Win7;
// _46/_47 come with newer Windows.
bool d3dcompiler_available() {
static const wchar_t *names[] = {
L"d3dcompiler_47.dll",
L"d3dcompiler_46.dll",
L"d3dcompiler_43.dll",
};
for (auto name : names) {
HMODULE mod = GetModuleHandleW(name);
if (!mod) {
mod = LoadLibraryW(name);
}
if (mod && GetProcAddress(mod, "D3DCompile")) {
return true;
}
}
return false;
}
} // namespace
void graphics_d3d11_init() {
@@ -223,6 +244,14 @@ void graphics_d3d11_init() {
return;
}
// no d3dcompiler -> overlay can't build shaders; skip dx11 overlay
if (!d3dcompiler_available()) {
log_warning(
"graphics::d3d11",
"d3dcompiler not found; dx11 overlay disabled");
return;
}
std::lock_guard<std::mutex> lock(g_init_mutex);
if (g_poll_thread.joinable()) {
return; // already initialized
@@ -1535,6 +1535,9 @@ void graphics_d3d9_on_present(
log_warning("graphics::d3d9",
"failed to get back buffer, hr={}",
FMT_HRESULT(hr));
if (capture) {
graphics_capture_skip(capture_screen);
}
return;
}
@@ -1545,6 +1548,9 @@ void graphics_d3d9_on_present(
"failed to acquire back buffer descriptor, hr={}",
FMT_HRESULT(hr));
buffer->Release();
if (capture) {
graphics_capture_skip(capture_screen);
}
return;
}
@@ -1558,6 +1564,9 @@ void graphics_d3d9_on_present(
"failed to acquire temporary surface, hr={}",
FMT_HRESULT(hr));
buffer->Release();
if (capture) {
graphics_capture_skip(capture_screen);
}
return;
}
@@ -1568,6 +1577,9 @@ void graphics_d3d9_on_present(
FMT_HRESULT(hr));
temp_surface->Release();
buffer->Release();
if (capture) {
graphics_capture_skip(capture_screen);
}
return;
}
+55 -10
View File
@@ -5,6 +5,7 @@
#include "graphics.h"
#include <chrono>
#include <set>
#include <vector>
#include <mutex>
@@ -61,6 +62,19 @@ static std::mutex GRAPHICS_CAPTURE_SCREENS_M {};
static CaptureData GRAPHICS_CAPTURE_BUFFER[GRAPHICS_CAPTURE_SCREEN_NO] {};
static std::mutex GRAPHICS_CAPTURE_BUFFER_M[GRAPHICS_CAPTURE_SCREEN_NO] {};
static std::condition_variable GRAPHICS_CAPTURE_CV[GRAPHICS_CAPTURE_SCREEN_NO] {};
static bool GRAPHICS_CAPTURE_SKIP_SIGNAL[GRAPHICS_CAPTURE_SCREEN_NO] {};
static constexpr std::chrono::milliseconds GRAPHICS_CAPTURE_RECEIVE_TIMEOUT {2000};
static void graphics_capture_cancel_pending(int screen) {
std::lock_guard<std::mutex> lock(GRAPHICS_CAPTURE_SCREENS_M);
for (auto it = GRAPHICS_CAPTURE_SCREENS.rbegin(); it != GRAPHICS_CAPTURE_SCREENS.rend(); ++it) {
if (*it == screen) {
GRAPHICS_CAPTURE_SCREENS.erase(std::next(it).base());
return;
}
}
}
static std::optional<graphics_orientation> target_orientation_on_boot;
static UINT target_refresh_rate_on_boot = 0;
@@ -1209,18 +1223,20 @@ void graphics_capture_trigger(int screen) {
}
bool graphics_capture_consume(int *screen) {
auto flag = !GRAPHICS_CAPTURE_SCREENS.empty();
if (flag) {
std::lock_guard<std::mutex> lock(GRAPHICS_CAPTURE_SCREENS_M);
std::lock_guard<std::mutex> lock(GRAPHICS_CAPTURE_SCREENS_M);
*screen = GRAPHICS_CAPTURE_SCREENS.back();
GRAPHICS_CAPTURE_SCREENS.pop_back();
if (GRAPHICS_CAPTURE_SCREENS.empty()) {
return false;
}
return flag;
*screen = GRAPHICS_CAPTURE_SCREENS.back();
GRAPHICS_CAPTURE_SCREENS.pop_back();
return true;
}
void graphics_capture_enqueue(int screen, uint8_t *data, size_t width, size_t height) {
GRAPHICS_CAPTURE_BUFFER_M[screen].lock();
GRAPHICS_CAPTURE_SKIP_SIGNAL[screen] = false;
auto &capture = GRAPHICS_CAPTURE_BUFFER[screen];
capture.data.reset(data);
capture.width = width;
@@ -1231,6 +1247,14 @@ void graphics_capture_enqueue(int screen, uint8_t *data, size_t width, size_t he
}
void graphics_capture_skip(int screen) {
if (screen < 0 || screen >= static_cast<int>(GRAPHICS_CAPTURE_SCREEN_NO)) {
return;
}
{
std::lock_guard<std::mutex> lock(GRAPHICS_CAPTURE_BUFFER_M[screen]);
GRAPHICS_CAPTURE_SKIP_SIGNAL[screen] = true;
}
GRAPHICS_CAPTURE_CV[screen].notify_one();
}
@@ -1238,11 +1262,32 @@ bool graphics_capture_receive_jpeg(int screen, TooJpeg::WRITE_ONE_BYTE receiver,
bool rgb, int quality, bool downsample, int divide, uint64_t *timestamp,
int *width, int *height) {
// wait for capture event
if (screen < 0 || screen >= static_cast<int>(GRAPHICS_CAPTURE_SCREEN_NO)) {
return false;
}
// wait for capture event (with timeout)
std::unique_lock<std::mutex> lock(GRAPHICS_CAPTURE_BUFFER_M[screen]);
GRAPHICS_CAPTURE_CV[screen].wait(lock, [screen] {
return GRAPHICS_CAPTURE_BUFFER[screen].data != nullptr;
});
const bool ready = GRAPHICS_CAPTURE_CV[screen].wait_for(
lock,
GRAPHICS_CAPTURE_RECEIVE_TIMEOUT,
[screen] {
return GRAPHICS_CAPTURE_BUFFER[screen].data != nullptr
|| GRAPHICS_CAPTURE_SKIP_SIGNAL[screen];
});
if (!ready) {
lock.unlock();
graphics_capture_cancel_pending(screen);
return false;
}
if (GRAPHICS_CAPTURE_SKIP_SIGNAL[screen]) {
GRAPHICS_CAPTURE_SKIP_SIGNAL[screen] = false;
lock.unlock();
return false;
}
auto &capture = GRAPHICS_CAPTURE_BUFFER[screen];
auto capture_data = capture.data;
auto capture_width = capture.width;
+52 -6
View File
@@ -498,7 +498,7 @@ int main_implementation(int argc, char *argv[]) {
games::sdvx::ASIO_DRIVER = options[launcher::Options::spice2x_SDVXAsioDriver].value_text();
}
if (options[launcher::Options::SDVXAsioTwoChannel].value_bool()) {
WrappedAsio::FORCE_TWO_CHANNELS = true;
WrappedAsio::STEREO_DOWNMIX = WrappedAsio::StereoDownmix::Front;
}
if (options[launcher::Options::spice2x_SDVXSubPos].is_active()) {
auto txt = options[launcher::Options::spice2x_SDVXSubPos].value_text();
@@ -710,6 +710,7 @@ int main_implementation(int argc, char *argv[]) {
}
if (options[launcher::Options::GitaDoraTwoChannelAudio].value_bool()) {
games::gitadora::TWOCHANNEL = true;
WrappedAsio::STEREO_DOWNMIX = WrappedAsio::StereoDownmix::Center;
}
if (options[launcher::Options::GitaDoraLefty].is_active()) {
const auto text = options[launcher::Options::GitaDoraLefty].value_text();
@@ -1106,6 +1107,12 @@ int main_implementation(int argc, char *argv[]) {
auto &name = options[launcher::Options::DownmixAudioToStereo].value_text();
hooks::audio::DOWNMIX_ALGORITHM = hooks::audio::Downmix::name_to_algorithm(name.c_str());
}
if (options[launcher::Options::AsioDownmixToStereo].is_active()) {
// routes the selected pair onto the device's 2.0 front output; a non-None selection
// implies force-two-channel (see WrappedAsio::force_two_channels)
auto &name = options[launcher::Options::AsioDownmixToStereo].value_text();
WrappedAsio::STEREO_DOWNMIX = WrappedAsio::name_to_stereo_downmix(name.c_str());
}
if (options[launcher::Options::VolumeBoost].is_active()) {
const double decibels = std::strtod(
options[launcher::Options::VolumeBoost].value_text().c_str(), nullptr);
@@ -1125,6 +1132,9 @@ int main_implementation(int argc, char *argv[]) {
hooks::audio::EXCLUSIVE_BUFFER_MS = ms;
}
}
if (options[launcher::Options::AudioShared].value_bool()) {
hooks::audio::WASAPI_COMPATIBILITY_MODE = true;
}
if (options[launcher::Options::AudioBackend].is_active()) {
auto &name = options[launcher::Options::AudioBackend].value_text();
@@ -1175,7 +1185,20 @@ int main_implementation(int argc, char *argv[]) {
overlay::AUTO_SHOW_FPS = true;
}
if (options[launcher::Options::spice2x_FpsOpposite].value_bool()) {
overlay::FPS_SHOULD_FLIP = true;
// deprecated flag: equivalent to anchoring the FPS window top-left
overlay::FPS_LOCATION = overlay::FpsLocation::TopLeft;
}
if (options[launcher::Options::FpsLocation].is_active()) {
const auto txt = options[launcher::Options::FpsLocation].value_text();
if (txt == "topright") {
overlay::FPS_LOCATION = overlay::FpsLocation::TopRight;
} else if (txt == "topleft") {
overlay::FPS_LOCATION = overlay::FpsLocation::TopLeft;
} else if (txt == "bottomleft") {
overlay::FPS_LOCATION = overlay::FpsLocation::BottomLeft;
} else if (txt == "bottomright") {
overlay::FPS_LOCATION = overlay::FpsLocation::BottomRight;
}
}
if (options[launcher::Options::spice2x_SubScreenAutoShow].value_bool()) {
overlay::AUTO_SHOW_SUBSCREEN = true;
@@ -1465,10 +1488,15 @@ int main_implementation(int argc, char *argv[]) {
#else
#ifdef SPICE64
log_info("launcher", "SpiceTools Bootstrap (x64) (spice2x)");
#elif SPICE32_LARGE_ADDRESS_AWARE
log_info("launcher", "SpiceTools Bootstrap (x32 - Large Address Aware) (spice2x)");
#else
log_info("launcher", "SpiceTools Bootstrap (x32) (spice2x)");
// spice.exe and spice_laa.exe share the same compiled objects; the only
// difference is the large-address-aware bit set at link time. detect it
// at runtime so the log line stays accurate without a separate compile.
if (sysutils::is_large_address_aware()) {
log_info("launcher", "SpiceTools Bootstrap (x32 - Large Address Aware) (spice2x)");
} else {
log_info("launcher", "SpiceTools Bootstrap (x32) (spice2x)");
}
#endif
#endif
@@ -1560,6 +1588,13 @@ int main_implementation(int argc, char *argv[]) {
"!!! errors and loss of functionality. !!!\n"
"!!! !!!\n"
);
deferredlogs::defer_error_messages({
"-exec option disables all game-specific hooks and I/O emulation",
" you must combine this with other flags or have appropriate arcade hardware",
" this also turns off many auto-troubleshooter checks",
" which means that this analysis will be incomplete",
" you need to manually check the logs for failures"
});
}
if (launcher::signal::DISABLE && !cfg::CONFIGURATOR_STANDALONE) {
@@ -1609,12 +1644,23 @@ int main_implementation(int argc, char *argv[]) {
GRAPHICS_FS_ORIENTATION_SWAP = true;
}
// for cab usage - set environment variables (outside of -iidx module)
if (games::iidx::DISABLE_CAMS.has_value() &&
games::iidx::DISABLE_CAMS.value() &&
!cfg::CONFIGURATOR_STANDALONE) {
log_misc("launcher", "CONNECT_CAMERA env var set to 0");
log_misc("launcher::iidx", "CONNECT_CAMERA env var set to 0");
SetEnvironmentVariable("CONNECT_CAMERA", "0");
}
if (games::iidx::SOUND_OUTPUT_DEVICE.has_value() &&
games::iidx::SOUND_OUTPUT_DEVICE.value() != "auto" &&
!cfg::CONFIGURATOR_STANDALONE) {
log_info(
"launcher::iidx",
"using user-supplied \"{}\" for SOUND_OUTPUT_DEVICE",
games::iidx::SOUND_OUTPUT_DEVICE.value());
SetEnvironmentVariable("SOUND_OUTPUT_DEVICE", games::iidx::SOUND_OUTPUT_DEVICE.value().c_str());
}
// deleted options
if (options[launcher::Options::OpenKFControl].value_bool() && !cfg::CONFIGURATOR_STANDALONE) {
File diff suppressed because it is too large Load Diff
+12 -3
View File
@@ -40,6 +40,7 @@ namespace launcher {
spice2x_Dx9On12,
NoLegacy,
RichPresence,
DiscordAppID,
SmartEAmusement,
EAmusementMaintenance,
spice2x_EAmusementMaintenance,
@@ -56,6 +57,7 @@ namespace launcher {
NotificationPosition,
spice2x_FpsAutoShow,
spice2x_FpsOpposite,
FpsLocation,
spice2x_SubScreenAutoShow,
spice2x_IOPanelAutoShow,
spice2x_KeypadAutoShow,
@@ -197,6 +199,8 @@ namespace launcher {
spice2x_NvapiProfile,
DisableAudioHooks,
spice2x_DisableVolumeHook,
AudioShared,
spice2x_LowLatencySharedAudio,
AudioBackend,
AsioDriverId,
AsioDriverName,
@@ -205,6 +209,7 @@ namespace launcher {
VolumeBoost,
AudioResample,
AudioExclusiveBuffer,
AsioDownmixToStereo,
DelayBy5Seconds,
spice2x_DelayByNSeconds,
LoadStubs,
@@ -214,7 +219,6 @@ namespace launcher {
LogLevel,
EAAutomap,
EANetdump,
DiscordAppID,
BlockingLogger,
DebugCreateFile,
VerboseGraphicsLogging,
@@ -270,7 +274,6 @@ namespace launcher {
IIDXSubMonitorOverride,
spice2x_IIDXEmulateSubscreenKeypadTouch,
spice2x_AutoCard,
spice2x_LowLatencySharedAudio,
spice2x_TapeLedAlgorithm,
spice2x_NoNVAPI,
spice2x_NoD3D9DeviceHook,
@@ -306,7 +309,11 @@ namespace launcher {
enum class OptionsCategory {
Everything,
Basic,
GameOptions,
Display,
Audio,
Network,
Overlay,
Advanced,
Dev,
API
@@ -316,7 +323,9 @@ namespace launcher {
extern bool USE_CMD_OVERRIDE;
const std::vector<std::string> &get_categories(Options::OptionsCategory category);
const std::vector<std::string> &get_quick_setting_categories();
const std::vector<OptionDefinition> &get_option_definitions();
void validate_option_categories();
std::unique_ptr<std::vector<Option>> parse_options(int argc, char *argv[]);
std::vector<Option> merge_options(const std::vector<Option> &options, const std::vector<Option> &overrides);
+3 -1
View File
@@ -66,7 +66,9 @@ namespace ImGui {
void DummyMarker() {
// dummy marker that is the same width as HelpMarker/WarnMarker.
ImGui::Dummy(ImVec2(22, 0));
// "(?)" and "(!)" render to the same width, so calc it so the spacing
// tracks the current font size/scale instead of a fixed pixel count.
ImGui::Dummy(ImVec2(ImGui::CalcTextSize("(?)").x, 0));
}
void Knob(float fraction, float size, float thickness, float pos_x, float pos_y) {
+11
View File
@@ -146,6 +146,17 @@ namespace overlay::notifications {
float height = 0.f;
if (ImGui::Begin(window_id.c_str(), nullptr, TOAST_FLAGS)) {
// keep toasts above other overlay windows (e.g. the persistent FPS
// window, which may be toggled on after a toast already exists), but
// tuck them behind a blocking modal so they get dimmed/occluded by the
// modal backdrop instead of floating on top of it.
ImGuiWindow *toast_window = ImGui::GetCurrentWindow();
if (ImGuiWindow *modal = ImGui::GetTopMostPopupModal()) {
ImGui::BringWindowToDisplayBehind(toast_window, modal);
} else {
ImGui::BringWindowToDisplayFront(toast_window);
}
const ImVec2 win_pos = ImGui::GetWindowPos();
const ImVec2 win_size = ImGui::GetWindowSize();
+66 -41
View File
@@ -66,7 +66,7 @@ namespace overlay {
bool AUTO_SHOW_KEYPAD_P1 = false;
bool AUTO_SHOW_KEYPAD_P2 = false;
bool USE_WM_CHAR_FOR_IMGUI_CHAR_INPUT = false;
bool FPS_SHOULD_FLIP = false;
FpsLocation FPS_LOCATION = FpsLocation::TopRight;
std::optional<uint32_t> UI_SCALE_PERCENT;
// global
@@ -298,6 +298,7 @@ void overlay::SpiceOverlay::init() {
colors[ImGuiCol_Separator] = ImVec4(0.32f, 0.22f, 0.22f, 1.00f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.42f, 0.22f, 0.22f, 1.00f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.52f, 0.22f, 0.22f, 1.00f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.5f);
#ifdef IMGUI_HAS_DOCK
colors[ImGuiCol_DockingPreview] = ImVec4(0.85f, 0.15f, 0.15f, 0.40f);
@@ -307,16 +308,10 @@ void overlay::SpiceOverlay::init() {
// configure IO
auto &io = ImGui::GetIO();
io.UserData = this;
io.ConfigFlags = ImGuiConfigFlags_NavEnableKeyboard
| ImGuiConfigFlags_NavEnableGamepad
| ImGuiConfigFlags_NavEnableSetMousePos;
io.ConfigFlags = ImGuiConfigFlags_None;
if (!cfg::CONFIGURATOR_STANDALONE) {
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
}
if (is_touch_available("SpiceOverlay::init")) {
io.ConfigFlags |= ImGuiConfigFlags_IsTouchScreen;
}
// temporarily turn this off as it can cause crashes during font load failures
// turns back on in ImGui_ImplSpice_Init
@@ -396,14 +391,14 @@ void overlay::SpiceOverlay::init() {
bool set_overlay_active = false;
// referenced windows
this->window_add(window_fps = new overlay::windows::FPS(this));
// owned separately from `windows` so it never affects overlay activation/input gating
window_fps = std::make_unique<overlay::windows::FPS>(this);
if (!cfg::CONFIGURATOR_STANDALONE && AUTO_SHOW_FPS) {
window_fps->set_active(true);
set_overlay_active = true;
}
this->window_add(window_main_menu = new overlay::windows::ExitPrompt(this));
// owned separately from `windows` so it is not part of the overlay window layer
window_main_menu = std::make_unique<overlay::windows::ExitPrompt>(this);
// add default windows
this->window_add(window_config = new overlay::windows::Config(this));
@@ -544,9 +539,13 @@ void overlay::SpiceOverlay::new_frame() {
const bool draw_notifications = this->renderer != OverlayRenderer::SOFTWARE
&& overlay::notifications::has_pending();
// persistent FPS window: drawn whenever active, independent of the overlay
const bool draw_fps_persistent = this->renderer != OverlayRenderer::SOFTWARE
&& this->window_fps->get_active();
// check if there is nothing to draw
this->has_pending_frame = false;
if (!this->active && !draw_notifications) {
if (!this->active && !draw_notifications && !draw_fps_persistent) {
return;
}
@@ -577,11 +576,17 @@ void overlay::SpiceOverlay::new_frame() {
window->build();
}
// draw the main menu on top of the overlay windows
this->window_main_menu->build();
if (SHOW_DEBUG_LOG_WINDOW) {
ImGui::ShowDebugLogWindow(&SHOW_DEBUG_LOG_WINDOW);
}
}
if (draw_fps_persistent) {
this->window_fps->build();
}
// draw notifications last so they paint on top of any overlay windows
if (draw_notifications) {
overlay::notifications::draw();
@@ -750,13 +755,19 @@ void overlay::SpiceOverlay::d3d9_render_draw(const bool force_submit) {
void overlay::SpiceOverlay::update() {
// check overlay toggle
// there are three layers -
// bottommost layer - FPS, notifications (non-interactable)
// overlay layer - most windows
// topmost layer - main menu (popup)
auto overlay_buttons = games::get_buttons_overlay(eamuse_get_game());
bool toggle_down_new = overlay_buttons
// check overlay toggle
const bool toggle_down_new = overlay_buttons
&& this->hotkeys_triggered()
&& GameAPI::Buttons::getState(RI_MGR, overlay_buttons->at(games::OverlayButtons::ToggleOverlay));
&& GameAPI::Buttons::getState(RI_MGR, overlay_buttons->at(games::OverlayButtons::ToggleAllWindows));
if (toggle_down_new && !this->toggle_down) {
toggle_active(true);
toggle_active();
}
this->toggle_down = toggle_down_new;
@@ -769,17 +780,35 @@ void overlay::SpiceOverlay::update() {
}
this->main_menu_down = main_menu_down_new;
// check FPS toggle - controls the persistent FPS window only, never the overlay
const auto fps_down_new = overlay_buttons
&& this->hotkeys_triggered()
&& GameAPI::Buttons::getState(RI_MGR, overlay_buttons->at(games::OverlayButtons::ToggleFps));
if (fps_down_new && !this->fps_down) {
this->window_fps->toggle_active();
}
this->fps_down = fps_down_new;
// update windows
for (auto &window : this->windows) {
window->update();
}
// deactivate if no windows are shown
bool window_active = false;
for (auto &window : this->windows) {
if (window->get_active()) {
window_active = true;
break;
// FPS window
this->window_fps->update();
// main menu (owned separately from the overlay window layer)
this->window_main_menu->update();
// deactivate if nothing is shown - the main menu keeps the overlay active
// while open even though it is not part of `windows`
bool window_active = this->window_main_menu->get_active();
if (!window_active) {
for (auto &window : this->windows) {
if (window->get_active()) {
window_active = true;
break;
}
}
}
if (!window_active) {
@@ -791,20 +820,9 @@ bool overlay::SpiceOverlay::update_cursor() {
return ImGui_ImplSpice_UpdateMouseCursor();
}
void overlay::SpiceOverlay::toggle_active(bool overlay_key) {
void overlay::SpiceOverlay::toggle_active() {
// invert active state
this->active = !this->active;
// get rid of main menu if it was visible
if (this->window_main_menu) {
this->window_main_menu->set_active(false);
}
// show FPS window if toggled with overlay key
if (overlay_key) {
this->window_fps->set_active(this->active);
}
}
void overlay::SpiceOverlay::show_main_menu() {
@@ -814,12 +832,20 @@ void overlay::SpiceOverlay::show_main_menu() {
if (this->window_main_menu->get_active()) {
// window already visible - close the window
this->window_main_menu->set_active(false);
return;
}
if (ImGui::IsPopupOpen(0, ImGuiPopupFlags_AnyPopup)) {
// if the overlay was not visible when this came into view, turn off overlay as well
if (!this->overlay_active_when_main_menu_shown) {
this->set_active(false);
}
return;
}
// don't open on top of another genuinely-visible popup, but ONLY guard while
// the overlay is active
if (this->get_active() && ImGui::IsPopupOpen(0, ImGuiPopupFlags_AnyPopup)) {
return;
}
this->overlay_active_when_main_menu_shown = this->get_active();
if (this->get_active()) {
if (!ImGui::IsAnyItemActive() && !ImGui::IsAnyItemFocused()) {
this->window_main_menu->set_active(true);
@@ -847,9 +873,8 @@ bool overlay::SpiceOverlay::has_focus() {
}
bool overlay::SpiceOverlay::hotkeys_triggered() {
// check if disabled first
if (!this->hotkeys_enable) {
// prevent hotkeys in spicecfg
if (cfg::CONFIGURATOR_STANDALONE) {
return false;
}
+21 -6
View File
@@ -29,6 +29,14 @@ namespace overlay {
SOFTWARE,
};
// corner of the screen the FPS / clock / timer window is anchored to
enum class FpsLocation {
TopLeft,
TopRight,
BottomLeft,
BottomRight,
};
// settings
extern bool ENABLED;
extern bool AUTO_SHOW_FPS;
@@ -37,7 +45,7 @@ namespace overlay {
extern bool AUTO_SHOW_KEYPAD_P1;
extern bool AUTO_SHOW_KEYPAD_P2;
extern bool USE_WM_CHAR_FOR_IMGUI_CHAR_INPUT;
extern bool FPS_SHOULD_FLIP;
extern FpsLocation FPS_LOCATION;
extern bool SHOW_DEBUG_LOG_WINDOW;
extern std::optional<uint32_t> UI_SCALE_PERCENT;
@@ -57,10 +65,8 @@ namespace overlay {
D3DDEVICE_CREATION_PARAMETERS creation_parameters {};
D3DADAPTER_IDENTIFIER9 adapter_identifier {};
bool hotkeys_enable = true;
// windows
Window *window_fps = nullptr;
Window *window_iopanel = nullptr;
Window *window_config = nullptr;
Window *window_keypad1 = nullptr;
@@ -72,6 +78,15 @@ namespace overlay {
Window *window_sub = nullptr;
Window *window_log = nullptr;
// not part of `windows`: drawn/updated on the persistent layer (like
// notifications), independent of the overlay's active state and input gates.
std::unique_ptr<Window> window_fps;
// not part of `windows`: the main menu / launcher. owned and drawn
// separately from the overlay window layer; it drives the overlay's
// active state while shown so its buttons still receive input.
std::unique_ptr<Window> window_main_menu;
explicit SpiceOverlay(HWND hWnd, IDirect3D9 *d3d, IDirect3DDevice9 *device);
#ifdef SPICE_D3D11
explicit SpiceOverlay(HWND hWnd, ID3D11Device *d3d11_device,
@@ -87,7 +102,7 @@ namespace overlay {
// after render() when the frame is being presented. In-game overlay draws in render().
void d3d9_render_draw(bool force_submit = false);
void update();
void toggle_active(bool overlay_key = false);
void toggle_active();
void show_main_menu();
void set_active(bool active);
bool get_active();
@@ -182,13 +197,13 @@ namespace overlay {
std::vector<std::unique_ptr<Window>> windows;
Window *window_main_menu = nullptr;
std::function<bool(LONG *, LONG *)> subscreen_mouse_handler = nullptr;
bool active = false;
bool toggle_down = false;
bool main_menu_down = false;
bool overlay_active_when_main_menu_shown = false;
bool fps_down = false;
bool hotkey_toggle = false;
bool hotkey_toggle_last = false;
+54 -7
View File
@@ -3,6 +3,7 @@
#include "util/logging.h"
#include "games/io.h"
#include "misc/eamuse.h"
#include "external/imgui/imgui_internal.h"
overlay::Window::Window(SpiceOverlay *overlay) : overlay(overlay) {
@@ -30,11 +31,23 @@ void overlay::Window::update() {
// if the overlay is hidden just reactivate it
if (!this->overlay->get_active()) {
// but don't let the main menu occlude it if it was previously visible
if (this->overlay->window_main_menu) {
this->overlay->window_main_menu->set_active(false);
}
this->active = true;
this->overlay->set_active(true);
} else {
this->toggle_active();
}
// raise to the top, but only because the user pressed the hotkey and
// the window is now visible
if (this->active) {
this->bring_to_front();
}
}
this->toggle_button_state = toggle_button_new;
}
@@ -81,14 +94,29 @@ void overlay::Window::build() {
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
}
// create window
if (ImGui::Begin(
(this->title + "###" + to_string(this)).c_str(),
&this->active,
this->flags)) {
const bool custom_window_padding =
!this->remove_window_padding && this->window_padding.x >= 0.f;
if (custom_window_padding) {
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, this->window_padding);
}
// window attributes
this->calculate_initial_window();
// create window
// NoFocusOnAppearing: when the overlay is re-shown every window reappears at
// once and ImGui would auto-focus whichever is submitted last, stealing the
// top spot. suppress that so only an explicit focus request (see below)
// decides what comes to the front.
const std::string window_id = this->title + "###" + to_string(this);
if (ImGui::Begin(
window_id.c_str(),
&this->active,
this->flags | ImGuiWindowFlags_NoFocusOnAppearing)) {
// window attributes - init_pos / init_size are only honored once
// (ImGuiCond_Once), so compute them a single time instead of every frame
if (!this->initial_window_calculated) {
this->initial_window_calculated = true;
this->calculate_initial_window();
}
ImGui::SetWindowPos(this->init_pos, ImGuiCond_Once);
ImGui::SetWindowSize(this->init_size, ImGuiCond_Once);
@@ -103,12 +131,27 @@ void overlay::Window::build() {
// end window
ImGui::End();
// apply an explicit focus request now that the window exists. FocusWindow
// with UnlessBelowModal raises it to the front, but keeps it right below
// any blocking popup/modal instead of jumping in front of it (this also
// re-orders brand-new windows that ImGui places on top by default).
if (this->request_focus) {
this->request_focus = false;
if (ImGuiWindow *w = ImGui::FindWindowByName(window_id.c_str())) {
ImGui::FocusWindow(w, ImGuiFocusRequestFlags_UnlessBelowModal);
}
}
if (this->remove_window_padding) {
ImGui::PopStyleVar();
ImGui::PopStyleVar();
ImGui::PopStyleVar();
}
if (custom_window_padding) {
ImGui::PopStyleVar();
}
} else {
// add raw content
@@ -142,6 +185,10 @@ void overlay::Window::set_active(bool active) {
}
}
void overlay::Window::bring_to_front() {
this->request_focus = true;
}
bool overlay::Window::get_active() {
// check for active children
+13
View File
@@ -24,15 +24,26 @@ namespace overlay {
void toggle_active();
void set_active(bool active);
bool get_active();
// raise this window to the top of the z-order on its next build. only
// call in response to an explicit user action (keyboard toggle, UI
// button) - not for auto-show / programmatic shows.
void bring_to_front();
protected:
// state
SpiceOverlay *overlay;
bool active = false;
// set when the window transitions to visible so build() raises it to the
// top of the z-order on the next frame
bool request_focus = false;
std::vector<Window*> children;
// settings
bool remove_window_padding = false;
// custom inner window padding, applied before Begin() (preserving border /
// rounding) when x >= 0; ignored if remove_window_padding is set
ImVec2 window_padding = ImVec2(-1, -1);
bool draws_window = true;
ImGuiSizeCallback resize_callback = nullptr;
std::string title = "Title";
@@ -41,6 +52,8 @@ namespace overlay {
bool toggle_button_state = false;
// init settings
// calculate_initial_window() runs only once; results feed ImGuiCond_Once
bool initial_window_calculated = false;
ImVec2 init_pos = ImVec2(0, 0);
ImVec2 init_size = ImVec2(0, 0);
ImVec2 size_min = ImVec2(0, 0);
+9 -3
View File
@@ -166,7 +166,7 @@ namespace overlay::windows {
if (ImGui::BeginPopupModal("Card Editor", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
// card ID field (only editable for new cards)
ImGui::BeginDisabled(this->current_card);
ImGui::InputTextWithHint("Card ID", "E0040123456789AB",
ImGui::InputTextWithHint("Card ID", "E0040100FFFFFFFF",
this->card_buffer,
std::size(this->card_buffer),
ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
@@ -385,10 +385,16 @@ namespace overlay::windows {
ImGui::Spacing();
// cards list
// use all available vertical space, minus height footer (a row of buttons and separator)
// use all available vertical space, minus the footer that follows in
// build_content(): a separator + spacing, then a row of buttons
const ImGuiStyle &style = ImGui::GetStyle();
const float footer_height =
style.ItemSpacing.y * 3.f // spacing around the separator and before the footer
+ 1.f // separator line
+ ImGui::GetFrameHeightWithSpacing(); // footer button row
if (ImGui::BeginChild(
"cards",
ImVec2(0, ImGui::GetContentRegionAvail().y - ImGui::GetFrameHeightWithSpacing() - 8.f))) {
ImVec2(0, ImGui::GetContentRegionAvail().y - footer_height))) {
// -card0 / -card1 override
for (size_t i = 0; i < 2; i++) {
+1 -1
View File
@@ -9,7 +9,7 @@ namespace overlay::windows {
struct CardEntry {
std::string name = "unnamed";
std::string id = "E004010000000000";
std::string id = "E0040100FFFFFFFF";
std::string search_string = "";
bool read_only = false;
float color[3] {};
File diff suppressed because it is too large Load Diff
+36 -12
View File
@@ -12,20 +12,24 @@
namespace overlay::windows {
// top-level tabs in the configuration window
enum class ConfigTab {
CONFIG_TAB_INVALID,
CONFIG_TAB_BUTTONS,
CONFIG_TAB_ANALOGS,
CONFIG_TAB_OVERLAY,
CONFIG_TAB_LIGHTS,
CONFIG_TAB_CONTROLLER,
CONFIG_TAB_CARDS,
CONFIG_TAB_PATCHES,
CONFIG_TAB_API,
CONFIG_TAB_OPTIONS,
CONFIG_TAB_ADVANCED,
CONFIG_TAB_DEV,
CONFIG_TAB_PRESETS,
CONFIG_TAB_SEARCH,
};
// sub-pages shown in the Controller tab's left navigation
enum class ControllerPage {
CONTROLLER_PAGE_INVALID,
CONTROLLER_PAGE_BUTTONS,
CONTROLLER_PAGE_KEYPADS,
CONTROLLER_PAGE_ANALOGS,
CONTROLLER_PAGE_OVERLAY,
CONTROLLER_PAGE_LIGHTS,
CONTROLLER_PAGE_PRESETS,
};
struct MatchEntry {
@@ -45,8 +49,9 @@ namespace overlay::windows {
std::vector<Game> games_list;
std::vector<const char *> games_names;
// tabs ui
// currently selected top-level tab and Controller sub-page
ConfigTab tab_selected = ConfigTab::CONFIG_TAB_INVALID;
ControllerPage controller_page_selected = ControllerPage::CONTROLLER_PAGE_INVALID;
// buttons tab
bool buttons_keyboard_state[0xFF];
@@ -134,6 +139,18 @@ namespace overlay::windows {
std::string search_filter = "";
std::string search_filter_in_lower_case = "";
// Options tab left-nav: selected group, currently highlighted category, and a pending scroll
std::string options_group_selected = "";
std::string options_category_selected = "";
bool options_scroll_pending = false;
bool options_scroll_top = false;
// Controller tab left-nav: selected sub-page
std::string controller_page_label = "";
// Cards tab left-nav: selected sub-page
std::string cards_page_label = "";
std::filesystem::path file_picker_path;
std::thread *file_picker_thread = nullptr;
bool file_picker_done = false;
@@ -186,11 +203,18 @@ namespace overlay::windows {
const std::string &target_device);
ControllerTemplate capture_current_bindings(const std::string &name);
void build_cards();
void build_cards_tab(float page_offset);
void build_cards_virtual();
void build_cards_reader();
void build_cards_manager();
std::string build_option_value_picker_title(const OptionDefinition& option);
void build_option_value_picker(Option& option);
void build_options(
std::vector<Option> *options, const std::string &category, const std::string *filter=nullptr);
std::vector<Option> *options, const std::string &category, const std::string *filter=nullptr,
bool quick_only=false);
void build_options_tab(float page_offset);
void build_controller_tab(float page_offset, ControllerPage *page_selected_new);
bool build_nav_header(const char *label, bool active);
void build_about();
void build_launcher();
void build_keypad_warning();
+1 -1
View File
@@ -467,7 +467,7 @@ namespace overlay::windows {
void Control::cards_view() {
if (ImGui::CollapsingHeader("Cards")) {
ImGui::InputTextWithHint("Card ID", "E0040123456789AB",
ImGui::InputTextWithHint("Card ID", "E0040100FFFFFFFF",
this->card_input,
std::size(this->card_input),
ImGuiInputTextFlags_CharsHexadecimal
+71 -26
View File
@@ -1,5 +1,6 @@
#include "exitprompt.h"
#include "avs/game.h"
#include "build/defs.h"
#include "misc/eamuse.h"
#include "util/logging.h"
#include "games/iidx/iidx.h"
@@ -9,7 +10,7 @@
namespace overlay::windows {
ExitPrompt::ExitPrompt(SpiceOverlay *overlay) : Window(overlay) {
this->title = "spice2x";
this->title = "spice2x (" + to_string(VERSION_STRING_CFG) + ")";
this->init_size = ImVec2(
(ImGui::GetFontSize() * 14) + (ImGui::GetStyle().ItemSpacing.x * 2),
overlay::apply_scaling(120));
@@ -20,22 +21,37 @@ namespace overlay::windows {
this->flags = ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoCollapse
| ImGuiWindowFlags_AlwaysAutoResize
| ImGuiWindowFlags_NoDocking;
| ImGuiWindowFlags_NoDocking
| ImGuiWindowFlags_NoMove;
// the menu renders itself as a popup, not a normal overlay window
this->draws_window = false;
}
void ExitPrompt::update() {
Window::update();
// allow the popup to be reopened the next time the menu is shown.
// also reset while the overlay is hidden: new_frame() doesn't submit the
// popup then, so ImGui closes it and it must be re-opened when shown again
if (!this->active || !this->overlay->get_active()) {
this->popup_opened = false;
}
}
void ExitPrompt::build_button(
Window *window, std::string label, const ImVec2 &size, NextItem next, bool is_toggle) {
Window *window, std::string label, const ImVec2 &size, NextItem next) {
if (window == nullptr) {
return;
}
if (ImGui::Button(label.c_str(), size)) {
if (is_toggle) {
window->toggle_active();
} else {
window->set_active(true);
this->set_active(false);
window->toggle_active();
// raise to the top when the user toggled it visible from the menu
if (window->get_active()) {
window->bring_to_front();
}
}
if (next == NextItem::NEW_LINE) {
@@ -46,42 +62,64 @@ namespace overlay::windows {
}
void ExitPrompt::build_content() {
// use ### so the visible label is the full title (with version) while the
// popup keeps a stable identifier regardless of the title text
const std::string popup_id_str = this->title + "###mainmenu";
const char *popup_id = popup_id_str.c_str();
// open the popup once when the menu becomes active; popup_opened is reset
// in update() while inactive so it reopens the next time it is shown
if (!this->popup_opened) {
ImGui::OpenPopup(popup_id);
this->popup_opened = true;
}
// position at the top center of the screen
const ImVec2 menu_pos(
ImGui::GetIO().DisplaySize.x / 2 - this->init_size.x / 2,
overlay::apply_scaling(10));
ImGui::SetNextWindowPos(menu_pos, ImGuiCond_Appearing);
bool open = true;
if (!ImGui::BeginPopupModal(popup_id, &open, this->flags)) {
// dismissed via escape - close the menu
this->set_active(false);
return;
}
const ImVec2 size(ImGui::GetFontSize() * 14, ImGui::GetFontSize() * 1.9f);
const ImVec2 size_half(
(size.x - ImGui::GetStyle().ItemSpacing.x) / 2,
ImGui::GetFontSize() * 1.9f);
const ImVec2 size_third(
(size.x - (ImGui::GetStyle().ItemSpacing.x * 2)) / 3,
ImGui::GetFontSize() * 2.5f);
ImGui::GetFontSize() * 1.9f);
if (ImGui::Button("Hide overlay", size)) {
overlay::OVERLAY->set_active(false);
}
ImGui::Spacing();
build_button(this->overlay->window_config, "Show Config", size, NextItem::NEW_LINE, false);
build_button(this->overlay->window_config, "Options", size, NextItem::NEW_LINE);
std::string sub = "Show Subscreen";
std::string sub = "Subscreen";
if (avs::game::is_model("LDJ")) {
if (games::iidx::TDJ_MODE) {
sub = "Show TDJ Subscreen";
sub = "IIDX TDJ Subscreen";
} else {
sub = "Show LDJ LED Ticker";
sub = "IIDX LDJ LED Ticker";
}
} else if (avs::game::is_model("KFC")) {
sub = "Show Valkyrie Subscreen";
sub = "SDVX Valkyrie Subscreen";
} else if (avs::game::is_model("REC")) {
sub = "Show DRS Dance Floor";
sub = "DRS Dance Floor";
} else if (games::gitadora::is_arena_model()) {
sub = "Show GITADORA Subscreen";
sub = "GITADORA Subscreen";
} else if (games::popn::is_pikapika_model()) {
sub = "Show Pop'n Subscreen";
sub = "Pop'n Subscreen";
}
build_button(this->overlay->window_sub, sub, size, NextItem::NEW_LINE, false);
build_button(this->overlay->window_sub, sub, size, NextItem::NEW_LINE);
ImGui::TextDisabled("Graphics");
build_button(this->overlay->window_camera, "Camera control", size, NextItem::NEW_LINE);
build_button(this->overlay->window_fps, "FPS", size_half, NextItem::SAME_LINE);
build_button(this->overlay->window_fps.get(), "FPS", size_half, NextItem::SAME_LINE);
build_button(this->overlay->window_resize, "Resize", size_half, NextItem::NEW_LINE);
ImGui::TextDisabled("I/O");
@@ -92,9 +130,9 @@ namespace overlay::windows {
build_button(this->overlay->window_iopanel, "I/O panel", size_half, NextItem::NEW_LINE);
} else {
// 1p and 2p
build_button(this->overlay->window_keypad1, "Keypad\n P1", size_third, NextItem::SAME_LINE);
build_button(this->overlay->window_iopanel, " I/O\npanel", size_third, NextItem::SAME_LINE);
build_button(this->overlay->window_keypad2, "Keypad\n P2", size_third, NextItem::NEW_LINE);
build_button(this->overlay->window_keypad1, "P1 #", size_third, NextItem::SAME_LINE);
build_button(this->overlay->window_iopanel, "I/O", size_third, NextItem::SAME_LINE);
build_button(this->overlay->window_keypad2, "P2 #", size_third, NextItem::NEW_LINE);
}
ImGui::TextDisabled("Debug");
@@ -157,5 +195,12 @@ namespace overlay::windows {
ImGui::EndPopup();
}
ImGui::Spacing();
ImGui::EndPopup();
// title-bar X was clicked - close the menu
if (!open) {
this->set_active(false);
}
}
}
+6 -1
View File
@@ -14,8 +14,13 @@ namespace overlay::windows {
public:
ExitPrompt(SpiceOverlay *overlay);
void build_content() override;
void update() override;
private:
void build_button(Window *window, std::string label, const ImVec2 &size, NextItem next, bool is_toggle=true);
void build_button(Window *window, std::string label, const ImVec2 &size, NextItem next);
// latch so the popup is opened once per activation; reset in update()
// whenever the menu is inactive
bool popup_opened = false;
};
}
+89 -23
View File
@@ -1,58 +1,124 @@
#include <iomanip>
#include <sstream>
#include <algorithm>
#include "external/fmt/include/fmt/chrono.h"
#include "fps.h"
namespace overlay::windows {
// tighter internal cell padding than the imgui default (4, 2)
static const ImVec2 FPS_CELL_PADDING(4.0f, 1.0f);
// tighter window padding than the imgui default (8, 8)
static const ImVec2 FPS_WINDOW_PADDING(6.0f, 4.0f);
FPS::FPS(SpiceOverlay *overlay) : Window(overlay) {
this->title = "Stats";
this->flags = ImGuiWindowFlags_NoTitleBar
| ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoCollapse
| ImGuiWindowFlags_AlwaysAutoResize
| ImGuiWindowFlags_NoFocusOnAppearing
| ImGuiWindowFlags_NoBringToFrontOnFocus
| ImGuiWindowFlags_NoNavFocus
| ImGuiWindowFlags_NoNavInputs
| ImGuiWindowFlags_NoNav
| ImGuiWindowFlags_NoMove
| ImGuiWindowFlags_NoInputs
| ImGuiWindowFlags_NoDocking;
this->bg_alpha = 0.5f;
this->window_padding = FPS_WINDOW_PADDING;
this->start_time =
std::chrono::floor<std::chrono::seconds>(std::chrono::system_clock::now());
}
void FPS::calculate_initial_window() {
// width is 114x82 px with window decoration, 98x47 for the content
int pos_x =
overlay::FPS_SHOULD_FLIP ?
overlay::apply_scaling(8) :
ImGui::GetIO().DisplaySize.x - overlay::apply_scaling(122);
this->init_pos = ImVec2(pos_x, overlay::apply_scaling(8));
// size the window explicitly (no AlwaysAutoResize) so the corner anchoring
// below is exact; the footprint mirrors the fixed-fit table in build_content()
const float line_h = ImGui::GetTextLineHeight();
const int rows = 3;
// widest label and widest value drive the two fixed-fit columns
const float label_w = (std::max)(
ImGui::CalcTextSize("Time").x,
ImGui::CalcTextSize("Game").x);
const float value_w = ImGui::CalcTextSize("00:00:00").x;
const float win_w = label_w + value_w
+ FPS_CELL_PADDING.x * 2
+ FPS_WINDOW_PADDING.x * 2;
const float win_h = (line_h + FPS_CELL_PADDING.y * 2) * rows
+ FPS_WINDOW_PADDING.y * 2;
this->init_size = ImVec2(win_w, win_h);
// bottom-anchored windows use a larger edge margin (matching notification
// toasts) since they overlap the same on-screen UI; other edges hug closer
const float edge_margin = overlay::apply_scaling(4);
const float bottom_margin = overlay::apply_scaling(20);
const ImVec2 &display = ImGui::GetIO().DisplaySize;
const bool right =
overlay::FPS_LOCATION == overlay::FpsLocation::TopRight ||
overlay::FPS_LOCATION == overlay::FpsLocation::BottomRight;
const bool bottom =
overlay::FPS_LOCATION == overlay::FpsLocation::BottomLeft ||
overlay::FPS_LOCATION == overlay::FpsLocation::BottomRight;
const float pos_x = right ? display.x - win_w - edge_margin : edge_margin;
const float pos_y = bottom ? display.y - win_h - bottom_margin : edge_margin;
this->init_pos = ImVec2(pos_x, pos_y);
}
void FPS::build_content() {
// frame timers
ImGuiIO &io = ImGui::GetIO();
ImGui::Text("FPS: %.1f", io.Framerate);
// ImGui::Text("FT: %.2fms", 1000 / io.Framerate);
const auto now = std::chrono::system_clock::now();
const auto now_s = std::chrono::floor<std::chrono::seconds>(now);
// current time
{
const std::time_t tt = std::chrono::system_clock::to_time_t(now_s);
std::tm local_tm{};
localtime_s(&local_tm, &tt);
ImGui::TextUnformatted(fmt::format("Time: {:%H:%M:%S}", local_tm).c_str());
}
const std::time_t tt = std::chrono::system_clock::to_time_t(now_s);
std::tm local_tm{};
localtime_s(&local_tm, &tt);
// elapsed time
{
const auto uptime = now_s - this->start_time;
const auto uptime = now_s - this->start_time;
// right-align a label within the current cell so the label column reads
// flush against the value column instead of looking ragged. the label is
// only slightly dimmer than normal text (not the much darker "disabled" tone)
const ImGuiStyle &style = ImGui::GetStyle();
ImVec4 label_col = style.Colors[ImGuiCol_Text];
label_col.w *= 0.7f;
const auto label = [&label_col](const char *text) {
const float avail = ImGui::GetContentRegionAvail().x;
const float text_w = ImGui::CalcTextSize(text).x;
if (avail > text_w) {
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (avail - text_w));
}
ImGui::TextColored(label_col, "%s", text);
};
ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, FPS_CELL_PADDING);
if (ImGui::BeginTable("##fps_stats", 2, ImGuiTableFlags_SizingFixedFit)) {
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
label("FPS");
ImGui::TableSetColumnIndex(1);
ImGui::Text("%.2f", io.Framerate);
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
label("Time");
ImGui::TableSetColumnIndex(1);
ImGui::TextUnformatted(fmt::format("{:%H:%M:%S}", local_tm).c_str());
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
label("Game");
ImGui::TableSetColumnIndex(1);
ImGui::TextUnformatted(
fmt::format("Up: {:%H:%M:%S}",
fmt::format("{:%H:%M:%S}",
std::chrono::floor<std::chrono::seconds>(uptime)).c_str());
ImGui::EndTable();
}
ImGui::PopStyleVar();
}
}
-2
View File
@@ -15,7 +15,5 @@ namespace overlay::windows {
void calculate_initial_window() override;
void build_content() override;
bool should_flip = false;
};
}
+2 -2
View File
@@ -8,10 +8,10 @@
namespace deferredlogs {
const std::initializer_list<std::string> SUPERSTEP_SOUND_ERROR_MESSAGE = {
"audio initialization error was previously detected during boot!",
"audio initialization error was detected during boot!",
" this crash is most likely related to audio init failure",
" * try enabling WASAPI Force Shared Mode (-wasapishared)",
" * check if the default audio device has changed",
" * fix your audio device settings (e.g., sample rate)",
" * double check your spice audio options and patches",
" * ensure no other application is using the device in exclusive mode"
};
+18
View File
@@ -589,6 +589,24 @@ namespace sysutils {
(void**)&EnumDisplayDevicesA_orig);
}
bool is_large_address_aware() {
auto image_base = reinterpret_cast<const uint8_t *>(GetModuleHandleW(nullptr));
if (image_base == nullptr) {
return false;
}
auto dos_header = reinterpret_cast<const IMAGE_DOS_HEADER *>(image_base);
if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
return false;
}
auto nt_headers = reinterpret_cast<const IMAGE_NT_HEADERS *>(
image_base + dos_header->e_lfanew);
if (nt_headers->Signature != IMAGE_NT_SIGNATURE) {
return false;
}
return (nt_headers->FileHeader.Characteristics
& IMAGE_FILE_LARGE_ADDRESS_AWARE) != 0;
}
#if !SPICE_XP
bool is_running_as_admin() {
+4
View File
@@ -20,6 +20,10 @@ namespace sysutils {
const std::vector<MonitorEntry> &enumerate_monitors();
// reads the running module's PE header to determine whether the
// IMAGE_FILE_LARGE_ADDRESS_AWARE bit is set (i.e. spice_laa.exe)
bool is_large_address_aware();
extern std::string SECOND_MONITOR_OVERRIDE;
void hook_EnumDisplayDevicesA();
+2 -2
View File
@@ -115,9 +115,9 @@ void generate_ea_card(char card[17]) {
std::uniform_int_distribution<> uniform(0, 15);
// randomize card
strcpy(card, "E00401");
strcpy(card, "E0040100");
char hex[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
for (int i = 6; i < 16; i++) {
for (int i = 8; i < 16; i++) {
card[i] = hex[uniform(generator)];
}