update client visuals, performance and diagnostics

This commit is contained in:
st committed 2026-10-14 23:30:29 -05:00
1 parent 361892bf0b
commit 875bab0310
155 files changed
+40855 -421

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
# In-game optimizations
Enable the existing optimizations module in Utility. New settings autosave in
existing profiles; the module is not force-enabled in the user's profile.
- Reduce native particles: filters the verified named particle lookup before
emitter creation, with the existing supported empty-definition return path.
- Maximum particles kept: default 50%. Adaptive density lowers this in 10-point
steps when measured FPS falls below 90% of the target and restores it in
5-point steps above 110%. Measurement windows are at least half a second.
Foreground FPS caps lower the effective target. Menus/background suspend
adaptation. It reduces future emitters; existing emitters expire normally.
- Particle budget: default 200 accepted non-combat lookups per 100ms. Set 0 for
unlimited. A packed timestamp/count CAS makes the budget safe across threads.
- Preserve combat particles: defaults on; the separate Particle Controls module
can still suppress categories selected there. Both modules compose.
- HUD data refresh: defaults to 30Hz for local equipment, health/name metadata,
roster, XP and effects. Geometry, velocity, camera matrices, targeting and
nametag player positions are still sampled every rendered world frame. Cache
refreshes immediately on world/player/reader changes or an invalid frame.
Set 0 to restore per-frame metadata reads. These settings do not change game
simulation, inventory actions, packets or tick rates.
- Disable present vsync: optional, defaults off. Sends SyncInterval=0 through the
existing D3D11 Present hook, preserving TEST calls and all native flags. It
does not force tearing flags, overwrite game options, or bypass other FPS
limits. Presentation behavior depends on the game's swapchain/Windows.
Disabling the module restores full-rate reads, native sync and particle behavior
independently of Particle Controls. No speculative game offsets are introduced.
The original Windows scheduling controls/frame caps remain available.
Validation covers native particle forwarding/empty returns, combat exceptions,
filter composition, deterministic density, concurrent burst ceilings/rollovers,
adaptive recovery, refresh invalidation and native Present flags. Full FPS gains
need an in-game comparison in the same scene; none are claimed from unit tests.
+85
View File
@@ -0,0 +1,85 @@
# Quality-of-life modules
All eight additions start disabled. HUDs use the existing FPS card style, font,
background/color/scale controls, draggable editor, and grid snapping. Settings and
saved waypoint records use profile autosave.
- **Waypoints:** F8 (rebindable) or "save current location" adds a named location.
Sixteen slots can be renamed or deleted. The newest death gets a separate slot.
Choose a **world/server group** for each world you use; group selection is manual.
Locations filter by group and actual dimension. Marker distance, coordinates,
range, color, and scale are configurable. Saved data is hidden from the settings
panel but included in profile snapshots. Death recording requires the module
enabled and a captured alive-to-zero-health transition.
- **Compass:** camera-relative direction ticks, heading degrees, width, visible
angle, and optional waypoint/death markers. Works with the freelook camera.
- **Session stats:** time spent in a world while enabled, horizontal/3D distance,
deaths, and positive XP gains. Reset action starts a new session. World or
dimension changes reset measurement baselines; teleports and long frame gaps do
not add traveled distance. Counters are session-only, not lifetime statistics.
- **Durability alerts:** held item/armor selection, percent threshold, notification
duration, and repeat interval (zero = once). Repairing or changing items rearms
alerts. Damage comes from the native `Damage` NBT IntTag, not stack auxiliary data.
- **Tool info:** held item, remaining/max durability and percent, enchantments with
levels, and verified native **base attack bonus**. This is the item's bonus,
not a prediction including enchantments, player attributes, or armor mitigation.
- **Status effects:** potion bottle symbols, names/strength, timers, optional bars,
adjustable expiry flashing, empty-state hiding, width, and row limit. Infinite
effects display "infinite". Bars use the longest duration observed while enabled.
- **Particle controls:** percentage of supported named particle requests to keep,
with portal/weather/combat/smoke-fire/potion/other category switches. Unchecked
categories retain normal behavior. The hook filters definition lookup before
emitter creation; existing emitters finish naturally. Legacy unnamed particles
and effects that reuse a definition without another lookup are not covered.
- **Sound indicators:** native positional SoundInstance start events, names,
direction and distance. Configure lifetime, range, row count, footsteps/combat/
ambient/other filters, optional name substring, and nearby-sound hiding. Audio
is forwarded unchanged. UI/non-positional sounds and other native audio-instance
implementations are not displayed. Indicators show events already started by
the client, not arbitrary nearby entities.
## Native verification (26.52 / package 1.26.5203.0)
Read-only live checks confirmed Speed I's effect ID, decreasing ticks, and zero
amplifier. MobEffectsComponent contains indexed 144-byte instances; ID +0, duration
+4, amplifier +0x20. Inactive slots have ID zero. DimensionTypeComponent is a bounded
0/1/2 integer. Native getters still go through the verified sparse ECS access.
The held realm diamond axe reported Damage 546 / max 1561 (1015 remaining), with
Unbreaking III, Sharpness V, Efficiency IV, and Mending I. CompoundTag uses a bounded
native map; ListTag contains pointers to compound entries with ShortTag `id`/`lvl`.
Tag type getters and the exact max-damage getter are checked before reading. The
attack getter must be a verified read-only integer leaf at +0x218 or +0x228.
All three hook patterns have exactly one match in the captured executable:
particle definition lookup RVA 0x21529c0, continuous SoundInstance update RVA
0xb3a4890, and short SoundInstance update RVA 0xb3a9ec0.
Particle input is HashedString (native string +8), return is a shared-pointer pair.
The emitter's null-definition path returns an invalid handle and cleans its owned
arguments normally. Filtering does not skip an owning emitter wrapper destructor.
Sound name +0x20, position +0x100, positional flag +0x11c and channel +0x88 were
verified against native FMOD setup and live sound objects.
Short instances share name +0x20 and channel +0x88, with position +0xa8,
positional flag +0xbc and playback state +0xcc. Live portal and horse sounds
confirmed these fields. Both start paths are observed; repeated updates to an
already-playing channel do not add events.
## Tests and remaining live checks
The integration suite covers native-shaped item tags/getter validation, malformed
NBT/vector bounds, effect duration/amplifier bounds, waypoint serialization,
dimension filtering/actions, death latching, teleport rejection, session XP math,
particle sampling, null-handle/pass-through behavior, audio forwarding and start
deduplication, reader lifetime across toggles, and actual finite HUD geometry.
In-game interaction still needs verification after loading the rebuilt client:
new HUD appearance, saving/reloading waypoint profiles, death-marker capture,
audible world sound indicators, and visible reduction of supported particles.
The first live build received hundreds of particle requests and suppressed them
at the selected density. That check exposed the missing short-sound update path,
which is now included and covered by the forwarding/deduplication test.
The reloaded build subsequently received 32 native sound events and 973 particle
requests, with 593 particle requests suppressed at the active settings. Minecraft
remained responsive. This confirms live event delivery and filtering; the HUD
appearance and remaining interactions above still require visual verification.
+47
View File
@@ -1,5 +1,31 @@
# FOV Changer verification
## Debug startup scanning
Debug builds also show a read-only diagnostics dashboard after the intro. It
anchors to the top-right HUD grid, flows into columns to fit the display and
uses the current client fonts and text shadows with no background or border.
The compact readout reports rolling frame statistics,
client/module/Present elapsed times, process CPU and memory, adapter-local memory,
aggregate core hook readiness, world snapshot age, input counters, weather,
particles and profiles. Process CPU is normalized across logical processors;
process and GPU memory are for Minecraft as a whole, not just the client DLL.
Present elapsed time includes waiting. Slow counters refresh at 2 Hz; frame
timing stays live. Inactive readers remain inactive. Release builds exclude it.
`debug_metrics_tests.h` verifies statistics, grid alignment and screen bounds at
multiple resolutions/grid sizes, sampling cadence and passive reader behavior.
Signature searches use the longest literal run as an anchor, then verify all
wildcards at each candidate. This avoids checked `vector<bool>` access at every
executable byte in unoptimized Debug builds. Unique-match rejection is retained.
`sigscan_tests.h` compares 3,000 generated patterns against an independent matcher
and checks wildcard-only patterns, overlapping matches and guard-page boundaries.
The existing integration tests still check missing and ambiguous executable matches.
Debug builds write `startup-debug.log` beside `client.dll`, including named scans,
scan durations and the transition from world hooks to modules. If startup still
stalls in-game, inspect the last entry before assuming the remaining issue is a scan.
## World modules and HUD style
See [WORLD_MODULES.md](WORLD_MODULES.md) for the new modules, verified interfaces,
@@ -139,3 +165,24 @@ The Debug and Release client DLLs build successfully, and the isolated integrati
test passes. Visual behavior inside Minecraft still requires the in-game check.
Future game updates may require a new signature; a missing or ambiguous match
leaves the module unavailable.
# Window branding
The client applies `amnesia // minecraft {version}` to the game window when its
renderer initializes. The version comes from the running app's package identity;
package `1.26.5203.0` displays as `26.52`. Without a package identity the title
omits the version. Both window icon sizes use the embedded `src/assets/window.ico`.
Branding is checked once per second and the saved title and icon handles are
restored on unload. The injector's source icon is only copied, never modified.
Render callbacks only post branding requests. Title/icon reads and writes run
on the window thread through the input message handler, avoiding a synchronous
render-to-window wait. Unload requests restoration before removing that handler,
with a one-second timeout if the window thread is unavailable.
The integration suite uses a real hidden Win32 window to verify embedded icon
loading, branding reapplication, repeated install/unload, and restoration of the
original title and icons. Minecraft's title bar and task-switcher appearance still
need an in-game check after loading the rebuilt DLL.
The regression test schedules branding from another thread while the UI thread
does not process messages, then verifies application when messages resume and
restoration from a separate unload thread. It also covers unload before the first
posted branding request has run.
+54
View File
@@ -0,0 +1,54 @@
# Reference menu style
Style source: `D:/projects/menus/bitchbot/src/main.cpp` (read only).
Its UI uses FreeType-rasterized Verdana, white/gray text with four one-pixel black shadows,
square charcoal gradients, black inset borders, and accent #7a459c with a
half-brightness secondary stripe. Checkboxes use a solid gradient selection;
sliders use filled gradient tracks, centered values and +/- label controls;
combos use +/- indicators and accent selections; key binds use plain text.
The client retains its panel/category layout, HUD positions,
editor navigation, lowercase display and existing profile/module identifiers.
The mini player uses a separate, case-preserving Verdana face for external
song/artist/player metadata; other client text keeps the lowercase display.
Body and category text use the reference's 13px Verdana, with 11px secondary
labels. The font atlas uses FreeType with native mono hinting (grayscale antialiasing retained) and horizontal pixel
snapping, including the embedded fallback font. The backend is shared by the
DLL, integration tests and offscreen preview.
HUD text is measured at its actual rendered size, including non-integer
scales. Row cards balance top/bottom padding, values share right edges, and
mini-player art, text, progress and controls share consistent insets/gaps.
Module rows are 26px; action buttons, binds and combos are 22px;
toggle rows are 20px. Native controls use 3px vertical padding.
Existing user colors remain stored; legacy default HUD text/accent colors are
adapted at display time, without rewriting profiles or other custom colors.
Notifications follow `D:/projects/asm_notifications`: compact messages at the
top left, text-sized cards, 2px stack gaps, half-second eased horizontal slides
and exit fades, smoothed stack movement, blinking/bouncing warning lines.
Client timer and live-task progress bars remain available. Backgrounds, borders
and the accent use the shared menu theme; errors use its error color.
Module settings use the reference indent group: a 3px dark vertical guide
and 14px indentation. Expansion and collapse animate the reserved height and
clip the settings, with frame-rate-independent easing. Controls remain disabled
until the reveal finishes; the category owns scrolling.
Shared styling covers ClickGUI, profile dialogs, HUD editor, HUD cards, world
nametags, target/armor/tool/effect/session HUDs, keystrokes, inventory buttons
and picker, media art frames/controls, notifications and the startup screen.
Gameplay rendering colors (crosshair, particles, glint, fog, block outlines)
remain module settings rather than being replaced by the UI theme.
Small local ImGui rendering changes apply shadows, native control gradients,
native checkbox fills, popup/window gradients and accent borders consistently.
They do not change widget input handling or window layout. Keep these changes
when updating the vendored ImGui revision.
Verification: actual checkbox/slider clicks, slider value bounds, stable row
positions, nested draw-list splitting, open dropdown/style-stack balancing,
finite HUD geometry, native font glyph/layout checks and the full integration
suite. An offscreen D3D11/WARP preview uses the actual ClickGUI and widgets
with sample modules (`client/build/style-preview.png`). Final visual behavior
in Minecraft requires reloading the rebuilt DLL.
+6 -2
View File
@@ -56,9 +56,13 @@ the visible-cursor guard is enabled, window resizing, pixel-read failure, or mou
input failure. A held left mouse button is released on cancellation; failed releases
retain ownership for retry and prevent another run from starting.
Notifications appear at the upper right, with sliding/fading cards, reflow, shadows,
colored status icons, a spinner while running, and progress/lifetime bars. Trading
Notifications appear at the upper right, with half-second eased slides, fading
exits, smooth stack reflow, and info/success/warning/error icons in muted colors.
Rounded cards, borders, and fonts match the click GUI. Timed cards have shrinking
lifetime bars; warnings add a pulsing icon and a moving bar indicator. Trading
updates one persistent card rather than creating a toast for every attempt. The
live bar shows trade progress without restarting the entry animation. Repeated
dismissal requests do not postpone expiry. The
renderer remains active after Macro is disabled so final stop messages can finish.
## Verification
+31 -2
View File
@@ -187,8 +187,22 @@ only. In-game verification of the rebuilt DLL still requires loading it.
## HUD editor grid snapping
The clickgui's top bar has a `hud editor` popup with snap/grid toggles and a
4-64 pixel grid size (default 10). Hold Shift while dragging to bypass snapping.
Mouse input is gated both in the subclassed window procedure and in Bedrock's
native MouseDevice feed queue (verified unique signature, current RVA 0x361ad0).
While the menu is open, native motion, button presses, and wheel packets are
discarded; actual button releases still pass. Opening the menu posts a tagged
message to the game's window thread that queues releases for cached mouse
buttons at the last mouse position. It does not synthesize clicks or wheel input.
Closing the menu restores unmodified native event forwarding. Automated tests
cover forwarding arguments, blocked event types, release handling and reopening;
the final in-game click/scroll check remains necessary after reloading the DLL.
The clickgui's top bar has a `hud editor` button that opens a separate editing
screen. Category panels and profile controls are hidden there; its toolbar has
snap/grid toggles, a 4-64 pixel grid size (default 10), and `back to modules`.
Escape returns to the module screen; Right Shift closes the menu. Each new menu
opening starts on modules. Grid lines and HUD drag handles appear only in the
editor. Hold Shift while dragging to bypass snapping.
Only dragged HUD elements snap; opening the editor leaves existing layouts alone.
Mouse displacement is measured from the original grab point, rather than rounding
each frame's delta, so slow dragging does not get stuck between grid cells.
@@ -332,3 +346,18 @@ orbit deltas; reads of the restored player baseline do not reset that reference.
A regression checks that a repeated target contributes zero camera movement,
then a new target contributes only its incremental pitch/yaw change. This fixes
the observed continuous orbit after stopping the mouse.
## Steal/dump item picker
Right-clicking steal or dump opens a compact item list from the current source
slots. Counts aggregate all matching native item IDs; choosing a row transfers
all stacks of that exact ID. Dump choices include hotbar only when the existing
include-hotbar setting is enabled. Left-click continues to transfer everything.
The list scrolls with the mouse wheel, closes with Escape/outside clicks, and
consumes its mouse buttons so selecting a row cannot pick up a container item.
Closing/changing containers, disabling buttons/module or opening the clickgui
clears the picker. Requests carry a copied filter and expected controller identity;
no stale picker selection can attach to a newly opened container. Engine tests
cover duplicate stacks, missing IDs, exact apple/golden-apple distinction, dump
filtering, hotbar choices and filter reset. In-game picker interaction remains to
be checked after loading the rebuilt DLL.
+56
View File
@@ -0,0 +1,56 @@
# Atmosphere world visuals
Visual -> atmosphere keeps the existing module ID, fog/world colors and night
mode. New settings autosave in the existing profile system.
Choose a look preset, press apply selected look, then enable atmosphere:
- neon dusk: purple fog, rich saturation, violet shadows and pink highlights
- vaporwave: cycling pink/cyan palette, colored fog and soft bloom
- frost: pale blue grading, desaturation and cosmetic snow
- ember: warm highlights, purple shadows, amber fog and subtle grain
- golden hour: warm light, cooler shadows and brighter bloom
- noir: monochrome contrast, grain and cosmetic rain
- dreamscape: soft contrast, pastel fog and bloom
Applying a preset updates ordinary settings. All values remain editable; presets
are not reapplied each frame. Reset restores neutral grading and the original
fog defaults. Disabling restores native fog and disables the GPU effects pass.
Controls: exposure, contrast, saturation, shadow/highlight RGB + blend alpha,
world tint + alpha, fog RGB + alpha, night darkness, bloom/threshold, vignette,
chromatic offset, grain, two-color/rainbow palette animation and speed, optional
animated fog, rain/snow density and weather speed, weather renderer, radius, wind and colors.
The postprocess is a single D3D11 fullscreen pass. Bloom samples bright neighbors
only when enabled; chromatic offset adds samples only when enabled. Effects run
in active gameplay with the cursor hidden and ClickGUI closed. Client HUD/GUI
are drawn afterward. This screen-space pass includes Minecraft's own already
rendered UI; screen-overlay rain/snow remain available as a fallback. The default world
renderer draws custom camera-projected particles at world locations using
instanced streak/flake shaders and the native depth buffer with depth writes
disabled. It recognizes standard/reversed perspective matrices matching the
current FOV; if depth/projection cannot be verified, it skips drawing and
reports a waiting notification. Projection coefficients are read from the native camera matrix and normalized
from its OpenGL depth range to D3D11. FOV, matrix shape and the near plane are
validated against the live 26.52 GPU projection recovered during diagnosis.
CPU-side constant-buffer uploads remain an alternate observation path (Map/Unmap, UpdateSubresource and UpdateSubresource1); no GPU-buffer
copy/readback is used. World weather explicitly restores all changed D3D11 state
and leaves native targets/UAV bindings untouched. It never swaps or clears
the game context and only draws on the Present thread. Precipitation does not
yet check block columns for roofs and can spawn inside covered areas. Neither
renderer changes real weather. Native fog uses the existing verified dimension fog hook.
No fake world-time changes, packets or server-state writes are introduced.
Verification uses actual WARP shader execution and pixel readback for neutral
legacy tint/darkness, grayscale, vignette and split tones, all seven presets,
animated-palette changes and reset/disable. Existing tests cover fog isolation
and full D3D11 render-state restoration. A synthetic scene contact sheet renders
the real GPU pass; it is a shader preview, not a screenshot of Minecraft.
Live validation on 26.52: status 4 with an increasing draw count and projection
source 3 confirms the graphics boundary is drawing with the converted native
camera projection. The earlier graphics readback/context-state path was removed
after an NVIDIA-driver crash. Both the WARP and hardware tests now exercise
explicit state preservation, standard/reversed depth occlusion, camera motion
and projection conversion. Final particle appearance requires the user's visual
confirmation; draw counters alone do not establish visual quality.
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include "../src/gui/debug_metrics.h"
inline void test_debug_metrics() {
using namespace debug_metrics;
frame_history history;
assert(history.summarize().mean==0);
history.push(0);history.push(-1);history.push(std::numeric_limits<float>::infinity());
assert(history.count==0);
for(int i=0;i<239;++i)history.push(10);
history.push(100);
auto stats=history.summarize();
assert(stats.min==10 && stats.max==100 && stats.p95==10);
assert(std::fabs(stats.mean-10.375f)<.001f);
assert(std::fabs(stats.low-25.f)<.001f); // slowest 3 of 240 frames
history.push(20);assert(history.count==240 && history.next==1);
for(ImVec2 screen: {ImVec2{1920,1080},ImVec2{1280,720},ImVec2{800,600},ImVec2{320,240}})
for(int grid: {4,10,24,64})for(size_t count:{size_t(1),size_t(90),size_t(140)}) {
const auto box=arrange(screen,count,grid);
assert(box.columns*box.rows>=int(count));
assert(box.pos.x>=0 && box.pos.y>=0 && box.pos.x+box.size.x<=screen.x && box.pos.y+box.size.y<=screen.y);
assert(std::fabs(std::remainder(box.pos.x,float(grid)))<.01f && std::fabs(std::remainder(box.pos.y,float(grid)))<.01f);
assert(box.header+box.rows*box.row_height+box.padding<=box.size.y+.01f);
}
// Reading diagnostics must not activate native hooks or a media worker.
const auto particles=performance::particles.load();const auto weather=world_weather::enabled.load();auto* media_before=media::instance;
dashboard metrics;metrics.sample(nullptr);
assert(!metrics.rows.empty() && particles==performance::particles && weather==world_weather::enabled && media_before==media::instance);
assert(std::any_of(metrics.rows.begin(),metrics.rows.end(),[](const row& r){return r.label=="profile";}));
metrics.rows.push_back({"sample sentinel","",false});metrics.sample(nullptr);
assert(metrics.rows.back().label=="sample sentinel"); // expensive sampling is capped at 2 Hz
std::cout<<"PASS: Debug metrics frame statistics, responsive grid layout, bounded sampling and passive readers\n";
}
+59
View File
@@ -12,6 +12,12 @@
#include "../src/modules/trade_profile.h"
#include "../src/gui/notifications.h"
#include "../src/input.h"
#include "window_branding_tests.h"
#include "menu_input_tests.h"
#include "lowercase_font_tests.h"
#include "startup_intro_tests.h"
#include "style_widget_tests.h"
#include "sigscan_tests.h"
#pragma section(".fvtest", read, execute)
#pragma comment(linker, "/SECTION:.fvtest,ER")
__declspec(allocate(".fvtest")) unsigned char fixture[] = {0x56, 0x57, 0x53, 0x48, 0x83, 0xec, 0x60, 0x44, 0x0f, 0x29, 0x44, 0x24, 0x50, 0x0f, 0x29, 0x7c, 0x24, 0x40, 0x0f, 0x29, 0x74, 0x24, 0x30, 0x44, 0x89, 0xc3, 0x0f, 0x28, 0xf1, 0x48, 0x89, 0xce, 0x45, 0x84, 0xc0, 0x0f, 0x84, 0x23, 0x00, 0x00, 0x00, 0x48, 0x8b, 0x86, 0x88, 0x11, 0x00, 0x00, 0x48, 0x8b, 0x88, 0xf8, 0x03, 0x00, 0x00, 0x48, 0x8b, 0x01, 0x48, 0x8b, 0x80, 0xd8, 0x00, 0x00, 0x00, 0x48, 0x8d, 0x54, 0x24, 0x28, 0x41, 0xb8, 0x2f, 0x00, 0x00, 0x00, 0xf3, 0x0f, 0x10, 0x05, 0x18, 0x00, 0x00, 0x00, 0x0f, 0x28, 0x74, 0x24, 0x30, 0x0f, 0x28, 0x7c, 0x24, 0x40, 0x44, 0x0f, 0x28, 0x44, 0x24, 0x50, 0x48, 0x83, 0xc4, 0x60, 0x5b, 0x5f, 0x5e, 0xc3, 0x00, 0x00, 0x8c, 0x42};
@@ -271,6 +277,24 @@ static void test_crosshair_render() {
cross.set_enabled(false);draw_native();assert(native_crosshair_draws==3+i);
}
notifications::items.clear();
// Entry/exit match the reference's half-second eased slide; timers count down.
notifications::toast timed;timed.born=10;timed.duration=3;
auto motion=notifications::animate(timed,10);
assert(motion.slide==1 && motion.alpha==1 && motion.remaining==1);
motion=notifications::animate(timed,10.25);
assert(close_float(motion.slide,.25f));
motion=notifications::animate(timed,11.5);
assert(motion.slide==0 && close_float(motion.remaining,.5f));
motion=notifications::animate(timed,13.25);
assert(close_float(motion.slide,.75f) && close_float(motion.alpha,.25f) && motion.remaining==0);
motion=notifications::animate(timed,13.5);
assert(motion.slide==1 && motion.alpha==0);
timed.title="macro";timed.body="running";
assert(notifications::message(timed)=="macro: running");
timed.title.clear();assert(notifications::message(timed)=="running");
timed.body.clear();assert(notifications::message(timed).empty());
timed.duration=0;motion=notifications::animate(timed,100);
assert(motion.slide==0 && motion.alpha==1);
notifications::push("Trading","1 / 500 trade attempts",notifications::kind::info,0,"trade",0.1f);
notifications::push("Trading","2 / 500 trade attempts",notifications::kind::info,0,"trade",0.2f);
assert(notifications::items.size()==1 && notifications::items[0].progress==0.2f);
@@ -281,9 +305,32 @@ static void test_crosshair_render() {
assert(ImGui::GetForegroundDrawList()->VtxBuffer.Size>0);
for(const auto& vertex:ImGui::GetForegroundDrawList()->VtxBuffer) assert(std::isfinite(vertex.pos.x) && std::isfinite(vertex.pos.y));
ImGui::Render();
assert(close_float(notifications::items.front().y,5.f));
assert(notifications::items[1].y>notifications::items[0].y);
assert(notifications::items[2].y>notifications::items[1].y);
notifications::dismiss("trade");assert(notifications::items[0].duration>0);
const double dismissed_duration=notifications::items[0].duration;
notifications::dismiss("trade");assert(notifications::items[0].duration==dismissed_duration);
for(auto& item:notifications::items) item.born-=20;
ImGui::NewFrame();notifications::draw();assert(notifications::items.empty());ImGui::Render();
// All four types, wrapped text, and keyed progress updates render without restarting entry.
notifications::push("Working","A long notification body that should wrap across more than one line in the card.",notifications::kind::info,0,"live",.3f);
const double live_born=notifications::items[0].born;
notifications::push("Working","Updated progress",notifications::kind::info,0,"live",.7f);
assert(notifications::items[0].born==live_born);
notifications::dismiss("live");
notifications::push("Working","Resumed",notifications::kind::info,0,"live",.8f);
assert(!notifications::items[0].dismissed && notifications::items[0].duration==0);
for(auto type:{notifications::kind::info,notifications::kind::success,notifications::kind::warning,notifications::kind::error}) {
notifications::items.clear();
notifications::push("Status","Multiple lines\nwith a timer",type,3);
notifications::items[0].born-=1;
ImGui::NewFrame();notifications::draw();ImGui::Render();
assert(ImGui::GetDrawData()->TotalVtxCount>0);
for(const auto& vertex:ImGui::GetForegroundDrawList()->VtxBuffer)
assert(std::isfinite(vertex.pos.x) && std::isfinite(vertex.pos.y));
}
notifications::items.clear();
ImGui::DestroyContext();
}
@@ -344,8 +391,20 @@ static void write_code(unsigned char* target, const unsigned char* bytes, size_t
#include "anti_afk_tests.h"
#include "server_hud_tests.h"
#include "hud_grid_tests.h"
#include "qol_tests.h"
#include "performance_tests.h"
#include "world_weather_tests.h"
#include "debug_metrics_tests.h"
int main() {
test_debug_metrics();
test_sigscan_ranges();
test_lowercase_fonts();
test_startup_intro();
test_style_widgets();
menu_input_test::run();
test_window_branding();
test_qol_readers();test_qol_state();test_qol_event_forwarding();test_qol_modules();test_performance();test_world_weather();test_world_weather(D3D_DRIVER_TYPE_HARDWARE);
test_profiles();
test_world_math_and_hooks();
test_world_filter();
+4
View File
@@ -9,11 +9,14 @@
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<PropertyGroup><OutDir>$(ProjectDir)..\build\tests\</OutDir><IntDir>$(OutDir)obj\</IntDir></PropertyGroup>
<ItemDefinitionGroup>
<ResourceCompile><AdditionalIncludeDirectories>$(ProjectDir)..\src;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories></ResourceCompile>
<ClCompile><LanguageStandard>stdcpp17</LanguageStandard><WarningLevel>Level3</WarningLevel><UndefinePreprocessorDefinitions>NDEBUG</UndefinePreprocessorDefinitions><AdditionalIncludeDirectories>$(ProjectDir)..\vendor\minhook\include;$(ProjectDir)..\vendor\imgui;$(ProjectDir)..\vendor\imgui\backends</AdditionalIncludeDirectories></ClCompile>
<Link><AdditionalDependencies>user32.lib;%(AdditionalDependencies)</AdditionalDependencies></Link>
</ItemDefinitionGroup>
<ItemGroup>
<ResourceCompile Include="..\src\client.rc" />
<ClCompile Include="fov_changer_test.cc" />
<ClCompile Include="..\src\font_data.cc" />
<ClCompile Include="..\vendor\imgui\imgui.cpp" />
<ClCompile Include="..\vendor\imgui\imgui_draw.cpp" />
<ClCompile Include="..\vendor\imgui\imgui_tables.cpp" />
@@ -23,5 +26,6 @@
<ClCompile Include="..\vendor\minhook\src\trampoline.c" />
<ClCompile Include="..\vendor\minhook\src\hde\hde64.c" />
</ItemGroup>
<Import Project="$(ProjectDir)..\vendor\freetype\freetype.props" />
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
+20
View File
@@ -85,6 +85,26 @@ inline void test_inventory_tools() {
stock={{"apple",3}};state.panels[2].items=stock;worker.step(state,11200,true);
state.panels[2].items=stock;worker.step(state,11300,true);
assert(!worker.active() && cursor.count==0 && transferred_groups==std::vector<std::string>({"inventory_items","hotbar_items"}));include_hotbar=false;
// Filtered transfers use exact native item IDs and retain unrelated stacks.
stock={{"arrow",10},{"golden_apple",4},{"arrow",5},{"apple",3}};cursor={};
state.panels={{"container_items",stock},{"inventory_items",stock}};state.cursor=false;
transfers=0;transferred_groups.clear();worker.start({owner,action::steal,"","arrow"});
for(int i=0;i<12 && worker.active();++i){state.panels[0].items=stock;worker.step(state,16000+i*100,true);}
assert(!worker.active() && transfers==2 && stock[0].count==0 && stock[2].count==0 && stock[1].count==4 && stock[3].count==3);
transfers=0;worker.start({owner,action::steal,"","diamond"});
for(int i=0;i<12 && worker.active();++i){state.panels[0].items=stock;worker.step(state,18000+i*100,true);}
assert(!worker.active() && transfers==0 && stock[1].count==4);
stock={{"apple",3},{"golden_apple",4}};state.panels[1].items=stock;transfers=0;
worker.start({owner,action::dump,"","apple"});
for(int i=0;i<8 && worker.active();++i){state.panels[1].items=stock;worker.step(state,20000+i*100,true);}
assert(transfers==1 && stock[0].count==0 && stock[1].count==4);
snapshot picker_fixture;picker_fixture.panels={{"container_items",{{"arrow",10},{"arrow",5},{"apple",3}}},
{"inventory_items",{{"stone",64}}},{"hotbar_items",{{"arrow",20},{"stone",6}}}};
auto menu=choices(picker_fixture,action::steal,false);
assert(menu.size()==2 && menu[0].name=="apple" && menu[1].name=="arrow" && menu[1].count==15);
menu=choices(picker_fixture,action::dump,false);assert(menu.size()==1 && menu[0].name=="stone" && menu[0].count==64);
menu=choices(picker_fixture,action::dump,true);assert(menu.size()==2 && menu[0].name=="arrow" && menu[1].count==70);
worker.start({owner,action::dump,"","apple"});worker.cancel();assert(worker.filter.empty());
assert(next_minimum({},0)==-1);
// Additional controllers must not cancel an operation owned by a fresh chest.
auto old_tick=original_tick;auto old_current=current;auto old_published=latest();const bool old_enabled=enabled;
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include "../src/gui/fonts.h"
#include "../src/gui/hud_card.h"
inline void test_lowercase_fonts() {
ImGui::CreateContext();
fonts::load();
auto& io=ImGui::GetIO();
assert(io.Fonts->FontLoader==ImGuiFreeType::GetFontLoader());
io.DisplaySize={1280,720};io.DeltaTime=.016f;
io.BackendFlags|=ImGuiBackendFlags_RendererHasTextures;
ImGui::NewFrame();
for(ImFont* font : {fonts::body,fonts::semibold,fonts::label,fonts::heading}) {
for(float size : {11.f,13.f,14.f,20.f,35.f}) {
auto* baked=font->GetFontBaked(size);
for(ImWchar upper='A';upper<='Z';++upper) {
// Loading the second glyph can grow/reallocate the glyph array.
const auto* glyph=baked->FindGlyphNoFallback(upper);
assert(glyph);
const ImFontGlyph capital=*glyph;
const auto* lower=baked->FindGlyphNoFallback(upper+('a'-'A'));
assert(lower && capital.AdvanceX==lower->AdvanceX);
assert(capital.X0==lower->X0 && capital.X1==lower->X1 && capital.Y0==lower->Y0 && capital.Y1==lower->Y1);
}
const auto a=font->CalcTextSizeA(size,FLT_MAX,0,"Macro / Shift / FPS");
const auto b=font->CalcTextSizeA(size,FLT_MAX,0,"macro / shift / fps");
assert(a.x==b.x && a.y==b.y);
}
}
assert(fonts::media && fonts::media!=fonts::body);
auto* media_baked=fonts::media->GetFontBaked(13.f);
const ImFontGlyph capital=*media_baked->FindGlyphNoFallback('A');
const ImFontGlyph lower=*media_baked->FindGlyphNoFallback('a');
assert(capital.U0!=lower.U0 || capital.V0!=lower.V0);
// Exercise the real hinted fonts at non-integer HUD scales; glyphs and their
// shadows must fit the card sized by the same font, rather than scaled metrics.
for(float scale:{.7f,1.f,1.35f,2.5f}) {
const ImVec2 pos{40,40};const auto bounds=hud_card::size("fps","144",scale,"999");
auto* draw=ImGui::GetBackgroundDrawList();const int begin=draw->VtxBuffer.Size;
hud_card::draw(pos,"fps","144",scale,true,IM_COL32_WHITE,"999");
for(int i=begin;i<draw->VtxBuffer.Size;++i) {
const auto p=draw->VtxBuffer[i].pos;
assert(p.x>=pos.x-2 && p.x<=pos.x+bounds.x+2);
assert(p.y>=pos.y-2 && p.y<=pos.y+bounds.y+2);
}
}
ImGui::EndFrame();ImGui::DestroyContext();
fonts::body=fonts::semibold=fonts::label=fonts::heading=fonts::media=nullptr;
std::cout<<"PASS: lowercase glyphs and matching layout at all client font weights and sizes\n";
}
+4 -1
View File
@@ -42,7 +42,10 @@ inline void test_media_and_glint() {
state.duration=240;state.position=60;state.stamp=GetTickCount64();player.draw(state);
Microsoft::WRL::ComPtr<ID3D11Device> art_device;Microsoft::WRL::ComPtr<ID3D11DeviceContext> art_context;D3D_FEATURE_LEVEL art_level;
assert(SUCCEEDED(D3D11CreateDevice(nullptr,D3D_DRIVER_TYPE_WARP,nullptr,0,nullptr,0,D3D11_SDK_VERSION,&art_device,&art_level,&art_context)));
media_art::device=art_device.Get();state.art=cover;player.draw(state);media_art::device=nullptr;
media_art::device=art_device.Get();state.art=cover;player.draw(state);
state.app="Spotify.exe";player.draw(state);
state.app="SPOTIFY.EXE";player.draw(state);
state.app="test player";player.draw(state);media_art::device=nullptr;
g_menu_open=true;player.draw(state);g_menu_open=false;
assert(player.hud_drag_size().y<player.hud_size().y);
ImGui::Render();assert(ImGui::GetDrawData()->TotalVtxCount>100);
+48
View File
@@ -0,0 +1,48 @@
#pragma once
#include <vector>
#include "../src/input.h"
namespace menu_input_test {
struct event {void* device;char button,state;short x,y,dx,dy;char scrolling;};
inline std::vector<event> received;
inline void __fastcall receive(void* device,char button,char state,short x,short y,short dx,short dy,char scrolling) {
received.push_back({device,button,state,x,y,dx,dy,scrolling});
}
inline void run() {
const auto saved = input::original_mouse_feed;
const auto device = input::mouse_device;
const auto x = input::mouse_x, y = input::mouse_y;
const bool open = g_menu_open;
const auto buttons=input::blocked_mouse_buttons.load(), wheels=input::blocked_mouse_wheels.load(), moves=input::blocked_mouse_moves.load();
input::original_mouse_feed=receive; received.clear();
auto* fake = reinterpret_cast<void*>(0x1234);
g_menu_open=false;
input::mouse_feed_detour(fake,1,1,100,200,3,4,7);
assert(received.size()==1 && received[0].device==fake && received[0].button==1 && received[0].state==1);
assert(received[0].x==100 && received[0].y==200 && received[0].dx==3 && received[0].dy==4 && received[0].scrolling==7);
g_menu_open=true;
input::release_native_mouse();
assert(received.size()==6);
for(size_t i=1;i<received.size();++i) {
assert(input::mouse_release(received[i].button,received[i].state));
assert(received[i].x==100 && received[i].y==200 && received[i].dx==0 && received[i].dy==0);
}
const auto count=received.size();
for(char button : {char(0),char(1),char(2),char(3),char(4),char(5),char(6)})
input::mouse_feed_detour(fake,button,1,110,210,5,6,0);
input::mouse_feed_detour(fake,4,0,110,210,0,0,0); // Zero wheel state isn't a button release.
assert(received.size()==count);
assert(input::blocked_mouse_buttons==buttons+5 && input::blocked_mouse_wheels==wheels+2 && input::blocked_mouse_moves==moves+1);
for(char button : {char(1),char(2),char(3),char(5),char(6)})
input::mouse_feed_detour(fake,button,0,110,210,0,0,0);
assert(received.size()==count+5);
g_menu_open=false;
input::release_native_mouse();
assert(received.size()==count+5);
input::mouse_feed_detour(fake,4,-120,120,220,0,0,1);
assert(received.size()==count+6 && received.back().state==-120 && received.back().scrolling==1);
input::original_mouse_feed=saved;input::mouse_device=device;input::mouse_x=x;input::mouse_y=y;g_menu_open=open;
input::blocked_mouse_buttons=buttons;input::blocked_mouse_wheels=wheels;input::blocked_mouse_moves=moves;
std::cout<<"PASS: native menu mouse gate blocks clicks, wheel and motion; releases held buttons and resumes unchanged input\n";
}
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include <thread>
#include "../src/game/performance.h"
inline void test_performance() {
performance::reset();
assert(performance::present_sync(1,0)==1);
performance::uncapped_present=true;
assert(performance::present_sync(1,0)==0 && performance::present_sync(3,DXGI_PRESENT_TEST)==3);
performance::particles=true;performance::keep=50;performance::burst_limit=0;
int dropped=0;for(int i=0;i<100;++i)dropped+=performance::suppress(0,true,1000);
assert(dropped==50);
performance::keep=0;
assert(!performance::suppress(2,true,1000) && !performance::suppress(0,false,1000));
performance::keep=100;performance::burst_limit=10;
int allowed=0;for(int i=0;i<100;++i)allowed+=!performance::suppress(0,true,1000);
assert(allowed==10 && !performance::suppress(0,true,1100));
performance::budget_state=0;
std::atomic<int> total{0};std::vector<std::thread> workers;
for(int i=0;i<8;++i)workers.emplace_back([&]{for(int n=0;n<1000;++n)if(!performance::over_budget(2000,317))++total;});
for(auto& thread:workers)thread.join();assert(total==317);
assert(!performance::over_budget(2100,317));
// An older thread must not reset the next window's budget.
const auto newer=performance::budget_state.load();assert(performance::over_budget(2000,317));
assert(performance::budget_state==newer);
performance::adaptive_density adaptive;adaptive.reset(50);
for(int i=0;i<40;++i)adaptive.update(1./30,120,50);
assert(adaptive.current<50);
for(int i=0;i<960;++i)adaptive.update(1./240,120,50);
assert(adaptive.current==50);
const int saved=adaptive.current;adaptive.update(std::nan(""),120,50);assert(adaptive.current==saved);
performance::refresh_gate refresh;
assert(refresh.due(1000,1,1,0,30));assert(!refresh.due(1016,1,1,0,30));assert(refresh.due(1034,1,1,0,30));
assert(refresh.due(1035,2,1,0,30));assert(refresh.due(1036,2,2,0,30));assert(refresh.due(1037,2,2,1,30));
assert(refresh.due(1038,2,2,1,0));refresh.valid=false;assert(refresh.due(1039,2,2,1,30));
performance::reset();assert(!performance::particles && !performance::uncapped_present && performance::hud_hz==0);
std::cout<<"PASS: adaptive native particles, concurrent burst budgets, composed filters, HUD refresh invalidation and reversible Present sync\n";
}
+143
View File
@@ -0,0 +1,143 @@
#pragma once
#include "../src/modules/qol_modules.h"
#include "../src/config/profiles.h"
inline void test_qol_readers() {
auto put=[](void* p,size_t offset,auto value){memcpy(static_cast<unsigned char*>(p)+offset,&value,sizeof(value));};
unsigned char type2[]{0xb0,2,0xc3},type3[]{0xb0,3,0xc3},type9[]{0xb0,9,0xc3},type10[]{0xb0,10,0xc3};
uintptr_t vt2[6]{},vt3[6]{},vt9[6]{},vt10[6]{};
vt2[5]=uintptr_t(type2);vt3[5]=uintptr_t(type3);vt9[5]=uintptr_t(type9);vt10[5]=uintptr_t(type10);
struct node {uintptr_t left=0,parent=0,right=0;uint64_t flags=0;std::string key;unsigned char value[96]{};};
static_assert(offsetof(node,key)==32 && offsetof(node,value)==64);
struct compound {uintptr_t vt=0,head=0;size_t count=0;};
node head,damage,ench,ench_head,id,lvl;
compound tags{uintptr_t(vt10),uintptr_t(&head),2},enchantment{uintptr_t(vt10),uintptr_t(&ench_head),2};
head.parent=uintptr_t(&damage);damage.key="Damage";damage.left=uintptr_t(&head);damage.right=uintptr_t(&ench);
ench.key="ench";ench.left=ench.right=uintptr_t(&head);
put(damage.value,0,uintptr_t(vt3));put(damage.value,8,275);
ench_head.parent=uintptr_t(&id);id.key="id";id.left=uintptr_t(&ench_head);id.right=uintptr_t(&lvl);
lvl.key="lvl";lvl.left=lvl.right=uintptr_t(&ench_head);
put(id.value,0,uintptr_t(vt2));put(id.value,8,int16_t(17));put(lvl.value,0,uintptr_t(vt2));put(lvl.value,8,int16_t(3));
uintptr_t entry=uintptr_t(&enchantment);put(ench.value,0,uintptr_t(vt9));put(ench.value,8,uintptr_t(&entry));put(ench.value,16,uintptr_t(&entry+1));
unsigned char item[0x240]{},stack[152]{},max_getter[]{0x0f,0xb7,0x81,0x50,1,0,0,0xc3},attack_getter[]{0x8b,0x81,0x28,2,0,0,0xc3};
uintptr_t item_vt[38]{},counter=uintptr_t(item);item_vt[36]=uintptr_t(max_getter);item_vt[37]=uintptr_t(attack_getter);
put(item,0,uintptr_t(item_vt));put(item,0x150,uint16_t(1561));put(item,0x228,5);
const char* name="diamond_pickaxe";memcpy(item+0xd8,name,strlen(name));put(item,0xe8,uint64_t(strlen(name)));put(item,0xf0,uint64_t(15));
put(stack,8,uintptr_t(&counter));put(stack,16,uintptr_t(&tags));put(stack,0x22,uint8_t(1));
auto value=world::read_item(uintptr_t(stack),true);
assert(value.name==name && value.durability_known && value.damage==275 && value.max_damage==1561);
assert(value.attack_known && value.attack_bonus==5 && value.enchantments.size()==1 && value.enchantments[0].id==17 && value.enchantments[0].level==3);
put(damage.value,8,1600);assert(!world::read_item(uintptr_t(stack),true).durability_known);put(damage.value,8,275);
tags.count=129;assert(!world::read_item(uintptr_t(stack),true).durability_known);tags.count=2;
put(ench.value,16,uintptr_t(&entry)+513);assert(world::read_item(uintptr_t(stack),true).enchantments.empty());
assert(!world::read_item(uintptr_t(stack),false).durability_known);
unsigned char effect_data[144*3]{};uintptr_t effects[]{uintptr_t(effect_data),uintptr_t(effect_data+sizeof(effect_data)),uintptr_t(effect_data+sizeof(effect_data))};
put(effect_data,144,1);put(effect_data,144+4,1200);put(effect_data,144+0x10,14);put(effect_data,144+0x20,0);
put(effect_data,288,19);put(effect_data,288+4,60);put(effect_data,288+0x20,1);
std::vector<world::effect> active;assert(world::read_effects(uintptr_t(effects),active) && active.size()==2 && active[0].amplifier==0 && active[1].ticks==60);
put(effect_data,144+4,-1);assert(world::read_effects(uintptr_t(effects),active) && active[0].ticks==-1);
put(effect_data,144+0x20,256);assert(!world::read_effects(uintptr_t(effects),active));
effects[1]++;assert(!world::read_effects(uintptr_t(effects),active));
std::cout<<"PASS: native item Damage/enchantment tags, verified durability/attack getters and indexed effect timers\n";
}
inline void test_qol_state() {
qol::waypoint p{"home \"base\"","realm",{123,64,-256},0,false},restored;
assert(qol::decode(qol::encode(p),restored) && restored.name==p.name && restored.position.z==-256);
assert(!qol::decode("broken",restored));p.position.x=std::numeric_limits<float>::infinity();assert(!qol::decode(qol::encode(p),restored));
assert(qol::bearing({},{0,0,10})==0 && std::abs(qol::bearing({},{10,0,0})+90)<.01f);
world::frame f;f.valid=true;f.stamp=GetTickCount64();f.world_id=1;f.local.health_known=true;f.local.health=20;
f.xp_known=true;f.xp_level=1;f.xp_progress=0;
qol::session stats;assert(!stats.update(f,1));f.local.feet={3,0,4};f.xp_progress=.5f;
stats.update(f,1.5);assert(std::abs(stats.distance-5)<.01 && stats.seconds==.5 && stats.xp==4.5);
f.local.feet={1000,0,0};stats.update(f,1.6);assert(std::abs(stats.distance-5)<.01);
f.local.health=0;assert(stats.update(f,1.7) && stats.deaths==1);assert(!stats.update(f,1.8) && stats.deaths==1);
f.local.health=20;stats.update(f,1.9);f.local.health=0;assert(stats.update(f,2) && stats.deaths==2);
f.world_id=2;stats.update(f,2.1);assert(stats.deaths==2);
const double previous_xp=stats.xp;f.local.id=2;f.xp_level=100;stats.update(f,2.2);assert(stats.xp==previous_xp);
assert(qol::total_xp(16,0)==352 && qol::total_xp(17,0)==394 && qol::total_xp(31,0)==1507 && qol::total_xp(32,0)==1628);
assert(qol::clock_text(65)=="1:05" && qol::clock_text(3661)=="1:01:01");
module_manager manager;auto* points=manager.add<waypoints_module>();const auto defaults=config::capture(manager);
const auto saved=qol::encode({"realm home","my world",{10,64,20},0,false});
for(auto& setting:points->settings())if(setting.name=="saved waypoint 1")setting.text_value=saved;
config::snapshot loaded;assert(config::decode(config::encode(config::capture(manager)),loaded));
for(auto& setting:points->settings())if(setting.name=="saved waypoint 1")setting.text_value.clear();
config::apply(manager,defaults,loaded);
for(auto& setting:points->settings())if(setting.name=="saved waypoint 1")assert(setting.hidden && setting.text_value==saved);
qol_events::particle_categories=1;qol_events::density=0;assert(qol_events::suppress_particle("minecraft:portal_directional"));
assert(!qol_events::suppress_particle("minecraft:critical_hit_emitter"));
qol_events::particle_categories=0x3f;qol_events::density=50;qol_events::sequence=0;int dropped=0;
for(int i=0;i<100;++i)dropped+=qol_events::suppress_particle("minecraft:rain_splash");assert(dropped==50);
qol_events::density=100;assert(!qol_events::suppress_particle("minecraft:portal_directional"));
std::cout<<"PASS: waypoint round-trip, bearings, death latching, teleport rejection, session XP and particle sampling\n";
}
inline setting& qol_setting(module& m,const char* name) {
for(auto& s:m.settings())if(s.name==name)return s;
assert(false);return m.settings().front();
}
inline void test_qol_event_forwarding() {
auto put=[](void* p,size_t offset,auto value){memcpy(static_cast<unsigned char*>(p)+offset,&value,sizeof(value));};
const auto old_sound=qol_events::original_sound,old_short=qol_events::original_short_sound;const auto old_particle=qol_events::original_particle;
world::frame f;f.valid=true;f.stamp=GetTickCount64();f.world_id=17;world::publish(f);
unsigned char object[0x128]{};const char* name="zombie.hurt";
memcpy(object+0x20,name,strlen(name));put(object,0x30,uint64_t(strlen(name)));put(object,0x38,uint64_t(15));
put(object,0x100,world::vec3{12,64,20});put(object,0x11c,uint8_t(1));
qol_events::original_sound=+[](uintptr_t self,float dt) {
assert(dt==.125f);world::write(self+0x88,uintptr_t(12345));world::write(self+0xa8,3);
};
qol_events::sounds_enabled=true;qol_events::pending.clear();
qol_events::sound_detour(uintptr_t(object),.125f);
assert(qol_events::pending.size()==1 && qol_events::pending[0].name==name && qol_events::pending[0].position.x==12);
qol_events::sound_detour(uintptr_t(object),.125f);assert(qol_events::pending.size()==1);
put(object,0x88,uintptr_t(0));put(object,0x11c,uint8_t(0));qol_events::sound_detour(uintptr_t(object),.125f);assert(qol_events::pending.size()==1);
qol_events::pending.clear();put(object,0x88,uintptr_t(0));put(object,0xbc,uint8_t(1));put(object,0xa8,world::vec3{5,64,8});
qol_events::original_short_sound=+[](uintptr_t self,float dt) {
assert(dt==.125f);world::write(self+0x88,uintptr_t(23456));world::write(self+0xcc,1);
};
qol_events::short_sound_detour(uintptr_t(object),.125f);assert(qol_events::pending.size()==1 && qol_events::pending[0].position.x==5);
qol_events::short_sound_detour(uintptr_t(object),.125f);assert(qol_events::pending.size()==1);
qol_events::sounds_enabled=false;qol_events::pending.clear();
struct hashed {uint64_t hash=0;std::string text;};hashed particle;particle.text="minecraft:portal_directional";
uintptr_t output[]{111,222};
qol_events::original_particle=+[](uintptr_t cache,uintptr_t out,uintptr_t id) {
assert(cache==123 && id);world::write(out,std::array<uintptr_t,2>{11,22});return out;
};
qol_events::particles_enabled=true;qol_events::particle_categories=1;qol_events::density=0;
assert(qol_events::particle_detour(123,uintptr_t(output),uintptr_t(&particle))==uintptr_t(output) && output[0]==0 && output[1]==0);
qol_events::particles_enabled=false;qol_events::particle_detour(123,uintptr_t(output),uintptr_t(&particle));assert(output[0]==11 && output[1]==22);
performance::particles=true;performance::keep=0;
qol_events::particle_detour(123,uintptr_t(output),uintptr_t(&particle));assert(output[0]==0 && output[1]==0);
particle.text="minecraft:critical_hit_emitter";performance::protect_combat=true;
qol_events::particle_detour(123,uintptr_t(output),uintptr_t(&particle));assert(output[0]==11 && output[1]==22);
// Independent Particle Controls still applies its own selected categories.
qol_events::particles_enabled=true;qol_events::particle_categories=1u<<2;qol_events::density=0;
qol_events::particle_detour(123,uintptr_t(output),uintptr_t(&particle));assert(output[0]==0 && output[1]==0);
qol_events::particles_enabled=false;performance::reset();
qol_events::original_sound=old_sound;qol_events::original_short_sound=old_short;qol_events::original_particle=old_particle;world::publish({});
std::cout<<"PASS: native sound forwarding/start deduplication and particle empty-handle/pass-through paths\n";
}
inline void test_qol_modules() {
ImGui::CreateContext();auto& io=ImGui::GetIO();io.DisplaySize={1280,900};io.DeltaTime=.016f;
io.Fonts->AddFontDefault();unsigned char* pixels;int w,h;io.Fonts->GetTexDataAsRGBA32(&pixels,&w,&h);
world::frame f;f.valid=true;f.stamp=GetTickCount64();f.world_id=1;f.dimension=0;f.local.feet={10,64,20};f.local.health_known=true;f.local.health=20;
f.matrix[0]=f.matrix[5]=f.matrix[15]=1;f.matrix[10]=-1;f.xp_known=true;f.xp_level=28;f.xp_progress=.3f;
f.effects_known=true;f.effects={{1,1200,0},{19,80,1}};
f.local.held.name="diamond_axe";f.local.held.damage=1500;f.local.held.max_damage=1561;f.local.held.durability_known=true;f.local.held.enchantments={{17,3},{26,1}};
world::publish(f);const bool was_ready=world::ready;world::ready=true;
waypoints_module points;compass_hud compass(points);session_stats stats;durability_alerts alerts;tool_info tool;status_effects_hud effects;sound_indicators sounds;
points.set_enabled(true);tool.set_enabled(true);alerts.set_enabled(true);effects.set_enabled(true);stats.set_enabled(true);
assert(world::collect_item_details==2 && world::collect_effects==1 && world::extra_xp_readers==1);
qol_setting(points,"save current location").action();assert(points.points(f).size()==1);
f.dimension=1;assert(points.points(f).empty());f.dimension=0;
g_menu_open=true;ImGui::NewFrame();
module* hud_modules[]{&points,&compass,&stats,&alerts,&tool,&effects,&sounds};
for(module* m:hud_modules)m->on_render();
const auto notification_count=notifications::items.size();alerts.on_render();assert(notifications::items.size()==notification_count);
ImGui::Render();auto* data=ImGui::GetDrawData();assert(data->TotalVtxCount>100);
for(int i=0;i<data->CmdListsCount;++i)for(const auto& v:data->CmdLists[i]->VtxBuffer)assert(std::isfinite(v.pos.x) && std::isfinite(v.pos.y));
points.set_enabled(false);tool.set_enabled(false);alerts.set_enabled(false);effects.set_enabled(false);stats.set_enabled(false);
assert(world::collect_item_details==0 && world::collect_effects==0 && world::extra_xp_readers==0);
world::ready=was_ready;g_menu_open=false;world::publish({});notifications::items.clear();ImGui::DestroyContext();
std::cout<<"PASS: new HUD geometry, waypoint actions/dimension filtering, alerts and shared-reader lifetime\n";
}
+1 -1
View File
@@ -31,7 +31,7 @@ inline void test_server_hud() {
ImGui::NewFrame();g_menu_open=true;
world::frame frame;frame.valid=true;frame.stamp=GetTickCount64();frame.xp_known=true;frame.xp_level=28;frame.xp_progress=.3f;frame.roster_known=true;
for(int i=0;i<25;++i)frame.online_players.push_back("player "+std::to_string(i));world::publish(frame);
tab_list list;xp_progress_hud xp;list.on_render();xp.on_render();assert(list.hud_size().x==360 && xp.hud_size().y==54);
tab_list list;xp_progress_hud xp;list.on_render();xp.on_render();assert(list.hud_size().x==360 && xp.hud_size().y==43);
world::publish({});list.on_render();xp.on_render();list.on_disable();xp.on_disable();
assert(!world::collect_roster && !world::collect_xp);
ImGui::Render();auto* data=ImGui::GetDrawData();assert(data->TotalVtxCount>100);
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include <cassert>
#include <string>
#include "../src/game/sigscan.h"
inline void test_sigscan_ranges() {
// Compare optimized matching to a simple independent matcher, including
// leading/trailing wildcards, repeated anchors and overlapping matches.
unsigned state=0x5812;
auto random=[&] {state=state*1664525u+1013904223u;return state;};
unsigned char data[128];
sigscan::pattern pattern;
for(unsigned trial=0;trial<3000;++trial) {
const size_t size=1+random()%sizeof(data),length=1+random()%24;
for(size_t i=0;i<size;++i)data[i]=static_cast<unsigned char>((random()>>16)%4);
std::string text;
for(size_t i=0;i<length;++i) {
if((random()>>16)%3==0)text+="?? ";
else {text+="0";text+=char('0'+(random()>>16)%4);text+=' ';}
}
assert(sigscan::parse(text.c_str(),pattern));
size_t expected=0;unsigned char* first=nullptr;
if(length<=size)for(size_t at=0;at<=size-length;++at) {
bool match=true;
for(size_t i=0;i<length;++i)if(pattern.mask[i] && data[at+i]!=pattern.bytes[i]){match=false;break;}
if(match){++expected;if(!first)first=data+at;}
}
assert(sigscan::scan_range(data,data+size,pattern)==first);
assert(sigscan::count_matches(data,data+size,pattern)==expected);
}
assert(sigscan::parse("?? ??",pattern));
assert(sigscan::count_matches(data,data+4,pattern)==3);
assert(sigscan::scan_range(data,data,pattern)==nullptr);
assert(sigscan::scan_range(nullptr,nullptr,pattern)==nullptr);
assert(!sigscan::parse("",pattern));
assert(!sigscan::parse("4",pattern));
assert(!sigscan::parse("ZZ",pattern));
// A last-position anchor must never read into the following guard page.
SYSTEM_INFO info{};GetSystemInfo(&info);
auto* pages=static_cast<unsigned char*>(VirtualAlloc(nullptr,info.dwPageSize*2,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE));
assert(pages);DWORD old=0;
assert(VirtualProtect(pages+info.dwPageSize,info.dwPageSize,PAGE_NOACCESS,&old));
auto* end=pages+info.dwPageSize;
end[-4]=0x11;end[-3]=0x22;end[-2]=0x33;end[-1]=0x44;
assert(sigscan::parse("?? 22 33 44",pattern));
assert(sigscan::scan_range(end-4,end,pattern)==end-4);
assert(sigscan::scan_range(end-3,end,pattern)==nullptr);
assert(sigscan::parse("?? 22 33 45",pattern));
assert(sigscan::scan_range(end-4,end,pattern)==nullptr);
assert(VirtualFree(pages,0,MEM_RELEASE));
}
+77
View File
@@ -0,0 +1,77 @@
#pragma once
#include "../src/gui/startup_intro.h"
inline void test_startup_intro() {
using startup_intro::stage;
float progress=startup_intro::completion(stage::hooks,0,0);
for(unsigned i=0;i<=36;++i) {
const float next=startup_intro::completion(stage::modules,i,36);
assert(next>=progress && next<1);progress=next;
}
for(auto phase:{stage::input,stage::profile,stage::hud,stage::ready}) {
const float next=startup_intro::completion(phase,36,36);
assert(next>=progress && next<=1);progress=next;
}
assert(progress==1 && startup_intro::completion(stage::modules,100,36)==.75f);
assert(startup_intro::completion(stage::modules,0,0)==.35f);
using startup_intro::playback;
playback clock;
assert(clock.step(0,false)==0); // No startup delay.
for(int i=1;i<=600;++i) {
const auto age=clock.step(i/60.0,false);
assert(age>=0 && age<=startup_intro::hold_age && !clock.finished);
}
assert(clock.age==startup_intro::hold_age);
double now=10;
assert(clock.step(now+=.1,true)>startup_intro::hold_age);
for(int i=0;i<200;++i)clock.step(now+=1.0/60,true);
assert(clock.finished && clock.step(now+1,true)<0);
playback startup_stall;
startup_stall.step(0,true);
const float before=startup_stall.step(.1,true);
assert(startup_stall.step(8,true)<before+.02f); // Stall doesn't skip animation.
playback skipped;
assert(skipped.step(0,false,true)==startup_intro::hold_age && !skipped.finished);
assert(skipped.step(20,false,true)==startup_intro::hold_age && !skipped.finished);
now=20;
for(int i=0;i<100;++i)skipped.step(now+=1.0/60,true,true);
assert(skipped.finished); // Skip cannot bypass the readiness gate.
ImGui::CreateContext();auto& io=ImGui::GetIO();
io.DisplaySize={1280,720};io.DeltaTime=.016f;
io.Fonts->AddFontDefault();unsigned char* pixels;int width,height;
io.Fonts->GetTexDataAsRGBA32(&pixels,&width,&height);
Microsoft::WRL::ComPtr<ID3D11Device> device;
assert(SUCCEEDED(D3D11CreateDevice(nullptr,D3D_DRIVER_TYPE_WARP,nullptr,0,nullptr,0,
D3D11_SDK_VERSION,&device,nullptr,nullptr)));
startup_intro::initialize_texture(device.Get());assert(startup_intro::texture);
for(ImVec2 screen : {ImVec2{320,240},ImVec2{1280,720},ImVec2{3440,1440}}) {
io.DisplaySize=screen;
for(float age : {-1.f,0.f,.15f,.5f,1.25f,2.3f,2.7f,2.8f,5.f}) {
ImGui::NewFrame();startup_intro::render(age,screen,.5f,"loading modules",age);ImGui::Render();
auto* data=ImGui::GetDrawData();
if(age<0 || age>=startup_intro::duration)assert(data->TotalVtxCount==0);
else assert(data->TotalVtxCount>0);
if(age==0) {
// The first frame already covers gameplay with opaque pixels.
const auto* list=data->CmdLists[0];
for(int i=0;i<4;++i)assert((list->VtxBuffer[i].col>>IM_COL32_A_SHIFT)==255);
}
assert(data->TotalVtxCount<8000);
for(int i=0;i<data->CmdListsCount;++i)
for(const auto& vertex:data->CmdLists[i]->VtxBuffer)
assert(std::isfinite(vertex.pos.x) && std::isfinite(vertex.pos.y));
}
}
ImVec2 texture_position[2];
for(int i=0;i<2;++i) {
ImGui::NewFrame();startup_intro::render(startup_intro::hold_age,io.DisplaySize,.5f,"loading modules",double(i));ImGui::Render();
texture_position[i]=ImGui::GetDrawData()->CmdLists[0]->VtxBuffer[4].pos;
}
assert(texture_position[0].x!=texture_position[1].x || texture_position[0].y!=texture_position[1].y);
startup_intro::texture.Reset();
ImGui::DestroyContext();
std::cout<<"PASS: opaque readiness-gated intro, real loading-stage progress, GPU grain texture/motion and responsive geometry\n";
}
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include "../src/gui/widgets.h"
#include "../src/gui/indent_section.h"
#include "imgui_internal.h"
inline void test_style_widgets() {
ImGui::CreateContext();auto& io=ImGui::GetIO();io.IniFilename=nullptr;
io.DisplaySize={800,600};io.DeltaTime=1.f/60;io.ConfigInputTrickleEventQueue=false;
io.Fonts->AddFontDefault();unsigned char* pixels;int width,height;io.Fonts->GetTexDataAsRGBA32(&pixels,&width,&height);
theme::apply();
bool checked=false,open=false;int integer=25,selected=0;float number=.5f;
char text[32]="amnesia";ImVec2 check_pos{},slider_pos{},combo_pos{};
auto frame=[&](ImVec2 mouse,bool down) {
io.AddMousePosEvent(mouse.x,mouse.y);io.AddMouseButtonEvent(0,down);
ImGui::NewFrame();ImGui::SetNextWindowPos({20,20});ImGui::SetNextWindowSize({400,520});
ImGui::Begin("style controls",nullptr,ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoMove);
auto* draw=ImGui::GetWindowDrawList();draw->ChannelsSplit(2);draw->ChannelsSetCurrent(1);
check_pos=ImGui::GetCursorScreenPos();widgets::checkbox("toggle",&checked,260,24);
widgets::slider_int("integer",&integer,0,100,260);slider_pos=ImGui::GetItemRectMin();
widgets::slider_float("float",&number,0,1,260);
widgets::input_text("##text",text,sizeof(text),260);
combo_pos=ImGui::GetCursorScreenPos();open=widgets::begin_combo("##mode",selected ? "second" : "first",260);
if(open) {
if(widgets::selectable("first",selected==0))selected=0;
if(widgets::selectable("second",selected==1))selected=1;
ImGui::EndCombo();
}
widgets::button("action","apply",false,260,26);
draw->ChannelsMerge();ImGui::End();
assert(GImGui->ColorStack.empty() && GImGui->StyleVarStack.empty());
ImGui::Render();
for(int i=0;i<ImGui::GetDrawData()->CmdListsCount;++i)
for(const auto& v:ImGui::GetDrawData()->CmdLists[i]->VtxBuffer)
assert(std::isfinite(v.pos.x) && std::isfinite(v.pos.y));
};
frame({-100,-100},false);
const auto initial_check=check_pos,initial_slider=slider_pos,initial_combo=combo_pos;
frame({check_pos.x+7,check_pos.y+10},false);frame({check_pos.x+7,check_pos.y+10},true);frame({check_pos.x+7,check_pos.y+10},false);
assert(checked);
frame({slider_pos.x+200,slider_pos.y+10},false);frame({slider_pos.x+200,slider_pos.y+10},true);frame({slider_pos.x+200,slider_pos.y+10},false);
assert(integer>65 && integer<90 && number==.5f && std::string(text)=="amnesia");
assert(check_pos.x==initial_check.x && check_pos.y==initial_check.y);
assert(slider_pos.x==initial_slider.x && slider_pos.y==initial_slider.y);
assert(combo_pos.x==initial_combo.x && combo_pos.y==initial_combo.y);
frame({combo_pos.x+100,combo_pos.y+10},false);frame({combo_pos.x+100,combo_pos.y+10},true);frame({combo_pos.x+100,combo_pos.y+10},false);
assert(open);
// The settings reveal must move following rows, preserve scrolling bounds,
// and prevent partially revealed controls from accepting clicks.
float measured=0;bool activated=false;
auto reveal_frame=[&](float amount,ImVec2 mouse,bool down) {
io.AddMousePosEvent(mouse.x,mouse.y);io.AddMouseButtonEvent(0,down);
ImGui::NewFrame();ImGui::SetNextWindowPos({20,20});ImGui::SetNextWindowSize({400,520});
ImGui::Begin("reveal",nullptr,ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoMove);
const auto start=ImGui::GetCursorScreenPos();
widgets::indent_section(260,start.y,amount,measured,amount==1,[&](float w) {
ImGui::TextUnformatted("settings");
activated|=widgets::button("hidden action","apply",false,w,22);
});
const float occupied=ImGui::GetItemRectSize().y;
assert(std::abs(occupied-measured*amount)<.01f);
assert(ImGui::GetCurrentWindow()->DC.CursorMaxPos.y<=start.y+occupied+.01f);
const float below=ImGui::GetCursorScreenPos().y;
ImGui::Button("next module",{260,26});ImGui::End();
assert(GImGui->ColorStack.empty() && GImGui->StyleVarStack.empty() && GImGui->GroupStack.empty());
ImGui::Render();return below;
};
const float full=reveal_frame(1,{-100,-100},false);
const float half=reveal_frame(.5f,{-100,-100},false);
const float closed=reveal_frame(0,{-100,-100},false);
assert(full>half && half>closed);
// A click at the lower action's full-size location cannot fire while sliding.
reveal_frame(.5f,{80,full-13},false);reveal_frame(.5f,{80,full-13},true);reveal_frame(.5f,{80,full-13},false);
assert(!activated);
float a=0,b=0;
for(int i=0;i<12;++i)a=widgets::expand_step(a,true,1.f/60);
for(int i=0;i<24;++i)b=widgets::expand_step(b,true,1.f/120);
assert(std::abs(a-b)<.00001f && a>0 && a<1);
assert(widgets::expand_step(a,false,1.f/60)<a);
ImGui::DestroyContext();
std::cout<<"PASS: styled checkbox/slider interaction, stable row layout, nested draw layers and balanced dropdown style stacks\n";
}
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#include "../src/window_branding.h"
#include <future>
inline LRESULT CALLBACK branding_test_proc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp) {
if(window_branding::handle_message(hwnd,msg,wp,lp))return 0;
return DefWindowProcW(hwnd,msg,wp,lp);
}
inline void pump_branding_messages() {
MSG message{};
while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE))DispatchMessageW(&message);
}
inline void test_window_branding() {
PACKAGE_VERSION version{};version.Major=1;version.Minor=26;version.Build=5203;
assert(window_branding::display_version(version)==L"26.52");
version.Minor=21;version.Build=11401;
assert(window_branding::display_version(version)==L"1.21.114");
const auto module=GetModuleHandleW(nullptr);
WNDCLASSW wc{};wc.hInstance=module;wc.lpfnWndProc=branding_test_proc;wc.lpszClassName=L"AmnesiaBrandingTest";
assert(RegisterClassW(&wc));
HWND hwnd=CreateWindowExW(0,wc.lpszClassName,L"Original Minecraft title",WS_OVERLAPPEDWINDOW,
0,0,300,200,nullptr,nullptr,module,nullptr);
assert(hwnd);
auto original_small=LoadIcon(nullptr,IDI_WARNING),original_large=LoadIcon(nullptr,IDI_ERROR);
SendMessageW(hwnd,WM_SETICON,ICON_SMALL,reinterpret_cast<LPARAM>(original_small));
SendMessageW(hwnd,WM_SETICON,ICON_BIG,reinterpret_cast<LPARAM>(original_large));
for(int i=0;i<2;++i) {
// Simulate Present running while the UI thread cannot pump messages.
// Scheduling must finish without waiting for any UI response.
auto render=std::async(std::launch::async,[=] {
window_branding::install(hwnd,module);
window_branding::next_check=0;window_branding::tick();
});
assert(render.wait_for(std::chrono::milliseconds(500))==std::future_status::ready);
render.get();assert(!window_branding::window);
pump_branding_messages();
assert(window_branding::icon_small && window_branding::icon_large);
assert(window_branding::window_title(hwnd).find(L"amnesia // minecraft")==0);
assert(reinterpret_cast<HICON>(SendMessageW(hwnd,WM_GETICON,ICON_SMALL,0))==window_branding::icon_small);
SetWindowTextW(hwnd,L"Game changed title");
SendMessageW(hwnd,WM_SETICON,ICON_BIG,0);
window_branding::next_check=0;window_branding::tick();
pump_branding_messages();
assert(window_branding::window_title(hwnd)==window_branding::title);
assert(reinterpret_cast<HICON>(SendMessageW(hwnd,WM_GETICON,ICON_BIG,0))==window_branding::icon_large);
auto unload=std::async(std::launch::async,[] {window_branding::shutdown();});
const auto deadline=GetTickCount64()+2000;
while(unload.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready && GetTickCount64()<deadline) {
pump_branding_messages();Sleep(1);
}
assert(unload.wait_for(std::chrono::milliseconds(0))==std::future_status::ready);unload.get();
assert(window_branding::window_title(hwnd)==L"Original Minecraft title");
assert(reinterpret_cast<HICON>(SendMessageW(hwnd,WM_GETICON,ICON_SMALL,0))==original_small);
assert(reinterpret_cast<HICON>(SendMessageW(hwnd,WM_GETICON,ICON_BIG,0))==original_large);
assert(!window_branding::window && !window_branding::icon_small && !window_branding::icon_large);
}
// An unload before the first posted update must not brand the window later.
window_branding::install(hwnd,module);window_branding::shutdown();pump_branding_messages();
assert(window_branding::window_title(hwnd)==L"Original Minecraft title" && !window_branding::window);
DestroyWindow(hwnd);window_branding::shutdown();UnregisterClassW(wc.lpszClassName,module);
std::cout<<"PASS: asynchronous window branding without a pumping UI thread, embedded icons and unload restoration\n";
}
+33 -2
View File
@@ -1,4 +1,5 @@
#pragma once
#include <set>
#include "../src/modules/world_modules.h"
#include "../src/modules/fps_counter.h"
#include "../src/modules/keystrokes.h"
@@ -106,8 +107,38 @@ inline void test_world_filter() {
D3D11_MAPPED_SUBRESOURCE mapped{};assert(SUCCEEDED(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&mapped)));
auto* pixel=static_cast<unsigned char*>(mapped.pData)+16*mapped.RowPitch+16*4;
assert(std::abs(int(pixel[0])-128)<=1 && std::abs(int(pixel[1])-64)<=1 && std::abs(int(pixel[2])-32)<=1 && pixel[3]==255);
context->Unmap(staging.Get(),0);enabled=false;assert(!apply(device.Get(),context.Get(),rt));shutdown();
std::cout<<"PASS: actual D3D11 color/darkness shader and render-state restoration (WARP)\n";
context->Unmap(staging.Get(),0);
auto read_pixel=[&](int x,int y) {
context->CopyResource(staging.Get(),output.Get());
D3D11_MAPPED_SUBRESOURCE data{};assert(SUCCEEDED(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&data)));
const auto* p=static_cast<unsigned char*>(data.pData)+y*data.RowPitch+x*4;
const std::array<int,3> result{p[0],p[1],p[2]};context->Unmap(staging.Get(),0);return result;
};
tint=IM_COL32_WHITE;brightness=1;
grading grade;grade.saturation=0;configure(grade);
const float blue[4]={.2f,.4f,.8f,1};context->ClearRenderTargetView(rt,blue);assert(apply(device.Get(),context.Get(),rt));
const auto gray=read_pixel(16,16);assert(std::abs(gray[0]-gray[1])<=1 && std::abs(gray[1]-gray[2])<=1);
grade={};grade.vignette=.8f;configure(grade);context->ClearRenderTargetView(rt,white);assert(apply(device.Get(),context.Get(),rt));
assert(read_pixel(16,16)[0]>read_pixel(0,0)[0]+30);
grade={};grade.shadows=IM_COL32(255,0,0,255);grade.highlights=IM_COL32(255,0,0,255);configure(grade);
context->ClearRenderTargetView(rt,blue);assert(apply(device.Get(),context.Get(),rt));const auto toned=read_pixel(16,16);assert(toned[0]>51 && toned[2]<204);
ImGui::CreateContext();atmosphere looks;
auto setting=[&](const char* name)->struct setting& {for(auto& s:looks.settings())if(s.name==name)return s;assert(false);return looks.settings().front();};
std::set<std::array<int,3>> results;
for(int preset=0;preset<7;++preset) {
setting("look preset").int_value=preset;setting("apply selected look").action();looks.on_render();
assert(enabled && world::fog_enabled);
context->ClearRenderTargetView(rt,blue);assert(apply(device.Get(),context.Get(),rt));results.insert(read_pixel(16,16));
D3D11_PRIMITIVE_TOPOLOGY restored_topology;context->IAGetPrimitiveTopology(&restored_topology);
assert(restored_topology==D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
}
assert(results.size()>=5);
setting("palette animation").int_value=1;looks.on_render();const auto first=tint.load();
GImGui->Time+=5;looks.on_render();assert(tint!=first);
setting("reset atmosphere").action();looks.on_render();assert(!enabled && configuration().bloom==0 && configuration().contrast==1);
looks.on_disable();assert(!world::fog_enabled);ImGui::DestroyContext();
enabled=false;assert(!apply(device.Get(),context.Get(),rt));shutdown();
std::cout<<"PASS: actual D3D11 grading, vignette, split tones, seven presets, palette animation/reset and render-state restoration (WARP)\n";
}
inline void test_world_huds() {
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include "../src/game/world_weather.h"
inline void test_world_weather(D3D_DRIVER_TYPE driver=D3D_DRIVER_TYPE_WARP) {
using namespace world_weather;
float matrix[16]{};matrix[0]=matrix[5]=1;matrix[10]=-1.001f;matrix[11]=-1;matrix[14]=-.1f;
projection found;assert(find_projection(matrix,16,1,1,found) && found.b<0);
assert(!find_projection(matrix,16,2,1,found));matrix[15]=1;assert(!find_projection(matrix,16,1,1,found));
matrix[15]=0;matrix[10]=0;matrix[14]=.1f;assert(find_projection(matrix,16,1,1,found) && found.b>0);
matrix[10]=-1.001f;matrix[14]=-.1f;
ComPtr<ID3D11Device> device;ComPtr<ID3D11DeviceContext> context;
const D3D_FEATURE_LEVEL levels[]={D3D_FEATURE_LEVEL_12_1,D3D_FEATURE_LEVEL_12_0,D3D_FEATURE_LEVEL_11_1,D3D_FEATURE_LEVEL_11_0};
assert(SUCCEEDED(D3D11CreateDevice(nullptr,driver,nullptr,0,levels,4,D3D11_SDK_VERSION,&device,nullptr,&context)));
D3D11_TEXTURE2D_DESC td{};td.Width=td.Height=256;td.MipLevels=td.ArraySize=1;td.SampleDesc.Count=1;
td.Format=DXGI_FORMAT_R8G8B8A8_UNORM;td.BindFlags=D3D11_BIND_RENDER_TARGET;
ComPtr<ID3D11Texture2D> image;ComPtr<ID3D11RenderTargetView> target;
assert(SUCCEEDED(device->CreateTexture2D(&td,nullptr,&image)));assert(SUCCEEDED(device->CreateRenderTargetView(image.Get(),nullptr,&target)));
td.Format=DXGI_FORMAT_D32_FLOAT;td.BindFlags=D3D11_BIND_DEPTH_STENCIL;
ComPtr<ID3D11Texture2D> depth_texture;ComPtr<ID3D11DepthStencilView> dsv;
assert(SUCCEEDED(device->CreateTexture2D(&td,nullptr,&depth_texture)));assert(SUCCEEDED(device->CreateDepthStencilView(depth_texture.Get(),nullptr,&dsv)));
td.Format=DXGI_FORMAT_R8G8B8A8_UNORM;td.BindFlags=0;td.Usage=D3D11_USAGE_STAGING;td.CPUAccessFlags=D3D11_CPU_ACCESS_READ;
ComPtr<ID3D11Texture2D> staging;assert(SUCCEEDED(device->CreateTexture2D(&td,nullptr,&staging)));
ID3D11RenderTargetView* rt=target.Get();context->OMSetRenderTargets(1,&rt,dsv.Get());
D3D11_VIEWPORT viewport{0,0,256,256,0,1};context->RSSetViewports(1,&viewport);
context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
D3D11_BUFFER_DESC bd{};bd.ByteWidth=64;bd.BindFlags=D3D11_BIND_CONSTANT_BUFFER;D3D11_SUBRESOURCE_DATA initial{matrix,0,0};
ComPtr<ID3D11Buffer> native_cb;assert(SUCCEEDED(device->CreateBuffer(&bd,&initial,&native_cb)));
ID3D11Buffer* cb=native_cb.Get();context->VSSetConstantBuffers(0,1,&cb);
world::frame scene;scene.valid=true;scene.fov_x=scene.fov_y=1;scene.matrix[0]=scene.matrix[5]=scene.matrix[10]=scene.matrix[15]=1;
enabled=true;expected_x=expected_y=1;
observe({matrix,sizeof(matrix),reinterpret_cast<uintptr_t>(native_cb.Get())});
assert(discover(device.Get(),context.Get(),scene,found) && found.b<0);
settings options;options.snow=1;options.radius=8;options.snow_color=IM_COL32(255,0,0,255);
auto render=[&](float clear_depth,projection p,float camera_x) {
const float black[4]{0,0,0,1};context->ClearRenderTargetView(rt,black);context->ClearDepthStencilView(dsv.Get(),D3D11_CLEAR_DEPTH,clear_depth,0);
scene.camera.x=camera_x;assert(draw(device.Get(),context.Get(),scene,rt,dsv.Get(),viewport,p,options,3.5));
D3D11_PRIMITIVE_TOPOLOGY topology;context->IAGetPrimitiveTopology(&topology);assert(topology==D3D11_PRIMITIVE_TOPOLOGY_LINELIST);
ComPtr<ID3D11RenderTargetView> restored;ComPtr<ID3D11DepthStencilView> restored_depth;context->OMGetRenderTargets(1,&restored,&restored_depth);
assert(restored.Get()==rt && restored_depth.Get()==dsv.Get());
ComPtr<ID3D11Buffer> restored_cb;context->VSGetConstantBuffers(0,1,&restored_cb);assert(restored_cb.Get()==native_cb.Get());
context->CopyResource(staging.Get(),image.Get());D3D11_MAPPED_SUBRESOURCE map{};assert(SUCCEEDED(context->Map(staging.Get(),0,D3D11_MAP_READ,0,&map)));
uint64_t sum=0,hash=0;for(int y=0;y<256;++y)for(int x=0;x<256;++x) {auto* pixel=static_cast<unsigned char*>(map.pData)+y*map.RowPitch+x*4;sum+=pixel[0];hash=hash*31+pixel[0];}
context->Unmap(staging.Get(),0);return std::make_pair(sum,hash);
};
const auto visible=render(1,{-1.001f,-.1f},0);assert(visible.first>0);
assert(render(0,{-1.001f,-.1f},0).first==0);
assert(render(1,{-1.001f,-.1f},.5f).second!=visible.second);
assert(render(0,{0,.1f},0).first>0);assert(render(1,{0,.1f},0).first==0);
options.snow=0;options.rain=1;options.rain_color=IM_COL32(255,0,0,255);assert(render(1,{-1.001f,-.1f},0).first>0);
// Read the actual camera-layout projection path without any GPU staging copy.
alignas(16) unsigned char client_data[0x800]{},renderer_data[0x500]{},camera_data[0x1100]{};
const auto old_client=world::client.load();world::client=reinterpret_cast<uintptr_t>(client_data);
const uintptr_t renderer_pointer=reinterpret_cast<uintptr_t>(renderer_data),camera_pointer=reinterpret_cast<uintptr_t>(camera_data);
memcpy(client_data+0x1c0,&renderer_pointer,sizeof(renderer_pointer));memcpy(renderer_data+0x468,&camera_pointer,sizeof(camera_pointer));
float camera_projection_data[16]{};memcpy(camera_projection_data,matrix,sizeof(matrix));camera_projection_data[14]=-.025f;
memcpy(camera_data+0xf58,camera_projection_data,sizeof(camera_projection_data));
assert(camera_projection(scene));assert(discover(device.Get(),context.Get(),scene,found) && std::abs(found.b+.025f)<.000001f);
camera_projection_data[14]=-.05f;camera_projection_data[10]=-1.002f;memcpy(camera_data+0xf58,camera_projection_data,sizeof(camera_projection_data));
assert(camera_projection(scene));assert(discover(device.Get(),context.Get(),scene,found) && std::abs(found.a+1.001f)<.00001f && std::abs(found.b+.025f)<.000001f);
world::client=old_client;
// Run both upload observers against the real adapter without staging readback.
original_update=+[](ID3D11DeviceContext* c,ID3D11Resource* r,UINT sub,const D3D11_BOX* box,const void* data,UINT row,UINT depth){c->UpdateSubresource(r,sub,box,data,row,depth);};
cached_buffer=0;enabled=true;update_detour(context.Get(),native_cb.Get(),0,nullptr,matrix,0,0);
assert(discover(device.Get(),context.Get(),scene,found));
draw_context=context.Get();draw_thread=GetCurrentThreadId();
static int boundaries=0;boundaries=0;
before_target_change=+[](ID3D11DeviceContext* c){ComPtr<ID3D11DepthStencilView> d;c->OMGetRenderTargets(0,nullptr,&d);assert(d);++boundaries;};
target_boundary(context.Get(),dsv.Get());assert(boundaries==0);
target_boundary(context.Get(),nullptr);assert(boundaries==1);
before_target_change=nullptr;
shutdown();assert(!enabled && !vs);
std::cout<<"PASS: world-space rain/snow shaders, native projection matching, standard/reverse depth occlusion, camera parallax and complete pipeline restoration (GPU)\n";
}